Skip to content
Edytor
Esc
↑↓navigate↵open⌘Jpreview
On this page

Editing programmatically

Change the document from code with the one set of document operations, through the view (dispatched) or the bare document (raw), read their results, group writes with transact, and move blocks.

Every write is one of the document’s operations (insertBlocks, splitBlock, insertText, patchData, moveBlocks…), with one set of names and arguments and two entry points: through the view, edytor.insertText(…), it behaves like a user edit; on the bare document, edytor.document.insertText(…), it writes directly. Handles (Block, Text, InlineBlock) only read: you pass their ids. This page shows both entry points, how to read their results, and how to move blocks.

Through the view or on the document

edytor.<operation>(…) edytor.document.<operation>(…)
Names and arguments The document’s operations The same
Plugin hooks (onBeforeOperation, onAfterOperation) Yes: plugins can refuse, replace or rewrite them No
Normalization (normalizeContent, normalizeChildren) Yes No
Undo One step, by the view’s policy Captured as a headless edit
The caret it decides (a range deletion, a placed paste) Selected None
Refused in a readonly view Yes No
Result An OpResult; edytor.dispatcher.last records the command An OpResult
Needs a view Yes No, works headlessly

Write through the view for anything a user could have done, so your plugins see it. Write on the document for imports, migrations, server-side edits and code that must bypass plugins.

Operations address blocks by id and use block offsets, where an inline atom counts as one character: offset o of a text segment is text.segStart + o.

const id = 'intro';
const block = edytor.idToBlock.get(id)!;

// Insert blocks around it, at a destination: its parent (null: the root) and an index.
const at = { parent: null, index: block.index + 1 };
const inserted = edytor.insertBlocks(at, [{ type: 'paragraph', content: [{ text: 'After' }] }]);
const next = edytor.idToBlock.get(inserted.ids[0]!); // the new block's handle

// Change its kind, data, content or children in one step.
edytor.setBlock(id, { type: 'quote' }); // in place: a list's item set to a paragraph still shows as an item
// (`convertToKind` takes it out of the list, as Turn into does)
edytor.patchData(id, [{ path: ['icon'], value: '✦' }]); // one property; `block.data.icon = '✦'` is the same (see concepts/properties)
edytor.patchData(id, [{ path: [], value: { icon: '✦' } }]); // replace the whole `data`

// Structure.
edytor.nestBlock(id, block.previousBlock!.id); // last child of the previous sibling
edytor.unNestBlock(id); // after its parent; the siblings after it become its children
// (a list's item leaves the list instead, see concepts/blocks#containers)
edytor.mergeBackward(id); // join into the previous block (a list's first item leaves the list instead)
edytor.insertBlocks({ parent: id, index: 0 }, [{ type: 'paragraph' }]);
edytor.deleteBlock(id); // children take its place
edytor.deleteBlock(id, { keepChildren: false }); // the whole subtree

// Split at a block offset into a new block (its id is yours), of the kind you name.
edytor.splitBlock(id, 3, 'intro-tail', { type: 'paragraph' });
void next;
const id = 'intro';
edytor.insertText(id, 0, 'Hello'); // takes the marks the caret would give it
edytor.insertText(id, 5, 'link', { link: { href: 'https://example.com' } });
edytor.deleteText(id, 4, 1);
edytor.formatRange(id, 0, 5, { bold: true, italic: null }); // null removes a mark
edytor.clearMarks(id, 0, 5);
edytor.insertInline(id, 2, { type: 'mention', data: { name: 'Ada' } });

Through the view, an insertText without marks takes the marks the caret would give it (pending marks when it lands at the caret, then the neighboring text); pass {} for plain text.

Gestures on the selection are the editor’s and richTextOperations’:

import { richTextOperations } from 'edytor';

const { start, end, isCollapsed } = edytor.selection.projection;
if (start && end && !isCollapsed) edytor.deleteRange(start, end); // the selected range; the caret goes where the document says
edytor.deleteBlocks(edytor.selection.selectedMembers.map((block) => block.id)); // a selected list with its items

const rich = richTextOperations(edytor);
rich.setMarkAtRange('bold'); // toggle over the selection, or stage at a caret
rich.setLinkAtRange({ href: 'https://example.com' }); // unsafe URLs are dropped
rich.setMarkValueAtRange('color', '#dc2626');
rich.removeAllMarksAtRange();
rich.insertDividerAtSelection();

To change the block kind, see convertToKind. The full list of operations and their arguments is in Operations.

Results

Every operation answers an OpResult:

type OpResult = {
	status: 'applied' | 'noop' | 'refused';
	ids: readonly string[]; // what it created, moved or targeted (empty unless applied)
	reason?: string; // e.g. 'id-collision'; 'view' when the view or a plugin refused it
};

Through the view, each command also sets edytor.dispatcher.last, a CommandResult, which a gesture issuing several commands reads:

const merged = edytor.mergeBackward(block.id);
const into = edytor.idToBlock.get(merged.ids[0] ?? ''); // the block merged into
const { operation, status } = edytor.dispatcher.last!;
// status: 'applied' | 'noop' | 'refused' | 'failed'
void [into, operation, status];
Status Meaning
applied The command changed the document. A gesture that issues one command per part (a Tab over several sibling groups, Turn into over several blocks) is applied when any part applied: a part the document refuses or a plugin vetoes is skipped and the others apply (Refusing an edit).
noop It ran and changed nothing.
refused The view is readonly, the document is read-only, the document refused it (for example merging into a void block), or a plugin prevented it. Nothing was written and no undo step was recorded.
failed It threw. The error is in last.error and is rethrown.

When a plugin prevents a command and its prevent(cb) runs the same command in its place, the call you made answers refused (reason: 'view') and dispatcher.last is the replacement’s result.

On the document

edytor.document is the raw path: the same operations write the document directly, with no plugin hooks, no normalization, no undo policy and no readonly check (a readonly view’s app can still write through it). An empty operation (insertText(id, 0, '')) is noop; an unknown or deleted target is refused.

const { document } = edytor;
const id = 'intro';

document.insertText(id, 0, 'Hello ', { bold: true });
document.deleteText(id, 0, 6);
document.formatRange(id, 0, 5, { italic: true, bold: null }); // null removes a mark
document.insertBlocks(
	{ parent: null, index: 0 }, // null parent = the root
	[{ id: 'title', type: 'heading', data: { level: 'h1' }, content: [{ text: 'Title' }] }]
);
document.moveBlocks(['title'], { parent: null, index: 2 });
document.setBlock(id, { type: 'quote' });
document.deleteBlock(id); // { keepChildren: false } removes the subtree

Inserts (insertBlocks, setBlock’s children) take the JSONBlock shape that edytor.value and document.toJSON() use, ids kept and minted where you leave them out, or a BlockSpec (an id on every block, content items with a kind: { kind: 'text', text, marks? } or { kind: 'inline', id, type, data? }). To copy a block, mint every id with toBlockSpec(json, { freshIds: true }), or call duplicateBlock(id):

import { toBlockSpec } from 'edytor/crdt/edytor';

doc.insertBlocks({ parent: null, index: 1 }, [
	toBlockSpec(doc.blockJSON('title'), { freshIds: true })
]);

The prepare/apply two-phase form, the reads and the document’s lifecycle are in the document API reference.

Grouping with transact

edytor.transact(fn) runs several writes as one transaction: collaborators receive them as one update, normalization runs once at the end, and they are never split across undo steps. It is not a rollback: a throw from fn keeps the writes made before it, and normalization still runs on them before the error reaches you; a normalizer that fails then is logged, so the error you get is fn’s.

edytor.transact(() => {
	edytor.setBlock('title', { data: { level: 'h2' } });
	edytor.insertText('intro', 0, 'Updated: ');
});

Nested transact calls join the outer one. Without a view, use document.transact(fn).

Moving blocks

edytor.moveBlocks(ids, { parent, index }) moves blocks to a destination with their identity, children and content. edytor.move(request) resolves a move described the way a user makes it — relative to a target block, or one step in a direction — to the document’s move (moveBlocks, an outdent’s unNestBlocks, a beside placement’s placeBeside), as one undo step, and announces it to assistive technology:

const source = edytor.idToBlock.get('intro')!;
const target = edytor.idToBlock.get('outro')!;
const request = { blocks: [source], target, position: 'after' as const };
if (edytor.canMove(request)) edytor.move(request);

position is 'before', 'after', 'inside' (as the target’s last child), or 'left'/'right': beside the target, side by side. Hooks see moveBlocks, or placeBeside beside the target. Beside the target, with the columns plugin (a kind whose role says layout):

  • the blocks go in a new column next to the target’s column, or, when the target is in none, the target and the blocks are wrapped in a new two-column layout;
  • a list item or a code line stands for its whole list or code block, any other block for itself where it is (a toggle’s child is wrapped inside the toggle, unless that would put a layout in a column); a column stands for itself (right of it is the gap after it);
  • the move is refused without a layout kind, for a layout or a block holding one (no layout goes into a column), and beside the moved blocks themselves;
  • the column a move empties goes, and a layout left with one column shows as its blocks.

Or describe one relative step with direction:

Direction Result
up Before the previous sibling. From the first child, before the parent; from a column’s first block, before the layout (an emptied column goes).
down After the next sibling, never inside its children. From the last child, after the parent; from a column’s last block, after the layout.
in Last child of the previous sibling; of its last item when it is a list the blocks are no items of (a position: 'inside' drop too). Refused when that list ends with a block that holds no children, such as an image, as under that block.
out After the parent. The siblings after the last moved block become its children (an outdent). An item of a list container leaves the list instead: before it, after it, or between its two halves, without the items after it (Containers).
const moved = edytor.move({ blocks: [...edytor.selection.selectedBlocks], direction: 'down' });
  • A group moved by direction must be siblings, and keeps its document order. With target and position, the blocks land in the order you pass them.
  • With in or out, siblings that have another block between them move as separate runs of adjacent siblings, as Tab and Shift+Tab do, so the text keeps its order: [a, c] out of a list a to e leaves b between them. A run that cannot move stays where it is, and the result lists only the blocks that moved; canMove is true when at least one run can move. With up or down the group moves together.
  • move returns the blocks it moved, or [] when the move was refused (dispatcher.last.status is then 'refused', also for a move canMove rejects).
  • A closed toggle the blocks land in, or that takes blocks as children (out), opens, so a moved block is never hidden. Every move through the view (moveBlocks, nestBlock, unNestBlock, unNestBlocks, placeBeside) opens it too; a peer’s move, an undo or a redo opens nothing.
  • canMove answers whether the move is structurally allowed. It is false for a destination inside a void block or an island, for blocks that sit inside an island, for a destination inside the moved blocks’ own subtree, and directly inside a list for a block that is not a list item (a move keeps kinds; see Containers). Direction out answers as Shift+Tab does: a paragraph under a list item outdents into the list as a list item, and an image, a code block or a heading there is refused. A plugin can still refuse the command.

These are the same moves block handles, Alt+arrows on a focused handle and Mod+↑/↓ (createArrowMovePlugin()) perform. The types are exported as BlockMoveRequest, BlockMovePosition and BlockMoveDirection.

Was this page helpful?