diff --git a/src/lib/export/CLAUDE.md b/src/lib/export/CLAUDE.md index 5d398a3..577f8ad 100644 --- a/src/lib/export/CLAUDE.md +++ b/src/lib/export/CLAUDE.md @@ -55,15 +55,18 @@ fallback download shows a one-time hint (`edentext-download-hint`) that the brow - **Bibliography** (`replaceBibEntries`/`applyBibEntries`, `applyBibliographyDocx`): a `BIB` sentinel becomes a `` whose attributes are the whole source record and which **wraps** the text the citation shows (unlike an index mark, which is a point). The `` index writes an entry template per type actually cited, spelling out the same "key: author, title, year" the node view prints — LibreOffice regenerates the rows from it, so a template that said anything else would rewrite them. DOCX cites by tag (`CITATION "key"`) and keeps the sources in a **custom-XML part** the `docx` package knows nothing about, so the post-pack pass mints all four pieces itself: `customXml/item1.xml` (`b:Sources`), its `itemProps1.xml`, both relationships and the properties part's content type. (Probed: LibreOffice's own DOCX export writes the `CITATION` field but no sources at all.) - **Ruby** (`replaceRuby`/`applyRuby`, `applyRubyDocx`): an `RBY` sentinel becomes a `` holding both halves plus one minted `style:family="ruby"` automatic style (centred, above — probed: LibreOffice writes that style straight back out, adding only its own `loext:` mirror of the position). Word's is a `` run the `docx` package cannot emit, so a post-pack pass swaps the sentinel run for it; the `w:rubyPr` sizes are half-points of the 12pt body default, which is what LibreOffice's own export writes. - **Cell formulas** (`applyCellFormulas`, `formulaCellContent`): ODF puts the formula on the **cell**, so the pass walks ``. They are re-emitted at the item's end (after a nested list, which is where they usually belong) wearing the item's own paragraph style. DOCX needs none of it: `listToParagraphs` writes the extras as unnumbered paragraphs at the item's indent, which is Word's own shape. +- **`mergeListItemBlocks`/`applyListItemBlocks`** — odf-kit writes a list item's **first paragraph only**, so the item's further blocks ride it `SEG`-separated and the pass splits them back out inside the same ``. They are re-emitted at the item's end (after a nested list, which is where they usually belong) wearing the item's own paragraph style — or a minted `LX#` under it where the extra carries alignment/spacing/line-height/box of its own (collected from the tree *before* `mergeListItemBlocks`, which is what folded them in). A heading extra goes back out as `` under its level's style, which is what ODF holds in a list item. DOCX needs none of it: `listToParagraphs` writes the extras as unnumbered paragraphs at the item's indent, which is Word's own shape. - **`applyTableHeaderRows`** — `` around the first row when the table asks for the repeat **or** that row's cells are header cells: ODF spells both with the one element, as `w:tblHeader` does, so a header row reads back as one (and as repeating, in both formats). -- **`applyListItemStyles`** — per-item alignment/spacing/line-height for top-level lists (odf-kit's ListBuilder has no per-item options) via minted automatic styles. +- **`applyListItemStyles`** — per-item alignment/spacing/line-height for top-level lists (odf-kit's ListBuilder has no per-item options) via minted automatic styles. It runs **after** `applyListItemBlocks`, so an extra block's own style parents to the item's list style rather than to the `LP#` minted here. Both take their descriptors in list-item order, and `collectListItemStyles` therefore skips tables: a cell's list is still `SEG`-segmented text at this point (`applyCellBlocks` rebuilds it later), so counting its items would shift every body item's style. A **page break** before an item rides here too: `replacePageBreaks` is top-level only (its PGB sentinel would corrupt the `SEG` rebuild), and LibreOffice keeps `fo:break-before` on a list item's paragraph (probed). - **`applyListIndents`** — a top-level list's whole-list `indent` (cm) added to its `L#` list-style per-level `fo:margin-left`/`text:list-tab-stop-position` (label-alignment mode ignores the paragraph margin, so the shift must live in the list style). Import reverses it in `convertList` (level-1 margin minus the 1.27cm base). - **`applyNestedListTypes`** — odf-kit emits nested lists as bare `` sharing the top-level list style, so a nested list of a different kind/format (e.g. ordered inside bullets) gets its own minted 6-level list style. - **`applyListStyleNames`** — a list carrying an unoverridden `listStyleName` is repointed from its `L#` automatic style to the named `` `applyNamedStyles` writes into styles.xml (its nested lists stay bare and inherit); runs after every `L#`-keyed pass. The list collectors resolve attrs through `effectiveListLevel`, so an overridden styled list keeps a fully resolved `L#` clone; `applyListLevelKinds` runs first and switches an `L#` level element's species where the style's level kind differs from the node's (a `
    ` depth the style numbers), format/char baked in — see `src/lib/styles/CLAUDE.md`. **DOCX**: `Numbering.refForStyle` shares one abstract per style (each list its own `w:num` instance, so numbering restarts) and `applyListStylesDocx` injects the `w:styleLink` + the `w:type="numbering"` style's real numId post-pack — the library can express neither. A list with a `start` attr keeps a private clone (the shared abstract starts every instance at the style's start). Probed: LibreOffice ignores DOCX numbering styles both ways (its import mints `WWNum#`, its export flattens to the look) — the identity is a Word capability; ODF carries it in both products. - **`applyListStartValues`** — odf-kit drops an ordered list's `start` attr; a Word list continued across an intervening paragraph (same numId, split into separate `orderedList` nodes with `start` > 1 by the importer) gets `text:start-value` on its first `` so numbering keeps counting instead of restarting at 1. - **`applyTableRowHeights`** — dragged row heights → `style:min-row-height` automatic table-row styles. - **`collapseRunWhitespace`** — strips the bare `\n` separators odf-kit inserts between runs inside a paragraph (they'd otherwise collapse to spurious spaces mid-word). +- **A field's cached run carries its formatting.** `SimpleField` writes a bare `TextRun` for the cached value, so a `STYLEREF` running head or an auto date field lost its own marks; `StyledField` pushes the run with them instead. +- **A sentinel pass must cover the note parts.** A footnote's or endnote's text is its own package part, so a post-pack pass that only rewrote `word/document.xml` left the sentinel standing there — a formula in a note read back as its index, a ruby as its base. `NOTE_BEARING_PARTS` is the list the formula and ruby passes walk (`docx.ts`). +- **Vertical margins travel in pairs.** LibreOffice reads a style declaring only one of `fo:margin-top`/`fo:margin-bottom` as resetting the other to the *default* style's, not the parent's (probed: re-saving a `Heading_20_2` automatic style with only `fo:margin-top` comes back with `fo:margin-bottom="0cm"`). So `pairMargins` writes the named style's partner out beside a block whose spacing is direct formatting — top-level and in a table cell, where a heading keeps its level's margins — and `ownStyleAttrs` does the same for a named style — otherwise setting a heading's space-before silently zeroes its space-after. - **`rewriteStylesXml`** — `style:page-usage="mirrored"` on the page layout when the margins mirror (the left/right pair is already the inner/outer one), default font Liberation Serif → Times New Roman, heading sizes/margins → the editor's values, Standard's `fo:margin-bottom` → 0 (odf-kit emits 0.212cm; every paragraph and list item inherits it, and the editor has no paragraph spacing — see below). - **`normalizeColor`** — coerces colors to `#RRGGBB` (ODF requirement; rejects/normalizes `rgb()` and short hex). - **Schema conformance** (guarded by `tests/schema-validation.test.ts`; LibreOffice forgives all of this, Word's strict reader does not): `applyOdfVersion` stamps every ODF part **1.3** — the version LibreOffice writes, and the first with `style:header-first` — over odf-kit's 1.2. `draw:image` carries the `xlink:type/show/actuate` trio (`xlink:type` is mandatory beside `xlink:href`); `text:time-value` is an xsd dateTime, never a `PT…S` duration (the ODT importer still reads the legacy duration); `index-entry-link-start/-end` only in TOC entry templates; `text:dont-balance-text-columns` on `style:section-properties`. DOCX: `orderDocxSettings` (last pass) re-sorts `w:settings` children into the fixed CT_Settings sequence the prepend-passes scramble; `w14:paraId` in comments.xml requires `mc:Ignorable="w14"` on the root. `w:numPr` sits after the keep flags in a heading style's `w:pPr`, and `w:pBdr` sides are re-sorted post-pack (`orderParagraphBorders`: the library writes top, bottom, left, right). `tests/package-lint.test.ts` guards the invariants the schemas cannot express (unique style ids, no dangling style/num/rel references, balanced ranges, manifest completeness). diff --git a/src/lib/export/docx.ts b/src/lib/export/docx.ts index 1953325..a23d904 100644 --- a/src/lib/export/docx.ts +++ b/src/lib/export/docx.ts @@ -604,12 +604,20 @@ function dateTimeFieldParts(node: TiptapNode): { fixed: boolean; instr: string; }; } +// SimpleField's own cached run is a bare TextRun, so a field carrying marks would lose +// its look; this pushes the run with the marks' props instead. +class StyledField extends SimpleField { + constructor(instruction: string, cachedValue: string, marks: TiptapNode['marks']) { + super(instruction); + this.addChildElement(new TextRun({ text: cachedValue, ...runPropsFromMarks(marks) })); + } +} + function dateTimeRun(node: TiptapNode): Inline { const { fixed, instr, text } = dateTimeFieldParts(node); - // A fixed field is a plain run, so carry its font/size/etc.; SimpleField takes no - // run props, so an auto field inherits the paragraph font (Word recomputes it). + // A fixed field is a plain run — Word has no fixed-date field. if (fixed) return new TextRun({ text, ...runPropsFromMarks(node.marks) }); - return new SimpleField(instr, text); + return new StyledField(instr, text, node.marks); } // The XE field instruction; a literal quote is backslash-escaped, as Word writes it, @@ -753,7 +761,7 @@ function inlineToRuns(content: TiptapNode[] = [], force: TextProps = {}): Inline // Word's running head: STYLEREF picks the heading of that level in force on the // page. The numeric form means outline level; a style name would be looked up // localized ("Heading 1" errors in a German Word, which wants "Überschrift 1"). - out.push(new SimpleField(`STYLEREF ${Number(node.attrs?.level) || 1} \\* MERGEFORMAT`, String(node.attrs?.text ?? ''))); + out.push(new StyledField(`STYLEREF ${Number(node.attrs?.level) || 1} \\* MERGEFORMAT`, String(node.attrs?.text ?? ''), node.marks)); } else if (node.type === 'dateTimeField') { out.push(dateTimeRun(node)); } else if (node.type === 'sequenceField') { @@ -1607,28 +1615,30 @@ function applyBibliographyDocx(bytes: Uint8Array, sources: BibSource[], cite: Ci return zipSync(out); } -// Post-pack pass: swap each sentinel run in word/document.xml for its . A -// display formula additionally wraps its paragraph's content in , which -// is how Word centers a formula on its own line. +// The parts a body run can land in: a note's text is its own part, so a sentinel pass +// that only rewrote document.xml would leave the sentinel standing in a note. +const NOTE_BEARING_PARTS = ['word/document.xml', 'word/footnotes.xml', 'word/endnotes.xml']; + +// Post-pack pass: swap each sentinel run for its . A display formula +// additionally wraps its paragraph's content in , which is how Word +// centers a formula on its own line. function applyFormulasDocx(bytes: Uint8Array, formulas: FormulaDocx[]): Uint8Array { if (!formulas.length) return bytes; const files = unzipSync(bytes); - const docBytes = files['word/document.xml']; - if (!docBytes) return bytes; - let xml = strFromU8(docBytes); // Tempered pattern: the match stays inside the one run that holds the sentinel — it // may cross neither nor a nested (a box's drawing run wraps whole // paragraphs, so matching from it would swallow the box preamble). - xml = xml.replace( - new RegExp(`]*?>(?:(?!])[\\s\\S])*?${MTH}(\\d+)${MTH}(?:(?!])[\\s\\S])*?`, 'g'), - (_m, idx: string) => { + const pattern = new RegExp(`]*?>(?:(?!])[\\s\\S])*?${MTH}(\\d+)${MTH}(?:(?!])[\\s\\S])*?`, 'g'); + for (const part of NOTE_BEARING_PARTS) { + const partBytes = files[part]; + if (!partBytes) continue; + files[part] = strToU8(strFromU8(partBytes).replace(pattern, (_m, idx: string) => { const f = formulas[Number(idx)]; if (!f) return ''; const omath = ommlDocument(parseLatex(f.latex)); return f.display ? `${omath}` : omath; - }, - ); - files['word/document.xml'] = strToU8(xml); + })); + } const out: Record = {}; for (const [path, data] of Object.entries(files)) out[path] = [data, { level: 6 }]; return zipSync(out); @@ -1640,13 +1650,10 @@ function applyFormulasDocx(bytes: Uint8Array, formulas: FormulaDocx[]): Uint8Arr function applyRubyDocx(bytes: Uint8Array, rubies: RubyDocx[]): Uint8Array { if (!rubies.length) return bytes; const files = unzipSync(bytes); - const docBytes = files['word/document.xml']; - if (!docBytes) return bytes; - let xml = strFromU8(docBytes); // Tempered like the formula pass: crossing a nested would let a match starting // at a box's drawing run swallow the box preamble. - xml = xml.replace( - new RegExp(`]*?>(?:(?!])[\\s\\S])*?${RBY}(\\d+)${RBY}(?:(?!])[\\s\\S])*?`, 'g'), + const pattern = new RegExp(`]*?>(?:(?!])[\\s\\S])*?${RBY}(\\d+)${RBY}(?:(?!])[\\s\\S])*?`, 'g'); + const rewrite = (xml: string) => xml.replace(pattern, (_m, idx: string) => { const r = rubies[Number(idx)]; if (!r) return ''; @@ -1658,7 +1665,9 @@ function applyRubyDocx(bytes: Uint8Array, rubies: RubyDocx[]): Uint8Array { + `${run(r.text, 12)}${run(r.base)}`; }, ); - files['word/document.xml'] = strToU8(xml); + for (const part of NOTE_BEARING_PARTS) { + if (files[part]) files[part] = strToU8(rewrite(strFromU8(files[part]))); + } const out: Record = {}; for (const [path, data] of Object.entries(files)) out[path] = [data, { level: 6 }]; return zipSync(out); diff --git a/src/lib/export/odt.ts b/src/lib/export/odt.ts index b580dcb..666147d 100644 --- a/src/lib/export/odt.ts +++ b/src/lib/export/odt.ts @@ -1248,13 +1248,18 @@ type ParaStyle = { indent: number | null; indentFirst: number | null; indentRight: number | null; + // A page break before the item — list paragraphs only; LibreOffice ignores one in a cell. + breakBefore: boolean; }; +// A list item's blocks past its first: each one's own style, and its heading level. +type ListItemExtra = { style: ParaStyle; level: number | null }; + function paraStyleIsEmpty(s: ParaStyle): boolean { return s.align === null && s.spaceBefore === null && s.spaceAfter === null && s.lineHeight === null && s.background === null && s.borderTop === null && s.borderRight === null && s.borderBottom === null && s.borderLeft === null && s.dir === null - && s.indent === null && s.indentFirst === null && s.indentRight === null; + && s.indent === null && s.indentFirst === null && s.indentRight === null && !s.breakBefore; } // ODF writes a direction as a writing mode; the vertical ones are not ours to emit. @@ -1290,9 +1295,21 @@ function paraStyleFromAttrs(attrs: TiptapNode['attrs'], withIndents = true): Par indent: cm(attrs?.indent), indentFirst: cm(attrs?.indentFirst), indentRight: cm(attrs?.indentRight), + breakBefore: false, }; } +// LibreOffice keeps the two vertical margins in one item: a style declaring only one +// resets the other to the *default* style's, not its parent's (probed), so the named +// style's partner rides along whenever one of the two is direct formatting. +function pairMargins(style: ParaStyle, styleName: string): ParaStyle { + if ((style.spaceBefore == null) === (style.spaceAfter == null)) return style; + const own = resolveStyle(exportSheet, styleName, 'paragraph').para; + return { ...style, + spaceBefore: style.spaceBefore ?? (own.spaceBefore || null), + spaceAfter: style.spaceAfter ?? (own.spaceAfter || null) }; +} + // fo:* paragraph-properties attribute strings for a ParaStyle override. function paraStyleProps(style: ParaStyle): string[] { const props: string[] = []; @@ -1303,6 +1320,7 @@ function paraStyleProps(style: ParaStyle): string[] { if (style.indent != null) props.push(`fo:margin-left="${style.indent}cm"`); if (style.indentFirst != null) props.push(`fo:text-indent="${style.indentFirst}cm"`); if (style.indentRight != null) props.push(`fo:margin-right="${style.indentRight}cm"`); + if (style.breakBefore) props.push('fo:break-before="page"'); if (style.background) props.push(`fo:background-color="${style.background}"`); // The canonical border attr ('pt solid #RRGGBB') is itself a valid fo:border value. for (const [attr, side] of [ @@ -1332,23 +1350,34 @@ type CellBlock = // A table's own margins in cm (0/0 tables are recorded as null). type TableProps = { ml: number; mr: number; mt: number; mb: number; keepRows: boolean; repeatHeader: boolean }; -// Collect the alignment + paragraph spacing of each listItem's first paragraph, -// in DFS order — matching the order that odf-kit emits elements -// into content.xml. Items without overrides yield an all-null descriptor. -function collectListItemStyles(node: TiptapNode, result: ParaStyle[]): void { +// Collect the alignment + paragraph spacing of each listItem's first paragraph, and in +// `extras` the same for its further blocks, in DFS order — matching the order odf-kit +// emits in. Items without overrides yield an all-null descriptor. +function collectListItemStyles(node: TiptapNode, result: ParaStyle[], extras: ListItemExtra[][] = []): void { if (node.type === 'listItem') { + const blocks = (node.content ?? []).filter(c => c.type === 'paragraph' || c.type === 'heading'); + extras.push(blocks.slice(1).map(b => ({ style: paraStyleFromAttrs(b.attrs, false), + level: b.type === 'heading' ? (b.attrs?.level as number) ?? 1 : null }))); const firstPara = node.content?.find(c => c.type === 'paragraph'); - result.push(paraStyleFromAttrs(firstPara?.attrs, false)); + // replacePageBreaks skips list paragraphs (its sentinel would corrupt the SEG + // rebuild), so the item's own break rides its style instead — as LibreOffice + // writes it (probed: it keeps fo:break-before on a list item's paragraph). + result.push({ ...paraStyleFromAttrs(firstPara?.attrs, false), + breakBefore: firstPara?.attrs?.breakBefore === 'page' }); // Recurse into nested lists only (their listItems extend the DFS sequence). for (const child of node.content ?? []) { if (child.type === 'bulletList' || child.type === 'orderedList') { - collectListItemStyles(child, result); + collectListItemStyles(child, result, extras); } } return; } + // Not into a table: a cell's list is still SEG-segmented text when the two passes + // below run (applyCellBlocks rebuilds it after them), so counting its items here + // would shift every body item's style by that many. + if (node.type === 'table' || node.type === CUST_TABLE) return; for (const child of node.content ?? []) { - collectListItemStyles(child, result); + collectListItemStyles(child, result, extras); } } @@ -1542,20 +1571,37 @@ function odfLookAttrs(look: TableLook): string { // odf-kit's ListBuilder has no per-item paragraph options, so list-item paragraphs all // emit as List_20_Bullet/Number. Rewrite content.xml to point those at automatic styles // that inherit the list style and add fo:text-align / fo:margin-top / fo:margin-bottom. -// Split a list item's paragraph back into the blocks mergeListItemBlocks merged into it. -// ponytail: they are re-emitted at the item's end, so a block before a nested list lands -// after it — and each takes the item's own paragraph style. -function applyListItemBlocks(odtBytes: Uint8Array): Uint8Array { +// Split a list item's paragraph back into the blocks mergeListItemBlocks merged into it, +// each with its own paragraph style. ponytail: they are re-emitted at the item's end, so +// a block before a nested list lands after it. +function applyListItemBlocks(odtBytes: Uint8Array, extras: ListItemExtra[][] = []): Uint8Array { const files = unzipSync(odtBytes); const contentBytes = files['content.xml']; if (!contentBytes) return odtBytes; const content = strFromU8(contentBytes); let out = ''; let i = 0; + let item = 0; let touched = false; + // An extra block keeps its own alignment/spacing/line-height/box: a minted style + // under the item's own, which is where the item's list formatting stays. + const minted: string[] = []; + const nameByKey = new Map(); + const styleFor = (style: ParaStyle, parent: string): string => { + const props = paraStyleProps(style).join(' '); + const key = `${parent}|${props}`; + let name = nameByKey.get(key); + if (!name) { + name = `LX${nameByKey.size + 1}`; + nameByKey.set(key, name); + minted.push(``); + } + return name; + }; for (;;) { const at = content.indexOf('', pStart); const pEnd = gt < 0 ? -1 : content.indexOf('', gt); @@ -1571,16 +1617,27 @@ function applyListItemBlocks(odtBytes: Uint8Array): Uint8Array { if (close < 0) break; if (open >= 0 && open < close) { depth++; scan = open; } else { depth--; scan = close; } } - const [first, ...extras] = inner.split(SEG); + const [first, ...rest] = inner.split(SEG); const attrs = content.slice(pStart + 7, gt); + const itemStyle = /text:style-name="([^"]*)"/.exec(attrs)?.[1] ?? 'Standard'; + // A heading stays one: ODF holds in a list item, and it is where a numbered + // heading lives. Its own style is the level's, not the item's list paragraph style. + const blockFor = (e: string, n: number) => { + const { style, level } = own[n] ?? { style: null, level: null }; + const parent = level ? `Heading_20_${level}` : itemStyle; + const tag = level ? 'text:h' : 'text:p'; + const named = style && !paraStyleIsEmpty(style) ? ` text:style-name="${styleFor(style, parent)}"` + : level ? ` text:style-name="${parent}"` : attrs; + return `<${tag}${named}${level ? ` text:outline-level="${level}"` : ''}>${e}`; + }; out += content.slice(i, gt + 1) + first + '' + content.slice(pEnd + 9, scan) - + extras.map(e => `${e}`).join(''); + + rest.map(blockFor).join(''); i = scan; touched = true; } if (!touched) return odtBytes; - files['content.xml'] = strToU8(out); + files['content.xml'] = strToU8(minted.length ? injectAutomaticStyles(out, minted.join('')) : out); return zipSync(files, { level: 6 }); } @@ -3732,7 +3789,8 @@ function buildCellContent(cell: TiptapNode, c: CellBuilder, force: TextProps = { blocks.push({ kind: 'paragraph', style: cellParaStyle(block.attrs) }); } else if (block.type === 'heading') { emitSegment(block.content); - blocks.push({ kind: 'heading', level: (block.attrs?.level as number) ?? 1, style: paraStyleFromAttrs(block.attrs) }); + const level = (block.attrs?.level as number) ?? 1; + blocks.push({ kind: 'heading', level, style: pairMargins(paraStyleFromAttrs(block.attrs), `Heading ${level}`) }); } else if (block.type === 'bulletList' || block.type === 'orderedList') { blocks.push(walkList(block)); } @@ -4945,7 +5003,8 @@ export async function buildOdt(docJson: TiptapNode, margins: PageMargins = DEFAU const bibMarks: BibExport[] = []; const rubies: RubyExport[] = []; const sentinels = replaceRuby(replaceBibEntries(replaceIndexEntries(replaceRevisions(replaceSequenceFields(replaceComments(replaceBookmarks(replaceFormulas(replacePlaceholderFields(replaceDateTimeFields(replaceImages(replaceTabs(replaceHardBreaks(replaceSectionBreaks(replaceNotes(replaceColumns(replaceTextBoxes(replacePageBreaks(replaceTableOfContents(docJson, tocs)), textBoxes), columns), notes)))), images), dateFields), placeholderLabels), formulas), crossRefs), commentList), seqFields), revisionList), indexMarks), bibMarks), rubies); - const raw = mergeListItemBlocks(markTextEffects(bakeListCharStyles(sentinels, styles), DEFAULT_FONT_SIZE_PT, styles)); + const unmerged = markTextEffects(bakeListCharStyles(sentinels, styles), DEFAULT_FONT_SIZE_PT, styles); + const raw = mergeListItemBlocks(unmerged); let headerPara = hf && !hfIsEmpty(hf.header) ? (hf.header!.content![0] as TiptapNode) : null; let footerPara = hf && !hfIsEmpty(hf.footer) ? (hf.footer!.content![0] as TiptapNode) : null; // Different first page (ODF header-first): page 1 gets its own zone content. @@ -5047,8 +5106,9 @@ export async function buildOdt(docJson: TiptapNode, margins: PageMargins = DEFAU if (ta === 'left' || ta === 'center' || ta === 'right' || ta === 'justify') { opts.align = ta; } - if (node.attrs?.spaceBefore != null) opts.spaceBefore = `${node.attrs.spaceBefore}pt`; - if (node.attrs?.spaceAfter != null) opts.spaceAfter = `${node.attrs.spaceAfter}pt`; + const spacing = pairMargins(paraStyleFromAttrs(node.attrs), styleOf(node)); + if (spacing.spaceBefore != null) opts.spaceBefore = `${spacing.spaceBefore}pt`; + if (spacing.spaceAfter != null) opts.spaceAfter = `${spacing.spaceAfter}pt`; // Left indent → fo:margin-left (odf-kit emits it natively from indentLeft). if (typeof node.attrs?.indent === 'number' && node.attrs.indent > 0) { opts.indentLeft = `${node.attrs.indent}cm`; @@ -5136,7 +5196,12 @@ export async function buildOdt(docJson: TiptapNode, margins: PageMargins = DEFAU const listStyles: ParaStyle[] = []; collectListItemStyles(raw, listStyles); - const styledLists = applyListItemBlocks(applyListItemStyles(numberedOdt, listStyles)); + // The extras' own styles come from before the merge, which is what folded them in. + const listExtraStyles: ListItemExtra[][] = []; + collectListItemStyles(unmerged, [], listExtraStyles); + // Blocks first: the extras' own styles then parent to the item's list style, not to + // the LP# the pass below mints for the item's first paragraph. + const styledLists = applyListItemStyles(applyListItemBlocks(numberedOdt, listExtraStyles), listStyles); // Whole-list indent → added to each L# list-style's level margins. const listLevels: ListLevelProps[][] = [];