Operations
The one set of document operations, written through the view (dispatched) or a bare document (raw), and how onBeforeOperation sees every write and its planned steps to veto, replace or rewrite it.
Every write is one of the document’s operations: insertBlocks, splitBlock, insertText, patchData, moveBlocks and the others listed below. There is one set, with two entry points under the same names and arguments:
- Through a view,
edytor.insertText(id, offset, text): the write is dispatched. A readonly view or a read-only document refuses it, every plugin’sonBeforeOperationsees it and each step it plans before anything is written, it is one transaction and one undo step, the blocks it touches are normalized, and the caret it decides (a range deletion, a placed paste) is selected. This is how your app, your plugins and the editor’s own keys, menus and drags write. - On a bare document,
edytor.document.insertText(id, offset, text): the write is raw. No hook sees it, no view’s undo policy applies, and no readonly check runs. Use it headless, on a server, or for a write that must not look like the user’s (the document API).
Both answer the document’s OpResult: status ('applied', 'noop' or 'refused') and ids, the blocks the operation is about (the inserted or split-off block, the merge target). A view’s write refused by the view itself (readonly) or by a plugin answers refused with reason: 'view'.
Handles (Block, Text, InlineBlock) only read: pass their ids to the operations. Offsets are block offsets, an inline atom counting 1: a text segment’s offset o is text.segStart + o.
const result = edytor.insertBlocks({ parent: null, index: 1 }, [
{ type: 'heading', data: { level: 2 }, content: [{ text: 'Notes' }] }
]);
if (result.status === 'applied') {
const [id] = result.ids;
edytor.insertText(id!, 5, '!');
edytor.patchData(id!, [{ path: ['level'], value: 3 }]);
}
Through a view, an insertText without marks takes the insertion’s marks, as typing does (the text before it, or the caret’s pending marks when it lands at the caret); pass {} for plain text. A range deletion or a placed paste reads the view’s hidden blocks (a closed toggle’s body) unless you pass a view of your own.
The change payload
onBeforeOperation receives one object per command and per step:
operationstring
The operation's name, such as 'insertText' or 'mergeBackward'. Narrows payload.
stringpayloadunknown[] | object
A document operation's arguments, as a tuple (insertText: [id, offset, text, marks?]); a view command's payload object (table below).
unknown[] | objectblockBlock
The block the operation names first: its block, the first of its blocks, a destination's parent, a position's block (the root for none).
Blocktext?Text
The text segment at the offset a text operation names.
Texteffect?PlanEffect
What the command would do. Present on a command that is one document plan; absent on steps.
PlanEffectprevent(cb?: () => void) => void
Refuse the whole command, optionally running cb in its place.
(cb?: () => void) => voidCommands and steps
A command is shown first, under its own name. Each step it plans is then shown as the operation it performs, with that operation’s arguments: insertBlocks, moveBlocks, deleteBlock, splitBlock, mergeBlocks, setBlockType, patchData, insertText, insertInline, deleteText, removeInline or formatRange. A step that is the command itself (same name, same block) is not shown twice, and a write into a block the plan creates is part of that creation. A few examples:
| Gesture | Command | Steps shown after it |
|---|---|---|
| Typing | insertText |
none |
| Enter | splitBlock, insertBlocks, unNestBlock or setBlock, by the block’s role |
the steps it plans |
| Backspace at a block start | setBlock, unNestBlock or mergeBackward, by the block’s role |
setBlockType, moveBlocks, mergeBlocks |
| Tab, Shift + Tab | nestBlock, unNestBlock; over several selected blocks, one moveBlocks or unNestBlocks per run of adjacent siblings |
the moves it plans |
| Deleting a range across blocks | deleteRange (replaceRange when typing or a paste replaces it) |
deleteText, deleteBlock, mergeBlocks |
| Deleting a block selection | deleteBlocks |
one deleteBlock per selected block |
| Paste or drop | insertFlow |
splitBlock, insertText, insertBlocks |
| Dragging selected text in the editor | moveText (one undo step) |
the placement’s steps, then the range’s deletion’s (with Alt, a copy: the placement’s) |
| Markdown shortcut or slash command | setBlock |
deleteText for the removed trigger text, setBlockType |
| Turn into (menus, Mod + Alt + digit) | setBlock, or insertBlocks for a kind inserted after the block; over several blocks, one per block |
the moves and inserts that place the kind |
| Formatting | formatRange, clearMarks |
none |
| Block handle or arrow-move | moveBlocks, unNestBlocks or placeBeside |
the moves it plans |
| Duplicate (block menu, Mod + D) | duplicateBlock |
insertBlocks on the parent |
Normalization a write asks for runs in its transaction and is not shown separately.
A command the document itself refuses is still shown, without steps, so a plugin can replace it.
Refusing an edit
Call prevent() on the command or on any of its steps to refuse the whole command. Nothing is written and no undo step is recorded. prevent records the veto and returns, so the rest of your hook still runs (return after it when nothing else should happen); the first call decides.
A gesture over several blocks that issues one command per part refuses only the part you veto, as the document refuses a part it cannot apply. The other parts apply, together one undo step, and dispatcher.last reports applied when one did. Your own gesture gets the same rule from edytor.dispatcher.each(kind, parts, part).
| Gesture | Commands | A veto keeps |
|---|---|---|
| Turn into over several blocks | One per block | The vetoed block |
| Tab and Shift + Tab over several runs of siblings | One per run | The vetoed run |
| Tab and Shift + Tab over several lines of a code block | One insertText or deleteText per line |
The vetoed line |
| Formatting across blocks | One formatRange per block |
The vetoed block |
| The block menu’s Duplicate | One per block | The vetoed block |
| A block-selection delete, from the keyboard (any Backspace or Delete chord) or the block menu | One | Every block |
| Typing or a paste over a block selection | One insertFlow replacing the blocks (onDeleteSelectedBlocks runs first, see Writing plugins) |
Every block |
import type { Plugin } from 'edytor';
/** Blocks with data.locked cannot be deleted or merged away. */
export const lockedBlocksPlugin: Plugin = (edytor) => ({
onBeforeOperation: ({ effect, prevent }) => {
if (!effect) return;
const leaving = [...effect.removes, ...effect.merges.map(([from]) => from)];
if (leaving.some((id) => edytor.idToBlock.get(id)?.data.locked)) prevent();
}
});
Because steps are shown too, this catches every path that would remove a locked block: Backspace, a range deletion, a cut, a block-selection delete.
Typing, Enter or a paste over a text range runs two commands: replaceRange removes the range, then the insertion (insertText, splitBlock, insertFlow) runs at the caret it leaves. Refusing the insertion alone leaves the range deleted; to keep the range, refuse replaceRange or one of its steps.
effect describes the whole plan:
creates?string[]
Ids of blocks the command creates.
string[]removes?string[]
Ids of blocks that leave the document.
string[]merges?[from: string, into: string][]
Blocks merged into another.
[from: string, into: string][]moves?string[]
Blocks given a new place.
string[]meta?string[]
Blocks whose type or data changes.
string[]textRanges?{ block, offset, length }[]
Text ranges written.
{ block, offset, length }[]A step’s veto refuses the command it belongs to, so check the operation name before you veto a step that many commands share, such as insertText or deleteText.
Replacing an edit
prevent(cb) refuses the command and runs cb instead. This replaces a typed @ with an inline atom at the caret (for a menu of people, use a trigger, as the mention plugin does):
import type { Plugin } from 'edytor';
export const atMention: Plugin = (edytor) => ({
onBeforeOperation: (change) => {
if (change.operation !== 'insertText') return;
const { payload, block, prevent } = change;
const [, offset, typed] = payload;
// Only an `@` typed at the caret: { block, offset }, an inline atom counting 1.
const caret = edytor.selection.caret;
if (typed !== '@' || caret?.block.id !== block.id || caret.offset !== offset) return;
prevent(() => {
const atom = edytor.insertInline(block.id, offset, { type: 'mention', data: {} });
if (atom.status === 'applied') edytor.selection.setCaret({ block, offset: offset + 1 });
});
}
});
The callback is a command of its own. If another plugin refuses one of the operations it issues, that operation writes nothing and the callback carries on. Each plugin replaces a given command at most once: while your callback runs, your own prevent(cb) on the operations it issues is ignored, so the callback can call the operation it replaced without recursing.
Triggers: one plan
A trigger plugin (:smile: → 😄, @query → a mention) removes the text that triggered it and writes its replacement. Input rules and triggers do this for you, declared as data; this section is the machinery they are built on, for a replacement they do not cover. Issued as two operations, a veto of the second leaves the trigger text already gone. Three dispatcher members make the pair one refusable command, as the slash menu and markdown shortcuts do:
edytor.dispatcher.lead(plan, body)runsbodywithplan, prepared now, composed into the first operationbodydispatches: one plan in one transaction. Hooks see the lead’s steps with that operation’s; a veto of any of them, or a refusal, writes neither. When the lead deletes a block’s whole content and that operation replaces it, the lead’s step is dropped. It answers{ out, taken }:body’s result, and whether an operation took the lead. Whentakenisfalse, nothing of the lead was written: eitherbodydispatched nothing (remove the trigger yourself, as the slash menu does for a command that writes later), or the lead was a refusal andbodydid not run.edytor.dispatcher.plan(operation, payload, prepare, block?)dispatches a command of your own, under your own name, that is one prepared plan: admission,onBeforeOperationfor the command and each stepprepare(payload)plans (a rewritten payload is prepared again), one transaction, normalization,dispatcher.lastandonAfterOperation. It answers the plan’sOpResult,refusedwithreason: 'view'when the view or a plugin refused it.edytor.dispatcher.caret(caret, ops?)is the command’s result caret,{ block, offset }in block offsets: selected once, recorded ondispatcher.last.selection, and shown after the DOM update. Withops, a write answering itsOpResult, the caret is declared beforeopsruns, so it follows the edit, and is written only whenopsis not refused. A caret inside text the edit deletes does not survive: set it after the edit instead.
edytor.dispatcher.permits() answers whether the view accepts writes now: it is false in a readonly view, on a document that has become read-only, and before a document that requires hydration is decided. Every command asks it first and is refused when it answers false; ask it yourself before a raw write of your own on edytor.document.
One more dispatcher member is not about triggers: edytor.dispatcher.outside(body) runs body’s commands outside the undo history. They are admitted, shown to hooks and recorded in dispatcher.last like any command, but they start no undo step and join none. Use it for a write that completes a step already taken, whose undo covers it, such as an upload’s URL filling the image block its paste placed (History). In development, it throws when a transaction is already open (a production build does not check).
Prepare plans on the document itself: edytor.document.prepare.<op>(…) returns a Prepared: a Plan, or the operation’s refusal. It writes nothing, so preparing outside the dispatcher is safe; what the plan writes goes through the command that applies it. Both types are exported from edytor, and 'writes' in prepared tells them apart. See the document API.
import type { Plugin } from 'edytor';
const EMOJI: Record<string, string> = { smile: '😄' };
/** Typing the closing `:` of `:smile:` replaces the whole trigger with its emoji. */
export const emojiPlugin: Plugin = (edytor) => ({
onBeforeOperation: (change) => {
if (change.operation !== 'insertText') return;
const { payload, block, prevent } = change;
const [, offset, typed] = payload;
// Only a `:` typed at the caret: another insertion completes no trigger.
const caret = edytor.selection.caret;
if (typed !== ':' || caret?.block.id !== block.id || caret.offset !== offset) return;
const at = block.textAtOffset(offset);
const match = at && /:(\w+)$/.exec(at.text.stringContent.slice(0, at.offset));
const emoji = match && EMOJI[match[1]!];
if (!match || !emoji) return;
const from = offset - match[0].length;
prevent(() => {
const { dispatcher, document } = edytor;
const trigger = document.prepare.deleteText(block.id, from, match[0].length);
dispatcher.lead(trigger, () => edytor.insertText(block.id, from, emoji));
if (dispatcher.last?.status === 'applied')
dispatcher.caret({ block, offset: from + emoji.length });
});
}
});
If another plugin refuses the insertText, or the deleteText step that removes :smile, nothing is written and no undo step is recorded: the trigger text stays.
Rewriting the payload
Return new arguments from onBeforeOperation to replace the command’s. The code plugin auto-pairs brackets this way:
import type { Plugin } from 'edytor';
export const pairs: Plugin = () => ({
onBeforeOperation: (change) => {
if (change.block.type !== 'codeLine' || change.operation !== 'insertText') return;
const [id, offset, typed, marks] = change.payload;
if (typed === '(') return [id, offset, '()', marks];
}
});
The replacement is prepared again and shown to every plugin from the start. A Turn into is placed for the kind its replacement names (rewritten to a list’s item, it stays in the list; rewritten to a heading, it leaves the list), that kind’s normalizeContent runs on it, and the caret goes into it. Each plugin rewrites a command at most once. A payload returned for a step is ignored, with a warning in development.
After an edit
onAfterOperation runs once per command, after its transaction, with the original payload and the plan’s effect. It does not run for steps or for refused commands, and it has no prevent. Its payload (AfterOperationPayload) narrows by operation, as onBeforeOperation’s does:
import type { Plugin } from 'edytor';
export const logTurnInto: Plugin = () => ({
onAfterOperation: (change) => {
if (change.operation === 'setBlock') console.log(change.block.id, 'is now', change.block.type);
if (change.operation === 'insertText') console.log('typed', change.payload[2], 'in', change.block.id);
}
});
Reading the result
A view’s operation answers its OpResult, and edytor.dispatcher.last holds the last command’s result (read-only: the dispatcher records it), for a gesture that issues several:
const merged = edytor.mergeBackward(block.id);
if (merged.status === 'refused') {
// A plugin, a readonly editor or the document refused it.
}
if (edytor.dispatcher.last?.status === 'refused') {
// The same, read from the last command.
}
dispatcher.last.status is 'applied' (it wrote), 'noop' (it ran and changed nothing), 'refused' (a plugin, the readonly state or the document refused it) or 'failed' (it threw; the error is rethrown and kept in error). A refusal is reported, never thrown.
A readonly editor, or a document that has become read-only, refuses every command that would write. An error thrown by a hook is not swallowed: it surfaces to the caller.
Operation reference
The document’s operations, the same on edytor (dispatched) and on edytor.document (raw). A hook’s payload is their arguments, in this order; offsets are block offsets.
| Operation | Arguments |
|---|---|
insertBlocks |
(dest: { parent, index }, blocks: JSONBlock[]); ids are minted where missing |
moveBlocks |
(ids, dest); the index counts the destination’s children without the moved blocks: within one parent, one place right of index i is { parent, index: i + 1 } |
nestBlock |
(id, parent): the last child of parent (under its last item when it is a list) |
unNestBlock, unNestBlocks |
(id), (ids): after their parent, the siblings after the last one becoming its children |
liftOut |
(id, kind, { keep?, after? }): out of the containers a kind cannot sit in |
wrapInLayout |
(ids, kind?, columns?): a new layout around sibling blocks |
placeBeside |
(ids, target, side, kind?): a new column beside target |
splitBlock |
(id, offset, newId, tail?): the content after offset into a new block newId of tail’s kind (the block’s by default) |
mergeBlocks |
(from, into) |
mergeBackward, mergeForward |
(id): into the block before it, or the block after it into it |
deleteBlock |
(id, { keepChildren? }): its children take its place unless keepChildren: false, which deletes the whole subtree (a container whose children belong to it, a tab of a tabs block) |
deleteBlocks |
(ids): a block selection; only the members leave |
setBlock |
(id, { type?, data?, content?, children? }): content and children (JSON or specs) replace the block’s |
setBlockType |
(id, type) |
patchData |
(target, patches): target a block id, { block, atom } for an inline atom, null for the document; each patch { path, value? } (no value deletes), { path, splice } or { path, order } (Properties) |
duplicateBlock |
(id, freshId?): a copy of the block and its subtree after it, under fresh ids |
insertText |
(id, offset, text, marks?) |
deleteText |
(id, offset, length) |
formatRange |
(id, offset, length, marks): null removes a mark |
clearMarks |
(id, offset, length): every mark in the range |
insertInline |
(id, offset, { id?, type, data? }) |
removeInline |
(id, atom) |
deleteRange, replaceRange |
(from: { block, offset }, to, view?): a range across blocks (replaceRange keeps the head for a replacement) |
insertFlow |
(target, flow, view?): a paste’s lines at a position, over blocks ({ replace: ids }) or at a slot |
A view’s commands that are one plan of several operations, with their payload objects:
| Command | Payload |
|---|---|
moveText |
{ from: { start, end }, to, copy }: selected text dragged to to (positions are { block, offset }), moved, or copied with Alt; one undo step |
inlineMarkdown |
{ value, start, end }: a closing marker typed after marked-up text (**bold**) |
insertDivider |
{} |
acceptSuggestion |
{ suggestion: { id, at, content } }: a suggestion accepted, one undo step; its planned steps follow it (for a text range, its deletion’s). A shared one’s: { changes }, the changes accepted; the block operations they run follow it (deleteBlock, mergeBlocks) |
rejectSuggestion |
{ changes }: a shared suggestion’s changes rejected (by a reviewer, or by its author: discard()), one undo step; the block operations that take its blocks away follow it (deleteBlock, mergeBlocks) |
replaceMatches |
{ matches: { block, offset, length }[], replacement }: find and replace’s Replace or Replace all, one undo step; a deleteText and an insertText step follow it per match |
addComment |
{ thread, runs }: a comment’s anchor |
insertTableRow, deleteTableRows, insertTableColumn, deleteTableColumn, moveTableColumn, moveTableRows, fillTableCell |
the table’s rows and columns |