Editing and formattingDocument
Paragraph styles, character formatting, lists, links, page breaks, symbols, the format painter and the exec command API of Birch UI Document Editor.
Everything the toolbar does is also available from code through exec(command, value?). It returns true when the command ran. canExec(command, value?) tells you whether it would run, and getFormatState() describes the selection so you can build your own toolbar.
editor.exec('paragraphStyle', 'Heading2');
editor.exec('bold');
editor.exec('fontSize', 14);
editor.exec('textColor', '#c00000');
const format = editor.getFormatState();
// { bold: true, italic: false, fontSize: 14, paragraphStyle: 'Heading2', align: 'left', bulletList: false, inTable: false, … }Commands act on the selection. Use setSelection(from, to?) and getSelection() to read or move it; positions are document positions: integers that count one token per character or leaf node and two per enclosing node, from the start of the document.
Paragraph styles#
| Style id | Word style | Notes |
|---|---|---|
Normal |
Normal | 11 pt, 8 pt after, 1.15 line spacing. |
Title, Subtitle |
Title, Subtitle | Kept with the next paragraph. |
Heading1 … Heading6 |
heading 1 … heading 6 | Appear in the navigation pane and the table of contents, kept with the next paragraph. |
Quote |
Quote | Centred, italic, indented. |
Code |
Code | Monospace, shaded, single spaced. |
Paragraph commands: paragraphStyle, align ('left' | 'center' | 'right' | 'justify'), alignLeft, alignCenter, alignRight, alignJustify, lineSpacing (a multiple such as 1.5), spaceBefore and spaceAfter (points), indent and outdent (36 pt steps, or list levels inside a list) and textDirection ('rtl' or 'ltr'). The ruler's markers set the left, right and first-line indents.
Character formatting#
bold, italic, underline, strike, superscript and subscript toggle. fontFamily, fontSize (points), textColor and highlight take a value; pass null to remove it. clearFormatting removes character formatting and resets the paragraph to Normal, keeping links, comments and tracked changes.
The fonts and sizes offered in the toolbar come from the fonts and fontSizes options. The document default font and size live in DocumentData.defaults and are read from DOCX files.
Format painter#
exec('formatPainter') (or the toolbar brush) copies the formatting of the text at the cursor, including its paragraph style, alignment and spacing. The next selection made with the mouse receives it. Press Escape to cancel.
Lists#
bulletList and orderedList toggle a list, or switch an existing list to the other kind. Tab and Shift+Tab move an item down and up a level, and Enter on an empty item ends the list. listStyle changes the marker: 'disc' | 'circle' | 'square' for bullets, 'decimal' | 'lowerAlpha' | 'upperAlpha' | 'lowerRoman' | 'upperRoman' for numbers. Lists export to Word numbering definitions, so nested levels and start numbers survive a round trip.
Links, breaks and symbols#
| Command | Value | Effect |
|---|---|---|
link |
URL | Links the selection, or inserts the URL as linked text. Ctrl+K opens the Insert link dialog for web, e-mail and in-document targets. |
unlink |
Removes the link at the cursor. | |
pageBreak |
Starts a new page (Ctrl+Enter). | |
hardBreak |
Line break inside a paragraph (Shift+Enter). | |
horizontalRule |
A full-width line. | |
insertSymbol, insertText |
text | Inserts text at the cursor. |
insertTableOfContents |
max level (1–6) | Inserts a table of contents built from the headings, with page numbers. |
updateTableOfContents |
Refreshes every table of contents. |
Find and replace#
Ctrl+F opens the find bar and Ctrl+H opens it with replace. Matching can be case sensitive, limited to whole words or use regular expressions; replacements in regular-expression mode understand $1, $& and $$.
editor.find('INV-(\\d+)', { regex: true, matchCase: true }); // { count: 2, current: 0 }
editor.findNext();
editor.replace('Invoice $1');
editor.replaceAll('Supplier', 'Contractor', { wholeWord: true }); // 14
editor.clearFind();Search starts at the cursor, like Word, and never matches across a picture or field.
wildcards: true reads the query as Word wildcards: ? is any character, * any run of characters, @ one or more of the previous item, [a-z] and [!a-z] are ranges, {2,4} a count, < and > the start and end of a word, and (…) groups that \1 to \9 use in the replacement. Wildcard searches are case sensitive, as in Word. format limits matches to text with the given formatting.
editor.find('INV-[0-9]{4}', { wildcards: true });
editor.replaceAll('(Priya) (Raman)', '\\2, \\1', { wildcards: true });
editor.find('Priya Raman', { format: { bold: true } });
editor.replaceAll('payment', 'settlement', { format: { styleId: 'Heading2' } });format accepts bold, italic, underline, strike and highlight (each true or false) and styleId. The find pane has the same choices as Use wildcards and Formatting.
Read-only and spellcheck#
readOnly: true (or setReadOnly(true)) keeps navigation, selection, find, comments panel and printing but blocks every edit. The browser's spellchecker is on by default; pass spellcheck: false to turn it off.
Your own spellchecker#
Pass a function instead of a boolean to check text with your own service or dictionary. It receives the text of one paragraph and the language, and returns the ranges that are wrong:
const editor = createDocumentEditor(host, {
spellcheck: async (text, language) => {
const response = await fetch('/api/spell', { method: 'POST', body: JSON.stringify({ text, language }) });
return response.json(); // [{ from: 8, to: 15, suggestions: ['receive'], message: 'Spelling' }]
},
});
await editor.checkSpelling(); // resolves when every paragraph was checked
editor.getSpellingIssues(); // [{ from, to, text, suggestions, message }] in document positions
editor.replaceSpelling(issue.from, 'receive');
editor.ignoreSpelling('Northwind');
editor.exec('spellingSuggestions'); // opens the menu for the word at the cursorReported words get a wavy underline. A right click on one (or the context-menu key with the cursor inside it) opens the suggestions and Ignore. Only paragraphs that changed are sent again, one at a time, 300 ms after the last edit. The browser's own spellchecker is switched off while a function is set. The editor ships no dictionary.
Typing in other scripts, drag and drop and the clipboard#
- Input methods. Composition (Japanese, Chinese, Korean and dead keys) happens in place; with track changes on, the committed text becomes one tracked insertion. This is tested in Chrome by driving the composition through the DevTools protocol.
- Drag and drop. Selected text can be dragged to another place, and a picture file dropped on the page becomes an image.
- Clipboard. Copying puts semantic HTML on the clipboard (headings, bold, tables), which Word and other editors read; pasting it back keeps the styles and tables.
Pasting from Word and Google Docs#
Clipboard HTML from another application is parsed with DOMParser in an inert document and rebuilt from that tree, so scripts, event handlers and pictures in the clipboard never run or load, and nothing is assigned to the page. Only the fragment the source marked as copied is used.
| In the clipboard | In the document |
|---|---|
Word list paragraphs (mso-list:l0 level2 lfo1) |
Nested bulleted and numbered lists. The number format (decimal, lower or upper letters, lower or upper roman) comes from Word's list definitions, the start value from the first number shown, and disc, circle and square bullets from the bullet glyph. Word's marker text is dropped. |
| Google Docs lists | Nested lists. Google Docs writes a sub-list beside its parent item; it is moved into the item, and list-style-type on the items sets the bullet or number format. |
| Tables | Kept with colspan and rowspan, so merged cells stay merged. |
Word tracked changes (<ins>, <del>, span.msoIns, span.msoDel) |
With Keep source formatting: tracked insertions and deletions carrying the author and time Word recorded, which you can accept or reject. With Merge formatting: resolved, so inserted text is kept and deleted text is dropped. Keep text only and Picture use the plain text the source put on the clipboard; pasteHtml(html, 'textOnly') resolves the changes the same way. |
| Word comments | The comment anchors and the comment list are removed; the commented text stays. Comments are not imported by a paste; open the .docx file to keep them. |
Pictures with a file:// source (Word writes v:imagedata and an img pointing at a temporary file) |
An empty picture that keeps the alternative text and size. No request is made. resolvePastedImage can supply the picture. |
Pictures with an http(s) source (Google Docs) |
A remote picture, shown only with allowRemoteImages or resolveImage, like any other remote picture. |
| Links | http, https, mailto and tel links are kept. Links with another scheme, such as file://, are kept as text with a blocked address unless linkSchemes allows them. javascript:, vbscript: and data: links are removed and their text stays. |
A browser cannot read the file:// path that Word puts on the clipboard. Word also places the pictures in the RTF flavour of the same copy, and resolvePastedImage(src, context) is called once for each such picture so your application can supply it. Return a data:image/… URL, null, or a promise of either. A value returned directly is part of the paste; a promise fills the empty picture when it resolves, wherever the picture has moved to in the meantime, and does nothing when the picture was deleted. context holds source ('word', 'googleDocs' or 'other'), the index of the picture in the paste, its alt text, the clipboard html and rtf, and the clipboard files. rtf and files are empty when the paste came from pasteHtml or the Paste special dialog.
const pastedPictures = new Map<string, string>(); // file name -> data URL, filled by your RTF reader
const editor = createDocumentEditor(host, {
resolvePastedImage: (src, context) => {
if (context.source !== 'word' || !context.rtf) return null;
const fileName = src.slice(src.lastIndexOf('/') + 1); // clip_image002.png
return pastedPictures.get(fileName) ?? null;
},
});A copy that holds only a picture arrives as a clipboard file and is inserted through uploadImage or as a data: URL, as before.
Undo and redo#
undo(), redo(), canUndo() and canRedo() work on the editor's history; the historyChange event fires when either flag changes. Steps applied with applySteps() from collaborators are not added to the local history.