Skip to Content
API Referencecorecore/commands

@stesura/core/commands

Document mutations, as ProseMirror Commands or factories that return one, plus a few related predicates and builders. Run a command with command(view.state, view.dispatch, view); call it without dispatch to check whether it applies (for a toolbar’s enabled state) without changing anything. Group commands into one undo step with composeCommands, or all-or-nothing with sequenceCommands.

Core

clearFormatting

Strips inline marks from the selection, keeping the track-changes marks (insertion / deletion / modification) so clearing formatting never erases a pending suggestion. Refused inside code blocks.

A selection over several textblocks is cleared in chunks (a bulk command), as a batch in edit mode, with the same result as clearFormattingTr.

Transaction form: clearFormattingTr.

Parameters:
NameTypeDefault
optionsClearFormattingOptions

expandSelectionToWord (default true) makes a bare cursor clear the surrounding word rather than just the stored marks; clearCharacterFormatting: false keeps the marks (Word’s Ctrl+Q); clearTextBlockFormatting also resets the paragraph/heading’s indent, alignment, background, borders, line height, tab stops, direction, pagination and spacing; resetStyleToNormal also returns the block to the Normal style and removes its numbering.

Returns:
Command

composeCommands

Runs every command against ONE transaction and dispatches once, so the whole group undoes in a single step and each command sees what the previous ones wrote. Succeeds if any command did something; one that returns false keeps whatever it already wrote.

Not chainCommands from prosemirror-commands, which runs commands until the first one succeeds and stops there.

Parameters:
NameTypeDefault
commandsCommand[]
Returns:
Command

deleteNode

Deletes the node at pos. False when pos is null or holds no node.

Parameters:
NameTypeDefault
posnumber
Returns:
Command

insertContent

insertContentAt targeting the current selection.

Parameters:
NameTypeDefault
valuestring | Node | JSONContent | Fragment | JSONContent[]
Returns:
Command

insertOrWrapNode

Inserts a node of the given type at the cursor, or wraps the selection in it.

The type is resolved by name and routed on its shape: block types wrap the selected blocks (via wrapIn) or, at a bare cursor, insert an instance holding a placeholder paragraph; inline types wrap the selected inline content or insert an instance holding placeholder text. Content is built with createAndFill, so a type that cannot hold the content refuses (returns false) rather than throwing.

Warns and returns false when the schema has no node of that name.

Parameters:
NameTypeDefault
nodeNamestring
attributesAttrs
Returns:
Command

insertSymbol

Inserts a literal character at the selection, keeping the current marks.

Parameters:
NameTypeDefault
symbolstring
Returns:
Command

resetAttributes

Resets the named attributes to their schema defaults on every node — or mark — of the given type in the selection, without dispatching.

Transaction form: resetAttributesTr.

Parameters:
NameTypeDefault
__0{ attributes: string | string[]; typeOrName: string | NodeType | MarkType; }
Returns:
Command

sequenceCommands

Like composeCommands, but stops at the first command that returns false and dispatches nothing — the group is all-or-nothing.

Parameters:
NameTypeDefault
commandsCommand[]
Returns:
Command

setMark

Applies a mark to the selection, merging attributes into any existing mark of that type; a merge left with only null attrs removes the mark. A cursor inside a word marks the whole word; at a word boundary the mark is stored for the next keystroke. Returns false, with no steps, when it cannot apply.

A selection over several textblocks is applied in chunks (a bulk command), with the same result as setMarkTr.

A dry run only checks canSetMark. False when typeOrName is undefined.

Transaction form: setMarkTr.

Parameters:
NameTypeDefault
typeOrNamestring | MarkType
attributesAttrs
Returns:
Command

setNode

Turns the selected blocks into typeOrName, carrying over the current node’s attrs when the selection sits in a single parent. Falls back to clearNodes first when the target type isn’t directly reachable.

Textblock types only.

Parameters:
NameTypeDefault
typeOrNamestring | NodeType
attributes{}
Returns:
Command

toggleHeading

Toggles the selected blocks between heading at level and paragraph, applying the Heading<level> style on the way up and returning to Normal on the way down, as Word does. Not plain toggleNode: it would carry the heading’s styleId across to the paragraph.

Parameters:
NameTypeDefault
levelnumber
Returns:
Command

toggleMark

Toggles a mark on the selection.

  • Cursor: inside a word the mark is toggled on the whole word; at a word boundary it is stored/removed for the next keystroke.
  • Range: the mark is added when any part of the range is missing it, removed when it is present everywhere.

textStyle is applied per inline node (applyToAllNodesInRange), so math nodes keep their LaTeX source unmarked.

A selection over several textblocks is toggled in chunks (a bulk command), with the same result as toggleMarkTr.

False when markType is undefined.

Transaction form: toggleMarkTr.

Parameters:
NameTypeDefault
markTypeMarkType
attrsAttrs
optionsToggleMarkOptions
Returns:
Command

toggleMarkOnEntireWord

toggleMark by mark name, with expandSelectionToWord pinned on: a bare cursor inside a word toggles the whole word. False when the mark is not in the schema.

Parameters:
NameTypeDefault
markNamestring
attrsAttrs
Returns:
Command

toggleNode

Switches the selected blocks to typeOrName, or back to toggleTypeOrName when they already are that type.

When the selection sits in a SINGLE parent, that parent’s attrs are carried over to the new node, whatever its type. A caller that must not inherit an attr has to overwrite it in attributes (hence toggleHeading resetting styleId).

Parameters:
NameTypeDefault
typeOrNamestring | NodeType
toggleTypeOrNamestring | NodeType
attributes{}
Returns:
Command

unsetMark

Removes a mark from the selection and from the stored marks, without dispatching. A selection over several textblocks is cleared in chunks (a bulk command), with the same result as unsetMarkTr.

Transaction form: unsetMarkTr.

Parameters:
NameTypeDefault
typeOrNamestring | MarkType
options{ extendEmptyMarkRange?: boolean; }

extendEmptyMarkRange makes a bare cursor remove the mark across its whole contiguous range (e.g. unlink the entire link under the caret) instead of doing nothing.

Returns:
Command

updateAttributeAt

Sets a single attr on the node at a known position. Fails (probe and real) when no node sits at pos — a stale nodeview getPos must not write onto whatever now occupies the position — or when type is given and mismatches.

Parameters:
NameTypeDefault
__0{ attribute: string; value: unknown; pos: number; type?: string | NodeType; }
Returns:
Command

updateAttributes

Merges attributes into every node (or mark) of the given type in the selection, plus the innermost enclosing node of that type; on a collapsed selection a matching stored mark is updated too. Undeclared or already-equal keys are skipped, so a no-op update produces no steps and returns false.

Transaction form: updateAttributesTr.

Parameters:
NameTypeDefault
propsUpdateAttributesProps
Returns:
Command

Borders

insertHorizontalRule

Inserts a horizontal_rule node at the selection.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

setBorders

Applies borders to whatever the selection targets, trying the horizontal rule, then table, then cells, then styled blocks — the first that applies wins. See setBordersTr.

Parameters:
NameTypeDefault
bordersBorders
Returns:
Command

toggleOutline

Toggles the editor-wide outline overlay — the dashed guides drawn where a block has no real border. Meta-only: the doc is untouched.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

Code Block

insertCodeBlock

Inserts an empty code_block at the selection. No-ops inside an existing one.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

splitCodeBlock

Splits the code block at the caret into two, breaking after the caret’s line: that line stays in the first block, the rest starts the second. Language, theme and line numbers carry over.

No-ops on the last line — there is nothing to split off.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

updateCodeBlockAttrs

Sets one attr (language, theme, line numbers, …) on the code block at pos.

Parameters:
NameTypeDefault
attributekeyof CodeBlockAttrs
valueunknown
posnumber
Returns:
Command

Document Attributes

setDocAttr

Sets one doc attr, typed against DocAttrs. A no-op (false) when the value is already in place, so toolbar dry-runs grey the control out.

Parameters:
NameTypeDefault
attrK
valueNonNullable<DocAttrs[K]>
Returns:
Command

dismissFindings

Dismisses a checker’s findings on this document, for every collaborator. A plain doc attr step, so undo brings them back. False when all already are.

Parameters:
NameTypeDefault
checkerstring
idsstring[]
Returns:
Command

restoreFindings

Brings dismissed findings back: ids, or all of the checker’s. False when none was dismissed.

Parameters:
NameTypeDefault
checkerstring
idsstring[]
Returns:
Command

setDocBgColor

Sets the canvas color behind the pages, as the docBgColor doc attr. themeRef is the theme slot it was picked from, and then decides the hex; without one, the ref clears.

Parameters:
NameTypeDefault
colorstring
themeRefstring
Returns:
Command

setDocDirection

Sets the document’s default text direction — the bottom of paragraph.dir ?? section.dir ?? doc.dir, and the one option a host sets to mount an RTL-by-default editor. Blocks and sections declaring their own dir keep overriding it; setDirection(null) clears a block’s override.

Document-global, so it forwards to the root doc when run from a sub-editor.

Parameters:
NameTypeDefault
dirTextDirection
Returns:
Command

setDocumentTheme

Word’s Design › Colors: sets doc.attrs.theme and moves every themed colour (runs, fills, borders, page colour, styles) onto it, as one undo step. Colours without a theme ref stay as they are. Like Word, not a tracked change. A bulk command: the doc attrs change in the first transaction, the nodes CHUNK_STEPS steps a transaction.

Parameters:
NameTypeDefault
themeDocumentTheme
Returns:
Command

File

applyFileNodeMove

Appends the steps that move the file node at pos one position among its siblings to tr, keeping the selection on it, and returns where the node now starts — or null, untouched, when there is no file there or nowhere to go. A plain delete + insert: a file node is an atom with no content to preserve, and adjacent files are ordinary siblings — “between two files” is already the gap cursor’s job.

A builder rather than only a command so a React caller can add what it knows and core cannot: that the node’s VIEW should survive the move (see preserveNodeViewKey in editor-react).

Parameters:
NameTypeDefault
trTransaction
posnumber
direction1 | -1
Returns:
number | null

insertFileUpload

Inserts an upload placeholder that resolves into a file node once the upload completes. Refused inside code blocks and tables.

With a file node selected it inserts AFTER it rather than refusing: two PDFs in a row are ordinary siblings, and refusing left “add another file here” with no route at all.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

moveFileNode

applyFileNodeMove as a command.

Parameters:
NameTypeDefault
posnumber
direction1 | -1
Returns:
Command

rotateFile

Turns a file node by a quarter turn (delta 90 or -90), wrapping at 360.

Parameters:
NameTypeDefault
posnumber
deltanumber
Returns:
Command

setFileDisplayPreview

Switches a file node between its preview and its card.

Parameters:
NameTypeDefault
posnumber
displayPreviewboolean
Returns:
Command

setFileRotation

Sets a file node’s whole-file rotation to one of the four storable angles.

Parameters:
NameTypeDefault
posnumber
rotationnumber
Returns:
Command

Format Painter

applyFormatPainter

Paints the armed formatting onto the selection — or the word under a bare cursor — replacing existing marks (except the track-changes ones).

The captured block type, numbering, indent, spacing, background, borders and style follow only when the target is a whole block, spans several, or is a bare cursor, matching Word: a partial selection inside one paragraph takes the character formatting alone. Numbering replaces the target’s wholesale: a leftover instanceId or level would split it off the source’s run. Disarms afterwards when the painter was armed for one use.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

disableFormatPainter

Disarms the format painter and restores the default cursor.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

enableFormatPainter

Picks up the formatting under the cursor — inline marks plus the textblock’s type and attrs — and arms the format painter with it. Refused in code blocks.

A source selection covering only part of a single block arms the marks alone (Word copies no paragraph formatting from a partial selection).

Parameters:
NameTypeDefault
__0{ once: boolean; }

Disarm after the first applyFormatPainter ; false keeps it armed until disableFormatPainter .

Returns:
Command

Formatting

alignJustifyLeftOnly

Justifies every start-aligned text block in the document.

Parameters:
This function does not accept any parameters.
Returns:
Command

alignJustifyLeftRight

Justifies every start- or end-aligned text block in the document.

Parameters:
This function does not accept any parameters.
Returns:
Command

incrementSpacing

Adds value to the effective spacing on one side (resolved through the stylesheet), floored at 0. Pass a negative value to decrement.

Only the incremented side is written: stamping the resolved value on the other side too would pin it against later stylesheet edits.

Transaction form: incrementSpacingTr.

Parameters:
NameTypeDefault
__0{ position: "before" | "after"; value: number; }
Returns:
Command

indent

Indents the block at the selection by one step, Word-style: a block without a first-line indent gets one first, later presses move the whole block. On a NUMBERED node it demotes the list level instead, and touches no paragraph geometry — the level definition supplies that.

Capped at MAX_INDENT_LEVEL steps (unnumbered blocks only; a numbered one is capped by the deepest level its list defines, in adjustLevel).

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

outdent

Reverses one indent step; no-ops once the block is fully outdented.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

resetAlignment

Resets textAlign to null for nodes in the selection (if ids is undefined) or for all nodes matching the given ids (node id or stylesheet id).

Parameters:
NameTypeDefault
idsstring[]
Returns:
Command

resetIndent

Resets the indent attr to null for nodes in the selection (if ids is undefined) or for all nodes matching the given ids (node id or stylesheet id).

Parameters:
NameTypeDefault
idsstring[]
Returns:
Command

resetLineHeight

Clears the lineHeight override in the selection, back to the stylesheet.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

resetPagination

Clears every pagination override in the selection (back to the stylesheet).

Parameters:
This function does not accept any parameters.
Returns:
Command

resetSpacing

Resets spacing, lineHeight and lineHeightAtLeast to null for nodes in the selection (if ids is undefined) or for all nodes matching the given ids.

Parameters:
NameTypeDefault
idsstring[]
Returns:
Command

setDirection

Sets the dir attr on the formatted blocks in the selection. null clears the override so direction inherits from the section, then the document.

Parameters:
NameTypeDefault
dirTextDirection
Returns:
Command

setFormatting

Merges a partial indent attr into every formatted node in the selection. A whole-table selection writes the table only, so the indent is not applied twice.

Transaction form: setFormattingTr.

Parameters:
NameTypeDefault
formattingFormattingUpdate
Returns:
Command

setLineHeight

Sets lineHeight on every formatted node in the selection.

Parameters:
NameTypeDefault
lineHeightnumber
Returns:
Command

setPaginationAttrs

Merges a partial pagination attr into every paginated block in the selection.

Parameters:
NameTypeDefault
partialPaginationAttrs
Returns:
Command

setSpacing

Merges spacing into every spaced node in the selection; sides not given keep their current value. A whole-table selection writes the table only.

Transaction form: setSpacingTr.

Parameters:
NameTypeDefault
spacingSpacingAttrs
Returns:
Command

setSpacingBeforeAfter

setSpacingTr for one side only, leaving the other untouched.

Transaction form: setSpacingBeforeAfterTr.

Parameters:
NameTypeDefault
__0{ position: "before" | "after"; value: number; }
Returns:
Command

setTextAlign

Sets textAlign on the formatted blocks in the selection.

Parameters:
NameTypeDefault
alignTextAlignType
Returns:
Command

setTextAlignOnlyOn

Rewrites textAlign document-wide, but only on text blocks whose effective alignment (own attr, else style, else start) is one of applyOnAlignments — a bulk realignment that leaves deliberately centered or justified blocks alone.

Parameters:
NameTypeDefault
__0{ applyOnAlignments: string[]; newAlignment: string; }
Returns:
Command

toggleDirection

Flips the selection’s RESOLVED direction (the one the toolbar shows), writing null when the target is what the block inherits anyway. Flipping the raw attr would leave an inheriting-RTL paragraph no route to LTR.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

deleteHeaderFooterContent

Deletes the variant header_footer_content from both the header and footer of the section. Refuses the “default” variant.

Parameters:
NameTypeDefault
sectionIdstring
variantHeaderFooterVariant
Returns:
Command

fixHeadersFooters

Repairs headers/footers before their editors mount:

  • a null variant becomes the default when none exists, else it is deleted;
  • duplicate variants are deleted;
  • a variant present in only one of header/footer is added to the other, and both always get a default;
  • every header_footer_content gets at least one paragraph (the schema says block+, but a custom schema may relax it). Returns false when nothing needed fixing.
Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

insertHeaderFooterContent

Adds a variant header_footer_content, holding one empty paragraph, to the section’s header and footer wherever it is missing.

Parameters:
NameTypeDefault
sectionIdstring
variantHeaderFooterVariant
Returns:
Command

insertPageNumberPreset

Inserts a page number into a section’s header (top) or footer (bottom) as a Word-style preset: a borderless 1×3 table whose columns hold a left-, center- and right-aligned paragraph, with the page number in the chosen column.

Must be dispatched on the MAIN editor state (not a header/footer sub-editor): it locates the section by id and creates the header/footer content when the variant doesn’t exist yet, all in one transaction. The guard/track-change metas allow the edit; an open sub-editor picks the change up through the headerFooterBindingPlugin’s normal main→inner sync.

Parameters:
NameTypeDefault
__0{ sectionId: string; variant?: HeaderFooterVariant; position: PageNumberPresetPosition; pageType?: PageNumberType; }
Returns:
Command

PageNumberPresetPosition

NameTypeDefault
vertical"top" | "bottom"
horizontal"center" | "left" | "right"

Highlight

disableHighlight

Disarms the highlighter and restores the default cursor.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

enableHighlight

Arms the highlighter with a color: the cursor becomes the marker and subsequent selections are highlighted until disableHighlight.

Parameters:
NameTypeDefault
colorstring
Returns:
Command

setHighlight

Applies the highlight mark in the given color to the selection.

Parameters:
NameTypeDefault
colorstring
Returns:
Command

toggleHighlight

Toggles the highlight mark. Only removes when the existing highlight is the same color — picking a different color recolors instead of clearing.

Parameters:
NameTypeDefault
colorstring
Returns:
Command

unsetHighlight

Removes the highlight mark from the selection.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

Floating objects

Placement of anchored pictures and text boxes: the floating attribute family. The *FloatingBox* commands act on a selected text box (floating_box).

cycleFloatingObjects

Tab / Shift-Tab on a selected positioned object: the next or previous one on its page (Word’s shape cycle). Consumes the key while one is selected, even when it is the only one, so Tab never indents the paragraph under it.

Parameters:
NameTypeDefault
dir1 | -1
Returns:
Command

deselectFloatingObject

Escape on a selected picture or text box: back to the text, the caret before the object.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

editFloatingBox

Opens the selected box’s editor (Enter on a selected box). Edit mode only: read-only and review modes never mount the sub-editor.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

getSelectedFloating

The selected positioned object (picture, text box) and its position.

Parameters:
NameTypeDefault
stateEditorState
Returns:
{ pos: number; node: Node; } | null

getSelectedFloatingBox

The selected text box and its position.

Parameters:
NameTypeDefault
stateEditorState
Returns:
{ pos: number; node: Node; } | null

insertFloatingBox

Inserts a text box anchored at the caret, where boxes may live (D5): square wrap on the right, white fill (Word’s inserted box; the schema’s null fill stays “no fill” for imported and existing boxes), one empty paragraph, the box selected. attrs override the defaults. open then opens its editor, caret inside (the Insert tab).

Parameters:
NameTypeDefault
attrsPartial<FloatingBoxAttrs>
options{ open?: boolean; }
Returns:
Command

moveFloating

Moves the object at pos to the inline position to, with position as its new placement when given: the drop of a drag. One transaction, untracked; the object keeps its marks (a tracked insertion stays one) and its id, and ends selected. Refuses a place a text box may not live (D5). A refused move (not a dry run) is traced by debugFloatRejection.

Parameters:
NameTypeDefault
posnumber
tonumber
positionFloatPosition
Returns:
Command

nudgeFloating

Nudges the selected object by dx/dy px (Alt+Arrow): offsets for front, behind and top-and-bottom objects; a square float’s side for Left/Right. The anchor stays; an aligned horizontal axis first becomes the offset it is drawn at, measured in view. Inline objects are refused (they are text). Selected objects always take the key, so Alt+Left never reaches the browser.

Parameters:
NameTypeDefault
dxnumber
dynumber
Returns:
Command

removeFloatingBox

Deletes the selected box and its content. Tracked like any inline node.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

reorderFloating

Brings the selected front or behind object forward past the next object overlapping it, or sends it backward past the previous one (Word’s bring forward / send backward). The object takes the order just past its neighbour’s and the layer’s objects from there up move one step, so every other pair keeps its order (renumbering the overlapping set alone could flip a neighbour against an object outside it). Needs the view to know what overlaps; without one it only says whether the object can be reordered.

Parameters:
NameTypeDefault
direction"forward" | "backward"
Returns:
Command

selectFloatingObject

Selects the next (1) or previous (-1) positioned object on the selection’s page, wrapping; from text, the page’s first (or last) one. Selection only, so it runs in every mode. Refuses when there is none, or when the only one is already selected.

Parameters:
NameTypeDefault
dir1 | -1
Returns:
Command

setFloatingBoxWidth

Sets the box at pos to width: a width set is no longer Word’s auto width.

Parameters:
NameTypeDefault
trTransaction
posnumber
widthnumber
Returns:
Transaction

setFloatOffset

Sets one axis’s offset of the selected object (the position fields): the axis becomes an offset, the alignment goes.

Parameters:
NameTypeDefault
axis"h" | "v"
offsetnumber
Returns:
Command

setFloatPosition

Sets where the selected object sits.

Parameters:
NameTypeDefault
positionFloatPosition
Returns:
Command

setFloatRelativeTo

Changes what one axis of the selected object is measured from, keeping it where it is drawn: a horizontal offset moves by the page margin between a column and a page frame; a vertical one by the anchor line’s distance from the paragraph start between a line and any other frame. Page and margin frames of a front or behind object the engine has placed are drawn on the page (L2) and convert through its page frame, an alignment becoming an offset; elsewhere they draw at the paragraph. A frame’s line form (yAlign="inline") has no offset, so it is refused.

Parameters:
NameTypeDefault
axis"h" | "v"
relativeTo"paragraph" | "page" | "character" | "column" | "insideMargin" | "leftMargin" | "margin" | "outsideMargin" | "rightMargin" | "bottomMargin" | "line" | "topMargin"
Returns:
Command

setFloatSide

Floats the selected object to a side of its column; floated wraps only.

Parameters:
NameTypeDefault
sideFloatSide
Returns:
Command

setFloatWrap

Sets how text wraps the selected positioned object, and with side the side a floated wrap sits on, in one step. Text above and below a picture is the block image, which setImageWrap converts to.

Parameters:
NameTypeDefault
wrapFloatWrap
sideFloatSide
Returns:
Command

setFloatingBoxAttrs

Sets the selected box’s own attrs (size, border, fill, padding, text anchor, label), keeping it selected. A Word frame has no text anchor (w:framePr has none, and its dialog no such field), so a frame is refused one.

Parameters:
NameTypeDefault
attrsPartial<Omit<FloatingBoxOwnAttrs, "id">>
Returns:
Command

unwrapFloatingBox

Converts the selected box to flow: its blocks go right after the host paragraph and the box goes. Untracked (D13), like lifting a callout: the text moves, nothing is written or removed.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

History

canRedo

Whether there is anything on the redo stack.

Parameters:
NameTypeDefault
stateEditorState
Returns:
boolean

canUndo

Whether there is anything on the undo stack.

Parameters:
NameTypeDefault
stateEditorState
Returns:
boolean

Images

cropImage

Crops the picture: a crop moves an edge of the box, so the box and the percentages change together.

Parameters:
NameTypeDefault
__0ImageCropState
posnumber
Returns:
Command

flipImage

Mirrors the picture horizontally or vertically.

Parameters:
NameTypeDefault
axis"horizontal" | "vertical"
posnumber
Returns:
Command

insertImageUpload

Inserts an upload placeholder that resolves into an image node once the upload completes. Refused in code blocks and with an image selected.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

resetImageEffects

Word’s Reset Picture: clears crop, turn and effects, the DOCX passthrough included (Word’s reset discards those too). The scale is kept, so an uncropped picture’s box grows to the whole bitmap.

Parameters:
NameTypeDefault
posnumber
Returns:
Command

resizeImage

Resizes the selected image, block image or inline image_anchored.

Parameters:
NameTypeDefault
sizeSize
Returns:
Command

rotateImage

Turns the picture by delta degrees clockwise.

Parameters:
NameTypeDefault
deltanumber
posnumber
Returns:
Command

setImageAlignment

Aligns the selected image. On a floated (square/tight) anchored image, start / end map to the float side; center and full-width apply to block images only.

Parameters:
NameTypeDefault
alignImageAlign
Returns:
Command

setImageAlt

Sets the alt text of an image (block or anchored). The three states are mutually exclusive, so this writes both attrs at once:

  • { alt: "…" } → meaningful
  • { decorative: true } → decorative (any alt text is discarded)
  • { alt: null } → undeclared

Blank/whitespace alt text is undeclared, not an empty label — an empty string is how decorative is expressed in the DOM, and it must not be reachable by typing spaces into the dialog.

Parameters:
NameTypeDefault
__0SetImageAltProps
Returns:
Command

setImageEffects

Sets some of the picture’s effects, validated; null clears one. Keys not in the patch are kept.

Parameters:
NameTypeDefault
patchPartial<Omit<ImageEffectAttrs, "docxPicture">>
posnumber
Returns:
Command

setImageRotation

Sets the picture’s rotation, degrees clockwise.

Parameters:
NameTypeDefault
rotationnumber
posnumber
Returns:
Command

setImageToFullWidth

Scales the selected block image to the width it lays out in: the content width, or its column in a column section (the content width again when it spans the columns), preserving its aspect ratio. An image that would then be taller than the page fits the page’s height instead, narrower, as Word fits a picture to the page.

Parameters:
This function does not accept any parameters.
Returns:
Command

setImageWrap

Sets the wrap mode of the selected image, converting between the two image node types when needed:

  • “top-bottom” → the BLOCK image node (text above and below).
  • anything else → the inline image_anchored node with that wrap (“inline” | “square” | “tight” | “front” | “behind”).

Block → anchored moves the image INTO the adjacent textblock (next, else previous, else a fresh paragraph in place). Anchored → block hoists the image out of its paragraph and places it as the following block sibling. Same-kind changes are plain attribute updates.

Parameters:
NameTypeDefault
wrapImageWrapMode
Returns:
Command

Invisible Characters

setInvisibleCharacters

Shows or hides the pilcrow / space / tab markers explicitly.

Parameters:
NameTypeDefault
showboolean
Returns:
Command

toggleInvisibleCharacters

Toggles the pilcrow / space / tab markers.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

Language

setDocLanguage

Sets the document’s default proofing language — the bottom of paragraph.proofingLanguage ?? style.language ?? doc.language.

Dispatches updateCounters because numbering labels are language-sensitive (cardinalText, ordinalText) and the label memo ignores language, so it would otherwise keep the stale words.

Parameters:
NameTypeDefault
languagestring
Returns:
Command

setLanguage

Sets the proofing language attribute for all proofread nodes in the current selection. Triggers the updateCounters meta when a modified node has numbering, or when the document holds a cross-reference.

The cross-reference half is not incidental: an aboveBelow reference renders its “above”/“below” in the TARGET’s language, and an AttrStep carries an empty step map, so the cross-reference plugin’s change detection never sees one. Without the meta an Italian “sopra” stayed “sopra” after the target moved to French (REF-46).

Parameters:
NameTypeDefault
languagestring

The language code (e.g., “en-GB”, “en-US”, “fr-FR”), or null to drop the explicit stamp and follow the style/document language.

Returns:
Command

Clears the pending-link state without creating a link. False when none is pending.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

Opens the link at pos (default: the selection’s anchor) in a new tab, as Ctrl/Cmd+click does. False without a link there or a safe URL, so a menu item probing it disables itself. Dispatches no transaction.

Parameters:
NameTypeDefault
posnumber
Returns:
Command

Removes the link from the selection, or the whole link under a bare cursor.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

Links the pending selection to url (sanitized), dropping code over it, and clears the pending state. False when nothing is pending or the URL is unsafe.

Parameters:
NameTypeDefault
urlstring
Returns:
Command

setLinkUrl

Links the pending selection to url (sanitized) and clears the pending state. False when nothing is pending or the URL is unsafe.

Parameters:
NameTypeDefault
urlstring
Returns:
Command

Enters the pending-link state that opens the link editor. A bare cursor selects the link under it, else the surrounding word. Refused in code blocks.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

Math

insertMathDisplay

Inserts a display math node, optionally prefilled, with the caret in its LaTeX source. From a text cursor it splits the block and inserts between the halves.

Parameters:
NameTypeDefault
initialTextstring
Returns:
Command

insertMathInline

Inserts an inline math node, optionally prefilled, with the caret in its LaTeX source.

Parameters:
NameTypeDefault
initialTextstring
Returns:
Command

Marks (shortcuts)

toggleBold

Toggles the strong mark, expanding a bare cursor to the whole word.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

toggleCode

Toggles the code mark, expanding a bare cursor to the whole word.

Refuses to APPLY inside a link (D10) — the toolbar toggle greys out via the same dry run. Removal is still allowed, so content that arrived carrying both marks (import, paste) can be cleaned up.

Deliberately not a schema excludes: that would strip the link when code is applied rather than refusing. The other direction is handled by the link commands, which drop code across the range they link.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

toggleItalic

Toggles the em mark, expanding a bare cursor to the whole word.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

toggleStrike

Toggles the strikethrough mark, expanding a bare cursor to the whole word.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

toggleSubscript

Toggles the subscript mark, expanding a bare cursor to the whole word.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

toggleSuperscript

Toggles the superscript mark, expanding a bare cursor to the whole word.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

toggleUnderline

Toggles the underline mark, expanding a bare cursor to the whole word.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

Numbering

adjustLevel

Moves every numbered block in the selection one level up/down, or to level (which wins over direction). Clamped to the list’s deepest defined level; demoting past level 1 removes the numbering.

When a style-numbered paragraph’s target level is bound to a paragraph style, the change becomes a STYLE switch — the paragraph adopts the bound style and drops its own numbering attr, so the binding keeps driving it (Word’s legal-template model).

Transaction form: adjustLevelTr.

Parameters:
NameTypeDefault
propsAdjustLevelProps
Returns:
Command

AdjustLevelProps

NameTypeDefault
direction"up" | "down"
levelnumber

applyListRef

Applies listRef as direct numbering. Collapsed selection: re-lists every item of the caret block’s instance, or numbers an unnumbered block (joining an adjacent same-list instance). Ranged: numbers every non-empty numberable block, each keeping its own instance.

Transaction form: applyListRefTr.

Parameters:
NameTypeDefault
listRefstring
Returns:
Command

cleanupUnusedListRefs

Drops doc.attrs.listConfigs entries that no node or style references, and default-ref entries identical to the built-in.

Transaction form: cleanupUnusedListRefsTr.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

continueNumbering

Rejoins a restarted list to the one before it (Word’s “Continue numbering”), from any item of the run: the run, from its first item, adopts the instanceId of the nearest preceding item of the same list (by root list, so a fork’s items count), so its counters carry on rather than starting at 1. Refused when no such item precedes the run.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

removeListConfig

Removes a list config from doc.attrs.listConfigs. Command form of removeListConfigTr, symmetric with saveListConfigToDocAttrs.

Parameters:
NameTypeDefault
referencestring

The listRef to remove.

Returns:
Command

removeNumbering

Removes numbering from the numbered block at the selection.

Transaction form: removeNumberingTr.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

restartNumbering

Restarts numbering at the selected numbered paragraph: it is stamped with a fresh instanceId and everything after it on the same list follows, through the numbering plugin’s adjacency carry. On a sub-level item only that level restarts: the new run carries on the outer levels (openingStack).

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

saveListConfigToDocAttrs

Saves a list config into doc.attrs.listConfigs — a doc attribute, so the change syncs to collaborators and travels with the document.

A built-in default ref may be written too: the defaults are seed values, immutable only at initialization, and a doc-attrs entry SHADOWS the built-in (getListConfigs spreads the doc layer last). An entry that would be identical to the built-in is dropped rather than stored — it is pure duplication, and writing one back is how a shadow is reset.

Parameters:
NameTypeDefault
referencestring
levelsILevelsOptions[]
Returns:
Command

setFollowBy

Command form of setFollowByTr.

Parameters:
NameTypeDefault
followBy"tab" | "space" | "nothing"
Returns:
Command

setListTabStop

Sets the tabStop on the LEVEL CONFIG of the list at the selection (Word’s “Add tab stop at:”, stored per level in the list definition and exported as the level’s w:tabs).

Writes the config rather than the node attrs, so the choice survives into new instances and into the exported file; updateNumbering copies a default or shared config before writing. See setLevelConfigFieldTr for the style-binding rule.

Parameters:
NameTypeDefault
tabStopnumber

width of the counter cell in px; null removes the value.

Returns:
Command

setNumberingAttrs

setNumberingAttrsTr as a standalone command.

Parameters:
NameTypeDefault
newNumberingAttrsPartial<NumberingAttrs>
options{ sameLevel?: boolean; }
Returns:
Command

toggleCounter

The list button (buttonType) or format dropdown (levelFormat) — pass exactly one.

Collapsed selection on a numbered block: a bullet↔number switch retargets the whole instance to the default list (unless it uses deeper levels), a repeat press toggles the block off, otherwise the level’s format is rewritten. On an unnumbered block: continues an adjacent list of matching type/format, else starts a new list.

Ranged selection: toggles off when every non-empty block is numbered and none switches type; otherwise re-lists them all onto one new instance.

Only the numbering attr is written; the plugin adds or removes the counter node.

Transaction form: toggleCounterTr.

Parameters:
NameTypeDefault
propsToggleCounterTrProps
Returns:
Command

updateNumbering

Saves levels as a list config and moves the listRef/instanceId instance onto it. The target ref is reused when an identical config exists, forked when the old one is a default or shared by other instances (see returnComputedListRef); only a fork retargets the instance’s nodes.

Also refuses when the transaction would not change the doc.

A bulk command: the config is saved in the first transaction, the nodes are updated CHUNK_STEPS steps a transaction. Transaction form: updateNumberingTr.

Parameters:
NameTypeDefault
propsUpdateNumberingProps
Returns:
Command

clearSearchState

Clears the query, range and match decorations, and closes the search UI.

Parameters:
This function does not accept any parameters.
Returns:
Command

disableSearchState

Closes the search UI, resetting the query. No-ops when already closed.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

enableSearchState

Opens the search UI with an empty query. No-ops when already open.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

findNext

Selects the next match after the selection, wrapping at the end of the range.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

findNextNoWrap

findNext without wrapping: fails once past the last match.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

findPrev

Selects the previous match before the selection, wrapping at the start of the range.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

findPrevNoWrap

findPrev without wrapping: fails once before the first match.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

replaceAll

Replaces the exact matches in the search range, at most replaceAllLimit, the first ones in document order: “Replaced N of M; run Replace All again to continue” (replaceAllCount). With an approximate query near misses are left alone, to be replaced one at a time after the user has seen them. A bulk command: matches are replaced last first, CHUNK_STEPS steps a transaction, or in edit mode as one batch step (replaceAllBatch). Fails when there is nothing to replace.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

replaceCurrent

Replaces the selected match in place, leaving the selection on the result.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

replaceNext

Replaces the selected match and moves to the next one. When no match is selected yet, selects the next one instead of replacing.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

replaceNextNoWrap

replaceNext without wrapping at the end of the range.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

toggleSearchState

Opens or closes the search UI, resetting the query either way.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

Sections

addSection

Splits the current section after the top-level block holding the cursor: the blocks after it move into a new section that inherits the current one’s page setup and header/footer. Refused in a flow layout mount.

Parameters:
This function does not accept any parameters.
Returns:
Command

HeaderFooterDistanceOptions

NameTypeDefault
headerFromTopnumber

Distance (px) from the top of the page to the header.

footerFromBottomnumber

Distance (px) from the bottom of the page to the footer.

insertColumnBreak

A column break (Word’s Ctrl+Shift+Enter): the next column, or the next page in one column. Refused with column sections off (columnSectionsEnabled).

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

insertPageBreak

A hard page break (Word’s Ctrl+Enter).

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

insertPageNumber

Inserts a page-number field (current page, total pages, …) at the cursor.

Parameters:
NameTypeDefault
__0PageNumberAttrs
Returns:
Command

insertPageOfPage

Inserts a “1 of 12” pair of page-number fields.

Parameters:
NameTypeDefault
middleTextstring

Separator word between the two fields, defaulting to “of”. A space is added on each side, so pass the bare word — ” of ” would render as “1 of 12”.

Returns:
Command

lineNumbersSuppressed

True when EVERY suppressible block in the selection is already suppressed. Mixed selections read as “not suppressed”, so one toggle suppresses them all.

Parameters:
NameTypeDefault
stateEditorState
Returns:
boolean

removeSectionBreak

Removes the break that ends the section holding the selection head; in the last section, the break above it (the previous section then takes on the last one’s settings, as in Word).

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

removeSectionBreakAt

Removes the section break after section index (mergeSectionIntoNext), in one undoable transaction. Refused with a toast when the doc has one section, or while track changes is suggesting (a tracked break deletion is not supported yet); refused silently when index is the last section.

Positional rather than selection-based so the section-break divider, which is chrome rather than a selectable position, can remove the break it draws.

Parameters:
NameTypeDefault
indexnumber
Returns:
Command

deleteAcrossSections

Delete/Backspace/type-over/paste over a selection whose ends lie in different sections. False for any other selection, so the usual commands run.

Parameters:
NameTypeDefault
replacementReplacement
Returns:
Command

setHeaderFooterDistance

Sets the section attrs headerFromTop / footerFromBottom.

Parameters:
NameTypeDefault
optionsHeaderFooterDistanceOptions
sectionIdstring
Returns:
Command

setLineNumbers

Merges lineNumberNewAttrs into the current section’s line numbering (starting from the defaults when it is off), clamped to bounds.

Parameters:
NameTypeDefault
lineNumberNewAttrsPartial<LineNumbersAttrs>
Returns:
Command

setOrientation

Switches the current section between portrait and landscape, swapping the page width and height. Refused when already in that orientation.

Parameters:
NameTypeDefault
orientation"portrait" | "landscape"
Returns:
Command

setPageBorders

Sets page borders on the current section, or every section; null removes them.

Parameters:
NameTypeDefault
pageBordersPageBorders
__1SetPageBordersOptions
Returns:
Command

setPageBordersSurround

Whether text-measured page borders enclose the header and footer (document-wide).

Parameters:
NameTypeDefault
surround{ header?: boolean; footer?: boolean; }
Returns:
Command

setSectionColumns

Sets the current section’s columns; null returns it to one column. Too narrow columns shrink the gap, then the count (see clampSectionColumns).

Parameters:
NameTypeDefault
columnsSectionColumns
Returns:
Command

setWatermark

Sets the watermark of the current section, or of every section; null removes it. Refuses a picture when the schema has no image node.

Parameters:
NameTypeDefault
watermarkWatermark
__1SetWatermarkOptions
Returns:
Command

setSectionFormat

Sets the current section’s orientation, page size and/or margins. A page size whose aspect contradicts the orientation is transposed to match it.

Parameters:
NameTypeDefault
optionsSectionOptions
Returns:
Command

toggleLineNumbers

Toggles line numbering on the current section: on with the defaults, or off (null).

Parameters:
This function does not accept any parameters.
Returns:
Command

toggleSpanColumns

Toggles spanColumns on the selected blocks of a column section: on unless they all span already. Only the blocks opening the section span (leadingColumnSpanners). Refused outside a column section.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

toggleSuppressLineNumbers

Toggles suppressLineNumbers on every suppressible block in the selection.

Word’s semantics, applied by the pagination engine: a suppressed block’s lines are SKIPPED by the section’s line counter, so the next counted line takes the next number — they are not merely hidden.

Parameters:
NameTypeDefault
suppressboolean

Force a value instead of toggling.

Returns:
Command

Style Sheets

createStyleDefinition

upsertStyleDefinition restricted to new styles — fails on an existing id.

Parameters:
NameTypeDefault
styleIdstring
styleDefStyleDefinition
Returns:
Command

deleteStyleDefinition

Deletes a custom style from the doc’s override map, re-pointing blocks and dependent styles (basedOn/next) at replaceWith. Throws for a DEFAULT_STYLE_SHEET style — those are reset, not deleted.

Parameters:
NameTypeDefault
styleDefIdstring
replaceWithstring
Returns:
Command

replaceStyleDefIds

Re-points every paragraph/heading using prevStyleDefId at newStyleDefId. A bulk command: the blocks are re-pointed CHUNK_STEPS steps a transaction.

Parameters:
NameTypeDefault
prevStyleDefIdstring
newStyleDefIdstring
Returns:
Command

setStyleNumberingBinding

Binds a paragraph style to a list level, or clears the binding with null.

Enforces the model’s invariant — at most ONE style per (listRef, level) — by resetting any other style already occupying the slot. Dual storage is deliberately avoided: the binding lives only on the stylesheet side, and the listRef → level → styleId map is derived from it.

Transaction form: setStyleNumberingBindingTr.

Parameters:
NameTypeDefault
styleIdstring
numberingStyleNumbering
Returns:
Command

setStyleSheet

Applies paragraph style styleSheetId to the paragraphs/headings in the selection, converting between paragraph and heading to match the style’s outline level. Refused for character styles and inside code blocks.

deleteMarks: true always strips direct-formatting marks; "sameStyle" strips them only when every block in the range already has this style.

Parameters:
NameTypeDefault
styleSheetIdstring
deleteMarkstrue | "sameStyle"
Returns:
Command

submitStyleDefChange

Applies a style-definition edit as one undo step.

  • Create (currentStyleDefId nullish): upsert under newStyleDefId.
  • In-place update (ids equal): the stored override is REPLACED, not merged — the caller (stylesheet panel) submits the complete definition, so a field it omits means “cleared / back to inherited”. Merging would make clearing a saved value impossible.
  • Rename (ids differ): rewrite doc block refs, remap dependent styles’ basedOn/next, drop the old override entry, then upsert under newStyleDefId. Renaming a DEFAULT_STYLE_SHEET key is rejected.
Parameters:
NameTypeDefault
currentStyleDefIdstring
newStyleDefIdstring
styleDefStyleDefinition
Returns:
Command

updateStyleDefinition

upsertStyleDefinition restricted to existing styles — fails on a missing id.

Parameters:
NameTypeDefault
styleIdstring
styleDefPartial<StyleDefinition>
Returns:
Command

upsertStyleDefinition

Upserts a (partial) style definition into the doc’s override map. The override map is sparse: only fields that diverge from DEFAULT_STYLE_SHEET live here. Existing overrides deep-merge with the incoming partial, so edits compose (e.g. setting fontSize then fontFamily keeps both). After merging, fields that match DEFAULT_STYLE_SHEET are pruned; if the whole override collapses to identity, the key is removed entirely.

Parameters:
NameTypeDefault
styleIdstring
styleDefPartial<StyleDefinition>
optionsUpsertStyleDefinitionOptions

falseIfExists / falseIfNotExists turn the upsert into a create-only / update-only operation, returning false (with a warning) when the precondition fails. See createStyleDefinition and updateStyleDefinition. replace skips the merge and stores styleDef as the whole override — for callers that submit a complete definition and need omitted fields to mean “cleared” rather than “unchanged” (the stylesheet panel). Dependent styles are unaffected: they store no copies, the resolver walks basedOn on read.

Returns:
Command

Tables

createTableNode

Builds a table node sized to maxWidth, the host cell or the section content width. Shared by insertTable and programmatic builders like insertPageNumberPreset.

Parameters:
NameTypeDefault
stateEditorState
optionsCreateTableOptions
Returns:
Node | null

deleteColumn

Removes the selected columns and redistributes their width across the remaining ones, so the table keeps its overall width. Refused when every column is selected, or every other one is pending deletion (TC-130).

With track changes on (or forced by review mode), neither happens yet. The track-changes engine (table-handler.ts) keeps each removed cell in the doc as a tracked deletion, so the grid stays rectangular while pending. Hence no skipTrackChanges here — that made the delete untracked (TC-41).

Width redistribution is skipped in that mode on purpose: the struck column keeps its width until accepted, and the resolver redistributes then (TC-104).

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
Returns:
boolean

deleteRow

Removes the selected rows. When the selection spans every row, deletes the whole table instead (via deleteTable), since a table cannot be empty.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

deleteTable

Delete a table and insert a paragraph in its place.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

deleteTableIfSelected

deleteTable, but only when the whole table is selected — so a Delete keypress inside a cell edits the cell instead of destroying the table.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

distributeColWidths

Sets every selected column to widthInput px, or — when omitted — to their average width (needs 2+ columns). Floored at 25px. A fixed/pct table’s width follows a typed width that changes its overall width (D9).

Parameters:
NameTypeDefault
widthInputnumber
Returns:
Command

incrementTableSpacing

Adds value to the table’s effective spacing on one side, floored at 0.

Parameters:
NameTypeDefault
__0{ position: "before" | "after"; value: number; }
Returns:
Command

insertColumnAfter

Inserts a column to the right of the selection, rescaling the existing columns so the table keeps its overall width.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

insertColumnBefore

Inserts a column to the left of the selection, rescaling the existing columns so the table keeps its overall width.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

insertRow

Inserts as many rows as the rect spans, at row index row. copyRow picks the row whose cell attrs (colspans, not rowspans) are copied: “bottom” the row at row, “top” the one above it, null plain cells. Rowspans crossing the insert point grow to cover the new rows. New rows are header rows when the row they copy is one (Word copies its “repeat as header row”), or, with nothing copied, when inserted above a header row.

Parameters:
NameTypeDefault
__0TableRect
rownumber
copyRow"top" | "bottom"
updateSelectionboolean
Returns:
TransactionFn

insertRowAfter

Inserts rows below the selection, one per selected row, copying the last selected row’s cell attrs.

Parameters:
NameTypeDefault
updateSelectionboolean
Returns:
Command

insertRowBefore

Inserts rows above the selection, one per selected row, copying the first selected row’s cell and row attrs, as Word’s Insert Above does. Above a header row the new rows are header rows too.

Parameters:
NameTypeDefault
updateSelectionboolean
Returns:
Command

insertTable

Inserts a table sized to the section’s content width, or its host cell’s, with the cursor in the first cell. Refused inside code blocks, inside a nested table (two levels at most), inside footnote/endnote bodies, and in a cell too narrow for cols columns.

Parameters:
NameTypeDefault
__0{ rows: number; cols: number; borders?: Borders | null; headerRowCount?: number; repeatHeaderRows?: boolean; }
Returns:
Command

mergeCells

Merges the selected cells into one. Only available when the selection’s outline forms a rectangle. Does not set skipTrackChanges — mergeCells does.

Transaction form: mergeCellsTr.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

selectEntireTable

Selects every cell of the table containing the selection.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

selectEntireTableAtPos

Selects every cell of the table at a known position, as a CellSelection.

Parameters:
NameTypeDefault
tablePosnumber
Returns:
Command

setCellAlignment

Sets the alignment of the selected cells’ content. The CellAlignment token is a <vertical>-<horizontal> pair (“top-start”, “middle-center”, …): the vertical half lands on the cells’ verticalAlign attr, the horizontal half is forwarded to setTextAlignTr for the blocks inside them.

Parameters:
NameTypeDefault
alignment"top-start" | "top-end" | "top-center" | "bottom-start" | "bottom-end" | "bottom-center" | "middle-start" | "middle-end" | "middle-center"
Returns:
Command

setCellAttrs

Sets attrs on the selected cells. A dry run reports false when the selection’s cell already has them, unless returnTrueOnSameValue.

Parameters:
NameTypeDefault
attrsInAttrs
returnTrueOnSameValueboolean
Returns:
Command

setCellBackgroundColor

The selected cells’ fill; themeRef is the theme slot it was picked from, and a fill without one clears the cell’s ref. No colour in a table with a table style is an explicit none (“transparent”), which hides the style’s band, as Word’s “No Color” does; elsewhere it clears the attr.

Parameters:
NameTypeDefault
colorstring
themeRefstring
returnTrueOnSameValueboolean
Returns:
Command

setCellAttr

setCellAttrs for one attr.

Parameters:
NameTypeDefault
namestring
valueunknown
returnTrueOnSameValueboolean
Returns:
Command

setRowHeight

Sets the height attr on every row covered by the selection. Pass null (or a value below the 30px minimum) to clear it, and its rule with it. rule sets Word’s height rule too (exact; null or atLeast is a minimum); left undefined, each row keeps its own.

Parameters:
NameTypeDefault
heightnumber
rule"atLeast" | "exact"
Returns:
Command

setRowHeightRule

Sets the height rule of every row covered by the selection: auto clears the height (the row fits its content), atLeast keeps the height as a minimum, exact pins the row at it. atLeast is stored as a null rule, which means the same (docs/executed/table-sizing-plan.md, D6). Refused for atLeast/exact when a covered row has no height to apply it to.

Parameters:
NameTypeDefault
ruleRowHeightRule
Returns:
Command

setRowKeepTogether

Sets keepTogether (Word’s w:cantSplit) on every row covered by the selection. Not applicable when every covered row already has keep.

Parameters:
NameTypeDefault
keepboolean
Returns:
Command

setHeaderRowCount

Sets how many leading rows of the selected table are header rows (th), clamped to its row count. Not applicable when it already has that many.

Parameters:
NameTypeDefault
countnumber
Returns:
Command

setHeaderRowsToSelection

The rows down to the selection’s last one become the header rows.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

setRepeatHeaderRows

Word’s “Repeat Header Rows”: paint the header rows again at the top of every page the table continues onto. Not applicable without header rows.

Parameters:
NameTypeDefault
repeatboolean
Returns:
Command

toggleHeaderRow

Word’s “Header Row”: the first row becomes a header row, or every header row a body row.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

setTableAlignment

Aligns the table within the section’s content width.

Parameters:
NameTypeDefault
alignmentTableAlign
Returns:
Command

setTableLayout

Sets the selected table’s layout, Word’s w:tblLayout. Carried for the DOCX round trip only: the editor always lays tables out with fixed columns (docs/executed/table-sizing-plan.md, D4).

Parameters:
NameTypeDefault
layoutTableLayout
Returns:
Command

setTableLook

Turns table-style regions on or off for the selected table (Word’s Style Options: Header Row, Total Row, First/Last Column, Banded Rows/Columns). Independent of the table’s header rows (headerRowCount), as in Word.

Parameters:
NameTypeDefault
lookPartial<TableLook>
Returns:
Command

setTableSortOptions

Stores the sort configuration (column, direction, value type) on the table. Persisting it lets sortTableRows re-run later with the same settings.

Parameters:
NameTypeDefault
optionsSortOptions
Returns:
Command

setTableSpacing

Merges spacing into the table’s space before/after; sides not given keep their current value. Requires the whole table to be selected.

Parameters:
NameTypeDefault
spacingSpacingAttrs
Returns:
Command

setTableSpacingBeforeAfter

setTableSpacing for one side only, leaving the other untouched.

Parameters:
NameTypeDefault
__0{ position: "before" | "after"; value: number; }
Returns:
Command

setTableStyle

Applies a table style to the selected table (Word’s Table Design gallery), or none. The cells’ own formatting is kept, over the style (Word’s “Apply (and Maintain Formatting)”). Not applicable for an id the sheet has no table style under, or the style the table already has.

Parameters:
NameTypeDefault
styleIdstring
Returns:
Command

setTableWidthMode

Sets the selected table’s width (docs/executed/table-sizing-plan.md): the sizing plugin then rescales its columns to it, keeping their shares. Refused when the table already has that width, or for a percentage with no width to take it of (a cell without column widths).

Parameters:
NameTypeDefault
widthTableWidth
Returns:
Command

setTableWidthType

Switches the selected table’s width type without changing its size: fixed at its current width, pct at its current share of the width it lays out in, auto the columns’ own. Refused when the type is already set, the table has a column without a width, or (pct) it is wider than its block.

Parameters:
NameTypeDefault
type"auto" | "fixed" | "pct"
Returns:
Command

sortTableRows

Reorders the table’s rows by a column’s value (text, number or date per orderBy). Falls back to the table’s stored sort options, then to defaults, when options is omitted. Refused (with a toast) on vertical merges or an out-of-range column; false when already sorted.

Parameters:
NameTypeDefault
optionsSortOptions
Returns:
Command

splitCell

Split a selected cell, whose rowspan or colspan is greater than one, into smaller cells. The new cells reuse the split cell’s own type.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
Returns:
boolean

splitTable

Splits the table in two at the cursor’s row, which becomes the first row of the second table. Refused on the first row, which would leave an empty table.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

Text Style

changeCase

Changes the case of the selected text — Word’s Sentence case, UPPERCASE, lowercase and Capitalize Each Word.

A rewrite, not a format: the characters themselves change and nothing is stored, so undo is the only way back (setCaps is the reversible half). One transaction covers the whole selection (at a caret, the word around it), and only the characters that actually differ are replaced, so the anchors of comments and proofread suggestions inside the range survive.

Parameters:
NameTypeDefault
modeCaseChange
Returns:
Command

clearBackgroundColor

Drops the direct background formatting so the block falls back to its stylesheet’s paragraphStyle.backgroundColor — the “use stylesheet value” action, as opposed to setBackgroundColor("transparent") which explicitly overrides the stylesheet with no fill.

Clears the run-level mark over the selection too: a leftover textStyle background would keep painting over the restored block color.

Transaction form: clearBackgroundColorTr.

Parameters:
This function does not accept any parameters.
Returns:
Command

clearFontColor

Clears the color override, back to the stylesheet’s.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

cycleCase

Word’s Shift+F3: the same three changes as a cycle — lowercase → UPPERCASE → Capitalize Each Word → lowercase — so repeated presses walk the selection round the ring.

The current case is read off the selected text itself, since nothing stores it: text that equals its own lowercasing is lowercase, text that equals its own uppercasing is uppercase, and anything else (capitalized or mixed) counts as the third state. Caseless text — digits, CJK — equals both, and lands on Capitalize, which rewrites nothing.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

incrementFontSize

Steps the font size to the next or previous entry of FONT_SIZES, without dispatching. Text with no explicit size starts from its stylesheet’s size, so stepping up from an inherited 11pt lands on 12pt rather than a hardcoded default. Above the list’s top entry (72pt) it steps to 80pt, then by 10pt up to 140pt; sizes typed above that (up to FONT_SIZE_MAX) are left where they are.

With a bare cursor inside a word the whole word is resized; at a word boundary the new size is stored for the next keystroke.

Transaction form: incrementFontSizeTr.

Parameters:
NameTypeDefault
direction"up" | "down"
Returns:
Command

setBackgroundColor

Sets a background color, choosing between a mark and a node attr so the fill covers exactly what the user selected.

  • Partial selection inside one block: a textStyle mark on the selected text.
  • Caret, whole block, or a selection spanning several blocks: the block’s own bgColor attr, so the fill extends to the block edges.
  • Table cells in the selection (including a whole paragraph inside a cell): the cell’s attr rather than the paragraph’s.

"transparent" is stored as-is — an explicit “no fill” that overrides the block’s stylesheet background. Pass null to clear the direct formatting instead and fall back to the stylesheet (clearBackgroundColor).

Refused inside code blocks.

themeRef is the theme slot the colour was picked from; without one, any ref the target had is cleared.

Transaction form: setBackgroundColorTr.

Parameters:
NameTypeDefault
colorstring
themeRefstring
Returns:
Command

setCaps

Sets the casing FORMAT on the selection: "all" (Word’s all caps), "small" (small caps), "none" (an explicit off that beats an inherited caps), or null to re-inherit. UPPERCASE/lowercase/Capitalize are text edits, not a format — they are not values here.

Parameters:
NameTypeDefault
valueCaps
Returns:
Command

setFontColor

Sets the textStyle mark’s color on the selection. themeRef is the theme slot the colour was picked from (it must resolve to color under the doc’s theme); without one, any ref the run had is cleared.

Parameters:
NameTypeDefault
colorstring
themeRefstring
Returns:
Command

setFontFamily

Sets the font family on the selection. An empty or null value clears the override.

Parameters:
NameTypeDefault
fontstring
Returns:
Command

setFontSize

Sets the font size (pt) on the selection. Null removes the override: the text takes its style’s size.

Parameters:
NameTypeDefault
fontSizenumber
Returns:
Command

Table of Contents

insertTOC

Inserts a toc node at the cursor. Refused inside tables.

Parameters:
This function does not accept any parameters.
Returns:
Command

setTocAttr

Sets one setting of the toc at pos. An imported TOC’s stored field instruction gets the matching switch rewritten, so the export keeps the rest of it. Only page numbers have a switch: number alignment and leader dots live in Word’s TOC styles, and Word has no section scope.

Parameters:
NameTypeDefault
__0{ pos: number; attribute: K; value: TOCattrs[K]; }
Returns:
Command

setTocSelection

Sets what the toc at pos lists, by rewriting its field instruction’s \o and \t switches. An editor-made TOC (no instruction) gets the one the export would derive for it first, so the two agree.

Parameters:
NameTypeDefault
__0SetTocSelectionProps
Returns:
Command

Callouts

insertCallout

Wraps the selected blocks (or the caret’s block) in a callout of kind. Where they can’t be wrapped, inserts a callout holding a placeholder paragraph. Refused past MAX_CALLOUT_DEPTH (the schema allows deeper, e.g. by paste).

Parameters:
NameTypeDefault
kindCalloutKind
Returns:
Command

liftCallout

Removes the callout around (or at) the selection, keeping its content.

Parameters:
NameTypeDefault
stateEditorState
dispatch(tr: Transaction) => void
viewEditorView
Returns:
boolean

setCalloutAttrs

Sets the kind and/or title of the callout at pos (a node view’s), else the one around (or at) the selection.

Parameters:
NameTypeDefault
attrsPartial<CalloutAttrs>
posnumber
Returns:
Command

Templates

insertField

Inserts a field for variable name at the cursor. Refused in code blocks.

Parameters:
NameTypeDefault
__0{ name: string; fallback?: string | null; }
Returns:
Command

insertContentSlot

Inserts the content_slot at the cursor. Refused inside tables (only section_content can hold it) and when the document already has one: a template has a single place for its content.

Parameters:
This function does not accept any parameters.
Returns:
Command

Escape

hasEscapeConsumer

Whether something is armed to consume the next Escape: an in-state consumer (format painter, highlighter, search, the paste-options button, a selected picture or text box, which Escape leaves for the text) or a registered external one (see registerEscapeConsumer).

Chrome with an Escape fallback (e.g. focus-to-toolbar) must ask here: ProseMirror’s captureKeyDown calls preventDefault() on every Escape, so event.defaultPrevented is always true. Read it in the capture phase — once ProseMirror has processed the key the consumer has already disarmed itself.

Parameters:
NameTypeDefault
stateEditorState
Returns:
boolean

registerEscapeConsumer

Declares that something outside the editor state (an open floating menu) will consume the next Escape for rootEditorId. Returns the unregister; call it when the consumer closes. The consumer owns its own dismissal — this only stops chrome fallbacks (focus-to-toolbar) from firing on the same keypress.

Parameters:
NameTypeDefault
rootEditorIdstring
Returns:
() => void
Last updated on