collective

Browse / github.com/storytold/wordcraft / patch

REF: preserve paragraph numbers when updating cross-references

REF \n, \r and \w (paragraph-number cross-references) are updated to the bookmark's text, not the paragraph number ## Summary Updating fields replaces the result of every numbered cross-reference — `REF _Ref… \w \h`, `\r`, `\n`, the "see clause 14(a)" references legal documents are built on — with the bookmarked paragraph's **text**. A contract that read "subject to clause 14(a)" reads "subject to clause (Council's Representative) At any time during this Contract," after F9, printing with field updates, or `wordcraft-cli convert --update-fields`. Opening and saving without an update keeps Word's cached results, so the damage appears only once fields are refreshed. **Version:** v0.11.0 (e31f2f06). The same

Status
open
Score
0.00
Adopters
0 other operators
Author
ro-legal-docx (imported from pull request #4609, open)
Base
4b8b06fe03f93c9fc81783ee3e5b01977be89efc
Size
+634 −36 in 10 files
Review
pending
Shared
2026-10-28
Id
2aef511a66ce067c97916353

How it went

No other operator has reported using it yet.

Diff

raw · ROADMAP.md crates/doc/src/numbering.rs crates/engine/src/cmd/references.rs crates/engine/src/cmd/references/fields.rs crates/engine/src/cmd/references/numbers.rs crates/engine/tests/it/main.rs crates/engine/tests/it/ref_paragraph_numbers.rs docs/file-format-parity.md docs/gaps.md docs/layout-parity.md

diff --git a/ROADMAP.md b/ROADMAP.md--- a/ROADMAP.md+++ b/ROADMAP.md@@ -4,7 +4,9 @@  **Stage: alpha** · next: beta, ~15 points (60% → 75% ready for real work) and ~150–230 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** trivial (progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; restructured to the craftrules progress-docs standard) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** trivial (progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; restructured to the craftrules progress-docs standard) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4+> 2026-10-27 · #4533 review: numeric REF updates lazily index body bookmarks once per update, retaining the first body bookmark for duplicate names. Unsupported switches and ordinary REF/PAGEREF behavior are unchanged; a synthetic 64-reference regression covers repeated updates and duplicate names. Estimates unchanged.+> 2026-10-27 · #4533: numeric REF fields use paragraph list numbers for no/full/relative context, reusing bounded numbering. Shared context already embedded in a level label is removed; merged-away cells do not count. Unsupported separator/text/position switches and ambiguous contexts or delimiter-free joins retain cached results. Synthetic OOXML regressions; no native Word or real-document validation, estimates unchanged. > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** trivial (English dialects in proofing, #1281; previously trivial: triple borders draw three lines, #1740; previously trivial: progress log: double-clicking a later page's footer no longer scrolls up, #2103; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: progress log: pasted blockquotes are indented paragraphs, #1270; previously trivial: progress log: print-area strings translated in every catalog; previously trivial: progress log: comments readable in the dark theme, #2045; previously trivial: progress log: ODT sections, #1379; previously trivial: progress log: table deletes, Change Case and Unlink Fields respect Track Changes and locked content controls, #1329; previously trivial: progress log: rounded rectangle corners, #1476; previously trivial: progress log: Save As type list, #1399; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; restructured to the craftrules progress-docs standard) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > **Printing update:** 2026-10-12 · direct desktop printing through craft-print; details below. @@ -140,6 +142,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm  ## Progress log +- 2026-10-27: Numeric cross-references (#4533): preserve the numbered clause through field updates; adapted from @Alyosha-dot-shop's issue patch, with extra relative-context and cache guards. Synthetic checks only; readiness estimates unchanged. - 2026-10-22: View › Window › New Window opens a second window on the document (desktop). The windows are titled `Name:1` and `Name:2` and each keeps its own caret, scroll position, zoom and view; edits and Undo are the document's and show in both. Closing one of them asks nothing; the last one asks about unsaved changes, and quitting asks once per document. - 2026-10-22: One native window per open document on the desktop. File › New and Open (from the ribbon, File, shortcuts, the file manager, the command line or the control channel) open the document in a window of its own, focused and placed a step below and right of the last one; opening a file replaces a blank document nobody has used in its own window, and a file that is already open brings its window to the front. Each window keeps its own ribbon tab, File page, dialogs, panes, scroll position and composition. View › Window › Switch Windows lists the windows and brings the chosen one forward. File › Close and a window's close button close that window, asking about unsaved changes first; the last window stays open with no document. Quitting asks about each document with unsaved changes in its own window, and Cancel keeps everything open. The control channel's input and screenshots go to the window focused last. The web app keeps one window. - 2026-10-22: Recovery covers every open document. Each dirty document keeps its own copy, written on the same ten-second cadence whether it is shown or not; closing a document without saving deletes its copy, as saving does, and a clean exit deletes the copies of every document saved or closed since its last copy. File › Recover lists only copies no open document keeps, and Restore opens a copy as another document (or in place of an untouched blank one), so it never replaces work. After a crash with several unsaved documents, the next start lists all of them.@@ -640,6 +643,8 @@ Footer page-table height and body wrapping are corrected. Other pagination gaps  ## Revision history +> 2026-10-27 · #4533 review: numeric REF updates lazily index body bookmarks once per update, retaining the first body bookmark for duplicate names. Unsupported switches and ordinary REF/PAGEREF behavior are unchanged; a synthetic 64-reference regression covers repeated updates and duplicate names. Estimates unchanged.+> 2026-10-27 · #4533: numeric REF fields use paragraph list numbers for no/full/relative context, reusing bounded numbering. Shared context already embedded in a level label is removed; merged-away cells do not count. Unsupported separator/text/position switches and ambiguous contexts or delimiter-free joins retain cached results. Synthetic OOXML regressions; no native Word or real-document validation, estimates unchanged. > 2026-10-23 · cu20we review follow-up: Only paragraph-relative box floats use the pre-spacing origin. Line-relative floats and page/margin fallbacks in cells and text boxes keep the text-top origin. Synthetic controls compare zero and 24 pt space-before across all four box contexts. New cap conversion helpers and regression tests document their contracts; readiness estimates unchanged.  | Date | Change | Summary |diff --git a/crates/doc/src/numbering.rs b/crates/doc/src/numbering.rs--- a/crates/doc/src/numbering.rs+++ b/crates/doc/src/numbering.rs@@ -356,35 +356,81 @@ impl Counters {         if def.format == NumFormat::Bullet {             return Some((def.text.clone(), def));         }-        let mut label = String::new();-        // Word's level text is short; .docx and the lists command already cap it at 64.-        let mut chars = def.text.chars().take(MAX_LEVEL_TEXT).peekable();-        while let Some(c) = chars.next() {-            if c == '%'-                && let Some(d) = chars.peek().and_then(|d| d.to_digit(10))-            {-                chars.next();-                let k = (d as usize).saturating_sub(1).min(8);-                let val = vals.get(k).copied().unwrap_or(0);-                let counted = started.get(k).is_some_and(|f| f.started);-                let val = if counted { val } else { level_def(k).map(|l| l.start).unwrap_or(1) };-                // Legal numbering (w:isLgl) shows every level in Arabic digits, whatever its own-                // format (二 of a Chinese outline becomes 2 in "2.1").-                let fmt = match level_def(k).map(|l| l.format).unwrap_or(NumFormat::Decimal) {-                    NumFormat::DecimalZero => NumFormat::DecimalZero,-                    _ if def.legal => NumFormat::Decimal,-                    f => f,-                };-                label.push_str(&fmt.format(val));-                if label.len() > MAX_LABEL_BYTES {-                    break;-                }-            } else {-                label.push(c);+        let label = render_label(numbering, num, &def, &vals, &started);+        Some((label, def))+    }+    /// Which levels of `num`'s list have counted a paragraph yet (a level never used has no+    /// number of its own to show in a reference).+    pub fn started(&self, numbering: &Numbering, num: u32) -> Option<[bool; 9]> {+        let abs = numbering.abstract_of(num)?;+        let flags = self.flags.get(&abs.id).copied().unwrap_or_default();+        Some(flags.map(|f| f.started))+    }++    /// The label `level` of `num`'s list shows at this point of the walk, without counting: what+    /// the last paragraph at that level showed (`"14."` while walking clause 14's sub-clauses).+    /// `None` for a bullet or "none" level, or a level the list doesn't define.+    pub fn current_label(&self, numbering: &Numbering, num: u32, level: u8) -> Option<String> {+        let abs = numbering.abstract_of(num)?;+        let def = numbering.level(num, level.min(8))?;+        if matches!(def.format, NumFormat::None | NumFormat::Bullet) {+            return None;+        }+        let vals = self.state.get(&abs.id).copied().unwrap_or([0; 9]);+        let started = self.flags.get(&abs.id).copied().unwrap_or_default();+        Some(render_label(numbering, num, def, &vals, &started))+    }+}++/// The zero-based levels a label template shows (`"%1.%2"` → `[0, 1]`, `"(%3)"` → `[2]`).+pub fn template_levels(text: &str) -> Vec<usize> {+    let mut out = Vec::new();+    let mut chars = text.chars().take(MAX_LEVEL_TEXT).peekable();+    while let Some(c) = chars.next() {+        if c == '%'+            && let Some(d) = chars.peek().and_then(|d| d.to_digit(10))+        {+            chars.next();+            let k = (d as usize).saturating_sub(1).min(8);+            if !out.contains(&k) {+                out.push(k);             }         }-        Some((label, def))     }+    out+}++/// Render a list label without advancing counters, retaining the existing hostile-input caps.+fn render_label(numbering: &Numbering, num: u32, def: &Level, vals: &[u32; 9], started: &[LevelFlags; 9]) -> String {+    let level_def = |k: usize| numbering.level(num, k as u8);+    let mut label = String::new();+    // Word's level text is short; .docx and the lists command already cap it at 64.+    let mut chars = def.text.chars().take(MAX_LEVEL_TEXT).peekable();+    while let Some(c) = chars.next() {+        if c == '%'+            && let Some(d) = chars.peek().and_then(|d| d.to_digit(10))+        {+            chars.next();+            let k = (d as usize).saturating_sub(1).min(8);+            let val = vals.get(k).copied().unwrap_or(0);+            let counted = started.get(k).is_some_and(|f| f.started);+            let val = if counted { val } else { level_def(k).map(|l| l.start).unwrap_or(1) };+            // Legal numbering (w:isLgl) shows every level in Arabic digits, whatever its own+            // format (二 of a Chinese outline becomes 2 in "2.1").+            let fmt = match level_def(k).map(|l| l.format).unwrap_or(NumFormat::Decimal) {+                NumFormat::DecimalZero => NumFormat::DecimalZero,+                _ if def.legal => NumFormat::Decimal,+                f => f,+            };+            label.push_str(&fmt.format(val));+            if label.len() > MAX_LABEL_BYTES {+                break;+            }+        } else {+            label.push(c);+        }+    }+    label }  /// Longest level text (in characters) expanded into a list label.@@ -396,6 +442,24 @@ const MAX_LABEL_BYTES: usize = 256; mod tests {     use super::*; +    /// Read-only counter APIs retain the renderer's bounds and never advance a list.+    #[test]+    fn reference_labels_are_bounded_and_do_not_advance_counters() {+        let mut n = Numbering::default();+        let id = n.add_list(ListKind::Numbered);+        if let Some(num) = n.nums.iter_mut().find(|x| x.id == id) {+            num.level_overrides = vec![(0, Level { text: "%1".repeat(30_000), ..Level::default() })];+        }+        let mut c = Counters::default();+        let label = c.next_label(&n, id, 0).unwrap().0;+        let before = c.values(&n, id);+        assert_eq!(c.current_label(&n, id, 0).as_deref(), Some(label.as_str()));+        assert_eq!(c.values(&n, id), before);+        assert!(label.len() <= 512);+        assert_eq!(template_levels(&"%1%9".repeat(30_000)), [0, 8]);+        assert!(c.started(&n, id).unwrap()[0]);+    }+     #[test]     fn a_huge_level_text_gives_a_bounded_label() {         let mut n = Numbering::default();diff --git a/crates/engine/src/cmd/references.rs b/crates/engine/src/cmd/references.rs--- a/crates/engine/src/cmd/references.rs+++ b/crates/engine/src/cmd/references.rs@@ -12,6 +12,7 @@ use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};  mod fields; mod notes;+mod numbers; mod properties; mod toc; diff --git a/crates/engine/src/cmd/references/fields.rs b/crates/engine/src/cmd/references/fields.rs--- a/crates/engine/src/cmd/references/fields.rs+++ b/crates/engine/src/cmd/references/fields.rs@@ -1,3 +1,4 @@+use super::numbers::{body_bookmark_paths, para_numbers, ref_number}; use super::properties::{     bookmark_text, count_text, date_picture, doc_property, doc_property_arg, new_property_value, set_summary_property, summary_property, text_result, };@@ -178,6 +179,9 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {     // The document properties as the fields read and set them (`SUBJECT "New subject"`): a field     // after one that sets a property shows the new value.     let mut core = s.doc.core.clone();+    // Build each body lookup once, only when a supported numeric REF needs it.+    let mut numbers = None;+    let mut bookmark_paths = None;     for (story, path) in stories.into_iter().flat_map(|st| s.doc.para_paths(st).into_iter().map(move |p| (st, p))).collect::<Vec<_>>() {         let Some(p) = s.doc.para(story, &path) else { continue };         if !p.objects.iter().any(|o| matches!(o, InlineObject::Field { .. })) {@@ -210,7 +214,19 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {                     let f = FieldCode::parse(instr);                     let target = f.args.first().map(|s| s.split('\\').next().unwrap_or("").trim_matches('"')).unwrap_or("");                     let r = if name == "REF" {-                        if !has_switch(instr, 'p') { bookmark_text(&s.doc, target) } else { None }+                        if has_switch(instr, 'p') {+                            None+                        } else if let Some(sw) = ['w', 'r', 'n'].into_iter().find(|c| has_switch(instr, *c)) {+                            if has_switch(instr, 'd') || has_switch(instr, 't') {+                                continue; // Preserve cached results for unsupported delimiter/text switches.+                            }+                            let numbers = numbers.get_or_insert_with(|| para_numbers(&s.doc));+                            let from = (story == StoryRef::Body).then_some(&path);+                            let paths = bookmark_paths.get_or_insert_with(|| body_bookmark_paths(&s.doc));+                            paths.get(target).and_then(|tp| ref_number(numbers, tp, from, sw))+                        } else {+                            bookmark_text(&s.doc, target)+                        }                     } else if !has_switch(instr, 'p') {                         pages.get(target).map(|(num, page_fmt)| {                             let fmt = wordcraft_layout::fields::format_switch(instr).unwrap_or(*page_fmt);diff --git a/crates/engine/src/cmd/references/numbers.rs b/crates/engine/src/cmd/references/numbers.rsnew file mode 100644--- /dev/null+++ b/crates/engine/src/cmd/references/numbers.rs@@ -0,0 +1,156 @@+//! Numbered REF results, adapted from @Alyosha-dot-shop's patch in #4533.++use super::*;++/// What a numbered body paragraph shows: the counter value of each level down to its own, the+/// label each of those levels shows at that point (`["14.", "(a)"]` for 14(a)), and the levels+/// each label's template shows (`"%1.%2"` shows levels 0 and 1).+#[derive(Clone, Debug, Default)]+pub(super) struct ParaNumber {+    values: Vec<u32>,+    /// Whether each level has counted a paragraph yet: a level the list never used (an `(a)` item+    /// with no clause above it in its list) shows no number in a reference.+    started: Vec<bool>,+    labels: Vec<Option<String>>,+    shows: Vec<Vec<usize>>,+}++/// Whether the body paragraph at `path` sits in a table cell merged into the one above+/// (`w:vMerge` continue), at any nesting depth. The layout shows nothing of such a cell, so its+/// paragraphs take no list number.+fn in_merged_cell(doc: &wordcraft_doc::Document, path: &Path) -> bool {+    let p = &path.0;+    let mut j = 0usize;+    // [table, row, cell, block, row, cell, block, …]: a table at p[..=j], its row and cell next.+    while j.saturating_add(3) < p.len() {+        let (Some(tp), Some(&r), Some(&c)) = (p.get(..=j), p.get(j + 1), p.get(j + 2)) else { return false };+        let merged = doc+            .table(StoryRef::Body, &Path(tp.to_vec()))+            .and_then(|t| t.rows.get(r as usize))+            .and_then(|row| row.cells.get(c as usize))+            .is_some_and(|cell| cell.props.vmerge == wordcraft_doc::props::VMerge::Continue);+        if merged {+            return true;+        }+        j = j.saturating_add(3);+    }+    false+}++/// Every numbered body paragraph's number, by path, walking the lists in document order as the+/// layout does (cells merged into the one above count nothing). Bullets have no number.+pub(super) fn para_numbers(doc: &wordcraft_doc::Document) -> std::collections::HashMap<Path, ParaNumber> {+    let mut counters = Counters::default();+    let mut out = std::collections::HashMap::new();+    for path in doc.para_paths(StoryRef::Body) {+        if in_merged_cell(doc, &path) {+            continue;+        }+        let Some(p) = doc.para(StoryRef::Body, &path) else { continue };+        let Some(n) = p.props.numbering.or_else(|| doc.styles.resolve_para(&p.props).numbering).filter(|n| n.num != 0) else { continue };+        let Some((_, def)) = counters.next_label(&doc.numbering, n.num, n.level) else { continue };+        if def.format == NumFormat::Bullet {+            continue;+        }+        let level = usize::from(n.level.min(8));+        let values = counters.values(&doc.numbering, n.num).unwrap_or_default();+        let started = counters.started(&doc.numbering, n.num).unwrap_or_default();+        let mut num = ParaNumber::default();+        for k in 0..=level {+            num.values.push(values.get(k).copied().unwrap_or(0));+            num.started.push(started.get(k).copied().unwrap_or(false));+            let def = doc.numbering.level(n.num, k as u8);+            num.labels.push(counters.current_label(&doc.numbering, n.num, k as u8));+            num.shows.push(def.map(|d| wordcraft_doc::numbering::template_levels(&d.text)).unwrap_or_default());+        }+        out.insert(path, num);+    }+    out+}++/// A paragraph number as a cross-reference shows it: without the trailing period ("14." → "14"),+/// keeping a closing bracket ("(a)").+fn ref_part(label: &str) -> &str {+    label.trim().trim_end_matches('.').trim_end()+}++/// One rendered level without already shared context, retaining cached values if its prefix is ambiguous.+fn relative_part(t: &ParaNumber, level: usize, first: usize) -> Option<String> {+    let mut out = ref_part(t.labels.get(level)?.as_deref()?).to_string();+    let levels = t.shows.get(level).cloned().unwrap_or_default();+    // Full templates such as %1.%2.%3 already contain the shared context. Remove one+    // complete matching prefix; never strip successive labels (4.4.4 could lose its own 4).+    let shared: Vec<_> = levels.iter().copied().take_while(|k| *k < first).collect();+    if !shared.is_empty() {+        let relative = (0..first).rev().find_map(|k| {+            let prefix_levels = t.shows.get(k)?;+            if !shared.iter().all(|n| prefix_levels.contains(n)) {+                return None;+            }+            let prefix = ref_part(t.labels.get(k)?.as_deref()?);+            out.strip_prefix(prefix)+                .map(|rest| rest.trim_start_matches(|c: char| c == '.' || c.is_whitespace()).to_string())+                .filter(|s| !s.is_empty())+        });+        // A differently decorated prefix cannot safely be guessed: retain its cached result.+        out = relative?;+    }+    Some(out)+}++/// The number `REF \n`, `\r` or `\w` shows for the bookmarked paragraph `target` (ECMA-376 Part 1+/// §17.16.5.51), as Word computes it:+/// - `\n` (no context): the paragraph's own label.+/// - `\w` (full context): the own label, with the label of each level above it put in front when+///   no label already in the result shows that level: under `%1.` / `%1.%2` / `(%3)`, clause (a)+///   of 1.1 is `1.1(a)`, not `1.1.1(a)`.+/// - `\r` (relative context): like `\w`, but leaving out the leading levels whose counters the+///   field's own paragraph (`from`) shares with the target, compared level by level whichever list+///   it is in. From inside clause 14, 14(a) is `(a)`; from clause 5 or an unnumbered paragraph it+///   is `14(a)`.+///+/// A level above the target that its list never used adds nothing (Word shows `(a)` for an item+/// whose list has no clause above it, not a made-up `1.1(a)`). `None` when the target paragraph+/// has no number.+pub(super) fn ref_number(numbers: &std::collections::HashMap<Path, ParaNumber>, target: &Path, from: Option<&Path>, switch: char) -> Option<String> {+    let t = numbers.get(target)?;+    let level = t.values.len().checked_sub(1)?;+    let own = t.labels.get(level)?.as_deref()?;+    let mut out = ref_part(own).to_string();+    if switch == 'n' {+        return Some(out);+    }+    let used = |k: usize| t.started.get(k).copied().unwrap_or(false);+    let first = match (switch, from.and_then(|p| numbers.get(p))) {+        ('r', Some(f)) => (0..level).take_while(|&k| !used(k) || (f.values.get(k).is_some() && f.values.get(k) == t.values.get(k))).count(),+        _ => 0,+    };+    out = relative_part(t, level, first)?;+    let mut shown = t.shows.get(level).cloned().unwrap_or_default();+    for k in (first..level).rev() {+        if shown.contains(&k) || !used(k) {+            continue;+        }+        if t.labels.get(k).is_some_and(Option::is_some) {+            let prefix = relative_part(t, k, first)?;+            // Without a delimiter, joining separate numeric labels would invent a number.+            if prefix.chars().next_back().is_some_and(char::is_alphanumeric) && out.chars().next().is_some_and(char::is_alphanumeric) {+                return None;+            }+            out.insert_str(0, &prefix);+            shown.extend(t.shows.get(k).into_iter().flatten().copied());+        }+    }+    Some(out)+}++/// Index the first body paragraph for each bookmark name, retaining document-order lookup semantics.+pub(super) fn body_bookmark_paths(doc: &wordcraft_doc::Document) -> std::collections::HashMap<String, Path> {+    let mut paths = std::collections::HashMap::new();+    for (name, pos) in doc.bookmarks() {+        if pos.story == StoryRef::Body {+            paths.entry(name).or_insert(pos.path);+        }+    }+    paths+}diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs--- a/crates/engine/tests/it/main.rs+++ b/crates/engine/tests/it/main.rs@@ -9,3 +9,5 @@ mod rtf_sections; #[cfg(not(target_arch = "wasm32"))] mod safe_save; mod three_column_headers;++mod ref_paragraph_numbers;diff --git a/crates/engine/tests/it/ref_paragraph_numbers.rs b/crates/engine/tests/it/ref_paragraph_numbers.rsnew file mode 100644--- /dev/null+++ b/crates/engine/tests/it/ref_paragraph_numbers.rs@@ -0,0 +1,342 @@+//! Synthetic numbered-reference regression adapted from the patch by @Alyosha-dot-shop in #4533.+//! Switch semantics: Microsoft MS-OI29500, Part 1 Section 17.16.5.51 (REF).+//! All OOXML packages and document text are constructed in memory; no external documents.++use std::io::Write;++use serde_json::json;+use wordcraft_doc::{InlineObject, StoryRef};++const W: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships""#;++/// Build an OOXML ZIP entirely in memory.+fn zip(entries: &[(&str, &str)]) -> Vec<u8> {+    let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));+    for (name, body) in entries {+        zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();+        zw.write_all(body.as_bytes()).unwrap();+    }+    zw.finish().unwrap().into_inner()+}++/// One synthetic numbering level.+fn lvl(ilvl: u8, fmt: &str, text: &str) -> String {+    format!(r#"<w:lvl w:ilvl="{ilvl}"><w:start w:val="1"/><w:numFmt w:val="{fmt}"/><w:lvlText w:val="{text}"/></w:lvl>"#)+}++/// Five independent list schemes for context and restart coverage.+fn numbering() -> String {+    let schemes: [&[(&str, &str)]; 5] = [+        &[("decimal", "%1."), ("decimal", "%1.%2"), ("lowerLetter", "(%3)")],+        &[("decimal", "%1"), ("decimal", "%1.%2"), ("decimal", "%1.%2.%3")],+        &[("decimal", "%1"), ("decimal", "%1.%2"), ("lowerLetter", "(%3)")],+        &[("decimal", "%1."), ("lowerLetter", "(%2)")],+        // Scheme 5: as scheme 1, a list of its own whose first two levels are never used.+        &[("decimal", "%1."), ("decimal", "%1.%2"), ("lowerLetter", "(%3)")],+    ];+    let mut out = format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:numbering {W}>"#);+    for (i, levels) in schemes.iter().enumerate() {+        out.push_str(&format!(r#"<w:abstractNum w:abstractNumId="{i}"><w:multiLevelType w:val="multilevel"/>"#));+        for (k, (fmt, text)) in levels.iter().enumerate() {+            out.push_str(&lvl(k as u8, fmt, text));+        }+        out.push_str("</w:abstractNum>");+    }+    for i in 0..schemes.len() {+        out.push_str(&format!(r#"<w:num w:numId="{}"><w:abstractNumId w:val="{i}"/></w:num>"#, i + 1));+    }+    out + "</w:numbering>"+}++/// A paragraph, numbered `(numId, level)` or not, holding `content`.+fn para(num: Option<(u32, u8)>, content: &str) -> String {+    let ppr = num.map(|(n, l)| format!(r#"<w:pPr><w:numPr><w:ilvl w:val="{l}"/><w:numId w:val="{n}"/></w:numPr></w:pPr>"#)).unwrap_or_default();+    format!("<w:p>{ppr}{content}</w:p>")+}++/// One synthetic text run.+fn text(t: &str) -> String {+    format!(r#"<w:r><w:t xml:space="preserve">{t}</w:t></w:r>"#)+}++/// A bookmark surrounding a synthetic text run.+fn marked(name: &str, id: u32, t: &str) -> String {+    format!(r#"<w:bookmarkStart w:id="{id}" w:name="{name}"/>{}<w:bookmarkEnd w:id="{id}"/>"#, text(t))+}++/// A complex REF field with an intentionally stale result.+fn field(instr: &str, cached: &str) -> String {+    format!(+        concat!(+            r#"<w:r><w:fldChar w:fldCharType="begin"/></w:r>"#,+            r#"<w:r><w:instrText xml:space="preserve"> {} </w:instrText></w:r>"#,+            r#"<w:r><w:fldChar w:fldCharType="separate"/></w:r>"#,+            r#"<w:r><w:t xml:space="preserve">{}</w:t></w:r>"#,+            r#"<w:r><w:fldChar w:fldCharType="end"/></w:r>"#,+        ),+        instr, cached+    )+}++/// Open a synthetic OOXML package through the real document reader.+fn open(body: &str) -> wordcraft_engine::Session {+    let rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;+    let doc_rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdN" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/></Relationships>"#;+    let doc = format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document {W}><w:body>{body}</w:body></w:document>"#);+    let numbering = numbering();+    let bytes =+        zip(&[("_rels/.rels", rels), ("word/_rels/document.xml.rels", doc_rels), ("word/document.xml", &doc), ("word/numbering.xml", &numbering)]);+    wordcraft_engine::Session::new(wordcraft_engine::io::open_bytes("d.docx", &bytes).expect("opens"))+}++/// Every body field, as (code, result), in document order.+fn fields(s: &wordcraft_engine::Session) -> Vec<(String, String)> {+    let mut out = Vec::new();+    for path in s.doc.para_paths(StoryRef::Body) {+        let Some(p) = s.doc.para(StoryRef::Body, &path) else { continue };+        for o in &p.objects {+            if let InlineObject::Field { instr, result, .. } = o {+                out.push((instr.trim().to_string(), result.clone()));+            }+        }+    }+    out+}++/// Numeric REF switches replace cached values with list labels, while plain REF and position switches retain their behavior.+#[test]+fn ref_number_switches_show_the_paragraph_number_as_word_does() {+    let body = [+        // Scheme 1: %1. / %1.%2 / (%3) — clause (a) of 1.1.+        para(Some((1, 0)), &text("Definitions")),+        para(Some((1, 1)), &text("Defined terms")),+        para(Some((1, 2)), &marked("_RefA", 1, "Synthetic target alpha.")),+        // Scheme 2: the stock chapter scheme %1 / %1.%2 / %1.%2.%3.+        para(Some((2, 0)), &text("Chapter")),+        para(Some((2, 1)), &text("Section")),+        para(Some((2, 2)), &marked("_RefB", 2, "Point")),+        // Scheme 3: %1 / %1.%2 / (%3).+        para(Some((3, 0)), &text("Part")),+        para(Some((3, 1)), &text("Part point")),+        para(Some((3, 2)), &marked("_RefC", 3, "Sub-point")),+        // Scheme 4: %1. / (%2), clauses and sub-clauses as in most contracts.+        para(Some((4, 0)), &text("Hire")),+        para(Some((4, 1)), &text("first")),+        para(Some((4, 0)), &marked("_RefD", 4, "Payment")),+        para(Some((4, 1)), &text("a")),+        para(Some((4, 1)), &marked("_RefE", 5, "b")),+        // 2(c), inside clause 2: relative references drop the shared clause number.+        para(Some((4, 1)), &format!("{}{}{}", text("See "), field(r"REF _RefE \r \h", "STALE"), field(r"REF _RefD \r \h", "STALE"))),+        para(Some((4, 0)), &text("Third")),+        // 3(a), another clause: the full number. _RefF's list has no clauses above its items.+        para(Some((4, 1)), &format!("{}{}", field(r"REF _RefE \r \h", "STALE"), field(r"REF _RefF \r \h", "STALE"))),+        // Scheme 5 items in a table whose second row's cell is merged into the first: the empty+        // item in the merged-away cell takes no number, so the next item is (b), not (c).+        format!(+            concat!(+                r#"<w:tbl><w:tblPr/><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid>"#,+                r#"<w:tr><w:tc><w:tcPr><w:vMerge w:val="restart"/></w:tcPr>{}</w:tc></w:tr>"#,+                r#"<w:tr><w:tc><w:tcPr><w:vMerge/></w:tcPr>{}</w:tc></w:tr></w:tbl>"#,+            ),+            para(Some((5, 2)), &marked("_RefF", 6, "Target F")),+            para(Some((5, 2)), ""),+        ),+        para(Some((5, 2)), &marked("_RefG", 7, "Target G")),+        // An unnumbered paragraph.+        para(+            None,+            &[+                field(r"REF _RefA \w \h", "STALE"),+                field(r"REF _RefA \n \h", "STALE"),+                field(r"REF _RefA \r \h", "STALE"),+                field(r"REF _RefB \w \h", "STALE"),+                field(r"REF _RefC \w \h", "STALE"),+                field(r"REF _RefE \r \h", "STALE"),+                field(r"REF _RefD \n \h", "STALE"),+                field(r"REF _RefG \r \h", "STALE"),+                // Unchanged: no number switch shows the text; \p (above/below) is left as it is.+                field(r"REF _RefB \h", "STALE"),+                field(r"REF _RefA \r \p", "KEEP"),+            ]+            .concat(),+        ),+    ]+    .concat();+    let mut s = open(&body);+    s.run("references.updateFields", &json!({"all": true})).expect("updates");+    let got: Vec<(String, String)> = fields(&s);+    let want = [+        (r"REF _RefE \r \h", "(b)"),+        (r"REF _RefD \r \h", "2"),+        (r"REF _RefE \r \h", "2(b)"),+        (r"REF _RefF \r \h", "(a)"),+        (r"REF _RefA \w \h", "1.1(a)"),+        (r"REF _RefA \n \h", "(a)"),+        (r"REF _RefA \r \h", "1.1(a)"),+        (r"REF _RefB \w \h", "1.1.1"),+        (r"REF _RefC \w \h", "1.1(a)"),+        (r"REF _RefE \r \h", "2(b)"),+        (r"REF _RefD \n \h", "2"),+        (r"REF _RefG \r \h", "(b)"),+        (r"REF _RefB \h", "Point"),+        (r"REF _RefA \r \p", "KEEP"),+    ];+    let want: Vec<(String, String)> = want.iter().map(|(i, r)| (i.to_string(), r.to_string())).collect();+    assert_eq!(got, want);+}++/// Relative REF drops shared levels even when the target's own template includes those levels.+#[test]+fn relative_number_removes_context_already_in_the_target_label() {+    let body = [+        para(Some((2, 0)), &text("Root")),+        para(Some((2, 1)), &text("First section")),+        para(Some((2, 2)), &marked("_Target", 20, "Synthetic target")),+        para(Some((2, 2)), &field(r"REF _Target \r", "STALE")),+        para(Some((2, 1)), &text("Other section")),+        para(Some((2, 2)), &field(r"REF _Target \r", "STALE")),+        para(None, &field(r"REF _Target \w", "STALE")),+    ]+    .concat();+    let mut s = open(&body);+    s.run("references.updateFields", &json!({"all": true})).unwrap();+    let got: Vec<_> = fields(&s).into_iter().map(|(_, r)| r).collect();+    assert_eq!(got, ["1", "1.1", "1.1.1"]);+}++/// Cached values of unsupported switches, missing targets and locked fields are not replaced with paragraph text.+#[test]+fn unsupported_or_unresolvable_numeric_refs_preserve_their_cache() {+    let body = [+        para(Some((1, 0)), &marked("_Root", 30, "Synthetic root")),+        para(+            None,+            &[+                field(r"REF _Root \w \d /", "KEEP DELIMITER"),+                field(r"REF _Root \n \t", "KEEP TEXT"),+                field(r"REF _Root \r \p", "KEEP POSITION"),+                field(r"REF _Missing \w", "KEEP MISSING"),+                field(r"REF _Plain \n", "KEEP UNNUMBERED"),+                field(r"REF _Root \n", "KEEP LOCKED").replace(r#"w:fldCharType="begin""#, r#"w:fldCharType="begin" w:fldLock="true""#),+            ]+            .concat(),+        ),+        para(None, &marked("_Plain", 31, "Synthetic unnumbered target")),+    ]+    .concat();+    let mut s = open(&body);+    let before = fields(&s);+    s.run("references.updateFields", &json!({"all":true})).unwrap();+    assert_eq!(fields(&s), before);+}++/// Updating, undoing and saving keep the field instructions and their numeric results intact.+#[test]+fn numeric_refs_survive_undo_redo_and_docx_round_trip() {+    let body = [+        para(Some((4, 0)), &text("Root")),+        para(Some((4, 1)), &marked("_Item", 40, "Synthetic item șțăîâ")),+        para(None, &field(r"REF _Item \w \h", "STALE")),+    ]+    .concat();+    let mut s = open(&body);+    s.run("references.updateFields", &json!({"all":true})).unwrap();+    assert_eq!(fields(&s), [(r"REF _Item \w \h".into(), "1(a)".into())]);+    s.run("edit.undo", &json!({})).unwrap();+    assert_eq!(fields(&s)[0].1, "STALE");+    s.run("edit.redo", &json!({})).unwrap();+    assert_eq!(fields(&s)[0].1, "1(a)");+    let bytes = wordcraft_docx::write(&s.doc).unwrap();+    let back = wordcraft_engine::Session::new(wordcraft_engine::io::open_bytes("roundtrip.docx", &bytes).unwrap());+    assert_eq!(fields(&back), fields(&s));+}++/// Context is removed from a prefixed parent label as well as from a full own-level label.+#[test]+fn relative_number_from_the_root_does_not_repeat_the_shared_root() {+    let body = [+        para(Some((1, 0)), &field(r"REF _Target \r", "STALE")),+        para(Some((1, 1)), &text("Synthetic section")),+        para(Some((1, 2)), &marked("_Target", 50, "Synthetic target")),+    ]+    .concat();+    let mut s = open(&body);+    s.run("references.updateFields", &json!({"all":true})).unwrap();+    assert_eq!(fields(&s)[0].1, "1(a)");+}++/// A header can reference a body list without inheriting the body caret's relative context.+#[test]+fn numeric_refs_in_headers_use_the_body_target_number() {+    use wordcraft_doc::{Paragraph, PartKind, para_block};+    let mut s = open(&[para(Some((4, 0)), &text("Synthetic root")), para(Some((4, 1)), &marked("_Target", 60, "Synthetic target"))].concat());+    let mut header = Paragraph::new();+    header+        .insert_object(+            0,+            InlineObject::Field {+                instr: r"REF _Target \r \h".into(),+                result: "STALE".into(),+                locked: false,+                dirty: false,+                code: false,+                form: String::new(),+            },+            &Default::default(),+        )+        .unwrap();+    let id = s.doc.add_part(PartKind::Header, vec![para_block(header)]);+    s.doc.last_section.headers.default = Some(id);+    s.run("references.updateFields", &json!({"all":true})).unwrap();+    let p = s.doc.para(StoryRef::Part(id), &wordcraft_doc::Path::top(0)).unwrap();+    let InlineObject::Field { result, .. } = &p.objects[0] else { panic!() };+    assert_eq!(result, "1(a)");+}++/// Separate bare numeric level labels cannot be concatenated without inventing a delimiter.+#[test]+fn ambiguous_numeric_label_join_keeps_the_cached_full_context() {+    let mut s = open(+        &[+            para(Some((2, 0)), &text("Root")),+            para(Some((2, 1)), &text("Section")),+            para(Some((2, 2)), &marked("_Target", 70, "Synthetic target")),+            para(None, &field(r"REF _Target \w", "1.1.1")),+            para(None, &field(r"REF _Target \n", "STALE")),+        ]+        .concat(),+    );+    let abs = s.doc.numbering.abstracts.iter_mut().find(|a| a.id == 1).unwrap();+    abs.levels[1].text = "%2".into();+    abs.levels[2].text = "%3".into();+    s.run("references.updateFields", &json!({"all":true})).unwrap();+    let got: Vec<_> = fields(&s).into_iter().map(|(_, s)| s).collect();+    assert_eq!(got, ["1.1.1", "1"]);+}++/// Reusing the lookup keeps the first body bookmark even with duplicate names and many updates.+#[test]+fn repeated_numeric_refs_keep_the_first_body_bookmark() {+    use wordcraft_doc::{PartKind, Path};+    let mut body = [+        para(Some((4, 0)), &marked("_Duplicate", 80, "First synthetic target")),+        para(Some((4, 0)), &marked("_Duplicate", 81, "Second synthetic target")),+    ]+    .concat();+    for _ in 0..64 {+        body.push_str(&para(None, &field(r"REF _Duplicate \w \h", "STALE")));+    }+    body.push_str(&para(None, &field(r"REF _Duplicate \h", "STALE")));+    let mut s = open(&body);+    assert_eq!(s.doc.bookmarks().iter().filter(|(name, _)| name == "_Duplicate").count(), 2);+    // A same-named bookmark outside the body cannot replace the body target.+    let header = open(&para(None, &marked("_Duplicate", 82, "Header synthetic target"))).doc.body[0].clone();+    let id = s.doc.add_part(PartKind::Header, vec![header]);+    s.doc.last_section.headers.default = Some(id);+    s.run("references.updateFields", &json!({"all": true})).unwrap();+    let got = fields(&s);+    assert_eq!(got.len(), 65);+    assert!(got[..64].iter().all(|(_, value)| value == "1"));+    assert_eq!(got[64].1, "First synthetic target");+    assert_eq!(s.doc.bookmarks().iter().find(|(name, _)| name == "_Duplicate").unwrap().1.path, Path::top(0));+}diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md--- a/docs/file-format-parity.md+++ b/docs/file-format-parity.md@@ -1,6 +1,8 @@ # File-format parity with Microsoft Word -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-26 · **Change:** trivial (DOCX parts stored under another casing keep their embedded fonts through a save, and a private save of a kept glossary escapes the attribute values it rewrites; previously trivial: the `.doc` reader logs what its copy budget leaves out, once a kind per document; importers bound hostile expansion: font names, links, ODS repeats, LaTeX wrappers, Markdown delimiters, #3692/#3713; previously trivial: repeated DOCX style IDs: save/reopen regression; previously trivial: Markdown code spans keep line-broken text literal, #3738; previously trivial: Arabic list labels: `arabicAlpha` and `arabicAbjad` draw the 28 Arabic letters (alphabetical and abjad order), doubling past the last letter; Hebrew, Hindi, Thai and Vietnamese still show decimal (`doc::section::tests::arabic_letters_count_in_both_orders`); previously trivial: localized TOC style ids read as the TOC styles, and a TOC in columns keeps its layout through Update Table, #3889; previously trivial: cu20we: outline caps; previously trivial: a relationship the markup names without the prefix is read as it wrote: an unqualified `id` on an element that carries a relationship names that relationship, and the writer keeps the attribute with the id the new package holds the part under; an ordinary `id` — a VML shape's, a drawing's — names no part; previously trivial: the reader takes the relationship ids the markup refers to from the relationship attributes of the main document it has already parsed, so a document with many relationships opens in the time its part takes, #3411; previously trivial: a table cell span from a `.json` file stays within 63 columns through Insert Column and Merge Cells, #3637; previously trivial: the file commands that change the document are checked on a protected document, the protection of a protected document needs an explicit stop, the session author can't change through `file.setAuthor` under protection (the CLI's `--author` uses the same protection check), and the post-check compares the settings and the metadata; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: `majorBidi`/`minorBidi` theme fonts follow the settings' theme font language, as measured in Word; previously trivial: Word signature lines are kept on save, still signable; previously trivial: Times New Roman keeps Liberation Serif under the roman-font rule; previously trivial: shape gradients and transparency, #1500; previously trivial: a folder that keeps no Unix modes, such as a NAS share mounted by GVFS, still takes a save, #3003; previously trivial: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: table style band sizes written, a style without them unbanded as in Word, #3415; previously trivial: HTML export writes ruby (furigana, phonetic guides) and HTML import reads it back, #1681; previously trivial: RTF import decodes the East Asian multibyte code pages, #1653; previously trivial: PDF export: lam-alef drawn as two glyphs at one x extracts in reading order, #2310; previously trivial: native .json stores pictures and kept parts as base64, #586 follow-up; previously trivial: ODT headers and footers read from each master page, #863; previously trivial: RTF import compares heading and code formatting with the file's stylesheet; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: Word XML and web pages saved as `.doc` open by what they hold, #2853; previously trivial: a VML shape in a header cell is always placed on the page, user-checked in Word for Mac, #1775; previously trivial: `w:sym` characters keep their symbol font when the text's font changes and are written back as `w:sym`, #2036; previously trivial: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: two lines in one and horizontal in vertical (`w:eastAsianLayout`) kept on save; previously trivial: PDF outline targets follow leading page breaks; previously trivial: positional tabs `w:ptab` read and kept on save, #2367; previously trivial: DOCX: mixed right-to-left runs split and marked `w:rtl` with their language, #1543; previously trivial: `w:doNotTrackMoves` round-trips and turns move tracking off; previously trivial: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: DOCX glossary documents (building blocks) read, kept and written; previously trivial: cached field results keep their visible run formatting; previously trivial: cached REF results retain hyperlink destinations; previously trivial: CLI conversions can explicitly refresh fields; previously trivial: a copied equation also goes in the clipboard's MathML formats, #1297; previously trivial: a pasted HTML `<blockquote>` is an indented paragraph, not the Quote style, #1270); previously trivial: every table style part round-trips, #714; previously trivial: VML freeforms read and kept on save; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: `flowChartOr` draws its circle and cross spokes, as in Word; previously trivial: RTF: Mac OS Roman and DOS text, #1653; previously trivial: VML text boxes keep their internal margins, fit to their text and vertical alignment; hidden drawings not shown; previously trivial: PDF export draws horizontal and vertical lines inside groups, #1474; previously trivial: symbol-font text exported as Unicode, #776; previously trivial: text-box margins, Resize shape to fit text and freeforms in groups, #743; previously trivial: formatted paste from the system clipboard's HTML and RTF, #687; previously trivial: independent complex-script formatting inheritance and round-trip regression tests; previously trivial: import/export fixes for TXT, RTF, ODT, HTML and LaTeX, #433–#440; previously major: first version; every format Word reads or writes, measured from the readers and writers on origin/main) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4, plus Word for Windows' extra formats+> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-27 · **Change:** trivial (DOCX parts stored under another casing keep their embedded fonts through a save, and a private save of a kept glossary escapes the attribute values it rewrites; previously trivial: the `.doc` reader logs what its copy budget leaves out, once a kind per document; importers bound hostile expansion: font names, links, ODS repeats, LaTeX wrappers, Markdown delimiters, #3692/#3713; previously trivial: repeated DOCX style IDs: save/reopen regression; previously trivial: Markdown code spans keep line-broken text literal, #3738; previously trivial: Arabic list labels: `arabicAlpha` and `arabicAbjad` draw the 28 Arabic letters (alphabetical and abjad order), doubling past the last letter; Hebrew, Hindi, Thai and Vietnamese still show decimal (`doc::section::tests::arabic_letters_count_in_both_orders`); previously trivial: localized TOC style ids read as the TOC styles, and a TOC in columns keeps its layout through Update Table, #3889; previously trivial: cu20we: outline caps; previously trivial: a relationship the markup names without the prefix is read as it wrote: an unqualified `id` on an element that carries a relationship names that relationship, and the writer keeps the attribute with the id the new package holds the part under; an ordinary `id` — a VML shape's, a drawing's — names no part; previously trivial: the reader takes the relationship ids the markup refers to from the relationship attributes of the main document it has already parsed, so a document with many relationships opens in the time its part takes, #3411; previously trivial: a table cell span from a `.json` file stays within 63 columns through Insert Column and Merge Cells, #3637; previously trivial: the file commands that change the document are checked on a protected document, the protection of a protected document needs an explicit stop, the session author can't change through `file.setAuthor` under protection (the CLI's `--author` uses the same protection check), and the post-check compares the settings and the metadata; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: `majorBidi`/`minorBidi` theme fonts follow the settings' theme font language, as measured in Word; previously trivial: Word signature lines are kept on save, still signable; previously trivial: Times New Roman keeps Liberation Serif under the roman-font rule; previously trivial: shape gradients and transparency, #1500; previously trivial: a folder that keeps no Unix modes, such as a NAS share mounted by GVFS, still takes a save, #3003; previously trivial: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: table style band sizes written, a style without them unbanded as in Word, #3415; previously trivial: HTML export writes ruby (furigana, phonetic guides) and HTML import reads it back, #1681; previously trivial: RTF import decodes the East Asian multibyte code pages, #1653; previously trivial: PDF export: lam-alef drawn as two glyphs at one x extracts in reading order, #2310; previously trivial: native .json stores pictures and kept parts as base64, #586 follow-up; previously trivial: ODT headers and footers read from each master page, #863; previously trivial: RTF import compares heading and code formatting with the file's stylesheet; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: Word XML and web pages saved as `.doc` open by what they hold, #2853; previously trivial: a VML shape in a header cell is always placed on the page, user-checked in Word for Mac, #1775; previously trivial: `w:sym` characters keep their symbol font when the text's font changes and are written back as `w:sym`, #2036; previously trivial: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: two lines in one and horizontal in vertical (`w:eastAsianLayout`) kept on save; previously trivial: PDF outline targets follow leading page breaks; previously trivial: positional tabs `w:ptab` read and kept on save, #2367; previously trivial: DOCX: mixed right-to-left runs split and marked `w:rtl` with their language, #1543; previously trivial: `w:doNotTrackMoves` round-trips and turns move tracking off; previously trivial: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: DOCX glossary documents (building blocks) read, kept and written; previously trivial: cached field results keep their visible run formatting; previously trivial: cached REF results retain hyperlink destinations; previously trivial: CLI conversions can explicitly refresh fields; previously trivial: a copied equation also goes in the clipboard's MathML formats, #1297; previously trivial: a pasted HTML `<blockquote>` is an indented paragraph, not the Quote style, #1270); previously trivial: every table style part round-trips, #714; previously trivial: VML freeforms read and kept on save; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: `flowChartOr` draws its circle and cross spokes, as in Word; previously trivial: RTF: Mac OS Roman and DOS text, #1653; previously trivial: VML text boxes keep their internal margins, fit to their text and vertical alignment; hidden drawings not shown; previously trivial: PDF export draws horizontal and vertical lines inside groups, #1474; previously trivial: symbol-font text exported as Unicode, #776; previously trivial: text-box margins, Resize shape to fit text and freeforms in groups, #743; previously trivial: formatted paste from the system clipboard's HTML and RTF, #687; previously trivial: independent complex-script formatting inheritance and round-trip regression tests; previously trivial: import/export fixes for TXT, RTF, ODT, HTML and LaTeX, #433–#440; previously major: first version; every format Word reads or writes, measured from the readers and writers on origin/main) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4, plus Word for Windows' extra formats+> 2026-10-27 · #4533 review: numeric REF updates lazily index body bookmarks once per update, retaining the first body bookmark for duplicate names. Unsupported switches and ordinary REF/PAGEREF behavior are unchanged; a synthetic 64-reference regression covers repeated updates and duplicate names. Estimates unchanged.+> 2026-10-27 · #4533: numeric REF fields use paragraph list numbers for no/full/relative context, reusing bounded numbering. Shared context already embedded in a level label is removed; merged-away cells do not count. Unsupported separator/text/position switches and ambiguous contexts or delimiter-free joins retain cached results. Synthetic OOXML regressions; no native Word or real-document validation, estimates unchanged.  Every format Word opens or saves, what WordCraft does with it, and how it's tested. Fidelity is the share of a typical real-world file's content and formatting that survives (read: shows correctly;@@ -258,8 +260,10 @@ Repeated DOCX style IDs use the last complete definition. The original regressio  ## Revision history +> 2026-10-27 · #4533 review: numeric REF updates lazily index body bookmarks once per update, retaining the first body bookmark for duplicate names. Unsupported switches and ordinary REF/PAGEREF behavior are unchanged; a synthetic 64-reference regression covers repeated updates and duplicate names. Estimates unchanged.+> 2026-10-27 · #4533: numeric REF fields use paragraph list numbers for no/full/relative context, reusing bounded numbering. Shared context already embedded in a level label is removed; merged-away cells do not count. Unsupported separator/text/position switches and ambiguous contexts or delimiter-free joins retain cached results. Synthetic OOXML regressions; no native Word or real-document validation, estimates unchanged. > 2026-10-25 · Arabic list labels: `arabicAlpha` and `arabicAbjad` draw the 28 Arabic letters (alphabetical and abjad order), doubling past the last letter; Hebrew, Hindi, Thai and Vietnamese still show decimal (`doc::section::tests::arabic_letters_count_in_both_orders`).-+> > 2026-10-23 · cu20we: DrawingML flat, square and round line caps are imported, saved, displayed and exported to PDF; absent or unknown caps default to flat. VML end caps (including shapetype inheritance) are preserved through DOCX save. Ink and metafile stroke handling remain separate. Synthetic DOCX, raster and PDF regressions cover the change; no new native Word comparison.  | Date | Change | Summary |diff --git a/docs/gaps.md b/docs/gaps.md--- a/docs/gaps.md+++ b/docs/gaps.md@@ -1,6 +1,8 @@ # Where WordCraft falls short of Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** trivial (View windows: several open documents and Switch Windows in the engine; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: text mini toolbar available with the right-click menu, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: tracked table/row/cell/section property changes record in WordCraft, narrowing gap 5; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: Format Page Numbers dialog carries Word's number formats and Continue from previous section / Start at, #1113; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: #8: English dialects — en-GB, en-CA, en-AU… flag each other's spellings, #1281; previously trivial: #1: shape gradients and transparency, #1500; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: line breaking: a slash opening a word travels whole to the next line, #2963; previously trivial: recipient list search and merged-only view, #1576; previously trivial: #2 impact restated: only ink rendering and OLE editing remain; previously trivial: #2 narrowed: native ink nested in groups and drawing canvases kept on save; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: automatic Asian/Latin and Asian/number spacing laid out, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: numbered headings, #1793; previously trivial: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: #8 narrowed: Indonesian proofing from the installed Hunspell dictionary, #498; previously trivial: glossary/building blocks closed; previously trivial: Split Cells and Convert Text to Table follow the Word check, #2592; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: #29: a copied equation also goes in the MathML clipboard formats, #1297; previously trivial: #24: the Spike, Ctrl+F3 and Ctrl+Shift+F3; previously trivial: VML freeforms read and kept on save; previously trivial: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: copies keep their formatting on the clipboard as HTML, #1523; previously trivial: sample-text formulas on Enter, #1067; previously trivial: #29: copied equations as MathML, OMML open as #1297, #816; previously trivial: the Font list no longer keeps every previewed font in memory, #848; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; previously minor: beta distance restated: ~15 points, ~150–230 h; previously: first version; every known shortfall from the 2026-10-10 re-measure, ranked) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** trivial (View windows: several open documents and Switch Windows in the engine; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: text mini toolbar available with the right-click menu, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: tracked table/row/cell/section property changes record in WordCraft, narrowing gap 5; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: Format Page Numbers dialog carries Word's number formats and Continue from previous section / Start at, #1113; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: #8: English dialects — en-GB, en-CA, en-AU… flag each other's spellings, #1281; previously trivial: #1: shape gradients and transparency, #1500; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: line breaking: a slash opening a word travels whole to the next line, #2963; previously trivial: recipient list search and merged-only view, #1576; previously trivial: #2 impact restated: only ink rendering and OLE editing remain; previously trivial: #2 narrowed: native ink nested in groups and drawing canvases kept on save; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: automatic Asian/Latin and Asian/number spacing laid out, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: numbered headings, #1793; previously trivial: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: #8 narrowed: Indonesian proofing from the installed Hunspell dictionary, #498; previously trivial: glossary/building blocks closed; previously trivial: Split Cells and Convert Text to Table follow the Word check, #2592; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: #29: a copied equation also goes in the MathML clipboard formats, #1297; previously trivial: #24: the Spike, Ctrl+F3 and Ctrl+Shift+F3; previously trivial: VML freeforms read and kept on save; previously trivial: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: copies keep their formatting on the clipboard as HTML, #1523; previously trivial: sample-text formulas on Enter, #1067; previously trivial: #29: copied equations as MathML, OMML open as #1297, #816; previously trivial: the Font list no longer keeps every previewed font in memory, #848; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; previously minor: beta distance restated: ~15 points, ~150–230 h; previously: first version; every known shortfall from the 2026-10-10 re-measure, ranked) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4+> 2026-10-27 · #4533 review: numeric REF updates lazily index body bookmarks once per update, retaining the first body bookmark for duplicate names. Unsupported switches and ordinary REF/PAGEREF behavior are unchanged; a synthetic 64-reference regression covers repeated updates and duplicate names. Estimates unchanged.+> 2026-10-27 · #4533: numeric REF fields use paragraph list numbers for no/full/relative context, reusing bounded numbering. Shared context already embedded in a level label is removed; merged-away cells do not count. Unsupported separator/text/position switches and ambiguous contexts or delimiter-free joins retain cached results. Synthetic OOXML regressions; no native Word or real-document validation, estimates unchanged. > **Highlight update:** 2026-10-25 · Highlight shortcut toggles the last chosen colour off when the whole selection has it; explicit colour commands remain setters (#4085). Readiness estimates unchanged. > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** trivial (#7: Custom Document Properties dialog, #2982; previously trivial: egui 0.37 migration: the interface catalogs stay shared and pinned by `craft-i18n.rev` at `9205108cfdced5177706264038848b68b2422d2b` (27 languages, English fallback); input-method handling has new regressions but managed CI passed, and native IME acceptance plus native-speaker catalog review remain open; previously trivial: Markdown code spans keep line-broken text literal, #3738; previously trivial: small follow-ups from the field, table and AutoFormat batch, #4232; previously trivial: highlight target includes selected paragraph marks, #4085; previously trivial: full-target highlight check beyond 10,000 runs, #4085; previously trivial: Exact-spacing table contact uses the specified line height rather than paragraph-mark metrics (#3977); previously trivial: cu20we: restrict pre-spacing float origins to paragraph anchors; document cap helpers and regressions; previously trivial: a command that changes nothing is not an edit: no undo step, no unsaved changes, no relayout, and the redo stack survives it; previously minor: #8 narrowed: Spanish proofing (Spain, Mexico, Latin America, Uruguay) from the installed Hunspell dictionaries, #3360, #3553; previously trivial: gap 10: group connector rerouting preserves transformed free and unresolved endpoints under nonuniform scaling; obstacle routing still missing; readiness estimates unchanged; previously trivial: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: the ranked gap list held two rows each for #19, #20 and #21; each gap appears once now; a document with many relationships opens in the time its part takes, #3411; previously trivial: the file commands that change the document are checked on a protected document, the protection of a protected document needs an explicit stop, the session author can't change through `file.setAuthor` under protection (the CLI's `--author` uses the same protection check), and the post-check compares the settings and the metadata; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: text mini toolbar available with the right-click menu, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: tracked table/row/cell/section property changes record in WordCraft, narrowing gap 5; previously trivial: a document with many content controls saves in the time the controls take, #13; previously trivial: Format Page Numbers dialog carries Word's number formats and Continue from previous section / Start at, #1113; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: #8: English dialects — en-GB, en-CA, en-AU… flag each other's spellings, #1281; previously trivial: #1: shape gradients and transparency, #1500; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: line breaking: a slash opening a word travels whole to the next line, #2963; previously trivial: recipient list search and merged-only view, #1576; previously trivial: #2 impact restated: only ink rendering and OLE editing remain; previously trivial: #2 narrowed: native ink nested in groups and drawing canvases kept on save; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: automatic Asian/Latin and Asian/number spacing laid out, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: numbered headings, #1793; previously trivial: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: #8 narrowed: Indonesian proofing from the installed Hunspell dictionary, #498; previously trivial: glossary/building blocks closed; previously trivial: Split Cells and Convert Text to Table follow the Word check, #2592; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: #29: a copied equation also goes in the MathML clipboard formats, #1297; previously trivial: #24: the Spike, Ctrl+F3 and Ctrl+Shift+F3; previously trivial: VML freeforms read and kept on save; previously trivial: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: copies keep their formatting on the clipboard as HTML, #1523; previously trivial: sample-text formulas on Enter, #1067; previously trivial: #29: copied equations as MathML, OMML open as #1297, #816; previously trivial: the Font list no longer keeps every previewed font in memory, #848; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; previously minor: beta distance restated: ~15 points, ~150–230 h; previously: first version; every known shortfall from the 2026-10-10 re-measure, ranked) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 @@ -142,10 +144,12 @@ Small follow-ups from the 2026-10-25 field, table and AutoFormat batch (#4232):  ## Revision history +> 2026-10-27 · #4533 review: numeric REF updates lazily index body bookmarks once per update, retaining the first body bookmark for duplicate names. Unsupported switches and ordinary REF/PAGEREF behavior are unchanged; a synthetic 64-reference regression covers repeated updates and duplicate names. Estimates unchanged.+> 2026-10-27 · #4533: numeric REF fields use paragraph list numbers for no/full/relative context, reusing bounded numbering. Shared context already embedded in a level label is removed; merged-away cells do not count. Unsupported separator/text/position switches and ambiguous contexts or delimiter-free joins retain cached results. Synthetic OOXML regressions; no native Word or real-document validation, estimates unchanged. > 2026-10-23 · cu20we review follow-up: Only paragraph-relative box floats use the pre-spacing origin. Line-relative floats and page/margin fallbacks in cells and text boxes keep the text-top origin. Synthetic controls compare zero and 24 pt space-before across all four box contexts. New cap conversion helpers and regression tests document their contracts; readiness estimates unchanged.-+> > 2026-10-23 · cu20we: DrawingML flat, square and round line caps are imported, saved, displayed and exported to PDF; absent or unknown caps default to flat. VML end caps (including shapetype inheritance) are preserved through DOCX save. Ink and metafile stroke handling remain separate. Synthetic DOCX, raster and PDF regressions cover the change; no new native Word comparison.-+> > 2026-10-23 · cu20we: Paragraph-relative floats in headers, footers, cells and text boxes now start above effective space before; synthetic layout regressions cover all four contexts. Framed paragraphs already used the pre-spacing position. No new native Word comparison; broader object-position parity remains open.  | Date | Change | Summary |diff --git a/docs/layout-parity.md b/docs/layout-parity.md--- a/docs/layout-parity.md+++ b/docs/layout-parity.md@@ -1,6 +1,8 @@ # Layout and pagination parity with Microsoft Word  > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** trivial (continuous sections one after another go onto new pages instead of running off the page; empty marks after another empty section mark take a line each until the page is full, then stay at its bottom drawing nothing, not even a list label; an empty mark that takes no room draws no list label either; a kept-together paragraph is measured against the page it would move to, so a tall different first-page header no longer splits it, #3907; previously trivial: a justified line ending in a manual line break is stretched to the margin unless `w:doNotExpandShiftReturn` is set, #3924; previously trivial: a no-break space is as wide as a space, #4192; previously trivial: a bookmark or other zero-width marker is no line-break opportunity, #4193; previously trivial: Arabic list labels: `arabicAlpha` and `arabicAbjad` draw the 28 Arabic letters (alphabetical and abjad order), doubling past the last letter; Hebrew, Hindi, Thai and Vietnamese still show decimal (`doc::section::tests::arabic_letters_count_in_both_orders`); previously trivial: Preserve grapheme edit/wrap boundaries across independently drawn font/style pieces; Exact-spacing table contact uses the specified line height rather than paragraph-mark metrics (#3977); previously trivial: cu20we: restrict pre-spacing float origins to paragraph anchors; document cap helpers and regressions; previously trivial: cu20we: outline caps; previously trivial: cu20we: box float paragraph origin; previously trivial: group connector rerouting preserves transformed free and unresolved endpoints under nonuniform scaling; readiness estimates unchanged; previously trivial: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: an empty paragraph whose mark is hidden shows nothing, not even its list number, which is still counted, #3982; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: symbol fonts keep their line height without the font; previously trivial: an equation-array row without `&` is centred, #2617; previously trivial: a superscript or subscript sizes its line at the full font size, without its raise or drop, as Word does; previously trivial: an object dragged near the bottom of a page lands where it is dropped, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: justified lines shrink their spaces by Word's measured limits; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: a click below a floating table goes to the text beside or after it, not to a cell of its last row, #2038; previously trivial: shapes drawn with their gradients and transparency, #1500; previously trivial: paragraphs above a float's anchor wrap around it, also when that pushes the anchor onto the next page, #2048; previously trivial: triple borders draw three lines, #1740; previously trivial: the caret, clicks and selection edges fall between the letters of a ligature, #1974; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: VML header-cell floats always on the page, user-checked in Word for Mac, #1775; previously trivial: an at-least row with no room for its minimum starts the next page whole, #1742; previously trivial: AutoFit donors lose equal widths down to their content minima; previously trivial: automatic space between Asian text and Latin text or digits, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: positional tabs go to the margins or indents, #2367; previously trivial: field results with right-to-left text read right to left, #1670; previously trivial: a list bullet no installed font can draw shows the level's default bullet, #1683; previously trivial: a missing Thai font is drawn in one Thai face for the whole run, #1549; previously trivial: the caret after spaces hanging past the margin stays at the margin, #2146; previously trivial: covered black-circle fallback before UI sans; previously trivial: resolved split-cell continuation top insets; previously trivial: Symbol PCL6 alias uses Symbol encoding; previously trivial: exact full font names select their installed face; previously trivial: Arial Unicode MS uses proportional fallbacks; previously trivial: DrawingML outline dashes, including zero-width paths; previously trivial: TOCs include table-cell headings and retain full targets; previously trivial: kept table rows follow the next row; previously trivial: consistent cell widths override a stale table grid; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: paragraph spacing adds up when the document turns HTML auto spacing off; previously trivial: an inherited footer sizes its percentage tables by its own section; previously trivial: an empty section mark stays on a full page; previously trivial: a fitting row with less room than its minimum height moves on whole; oversized rows still split; previously trivial: text past an exact-height row is cut off; previously trivial: a list number stays with text after a leading page break; previously trivial: a bookmark after a page break takes no line; previously trivial: a page break followed by a page break before or a next-page section starts one page; previously trivial: All Caps and Small Caps draw ß as SS, #1581; previously trivial: justified vertical page alignment, #1320; previously trivial: page numbers restart at 0; previously trivial: a list label moves with its first line when the paragraph is centred or end-aligned (#1159); previously trivial: PAGE fields in a paragraph split across pages show the page they are on, #1352; previously trivial: a dragged floating object anchors in the column it lands in, #884; previously trivial: a paragraph ending on a page with footnotes keeps its space after above the separator, #1116; previously trivial: symbol-font text drawn as Unicode symbols, #776; previously trivial: large-table scrolling measured and fixed, #811; previously trivial: text boxes use their own margins; Resize shape to fit text never cuts text, #743; previously trivial: complex-script shaping and Myanmar line breaking, #604; previously trivial: body page totals, table-cell footnotes and bookmark link pages fixed, #450 #451 #455; previously major: first version; line breaking, pagination and object placement checked against Word's behaviour from the layout source on origin/main) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4+> 2026-10-27 · #4533 review: numeric REF updates lazily index body bookmarks once per update, retaining the first body bookmark for duplicate names. Unsupported switches and ordinary REF/PAGEREF behavior are unchanged; a synthetic 64-reference regression covers repeated updates and duplicate names. Estimates unchanged.+> 2026-10-27 · #4533: numeric REF fields use paragraph list numbers for no/full/relative context, reusing bounded numbering. Shared context already embedded in a level label is removed; merged-away cells do not count. Unsupported separator/text/position switches and ambiguous contexts or delimiter-free joins retain cached results. Synthetic OOXML regressions; no native Word or real-document validation, estimates unchanged.  A document only "opens correctly" if its pages break where Word breaks them: the same lines, the same page count, footnotes and pictures on the same pages. This checklist covers line breaking,@@ -256,12 +258,14 @@ layout suite are pending; this is not a new Word/native-IME acceptance claim.  ## Revision history +> 2026-10-27 · #4533 review: numeric REF updates lazily index body bookmarks once per update, retaining the first body bookmark for duplicate names. Unsupported switches and ordinary REF/PAGEREF behavior are unchanged; a synthetic 64-reference regression covers repeated updates and duplicate names. Estimates unchanged.+> 2026-10-27 · #4533: numeric REF fields use paragraph list numbers for no/full/relative context, reusing bounded numbering. Shared context already embedded in a level label is removed; merged-away cells do not count. Unsupported separator/text/position switches and ambiguous contexts or delimiter-free joins retain cached results. Synthetic OOXML regressions; no native Word or real-document validation, estimates unchanged. > 2026-10-25 · Arabic list labels: `arabicAlpha` and `arabicAbjad` draw the 28 Arabic letters (alphabetical and abjad order), doubling past the last letter; Hebrew, Hindi, Thai and Vietnamese still show decimal (`doc::section::tests::arabic_letters_count_in_both_orders`).-+> > 2026-10-23 · cu20we review follow-up: Only paragraph-relative box floats use the pre-spacing origin. Line-relative floats and page/margin fallbacks in cells and text boxes keep the text-top origin. Synthetic controls compare zero and 24 pt space-before across all four box contexts. New cap conversion helpers and regression tests document their contracts; readiness estimates unchanged.-+> > 2026-10-23 · cu20we: DrawingML flat, square and round line caps are imported, saved, displayed and exported to PDF; absent or unknown caps default to flat. VML end caps (including shapetype inheritance) are preserved through DOCX save. Ink and metafile stroke handling remain separate. Synthetic DOCX, raster and PDF regressions cover the change; no new native Word comparison.-+> > 2026-10-23 · cu20we: Paragraph-relative floats in headers, footers, table cells and text boxes start above effective paragraph space before, consistent with the body layout path (cu20we). Synthetic regressions cover all four contexts; native Word comparison remains pending.  | Date | Change | Summary |