The dirty ranges ride the plugin state and are mapped through every transaction; the check after a pause swaps only those textblocks' squiggles, and the whole document is checked on a language or dictionary change. The pause after a keystroke in a 124-page document drops from 363 ms to 11 ms (Chromium) and from 1.4 s to 17 ms (Firefox). A unit test drives the recheck; the dom run asserts the pause is free.
24 KiB
src/lib/editor/extensions/
One file per feature (image.ts, indent.ts, …), never XyzExtension.ts. All are assembled in
../extensions.ts, which also lists the TipTap built-ins in use (Bold, Italic, Highlight
multicolor, TextStyle/FontFamily/FontSize, Heading, HardBreak, lists, Table family, History,
Placeholder, TextAlign). Document is widened to '(block | textBox | columns)+ noteSection?'.
Five topics are large enough to have their own deep-dive — read the file before changing them:
| Extension | Deep-dive |
|---|---|
pageBreaks.ts, columns.ts, columnsFlow.ts |
docs/architecture/pagination.md |
image.ts, textBox.ts |
docs/architecture/frames.md |
table*.ts, tableStyle.ts |
docs/architecture/tables.md |
textEffects.ts, indent.ts, tabStops.ts, listMarker.ts, paragraphBox.ts, dateTimeField.ts, bookmark.ts, crossReference.ts |
docs/architecture/formatting.md |
formula.ts |
docs/architecture/formulas.md |
notes.ts |
docs/architecture/notes.md |
paragraphStyle.ts, characterStyle.ts |
src/lib/styles/CLAUDE.md |
The rest, one line each
fontColor.ts(FontColor) —colorattr on the TextStyle mark; also emitsdata-colorso theme CSS (allBlack) can target color-bearing spans.fontWeight.ts(FontWeight) —fontWeightattr on TextStyle (setnormalto un-bold a heading without changing the node type). A parsed weight Bold already claims (bold/bolder/500+) is dropped: both files spell a run's weight as bold or not, so the attr would only repeat the mark and be lost on save.fontFamily.ts(FontFamily) — TipTap's, with a parse that keeps the first family of a value. A contenteditable types over a mixed selection by inserting a span carrying the computed style, so an unguarded parse lands a whole CSS stack (Arial, "Liberation Sans", sans-serif) as the font name — no name the picker or either file can use. A paste from the web arrives the same way.lineHeight.ts(LineHeight) —lineHeightattr on paragraph/heading.LINE_HEIGHT_RATIO = 1.15: ODF line spacing multiplies the font's natural line height (Liberation Serif ≈1.15× em), CSS multiplies the font size — so the on-screen value is scaled to match what LibreOffice renders. A spacing above single puts all of its extra leading below each line (probed: at 150% LibreOffice starts line 1 flush under the block above and adds 6.9pt after every line, the last included); CSS half-leads it, soeditor.cssshifts the block up by that half withposition:relative; top:, which leaves the flow alone — butoffsetTopreports the drawn position, not the flow one, sopageBreaks.ts(topWithin) takes the shift back off; without that a block pushed to a page top landed half a leading low.paragraphSpacing.ts(ParagraphSpacing) —spaceBefore/spaceAfterin pt, round-tripping 1:1 tofo:margin-top/fo:margin-bottom. Space after is a margin, space before rides--space-before(storage/spacingModel.tsdecides padding vs margin); pageBreaks.ts drops it where a page break put the block at a page top, as LibreOffice does. Both also ride--space-after/--space-beforesoeditor.csscan swap the pair inside a multi-column section: there the space above is the margin and the space below the padding, because every engine truncates a margin at a column break but keeps padding — so each column starts level (as LibreOffice draws it) and the add model's two spacings still sum. A named style's border padding yields to that swap.blockFontSize.ts— the font of the paragraph mark (Wordw:pPr/w:rPr, ODF the paragraph's own text properties).pageBreak.ts— the text-flow attrs of a paragraph/heading:breakBefore: 'page', pluskeepNext/keepLines(seedocs/architecture/pagination.md). OwnsMod-Enter. A plugin sweepsbreakBeforeoff every block whose ancestors are not all doc/columns/list: inside a table cell, a frame or a note body both formats drop it (probed), so keeping one would be a break that vanishes on save.textDirection.ts— a block's own base direction (dirattr; ODFstyle:writing-mode, Wordw:bidi), overriding the page's (storage/writingMode.ts). The HTMLdiris the whole rendering — it resolves the bidi run order andtext-align: startfollows it, so an unaligned block flips. Both importers suppress the direction the page already has: it is inheritance, not formatting. Set inParagraphDialog.svelte, where LibreOffice keeps it.formattingMarks.ts(FormattingMarks) — decorations marking spaces (·) and tabs (→) when.paper.show-formatting-marksis set.bulletList.ts/orderedList.ts— the TipTap lists plus a marker-type attr:setBulletChar(innermost list,null= default cycle) and the ordered numbering cycle (utils/orderedListTypes.ts, multilevel targets the outermost list).listStyle.ts— the named list style (listStyleNameon the outermost list; nested lists inherit) and the walk resolving every list's effective marker (data-eff-list-style,data-bullet+--bullet, indent, label alignment) from node attr > style level > depth cycle — the style level decides the depth's kind, so a number level numbers a<ul>(counter-offset viacounter-reset, since<ul>ignoresstart);setListStyleassigns (clearing the subtree's direct marker attrs and retyping each list to its level's kind),listStyleNameAtfeeds the dropdowns — seesrc/lib/styles/CLAUDE.md.link.ts— hyperlink mark; ownsMod-k, which fires the eventToolbar.sveltelistens for to open the link dialog. A#namehref targets a bookmark:Editor.svelte'shandleClickscrolls to it instead of opening a tab. Theplainattr (data-plain,editor.css) suppresses the editor's own blue: Word paints a link through its Hyperlink character style, which arrives as an ordinary mark, so every DOCX link is plain and one carrying no style is drawn like the text around it — while LibreOffice paints every ODFtext:astyled or not (probed), so those never are. The DOCX exporter paints#0563C1only on a non-plain link, which is how a round trip tells its own links from a file's.comment.ts— an annotation on a range of text, a mark likebookmark: the whole comment (author, date, body, resolved) rides its attrs, so two runs of one comment merge back together and no second store is needed.commentRanges(doc)walks every range (an id split by a paragraph boundary yields several, which is why the commands walk all of them),comments(doc)keeps one per id forCommentsPane.svelte. A point comment — LibreOffice's, made with nothing selected, written with nooffice:nameand no end element — attaches on import to the run before it, else the one after: the editor's comment is a mark and needs a range. A comment carries its thread in the same attrs (replies, one entry per answer, appended byreplyToComment): ODF gives an answer its ownoffice:annotationnaming its comment inloext:parent-name(probed) and Word its ownw:commenttied byw15:paraIdParentin commentsExtended.xml, so both importers fold the answers back into the comment they belong to instead of listing them beside it.commentIdAt(state)is the comment the selection lies within, which a plugin tints heavier (pm-comment-active, skipping a resolved one) andCommentsPane.svelte,ChangeBarLayer.svelteandConnectorLayer.svelteeach mark their own half of. It compares ranges, not the marks at the caret: the mark is non-inclusive, so$pos.marks()is empty at either end of it — and a click on the pane's card selects exactly that range, which would then match nothing.trackChanges.ts— theinsertion/deletionmarks plus the recording plugin.appendTransactionmarks whatever a transaction added, andadjacentInsertionreuses the id of the run just before it when the author matches, so a typed sentence is one change and not one per keystroke. A delete never reaches the document:filterTransactionrejects it and dispatches a mark pass instead (the author's own pending insertion is removed for real, as both word processors do). A replacement — typing or pasting over a selection — goes the same way (replacedRange), the new content landing after the struck-out text it replaces; recorded as the insertion alone, its other half was simply dropped and a reject lost the original. Every transaction of our own carries theRECORDINGmeta — accept/reject included, or itstr.deletewould be read as a fresh user deletion and marked up again. Loading a document carries it too (App.svelte'sloadContent, both for a new document and for an import): asetContentis one transaction that inserts the whole file, so without the meta an opened document arrives wholly marked as the reader's own insertion, underlined in the author colour. Both word processors record what is typed after an open, never the file.revisions(doc)merges adjacent runs of one id, so an export writes one change per id. The author's colour is a decoration, not the mark: a mark cannot know the document's other authors, so a plugin walks the revisions, hands outREVISION_AUTHOR_COLORS(LibreOffice's own author palette) in order of first appearance and paintspm-rev-ins/-del+pm-rev-a<n>. That span nests inside the mark's, so it carries the underline/strikethrough too — drawn by the ancestor it would take the fallback colour. Cached on the doc; the walk is the whole document anddecorationsruns on every view update. Theplainoption (fromstorage/markup) drops the decoration entirely where the display mode shows a finished text — and it is part of the cache key, or the set built before the switch would stand.acceptRevision(id)/rejectRevision(id)apply every range of one change, which is whatRevisionsPane.sveltelists as one row.revisionIdAt(state)is the change the selection lies within — the row the pane marks and the margin barChangeBarLayer.sveltedraws heavier — compared by range for the same reasoncommentIdAtis.placeholderField.ts— a template placeholder, an inline atom drawn gray as ‹label›: a click selects the whole field (NodeSelection) and typing replaces it; Tab/Shift-Tab from a selected field jump to the next/previous one. Round-trips to ODF<text:placeholder>and a tagged DOCXw:sdtcontent control.caption.ts— a caption is an ordinary paragraph in theCaptionstyle (LibreOffice's, probed: 10pt italic, 0.212cm above and below) holding onesequenceFieldatom, its running number.sequenceFields(doc)counts one counter per category in document order; the cachednumberattr is what an export writes, and anappendTransaction(off the undo stack) plus anonCreatepass keep it true — a file's own cached numbers are unreadable wherever the format is not arabic. The counter's name differs per format: ODFIllustration/Table, WordFigure/Table, andODF_SEQ_CATEGORYreads both back. The caption paragraph is boxed to the frame it captions (captionPlacement), so it stands under the picture instead of at the margin: LibreOffice frames picture and caption together, and a loose paragraph carries that over asindent/indentRight— the frame's own span in the column, measured (frameSpanCm), since that span comes from the wrap, the offset and the column, not from one attr. The indent is also what lifts the caption clear of a side-wrapped frame: a line with no room beside a float drops below it. It is centred in that box only under a frame that is itself centred; a block with no frame at all has only its own alignment to pass on.getFrameDebugreports the same two spans for the debug dump.CaptionDialog.svelte(References tab) owns the insert.ruby.ts— a reading printed over its base (LibreOffice's Format ▸ Asian Phonetic Guide, Word's Phonetic Guide). An inline atom carrying both halves, because that is what both formats write: one element holding a base and a reading, edited as a unit (RubyDialog.svelte). Rendered as a real<ruby>, so the browser sets it. Alignment and position are both products' defaults and are not offered.bookmark.ts/crossReference.ts— a named range of text (a mark) and the live references to it (REF/PAGEREF).ToolbarExpanded.svelteowns both dialogs, as it does the link one.searchReplace.ts— Find & Replace: decorations highlight all matches, commands navigate/replace. Touches the document only for actual replacements.useRegextakes the term as a pattern instead of escaping it (a whole-word search then wraps it in a non-capturing group first, so the\bguards bound the alternation); each match keeps its captures soexpandGroupscan fill$1…$9/$&in the replacement. AFormatSpec(weight/slant/underline, font, size and colour — LibreOffice's Format… — plus a paragraph style, its Paragraph Styles box) narrows a text search to the runs carrying it, and with no term is the search: every such run, or every paragraph in the style, empty ones included. The same spec on the replacement applies it — and a replacement with no text keeps the text and only reformats, which is how both dialogs restyle a document without retyping it. A style also switches the node type, assetParagraphStyledoes, so the extension takes the samesheetoption. Font, size and colour live together on one TextStyle mark, and a mark of one type replaces that type whole, so each run's own attrs are the base of the new one — replacing the colour leaves the font alone. Sizes compare by value (12pt and 12.0pt are one size), colours and family names case-insensitively.spellCheck.ts— decorations fromspell/controller.ts;spellErrorAtfeeds the context menu,wordRangeAtthe thesaurus (the word at a position, misspelled or not). Both define a word the same way, so what is looked up is what is highlighted. The check after a pause looks only at the textblocks edited since the last one (the dirty ranges ride the plugin state, mapped through every transaction) and swaps their squiggles in the set; the whole document is checked on a language or dictionary change. Building the whole set walks every block for every squiggle, seconds on a long document.outline.ts— the document's chapters forNavigatorPane.svelte: every top-level heading owning the blocks up to the next heading of its level or above (one inside a cell or a text box is not a chapter — moving it would move it out of its container). The two operations are pure functions the commands only apply:chapterMovereturns the range to lift and where to put it back — the insert position for a move down is already corrected for the delete — andchapterLevelsthe headings a promote/demote rewrites, null when any of the subtree would leave 1…maxLevel. A move swaps with the adjacent chapter at the same level and stops at a heading above it, so a subheading never reparents itself; the level shift rewritesstyleNametoo, or the paragraph would keep the old heading's look.indexEntry.ts— one place marked for the alphabetical index: an inline atom, not a mark, because that is what both formats write (a pointtext:alphabetical-index-mark, a WordXEfield). It carries the term, so the marked text and the word the index lists can differ, pluskey1for the heading it files under.indexRowsmerges the marks into the index's rows — one per term, its pages de-duplicated and sorted, the terms sorted case-insensitively by locale.bibliographyEntry.ts— one citation, an inline atom carrying the whole source record (identifier,type, and every remaining ODF field in onefieldsrecord, so a file's fields we have no UI for still round-trip). ODF puts that record on the mark itself, which is what lets the document travel without a database; Word keeps it in a custom-XML part and cites it by tag, so the same attrs feed both. The citation style (utils/citationStyle.ts— LibreOffice's cite-by-key, numbered, APA, MLA, Chicago) rides the bibliography index's node, which is where both formats keep it: a row is a token list, exactly what an ODF entry template is, so LibreOffice regenerates the same rows (it fills the types the document does not cite with its own default, so the import takes the first template reading as anything butkey). Word gets the style asb:Sources StyleName. Each citation's label is derived, kept true by anappendTransactionoff the undo stack like the caption numbers.bibliographyRowsis the list: one row per source, in document order — LibreOffice's own default is document position, not alphabetical — reading "key: author, title, year", the shape its entry templates produce.DOCX_SOURCE_TYPE/DOCX_BIB_FIELDmap onto Word's smaller set, and the fields it has no slot for survive only the ODF leg.tableOfContents.ts— a generated index. Theindexattr picks the family:toclists every heading down tomaxLevel(ODFtext:outline-level, Word'sTOC \orange, default 5 — listing deeper than the file asks inflates the block by pages).title: ''is an index that deliberately has none (its heading is a separate paragraph, as Word and LibreOffice write it); only a missing title falls back to "Table of Contents".levelStylesis the named paragraph style each level's entries use (ODF's per-level entry template, which is what LibreOffice regenerates from — the cached body paragraphs point at automatic styles derived from it): the rows carry it asdata-style, so the document stylesheet gives them the file's own indent, space-before and font, andeditor.css's 0.5cm-per-level fallback applies only to an index that names none.figures/tablesinstead list every caption paragraph counting that category (caption.ts), single-level as LibreOffice's are — ODFtext:illustration-index/text:table-index(found bytext:caption-sequence-name, not by outline level), Word the same TOC field with\c "Figure".bibliographylists the sources cited (bibliographyEntry.ts) and is the one family that never has a page number or a leader — a bibliography row is the source and nothing else, which is how both word processors print one. Any other family drops both where the file says so (pageNumbers: false— Word'sTOC \n, an ODF entry template naming no<text:index-entry-page-number/>; the export writes the stop out with the number, which is the pair LibreOffice's own dialog switches together).trailingNode.ts— keeps an empty paragraph after a trailing table, text box or columns section (they are isolating, so the caret would otherwise have nowhere to go). Also the trap at the start: Enter at the very first position of a table with nothing before it inserts a paragraph above and moves the caret there.headerFooter.ts(hfExtensions) — the header/footer schema:Documentconstrained to one paragraph, the body's marks,HardBreak,TextAlign, and thepageField.tsatoms. No image, no date field, no table.pageField.ts— inline atomspageNumber/pageCount/chapterField, rendered as<span data-page-field>;HeaderFooterLayer.sveltepatches each span's text to the real per-page value.chapterFieldis the running head (ODFtext:chapter, WordSTYLEREF): itslevelis the outline level to show,textthe file's cached name. The page's chapter follows LibreOffice (probed): a header shows the one in force at the page's top (a heading counts once it opens a page — theatTopbit), a footer the last one begun on the page (Editor.sveltecollects the heading→page map on each pagination pass, only when a zone shows one).autoCorrect.ts— AutoCorrect while typing (LibreOffice's Tools ▸ AutoCorrect Options): typographic quotes per document language, its dash matrix, its replacement table, sentence capitalization and TWo INitials. OnehandleTextInputplugin, listed last inextensions.tsso every input rule (list markers, the rule line) still fires first;autoCorrectFix(before, opts, lang)is pure — the whole table istests/unit/autocorrect.test.ts. URL recognition and auto-list are TipTap's own (Link autolink— gated by the same options — and the list input rules).wordCompletion.ts— LibreOffice's Word Completion (its AutoCorrect dialog's own tab): every word of at leastminLengthletters is collected as it is finished, and typing its first three letters offers the rest. Drawn as a widget decoration after the caret, not LibreOffice's tooltip and not its selected-text insert — the offer is outside the document until Enter takes it, so nothing has to be undone when it is not. Only while typing: the offer is dropped on a bare caret move, or an Enter meant to split the paragraph would complete a word instead.priority: 1000, so itshandleKeyDownsees Enter ahead of the keymaps. The list and its settings live instorage/wordCompletion.svelte.ts, the collection and matching rules inutils/wordCompletion.ts.autoText.ts— LibreOffice's AutoText / Word's Quick Parts: a named block of text, inserted from the library (AutoTextDialog.svelte) or by typing its shortcut and pressing F3, which is both products' key for it — and which the app also binds to find-next: the editor sees the key first, so it expands a shortcut where the caret has one and leaves the key alone otherwise (App.svelte's window handler returns ondefaultPrevented). An entry is stored as the nodes themselves (Fragment.toJSON()), so it keeps a text box: in an HTML string any block tag inside a<p>closes it, and the box holds blocks. An entry written before that keeps its HTML string, whichinsertContenttakes just as well. The library belongs to the app, not to a document (storage/autoText.svelte.ts) — as it does in both products, which keep it in a template of their own; nothing about it reaches a saved file.shortcuts.ts— seesrc/lib/editor/CLAUDE.md.
extensions.ts deliberately keeps TipTap's resizable: false (its columnResizing plugin stays
unloaded) and supplies the custom table view + drag plugins instead.
What a command refuses, and why (found by tests/monkey/): no note in a text box and no
text box in a note (neither format holds one there); no table in a table, a list item or a
note (nothing exports a nested one, ODF's list item holds no table, and ProseMirror would
wrap one in a text box to fit a note's inline content) — and a cell's content expression
says the same (CELL_CONTENT, extensions.ts), since a command's refusal is not the only
way one gets in; a selection stops at the notes' boundary (clampToSide); the notes
plugin's repairs ride the history event they follow. An anchor that lands where a note
cannot live — inside a note, or inside a text box, which a list toggle can pull one into —
is dropped by strayRefs, and its note goes with it: Word writes no note in a shape's
text, so the .docx lost both silently.
Blocks wrapped into a columns section lose a manual page break: pagination breaks a
fragment as a whole, so nothing there honours one — and only DOCX could write it.
What the schema refuses (same source): subscript and superscript exclude each other —
no run is raised and lowered at once, and a file keeps only whichever it writes last; a
noteRef takes no marks at all, since ODF's text:note-citation holds bare text (no span, no
style name) and the anchor wears its note class's look anyway. A list item's paragraph keeps
no indent of its own — the indent commands already refuse to set one, a list indents by nesting,
and neither importer reads one there — so indent.ts clears the three indent attrs whenever a
transaction leaves one inside a listItem (wrapping an indented paragraph into a list is the
usual door). A table's first row is all header cells or none: both formats spell a
repeating header as the whole row, and typing over a selection spanning two of them left
one behind (tableHeaderRow.ts) — the promotion carries the cell's own attrs, since
setNodeMarkup given a type and no attrs takes the type's defaults. A replace reaching
into a table rebuilds the cell it lands in the same way, so tableColumnResize.ts reads
the lost column weight back from the column's other rows. A list item holds no table:
neither file keeps one there, and a list toggle over a table would wrap it in silently
(LIST_ITEM_CONTENT, extensions.ts).