Skip to the content

The editor

Commands, state and lists

Everything the editor does goes through one object, editor:

PartWhat it's for
editor.commandsRun actions, ask whether they can run and whether they're on, add your own
editor.stateWhat's true now: the formatting at the cursor, the paragraph, counts, the license
editor.listsWhat the menus choose from: fonts, sizes, colours, styles, line spacings, symbols, page sizes, margins, shapes, icons, equations
editor.statistics()Counts and readability, as Word's Editor shows them
editor.crossReferenceTargets()What a cross-reference can point to now

Dorvyn's own interface is built only from these, so anything it does, your interface can do too.

Get the editor with await element.whenReady() (HTML), useEditor() (React, Next.js) or ed.editor() (Angular).

Commands#

JavaScript
await editor.commands.run("bold");                         // an action
await editor.commands.run("fontSize", 14);                 // with a value
await editor.commands.run("table.insert", { rows: 2, cols: 4 });

editor.commands.can("bold");      // can it run now? (false when read-only or without a license)
editor.commands.active("bold");   // is it on? (bold text, a centred paragraph, a bulleted list…)
editor.commands.has("bold");      // does it exist?
editor.commands.list();           // every command's id
  • run returns true when it ran and false when it couldn't (read-only, for example). An unknown id throws UnknownCommandError.
  • Commands that change the document never run while the editor is read-only.
  • Without its value, a command does what Word's button does without its dialog: table.insert makes a 3 × 3 table, picture.insert opens the file picker, file.open opens the file picker. Commands that only make sense with a value (link, caption, equation) do nothing without one: your own dialog collects it and passes it in.
  • The clipboard (cut, copy, paste, pasteText) works only from a person's click or key press: browsers don't let a page use the clipboard otherwise. Run them from a click handler.

Your own commands#

JavaScript
const remove = editor.commands.register("myapp.insertClause", {
  run: async () => editor.commands.run("symbol", "§"),
  can: (ctx) => !ctx.readOnly,     // optional
  active: () => false,             // optional
});

Ids are dotted camelCase and can be registered once. Your commands work everywhere ours do: <dorvyn-command-button command="myapp.insertClause">, useCommand("myapp.insertClause"), dorvynCommand="myapp.insertClause". register returns a function that removes the command.

State#

JavaScript
const s = editor.state.get();
s.format;      // the formatting at the cursor (below), or null before there's a document
s.paragraph;   // the paragraph at the cursor (below)
s.words;       // also: chars, pages, canUndo, canRedo, dirty, findCount, marks

// Watch one part: called only when it changes. Returns a function that stops watching.
const stop = editor.state.select((s) => s.format?.bold, (bold) => myButton.classList.toggle("on", bold));
FieldWhat it is
saveTo"download", or "page" with the onSave option: what Save does
readOnlyNothing can be edited: no license that allows editing, or Viewing chosen
viewingViewing chosen (the viewing command)
engine"loading", "ready", "failed" (didn't load, or didn't match this SDK), "off" (the engine: false option)
license"none", "valid", "refused", "unavailable", "lapsed" or "grace": see Events and license states
formatfont, size (points), bold, italic, underline, strike, sub, sup, ul, ol, align, styleKey, styleLabel, inTable, link (the link's address at the cursor), block, color (#rrggbb), highlight (#rrggbb, or "" for none)
paragraphlineSpacing (1.15 is Word's default), rtl, indentLeft, indentRight (inches), spaceBefore, spaceAfter (points)
words, chars, pagesCounts
canUndo, canRedoFor undo and redo buttons
dirtyChanges not yet kept as a draft
findCount, findIndexMatches of the last find, and the current one (0-based; -1 for none)
marksParagraph marks shown
hasSelectionText is selected (not only a cursor)
currentPage, saveStatusThe page the cursor is on; the draft: "saved", "saving", "unsaved", "toolarge"
editingWhere the cursor is: "body", or "header" / "footer" while editing them
pagewidth, height (inches), orientation, margins (top, right, bottom, left, inches)
pageNumbersposition ("none", "left", "center", "right"), withTotal ("Page X of Y"), where ("header" or "footer")
zoomPercent
pictureThe selected picture: width, height (pixels), alt, wrap, align; or null
equationThe selected equation (clicked in the document): tex, display; or null
commentsEvery comment: id, author, date, text, quote (the text it's on)
activeCommentThe id of the comment at the cursor, or null
headingsEvery heading: level, text, id (for a navigation pane: goTo the id)
bookmarksEvery bookmark's name
fileNameThe document's name (the saved file is named after it)
authorThe name on new comments

Lists#

ListWhat it is
editor.lists.fontsFont names, for fontFamily
editor.lists.sizesFont sizes in points, for fontSize
editor.lists.themeColorsWord's theme and standard colours, for color, paragraph.shading, table.cellShading
editor.lists.highlightsWord's highlight colours, for highlight
editor.lists.styles{ key, label } for every style, for style
editor.lists.galleryThe style keys Home's gallery shows, in Word's order
editor.lists.lineSpacings"1.0", "1.15", "1.5", "2.0", "2.5", "3.0", for lineSpacing
editor.lists.symbolsCommon symbols, for symbol
editor.lists.pageSizes{ name, label, width, height } (inches), for page.size
editor.lists.margins{ name, label, m } margin presets (inches), for page.margins
editor.lists.shapes{ key, label }, for shape.insert
editor.lists.iconsIcon names, for icon.insert (their drawings: await loadIcons() from @dorvyn/core)
editor.lists.equationsgallery ({ name, tex, mathml }: tex for equation, mathml to show it), and the structures and symbols an equation editor offers (LaTeX to type in)

The page sizes, margins, shapes and equations come from the engine, so they're empty until state.engine is "ready".

Dialogs, panes and notices#

JavaScript
// Ask for a dialog, pane or view; the editor fills in what it should start with (the selected text for
// a link, a suggested bookmark name, whether a caption has a picture or table to label…).
editor.open({ dialog: "link" });
editor.open({ pane: "find", mode: "replace" });
editor.open({ dialog: "equation", tex: "x^2" });

// Answer requests (from editor.open, and from the editor itself: Ctrl+K, Ctrl+F, Ctrl+H, Alt+=,
// clicking an equation or a comment).
const stop = editor.on("open", (req) => { /* req.dialog or req.pane or req.view, with its fields */ });
editor.on("notice", ({ message }) => { /* "Select a picture first", "Replaced 3 items" */ });

// An equation as MathML, for an equation editor's preview.
editor.mathml("\\frac{a}{b}", true);
RequestFields
{ dialog: "link" }text (selected), url, editing (the cursor is in a link)
{ dialog: "bookmark" }name (suggested from the selected word)
{ dialog: "crossReference" }(list the targets with crossReferenceTargets())
{ dialog: "caption" }label, position, hasTarget (a picture or table to label), next (the next number for each label)
{ dialog: "equation" }tex, display, editing (an equation in the document is being changed: equation.edit)
{ dialog: "wordcount" | "editor" | "shortcuts" | "about" | "options" }
{ pane: "find" }mode ("find" or "replace"), query (the selected text)
{ pane: "comments" | "navigation" }
{ view: "focus" }

<dorvyn-dialogs> and <dorvyn-panes> answer them with Dorvyn's own; <dorvyn-editor> also fires them as dorvyn-open and dorvyn-notice DOM events.

Statistics and cross-reference targets#

JavaScript
editor.statistics();
// { words, chars, charsNoSpaces, paragraphs, sentences, lines, avgWords, ease (0–100), grade }

editor.crossReferenceTargets();
// [{ kind: "Heading" | "Bookmark" | "Figure" | "Table" | "Equation", label, text, id }, …]
await editor.commands.run("crossReference", { kind: "Heading", id: targets[0].id });

Every command#

Value is what run(id, value) takes; "—" means none. On says what active(id) reports.

Clipboard#

CommandValueWhat it does
cut, copy—Cut or copy the selection (from a click)
paste—Paste, keeping formatting (from a click)
pasteText—Paste as plain text (from a click)
formatPainter—Copy the selection's formatting; the next selection gets it. On while armed

Characters#

CommandValueWhat it does
bold, italic, underline, strike, subscript, superscript—Toggle. On when the selection has it
fontFamilyfont nameSet the font
fontSizepointsSet the size
growFont, shrinkFont—One size up or down
color"#rrggbb"Text colour ("#000000": automatic)
highlight"#rrggbb" or nullHighlight, or remove it
clearFormatting—Remove character formatting
changeCase"sentence", "lower", "upper", "title", "toggle"Change case

Paragraphs#

CommandValueWhat it does
align.left, align.center, align.right, align.justify—Align. On for the current alignment
list.bulletsoptional "disc", "circle", "square"Bulleted list (with that bullet). On in a bulleted list
list.numbersoptional "decimal", "lower-alpha", "upper-alpha", "lower-roman", "upper-roman"Numbered list (with that numbering). On in a numbered list
list.checklist—Checklist
list.indent, list.outdent—A list level deeper or shallower
indent, outdent—Indent the paragraph
paragraph.indent{ left?, right? } (inches)Exact indents
lineSpacing"1.0" … "3.0"Line spacing
paragraph.spacing{ side: "before" | "after", pt: number | null }Space before or after (null: default)
paragraph.shading"#rrggbb" or nullShading
paragraph.border"bottom", "top", "all", "none"Borders
stylea style key (editor.lists.styles)Apply a style
tocLevel0–3Include the heading in the table of contents at this level (0: not at all)
direction"ltr" or "rtl"Text direction (state.paragraph.rtl says which)
dropCaptrue or falseDrop cap
marks—Show paragraph marks. On while shown

Tables#

CommandValueWhat it does
table.insertoptional { rows, cols }Insert a table (3 × 3 without a value)
table.insertRowAbove, table.insertRowBelow, table.insertColumnLeft, table.insertColumnRight—Add a row or column
table.deleteRow, table.deleteColumn, table.delete—Delete
table.mergeRight—Merge with the cell on the right
table.headerRow—Make the first row a header
table.borders—Toggle borders
table.cellShading"#rrggbb" or nullCell shading
table.select—Select the whole table
table.alignLeft, table.alignCenter, table.alignRight—Position the table on the page
object.move-1 or 1Move the table (or selected picture) up or down past a paragraph

Pictures and shapes#

CommandValueWhat it does
picture.insertoptional BlobInsert a picture (file picker without one)
picture.select<img> or nullSelect a picture in the document
picture.widthpixelsWidth (the height follows)
picture.alttextAlternative text
picture.wrap"inline", "left", "right", "topbottom"Text wrapping
picture.align"left", "center", "right"Position
picture.delete—Delete the selected picture
picture.heightpixelsHeight (the width follows)
picture.size{ width, height } (pixels)Both (stretches the picture)
picture.scalepercentWidth as a percentage of the text's width
picture.resetSize—Back to the picture's own proportions
object.align"left", "center", "right"Position the selected picture or shape on the page
shape.insertoptional shape key (lists.shapes)Insert a shape
icon.inserticon name (lists.icons)Insert an icon (as a picture)

Inserting#

CommandValueWhat it does
pageBreak, lineBreak, blankPage, coverPage, horizontalRule—Insert
coverPage.remove—Remove the cover page
symbolthe characterInsert a symbol
date"long", "short", "time"Insert today's date
textBox, signatureLine—Insert
link{ url, text? }Insert or change a link (unsafe addresses are refused)
link.remove—Remove the link at the cursor
link.open—Follow the link at the cursor (a place in the document, or the address in a new tab)
bookmarkoptional nameAdd a bookmark (named after the selected word without one)
bookmark.goTo, bookmark.deletename (state.bookmarks)Go to or delete a bookmark
goToan id (state.headings, a bookmark)Scroll to that place
equation{ tex, display? }Insert an equation from LaTeX
equation.selectthe equation's elementSelect an equation (clicking one does this)
equation.edit{ tex, display? }Change the selected equation (state.equation)
equation.delete—Delete the selected equation
equation.cancel—Stop editing the selected equation, unchanged
footnote—Insert a footnote
footnote.next, footnote.previous—Go to the next or previous footnote
footnote.show—Go to the footnotes
toc.insert, toc.update, toc.remove—Table of contents
caption{ text, label?: "Figure" | "Table" | "Equation", position?: "above" | "below" }Caption the picture or table
crossReference{ kind, id? }Insert a cross-reference
tableOfFigures"Figure", "Table" or "Equation"Insert a table of figures
tableOfFigures.update—Update every table of figures

Review#

CommandValueWhat it does
comment.new—Comment on the selection
comment.focusidGo to a comment and make it the active one
comment.edit{ id, text }Change a comment
comment.deleteoptional idDelete a comment (the active or last one without an id)
find{ query, matchCase?, wholeWord? }Find and highlight matches (state.findCount)
replace{ query, replacement, all?, matchCase?, wholeWord? }Replace the next match, or all
find.next, find.previous—The next or previous match (state.findIndex)
find.clear—Remove the matches' highlighting
readAloud—Read the document aloud. On while reading
spellcheck—Underline spelling mistakes. On while shown
authornameThe name on new comments
dictate—Type by voice. On while listening

Editing and view#

CommandValueWhat it does
undo, redo—Undo and redo (state.canUndo, state.canRedo)
selectAll, selectNone—Select all, clear the selection
viewingoptional true / falseViewing (read only, by choice) or Editing; toggles without a value. Choosing Editing never makes an unlicensed editor editable
zoompercent (10–500)Zoom
zoom.pageWidth—Zoom so the page fills the width
readingView—Reading view. On while shown
darkPage—Show the page dark (the saved file is unchanged). On while dark

Page#

CommandValueWhat it does
page.margins{ top, right, bottom, left } (inches)Margins
page.orientation"portrait" or "landscape"Orientation
page.size{ width, height } (inches)Page size
pageNumbersa position ("none", "left", "center", "right"), or { position, withTotal?, where? }Page numbers; withTotal writes "Page X of Y", where is "header" or "footer" (the footer by default)
header.edit, footer.edit—Start editing the header or footer (as double-clicking the margin does). On while editing it
headerFooter.close—Back to the body
header.remove, footer.remove—Remove the header or footer

Files#

CommandValueWhat it does
file.new"blank", "report" or "letter"A new document
file.openoptional Blob or ArrayBufferOpen a .docx (or web page, text, Markdown); file picker without one
file.save—Save (the Save button, Ctrl+S): to your store with the onSave option, otherwise as file.saveDocx
file.saveDocx—Save a copy as .docx (through Dorvyn's export service; needs a license that includes export)
file.saveHtml, file.saveText—Save as a web page or plain text
print—Print (or save as PDF from the print dialog)
file.discardDraft—Forget the draft kept in this browser
file.renamenameRename the document (state.fileName)

What the interface keeps to itself#

A few things in Dorvyn's interface are about the interface, not the document, so there are no commands for them: which menu, dialog or pane is open, the text being typed into a dialog's fields (the commands take the finished values), the ribbon's layout and collapsing, focus mode, the light or dark theme, and the accent colour. Your interface has its own versions of these.