From 734dedde28354fc71b17ed398dfdfb4e7fa6bb29 Mon Sep 17 00:00:00 2001 From: justinjohn0306 Date: Thu, 15 Oct 2026 12:12:27 +0530 Subject: [PATCH 001/609] #1913: apply paragraph spacing presets to styles --- ROADMAP.md | 5 ++-- crates/engine/src/cmd/design.rs | 45 ++++++++++++++++++++++++++++++--- docs/target-app-parity.md | 5 ++-- docs/ui-parity.md | 3 ++- 4 files changed, 49 insertions(+), 9 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 6ef6b33708..704e1a3ca9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,8 +2,8 @@ **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-14 · **Change:** 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-14 · **Change:** trivial (progress log: print-area strings translated in every catalog; 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 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-15 · **Change:** trivial (Design › Paragraph Spacing presets update built-in paragraph styles, #1913; 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-15 · **Change:** trivial (Design › Paragraph Spacing presets update built-in paragraph styles, #1913; progress log: print-area strings translated in every catalog; 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. WordCraft aims for complete parity with Microsoft Word, then goes further on speed, openness and @@ -135,6 +135,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm ## Progress log | Date | What landed | +| 2026-10-15 | Design › Paragraph Spacing presets update built-in paragraph styles, so existing styled paragraphs follow the preset (#1913) | | 2026-10-14 | DOCX row table border exceptions render and survive saving. Explicit cell borders win; a row exception does not change other rows. | | 2026-10-14 | Tab stops edited on the ruler: the corner selector picks Left/Center/Right/Decimal/Bar, a click sets a stop (Alt skips the snap), dragging moves it with a guide line and position tooltip, dragging off the ruler clears it; markers draw per kind and mirror for RTL; one `para.tabs` call and one undo step per gesture | | 2026-10-12 | Fields keep `w:dirty` through DOCX saves (#877): a begin marker flagged by a generator that couldn't compute a result (pandoc-style TOC placeholders) keeps the flag on open/save — as a buffered field or a range field — so Word still refreshes it on open; computing a result (Update Field, Update Table) clears it, like Word's F9 | diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index d1fedc1602..6e9d5b19e4 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -2,7 +2,7 @@ use serde_json::{Value, json}; use wordcraft_doc::props::{Border, BorderStyle, Borders, LineSpacing, Rgb, TextColor}; -use wordcraft_doc::{Watermark, styles}; +use wordcraft_doc::{StyleKind, Watermark, styles}; use super::sel_result; use crate::{CmdError, CmdResult, CommandSpec, Session, p}; @@ -190,9 +190,15 @@ fn para_spacing(s: &mut Session, v: &Value) -> CmdResult { "double" => (0.0, 8.0, 2.0), _ => (0.0, 8.0, 1.15), }; - s.doc.styles.default_para.space_before = Some(before); - s.doc.styles.default_para.space_after = Some(after); - s.doc.styles.default_para.line_spacing = Some(LineSpacing::Multiple(line)); + let apply = |p: &mut wordcraft_doc::props::ParaProps| { + p.space_before = Some(before); + p.space_after = Some(after); + p.line_spacing = Some(LineSpacing::Multiple(line)); + }; + apply(&mut s.doc.styles.default_para); + for style in s.doc.styles.styles.iter_mut().filter(|style| style.builtin && style.kind == StyleKind::Paragraph) { + apply(&mut style.para); + } sel_result(s) } @@ -237,3 +243,34 @@ fn page_borders(s: &mut Session, v: &Value) -> CmdResult { } sel_result(s) } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + use wordcraft_doc::{Document, Style}; + + #[test] + fn paragraph_spacing_preset_updates_builtin_styles_and_keeps_custom_styles() { + let mut s = Session::new(Document::new()); + s.doc.styles.styles.push(Style { + id: "CustomSpacing".into(), + name: "Custom Spacing".into(), + kind: StyleKind::Paragraph, + builtin: false, + para: wordcraft_doc::props::ParaProps { space_after: Some(24.0), ..Default::default() }, + ..Default::default() + }); + + s.run("design.paragraphSpacing", &json!({"value": "double"})).unwrap(); + + let normal = s.doc.styles.get("Normal").unwrap(); + assert_eq!(normal.para.line_spacing, Some(LineSpacing::Multiple(2.0))); + let heading = s.doc.styles.get("Heading1").unwrap(); + assert_eq!((heading.para.space_before, heading.para.space_after), (Some(0.0), Some(8.0))); + assert_eq!(heading.para.line_spacing, Some(LineSpacing::Multiple(2.0))); + let custom = s.doc.styles.get("CustomSpacing").unwrap(); + assert_eq!(custom.para.space_after, Some(24.0)); + assert_eq!(custom.para.line_spacing, None); + } +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2699ee237d..dfe2cb81bd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # WordCraft parity with Microsoft Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** trivial (Ink to Shape recognises arrows; previously trivial: Windows Magnifier follows the caret onto a new line, #1119; previously trivial: table border drags with Ctrl and Alt, from the left edge and of selected cells, #711; 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: all 12 bibliography styles, #383; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; 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; replaces the parity tables that lived in ROADMAP.md) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-15 · **Change:** trivial (Design › Paragraph Spacing presets update built-in paragraph styles, #1913; Ink to Shape recognises arrows; previously trivial: Windows Magnifier follows the caret onto a new line, #1119; previously trivial: table border drags with Ctrl and Alt, from the left edge and of selected cells, #711; 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: all 12 bibliography styles, #383; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; 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; replaces the parity tables that lived in ROADMAP.md) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 The authoritative assessment of how close WordCraft is to Microsoft Word. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) itemizes every shortfall; the deep checklists are @@ -57,7 +57,7 @@ full parity for the area. | Area | Weight | Parity | Was (2026-10-06) | Hours | Evidence and what's missing | |---|---|---|---|---|---| | Typing, selection, clipboard, undo, find/replace | 12 | 85% | 85% | 8–12 | Typing parity pinned by `tests_typing.rs` ([typing-parity.md](typing-parity.md)). Paste Special (#235), Advanced Find (#234) and Column Selection (#237) landed; Clipboard pane still missing (PR #264 open). | -| Character and paragraph formatting | 11 | 82% | 85% | 8–12 | Nearly every property, Font/Paragraph dialogs, character border, Phonetic Guide (#288), Enclose Characters (#297). Missing: Asian Typography, kerning/ligature/stylistic-set options in the Font dialog's Advanced tab. | +| Character and paragraph formatting | 11 | 82% | 85% | 8–12 | Nearly every property, Font/Paragraph dialogs, character border, Phonetic Guide (#288), Enclose Characters (#297); Design › Paragraph Spacing presets update built-in paragraph styles (#1913). Missing: Asian Typography, kerning/ligature/stylistic-set options in the Font dialog's Advanced tab. | | Styles and themes | 8 | 74% | 75% | 8–12 | Gallery, pane, create/modify, style sets, themes. Style Inspector landed (#236). Missing: Manage Styles (#270 open), style separators, linked-style edge cases; Word ships 11 Quick Style sets plus dozens of themes, we ship our own smaller set. | | Lists | 6 | 78% | 75% | 5–8 | Bullets, numbering, multilevel, restart, `w:lvlOverride` levels (#134), Word's list AutoFormat and Enter/Backspace behaviour. Missing: Define New Multilevel List dialog depth, list styles, legal numbering edge cases. | | Tables | 8 | 76% | 72% | 10–16 | Merge/split, styles (cell text takes style formatting, #104), custom table styles saved in the .docx (#256), Word 2013 edge, floating tables, rows split across pages, sort, formula, cell gridlines (#243), Draw Table and Eraser (#303). Missing: splitting or erasing around vertically merged cells, nested-table polish. Dragging column and row borders and the resize handle on the page (#217) and the column and row markers on the rulers (#700) landed, with Word's Ctrl, Alt, left-edge and selected-cells drags (#711), and so did selecting columns, rows and cells, the "+" insert buttons, the move handle and double-click AutoFit on the page, Select Column, and drags and Shift+arrows over cells selecting whole cells; right-clicking a cell offers the table's commands, following the selection as in Word (Delete Cells, Rows, Columns or Table, Merge and Split Cells, Distribute, AutoFit, Text Direction, Insert Caption…, Table Properties…); cell text direction landed (#245). | @@ -251,6 +251,7 @@ can be used without committing Word output. | Date | Change | Summary | |---|---|---| +| 2026-10-15 | trivial | Character and paragraph formatting: Design › Paragraph Spacing presets update built-in paragraph styles (#1913); no percentage change | | 2026-10-12 | minor | Czech proofing review: short-word splits rank after deletion, NOSUGGEST excludes suggestions while accepting typed forms, affix comments apply only to headers, ratios keep spaces and repeated-word messages use Czech quotes; synthetic engine end-to-end and latency checks | | 2026-10-12 | minor | Czech spelling from the installed Hunspell dictionary, runtime-table suggestions and generic checks; Czech interface writes cs-CZ documents; no Czech hyphenation patterns bundled; estimates unchanged | | 2026-10-13 | trivial | Windows Magnifier follows the caret onto a new line (#1119): Accessibility row updated; no percentage change | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b1c503f5c5..d78acade56 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity with Microsoft Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** trivial (Modify Table Style formats every table style part, #714); previously trivial: a click on the ribbon chrome hands the keyboard to the page in the same frame, #1093 follow-up; previously trivial: Page Setup vertical alignment, #1320; previously trivial: the app opens on the Home tab every launch, as in Word; previously trivial: no document behind the Start screen, #1129; previously trivial: equation pictures share a few textures, #1002; previously trivial: selection bar in the left margin, #856; 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 major: first version; ribbon, dialogs, shortcuts and on-canvas interaction measured from `crates/ui-egui` and the command registry) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-15 · **Change:** trivial (Design › Paragraph Spacing presets update built-in paragraph styles, #1913; Modify Table Style formats every table style part, #714); previously trivial: a click on the ribbon chrome hands the keyboard to the page in the same frame, #1093 follow-up; previously trivial: Page Setup vertical alignment, #1320; previously trivial: the app opens on the Home tab every launch, as in Word; previously trivial: no document behind the Start screen, #1129; previously trivial: equation pictures share a few textures, #1002; previously trivial: selection bar in the left margin, #856; 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 major: first version; ribbon, dialogs, shortcuts and on-canvas interaction measured from `crates/ui-egui` and the command registry) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 How WordCraft looks and feels next to Word: ribbon, dialogs, panes, keyboard, mouse and touch. Typing behaviour has its own checklist ([`typing-parity.md`](typing-parity.md)). All assets are our @@ -59,6 +59,7 @@ Document title opens Rename Document; the account badge opens Options › Genera | Date | Change | Summary | |---|---|---| +| 2026-10-15 | trivial | Design › Paragraph Spacing presets update built-in paragraph styles, so existing styled paragraphs follow the preset (#1913) | | 2026-10-13 | trivial | New/Modify Table Style: No Border on a part that inherits its lines hides them; emptying the font box makes the part's font inherited again (#1288) | | 2026-10-14 | trivial | Tab stops edited on the ruler: corner kind selector, click to set, drag to move or off to clear, per-kind markers mirrored for RTL; each gesture one `para.tabs` call and one undo step; Rulers 85% → 90% | | 2026-10-12 | trivial | Tables on the page: one selected cell (Select Cell, or a click along its left edge) is a cell selection when its border is dragged: the border moves in its row only (#962) | From 1f2510ddda2044742ed45772dfb679987ed88703 Mon Sep 17 00:00:00 2001 From: Diego Guerini Date: Thu, 15 Oct 2026 20:48:21 +0200 Subject: [PATCH 002/609] #2150: Latin text keeps its digits, spaces and punctuation in order in right-to-left text UAX #9 alone showed "2-naphthol" after a Persian word as "naphthol-2" in a right-to-left paragraph (the hyphen went with the Persian text) and "11 Windows" for "Windows 11", and in a left-to-right paragraph the digit after Arabic letters became an Arabic number placed before the Persian word. bidi_levels now keeps Latin text together: from the word with the first left-to-right letter to the word with the last letter or digit after it, without crossing a right-to-left letter, a tab or an explicit embedding mark, everything takes the letters' level, except sentence punctuation at either end. The spaces and punctuation between it and the right-to-left text take the paragraph's level (rule N2). Numbers alone and text across tabs are left to UAX #9. Co-Authored-By: Claude Opus 5.5 --- crates/layout/src/para.rs | 49 ++++++++++++++++++++++++- crates/layout/src/tests_bidi.rs | 64 +++++++++++++++++++++++++++++++++ docs/layout-parity.md | 5 +-- docs/target-app-parity.md | 3 +- 4 files changed, 117 insertions(+), 4 deletions(-) diff --git a/crates/layout/src/para.rs b/crates/layout/src/para.rs index 6b1ea46fd4..a40ffdbb32 100644 --- a/crates/layout/src/para.rs +++ b/crates/layout/src/para.rs @@ -625,7 +625,54 @@ pub fn bidi_levels(text: &str, rtl_para: bool) -> Vec { } let level = if rtl_para { unicode_bidi::Level::rtl() } else { unicode_bidi::Level::ltr() }; let info = unicode_bidi::ParagraphBidiInfo::new(text, Some(level)); - info.levels.iter().map(|l| l.number()).collect() + let mut levels: Vec = info.levels.iter().map(|l| l.number()).collect(); + keep_latin_text_together(text, level.number(), &mut levels); + levels +} + +/// Latin text keeps the digits, spaces and punctuation inside it: "2-naphthol" or "Windows 11" +/// after a Persian word reads as typed, as in Word, instead of "naphthol-2" or "11 Windows" +/// (UAX #9 alone sends a neutral between a Latin letter and a digit to the paragraph's direction, +/// and a digit after Arabic letters becomes an Arabic number) (#2150). The Latin text runs from +/// the word with the first left-to-right letter to the word with the last letter or digit after +/// it, without crossing a right-to-left letter, a tab or an explicit embedding mark; it all takes its +/// letters' level, except sentence punctuation at either end, which stays the paragraph's. The +/// spaces and punctuation between it and the right-to-left text around it then sit between +/// opposite directions and take the paragraph's level (rule N2), so a space after a Persian word +/// stays between the two. +fn keep_latin_text_together(text: &str, base: u8, levels: &mut [u8]) { + use unicode_bidi::BidiClass::{AL, AN, B, BN, CS, EN, ES, ET, FSI, L, LRE, LRI, LRO, NSM, ON, PDF, PDI, R, RLE, RLI, RLO, S, WS}; + let chars: Vec<(usize, char, unicode_bidi::BidiClass)> = text.char_indices().map(|(i, c)| (i, c, unicode_bidi::bidi_class(c))).collect(); + let stop = |c: &unicode_bidi::BidiClass| matches!(c, R | AL | B | S | LRE | RLE | LRO | RLO | PDF | LRI | RLI | FSI | PDI); + let sentence_end = |c: char| matches!(c, '.' | ',' | ';' | ':' | '!' | '?' | '…' | '،' | '؛' | '؟'); + for seg in chars.split(|(_, _, c)| stop(c)) { + let Some(first) = seg.iter().position(|(_, _, c)| *c == L) else { continue }; + let Some(last) = seg.iter().rposition(|(_, _, c)| matches!(c, L | EN | AN)) else { continue }; + let word_start = seg.get(..first).and_then(|s| s.iter().rposition(|(_, _, c)| *c == WS)).map_or(0, |k| k + 1); + let start = seg.get(word_start..first).and_then(|s| s.iter().position(|&(_, c, _)| !sentence_end(c))).map_or(first, |k| word_start + k); + let word_end = seg.get(last..).and_then(|s| s.iter().position(|(_, _, c)| *c == WS)).map_or(seg.len(), |k| last + k); + let end = seg.get(..word_end).and_then(|s| s.iter().rposition(|&(_, c, _)| !sentence_end(c))).map_or(0, |k| k + 1).max(last + 1); + let Some(span) = seg.get(start..end) else { continue }; + let mut letter_levels = span.iter().filter(|(_, _, c)| *c == L).filter_map(|&(i, _, _)| levels.get(i).copied()); + let Some(lv) = letter_levels.next() else { continue }; + if !letter_levels.all(|l| l == lv) { + continue; + } + let mut set = |&(i, c, _): &(usize, char, unicode_bidi::BidiClass), to: u8| { + if let Some(l) = levels.get_mut(i..i + c.len_utf8()) { + l.fill(to); + } + }; + span.iter().for_each(|ch| set(ch, lv)); + // Inside an explicit embedding the paragraph's level isn't the neutrals' one: leave them. + if lv > base.saturating_add(1) { + continue; + } + let neutral = |ch: &&(usize, char, unicode_bidi::BidiClass)| matches!(ch.2, WS | ON | CS | ES | ET | BN | NSM); + let before = seg.get(..start).unwrap_or_default().iter().rev().take_while(neutral); + let after = seg.get(end..).unwrap_or_default().iter().take_while(neutral); + before.chain(after).for_each(|ch| set(ch, base)); + } } /// Rule L2 of UAX #9: the visual order (left to right) of items with these levels: from the diff --git a/crates/layout/src/tests_bidi.rs b/crates/layout/src/tests_bidi.rs index 5d20141f6f..cddd6c65a7 100644 --- a/crates/layout/src/tests_bidi.rs +++ b/crates/layout/src/tests_bidi.rs @@ -82,6 +82,70 @@ fn levels_for_persian_with_latin_and_numbers() { assert_eq!(lv[at("Hello سلام", 6)], 1); } +/// #2150: Latin text with digits, hyphens, spaces, full stops and commas after a Persian word +/// reads as typed, as in Word, in a right-to-left and in a left-to-right paragraph; UAX #9 alone +/// showed "naphthol-2" and "11 Windows" (the neutral went with the Persian text) and, in a +/// left-to-right paragraph, put a digit before the Persian word. +#[test] +fn latin_text_keeps_its_digits_spaces_and_punctuation_in_order() { + let latin = [ + "2-naphthol", + "naphthol-2", + "(2-naphthol)", + "1,2-dichloroethane", + "naphthol 2", + "Windows 11", + "Fig. 3", + "e.g. 2, 3 and 4", + "version 2.0 of the paper", + ]; + for w in latin { + let s = format!("برای مثال {w}"); + for rtl in [true, false] { + let lv = bidi_levels(&s, rtl); + let word = at(&s, 10); + assert!(lv[word..].iter().all(|&l| l == lv[word]), "{s:?} (rtl {rtl}) is one left-to-right run: {:?}", &lv[word..]); + assert_eq!(lv[word] % 2, 0, "{s:?}"); + assert_eq!(lv[at(&s, 9)], u8::from(rtl), "{s:?}: the space before the Latin text takes the paragraph's level"); + let d = doc_of(&[(&s, rtl)]); + let l = lay(&d); + let xs: Vec = (10..s.chars().count()).map(|n| cluster_x(&l, 0, at(&s, n))).collect(); + assert!(xs.windows(2).all(|p| p[0] < p[1]), "{s:?} (rtl {rtl}) reads left to right: {xs:?}"); + let persian = cluster_x(&l, 0, 0); + if rtl { + assert!(xs.iter().all(|&x| x < persian), "{s:?}: the Latin text comes after the Persian words, on their left"); + } else { + assert!(xs.iter().all(|&x| x > persian), "{s:?}: the Latin text comes after the Persian words, on their right"); + } + } + } + // Sentence punctuation after the Latin text still ends the right-to-left sentence (far + // left), and Persian words after it keep their place. + let s = "برای مثال Windows 11. سلام"; + let lv = bidi_levels(s, true); + assert_eq!(lv[at(s, 19)], 2, "the last 1 is the Latin text's"); + assert_eq!(lv[at(s, 20)], 1, "the full stop is the paragraph's"); + assert_eq!(lv[at(s, 21)], 1, "and so is the space after it"); + // Joined to a Persian word by a colon: the colon is the paragraph's, the Latin text one run. + let s = "مثال:2-naphthol"; + let lv = bidi_levels(s, true); + assert_eq!(lv[at(s, 4)], 1); + assert!(lv[at(s, 5)..].iter().all(|&l| l == 2), "{lv:?}"); + // Inside an explicit isolate the Latin text is one run at the isolate's level. + let s = "سلام \u{2067}2-x\u{2069}"; + assert_eq!(&bidi_levels(s, true)[at(s, 6)..at(s, 9)], &[4, 4, 4]); + // Numbers alone and text across a tab are left to UAX #9. + for s in ["سال 5-10", "سال 2 و 3", "سلام 2\tx"] { + assert_eq!(bidi_levels(s, true), unicode_levels(s, true), "{s:?}"); + } +} + +/// UAX #9 levels with no adjustment. +fn unicode_levels(text: &str, rtl: bool) -> Vec { + let level = if rtl { unicode_bidi::Level::rtl() } else { unicode_bidi::Level::ltr() }; + unicode_bidi::ParagraphBidiInfo::new(text, Some(level)).levels.iter().map(|l| l.number()).collect() +} + #[test] fn rtl_paragraph_is_right_aligned_and_reads_right_to_left() { let s = "سلام دنیا"; diff --git a/docs/layout-parity.md b/docs/layout-parity.md index eb6ffad0a2..0618d2b91f 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -1,6 +1,6 @@ # Layout and pagination parity with Microsoft Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** 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 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-15 · **Change:** trivial (Latin text with digits and punctuation keeps its order in right-to-left text, #2150; 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 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, @@ -59,7 +59,7 @@ font can't match Word's metrics. | Vertical text (`tbRl`) in sections and text boxes; cell text direction | ✅ | cell text direction (#245); text-box text direction (#369); vertical sections (`tbRl`/`btLr`, #491): the page's text area turned, lines top to bottom stacking right to left, ideographs, kana and Hangul upright, Latin on its side, caret and clicks through the turn. Missing: OpenType `vert` alternates (punctuation is moved, not substituted), arrow keys along vertical lines, upright pictures take turned room | 2–4 | | Document grid (`w:docGrid`, lines per page, characters per line) | 🟡 | #391, #401: line grid snaps line heights to whole pitches (text centred in them; `w:snapToGrid` off opts a paragraph out); character grid puts East Asian characters on the character pitch (`linesAndChars`) or all text (`snapToChars`), Latin text proportional; View › Gridlines draws it. Not yet: run-level `w:snapToGrid`, grid in headers/footers, paragraph spacing in grid lines, Word's exact glyph placement in a cell | 1–2 | | Ruby / phonetic guide, enclose characters, combined characters | 🟡 | ruby (Phonetic Guide) landed (#288): ruby text over its base by alignment, line grows to fit, in PDF; enclose and combined characters missing; ruby not yet compared with Word page by page | 2–4 | -| Bidirectional paragraphs, mixed-direction lines; RTL tables and sections | 🟡 | #207; RTL tables (#362): grid columns from the right edge, start alignment and indent from the right margin, cell margins and left/right borders mirrored, merged and turned cells and nested tables included; RTL sections (#362): newspaper columns right to left with the line between mirrored. Right-hand page gutter (`w:rtlGutter`) missing | 1 | +| Bidirectional paragraphs, mixed-direction lines; RTL tables and sections | 🟡 | #207; RTL tables (#362): grid columns from the right edge, start alignment and indent from the right margin, cell margins and left/right borders mirrored, merged and turned cells and nested tables included; RTL sections (#362): newspaper columns right to left with the line between mirrored. Latin text keeps its digits, spaces and punctuation in order inside right-to-left text (#2150). Right-hand page gutter (`w:rtlGutter`) missing | 1 | | Equations: display layout, numbering, wrapping long display equations | ✅ | #191; long display equations break at top-level operators (`m:brkBin`, `m:brkBinSub`), manual breaks and `m:alnAt`, continuation lines indented by `m:wrapIndent` or set right (`m:wrapRight`) (#326) | — | | Hidden text excluded from breaking and hyphenation | ✅ | #173 | — | | Fields: PAGE, NUMPAGES, SECTIONPAGES, TOC page numbers | ✅ | #52; totals in the body need a second pass once the page count is known (#451) | — | @@ -159,6 +159,7 @@ No overall parity estimate changes from these probes. | Date | Change | Summary | |---|---|---| +| 2026-10-15 | trivial | Mixed-direction lines: Latin text with digits, hyphens, spaces, full stops and commas after a Persian or Arabic word reads as typed ("2-naphthol", "Windows 11"), as in Word, in right-to-left and left-to-right paragraphs, instead of "naphthol-2" (#2150) | | 2026-10-14 | trivial | Row table border exceptions draw without leaking into other rows | | 2026-10-14 | trivial | Consistent cell widths override a stale table grid | | 2026-10-14 | trivial | Paragraphs inside complex-field instructions take no flow height; empty result paragraphs keep their line. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2699ee237d..c8a0bfeada 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # WordCraft parity with Microsoft Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** trivial (Ink to Shape recognises arrows; previously trivial: Windows Magnifier follows the caret onto a new line, #1119; previously trivial: table border drags with Ctrl and Alt, from the left edge and of selected cells, #711; 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: all 12 bibliography styles, #383; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; 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; replaces the parity tables that lived in ROADMAP.md) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-15 · **Change:** trivial (Latin text with digits and punctuation keeps its order in right-to-left text, #2150; previously trivial: Ink to Shape recognises arrows; previously trivial: Windows Magnifier follows the caret onto a new line, #1119; previously trivial: table border drags with Ctrl and Alt, from the left edge and of selected cells, #711; 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: all 12 bibliography styles, #383; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; 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; replaces the parity tables that lived in ROADMAP.md) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 The authoritative assessment of how close WordCraft is to Microsoft Word. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) itemizes every shortfall; the deep checklists are @@ -251,6 +251,7 @@ can be used without committing Word output. | Date | Change | Summary | |---|---|---| +| 2026-10-15 | trivial | Complex scripts and right-to-left: Latin text with digits, hyphens, spaces and punctuation after a Persian or Arabic word reads as typed ("2-naphthol" no longer shows as "naphthol-2"), as in Word (#2150); no percentage change | | 2026-10-12 | minor | Czech proofing review: short-word splits rank after deletion, NOSUGGEST excludes suggestions while accepting typed forms, affix comments apply only to headers, ratios keep spaces and repeated-word messages use Czech quotes; synthetic engine end-to-end and latency checks | | 2026-10-12 | minor | Czech spelling from the installed Hunspell dictionary, runtime-table suggestions and generic checks; Czech interface writes cs-CZ documents; no Czech hyphenation patterns bundled; estimates unchanged | | 2026-10-13 | trivial | Windows Magnifier follows the caret onto a new line (#1119): Accessibility row updated; no percentage change | From ab35bfa94647f69d1ce20b49388e3e38fa97b547 Mon Sep 17 00:00:00 2001 From: Divyanshu Gupta Date: Fri, 16 Oct 2026 07:27:30 +0530 Subject: [PATCH 003/609] fix(doc): format hex number format as uppercase hex and support millions in cardinal text --- crates/doc/src/section.rs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/section.rs b/crates/doc/src/section.rs index 21591fa422..b0650ffa0c 100644 --- a/crates/doc/src/section.rs +++ b/crates/doc/src/section.rs @@ -262,6 +262,7 @@ impl NumFormat { use crate::cjk_numbers as cjk; match self { NumFormat::DecimalZero => format!("{n:02}"), + NumFormat::Hex => format!("{n:X}"), NumFormat::UpperRoman => roman(n).to_uppercase(), NumFormat::LowerRoman => roman(n), NumFormat::UpperLetter => letters(n).to_uppercase(), @@ -304,7 +305,6 @@ impl NumFormat { NumFormat::Chosung => cjk::chosung(n), NumFormat::Decimal | NumFormat::DecimalHalfWidth - | NumFormat::Hex | NumFormat::VietnameseCounting | NumFormat::Hebrew1 | NumFormat::Hebrew2 @@ -436,13 +436,21 @@ pub fn cardinal_text(n: u32) -> String { let h = format!("{} hundred", words(n / 100)); if n.is_multiple_of(100) { h } else { format!("{h} {}", words(n % 100)) } } - _ => { + 1_000..=999_999 => { let th = format!("{} thousand", words(n / 1000)); if n.is_multiple_of(1000) { th } else { format!("{th} {}", words(n % 1000)) } } + 1_000_000..=999_999_999 => { + let m = format!("{} million", words(n / 1_000_000)); + if n.is_multiple_of(1_000_000) { m } else { format!("{m} {}", words(n % 1_000_000)) } + } + _ => { + let b = format!("{} billion", words(n / 1_000_000_000)); + if n.is_multiple_of(1_000_000_000) { b } else { format!("{b} {}", words(n % 1_000_000_000)) } + } } } - capitalize(&words(n.min(999_999))) + capitalize(&words(n)) } /// English ordinal words (`Twenty-First`). @@ -883,6 +891,13 @@ mod tests { assert_eq!(NumFormat::OrdinalText.format(20), "Twentieth"); assert_eq!(NumFormat::OrdinalText.format(112), "One Hundred Twelfth"); assert_eq!(NumFormat::DecimalZero.format(3), "03"); + assert_eq!(NumFormat::Hex.format(10), "A"); + assert_eq!(NumFormat::Hex.format(15), "F"); + assert_eq!(NumFormat::Hex.format(16), "10"); + assert_eq!(NumFormat::Hex.format(255), "FF"); + assert_eq!(NumFormat::CardinalText.format(1_000_000), "One Million"); + assert_eq!(NumFormat::OrdinalText.format(1_000_000), "One Millionth"); + assert_eq!(NumFormat::CardinalText.format(2_000_000_000), "Two Billion"); assert!(!NumFormat::UpperRoman.format(u32::MAX).is_empty()); assert_eq!(NumFormat::LowerLetter.format(u32::MAX).len(), 30); assert_eq!([NumFormat::Chicago.format(1), NumFormat::Chicago.format(6)], ["*", "\u{2020}\u{2020}"]); From 73f0701255c15402d018e49f7d5d569b61d340ea Mon Sep 17 00:00:00 2001 From: justinjohn0306 Date: Fri, 16 Oct 2026 13:43:51 +0530 Subject: [PATCH 004/609] #1913: expose spacing templates in Backstage --- ROADMAP.md | 1 + crates/ui-egui/src/backstage.rs | 9 +++++++ crates/ui-egui/src/file_dialogs.rs | 39 ++++++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + docs/ui-parity.md | 1 + 5 files changed, 51 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index 704e1a3ca9..7e86461400 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -135,6 +135,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm ## Progress log | Date | What landed | +| 2026-10-16 | Design › Paragraph Spacing defaults can be saved as a `.dotx` from File › Save As and reused from File › New (#1913 follow-up) | | 2026-10-15 | Design › Paragraph Spacing presets update built-in paragraph styles, so existing styled paragraphs follow the preset (#1913) | | 2026-10-14 | DOCX row table border exceptions render and survive saving. Explicit cell borders win; a row exception does not change other rows. | | 2026-10-14 | Tab stops edited on the ruler: the corner selector picks Left/Center/Right/Decimal/Bar, a click sets a stop (Alt skips the snap), dragging moves it with a guide line and position tooltip, dragging off the ruler clears it; markers draw per kind and mirror for RTL; one `para.tabs` call and one undo step per gesture | diff --git a/crates/ui-egui/src/backstage.rs b/crates/ui-egui/src/backstage.rs index b89665ad3b..6b95383c06 100644 --- a/crates/ui-egui/src/backstage.rs +++ b/crates/ui-egui/src/backstage.rs @@ -319,6 +319,10 @@ fn home_page(app: &mut WordApp, ui: &mut Ui) { fn new_page(app: &mut WordApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); heading(ui, "New"); + if ui.button(tl!("Browse templates…")).clicked() { + app.new_from_template_dialog(); + } + ui.add_space(10.0); let id = egui::Id::new("backstage_template_search"); let mut query = ui.ctx().data(|d| d.get_temp::(id)).unwrap_or_default(); let search = ui.add(egui::TextEdit::singleline(&mut query).hint_text(tl!("Search for templates")).desired_width(360.0)); @@ -389,6 +393,9 @@ fn save_as_page(app: &mut WordApp, ui: &mut Ui) { if ui.button(egui::RichText::new(tl!("Browse…")).font(medium(14.0))).clicked() { app.save_as_dialog(); } + if ui.button(egui::RichText::new(tl!("Save as Template…")).font(medium(14.0))).clicked() { + app.save_template_dialog(); + } } fn info_page(app: &mut WordApp, ui: &mut Ui) { @@ -630,6 +637,7 @@ mod tests { h.run_steps(4); assert_eq!(h.state().ui.backstage_page, "new", "the link opens New"); assert!(h.query_by_label("Report").is_some(), "New shows every template"); + assert!(h.query_by_label("Browse templates…").is_some(), "New can create from a saved template"); assert!(h.query_by_label("Recent").is_none(), "New has no Recent list"); } @@ -709,6 +717,7 @@ mod tests { ); h.run_steps(4); assert!(h.query_by_label("Browse…").is_some(), "Save As has Browse button"); + assert!(h.query_by_label("Save as Template…").is_some(), "Save As can save a reusable template"); assert!(h.query_by_label("Recent").is_none(), "Save As has no list that opens documents"); } diff --git a/crates/ui-egui/src/file_dialogs.rs b/crates/ui-egui/src/file_dialogs.rs index 0dc13b1f3c..68498c797d 100644 --- a/crates/ui-egui/src/file_dialogs.rs +++ b/crates/ui-egui/src/file_dialogs.rs @@ -39,6 +39,7 @@ const DOCUMENTS: &[&str] = &["docx", "docm", "dotx", "dotm", "doc", "dot", "odt" /// The host's system dialog and the built-in browser offer the same. pub fn open_filters(purpose: &str) -> &'static [(&'static str, &'static [&'static str])] { match purpose { + "template" => &[("Word templates", &["dotx", "dotm"])], "picture" => &[("Pictures", PICTURES)], "font" => &[("Fonts", wordcraft_fonts::FONT_FILE_EXTS)], "recipients" => &[("Recipient lists", wordcraft_engine::cmd::mailings::RECIPIENT_EXTENSIONS), ("All files", &["*"])], @@ -50,12 +51,16 @@ pub fn open_filters(purpose: &str) -> &'static [(&'static str, &'static [&'stati pub(crate) enum AfterPick { /// Open the picked document. OpenDocument, + /// Create a document from a picked template. + NewFromTemplate, /// Insert the picked picture, or replace the pending Change Picture target. Picture, /// Save the document there, then carry on. SaveAs(AfterSave), /// Save a copy there in this format (`pdf`, `docx`, `png`…). Export { ext: String }, + /// Save the current document as a template. + SaveTemplate, /// Write the PDF of these print settings there (File › Print › Save these pages as PDF). PrintPdf { settings: Value }, /// Load the picked CSV/TSV/text file or spreadsheet as the mail-merge recipients (#240, #334). @@ -187,6 +192,12 @@ impl WordApp { self.ui.backstage = false; r } + AfterPick::NewFromTemplate => { + let Some(path) = picked else { return Ok(json!({"cancelled": true})) }; + let r = self.run("file.newFromTemplate", json!({"path": path})); + self.ui.backstage = false; + r + } AfterPick::Picture => { let Some(path) = picked else { self.change_picture_target = None; @@ -227,6 +238,10 @@ impl WordApp { } r } + AfterPick::SaveTemplate => { + let Some(path) = picked else { return Ok(json!({"cancelled": true})) }; + self.run("file.saveTemplate", json!({"path": path})) + } AfterPick::PrintPdf { settings } => { let Some(path) = picked else { return Ok(json!({"cancelled": true})) }; let mut params = settings; @@ -272,6 +287,17 @@ impl WordApp { let _ = self.save_as(AfterSave::Nothing); } + /// Save the current document as a reusable Word template. + pub(crate) fn save_template_dialog(&mut self) { + let name = format!("{}.dotx", self.title_stem()); + let _ = self.ask_file(FileDialogRequest::Save { name }, AfterPick::SaveTemplate); + } + + /// Pick a Word template and create a new document from it. + pub(crate) fn new_from_template_dialog(&mut self) { + let _ = self.ask_file(FileDialogRequest::Open { purpose: "template".into() }, AfterPick::NewFromTemplate); + } + /// Ask where to save, save there, then do `after`. pub(crate) fn save_as(&mut self, after: AfterSave) -> Asked { let name = self.default_save_name(); @@ -338,6 +364,19 @@ mod tests { use crate::Services; use wordcraft_engine::Session; + #[test] + fn saved_spacing_template_can_create_a_new_document() { + let root = std::env::temp_dir().join(format!("wordcraft-spacing-template-{}", std::process::id())); + let path = root.with_extension("dotx"); + let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default()); + app.run("design.paragraphSpacing", json!({"value": "double"})).unwrap(); + app.finish_pick(AfterPick::SaveTemplate, Some(path.to_string_lossy().into_owned())).unwrap(); + app.run("file.new", json!({})).unwrap(); + app.finish_pick(AfterPick::NewFromTemplate, Some(path.to_string_lossy().into_owned())).unwrap(); + assert_eq!(app.session.doc.styles.default_para.line_spacing, Some(wordcraft_doc::props::LineSpacing::Multiple(2.0))); + let _ = std::fs::remove_file(path); + } + const UNSAVED: &str = "My unsaved novel chapter"; /// Dialogs the fake host was asked to show, each with the channel its answer goes through. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index dfe2cb81bd..4e203fceca 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -250,6 +250,7 @@ can be used without committing Word output. ## Revision history | Date | Change | Summary | +| 2026-10-16 | trivial | Template save and create-from-template UI for reusable paragraph spacing defaults (#1913); no percentage change | |---|---|---| | 2026-10-15 | trivial | Character and paragraph formatting: Design › Paragraph Spacing presets update built-in paragraph styles (#1913); no percentage change | | 2026-10-12 | minor | Czech proofing review: short-word splits rank after deletion, NOSUGGEST excludes suggestions while accepting typed forms, affix comments apply only to headers, ratios keep spaces and repeated-word messages use Czech quotes; synthetic engine end-to-end and latency checks | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d78acade56..647ecc1457 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -58,6 +58,7 @@ Document title opens Rename Document; the account badge opens Options › Genera ## Revision history | Date | Change | Summary | +| 2026-10-16 | trivial | File › Save As exposes Save as Template and File › New can browse and create from a `.dotx`; spacing defaults survive the round trip (#1913) | |---|---|---| | 2026-10-15 | trivial | Design › Paragraph Spacing presets update built-in paragraph styles, so existing styled paragraphs follow the preset (#1913) | | 2026-10-13 | trivial | New/Modify Table Style: No Border on a part that inherits its lines hides them; emptying the font box makes the part's font inherited again (#1288) | From 1d890c093271aa11f7a0ef8913177b6df33383c3 Mon Sep 17 00:00:00 2001 From: justinjohn0306 Date: Fri, 16 Oct 2026 16:41:47 +0530 Subject: [PATCH 005/609] =?UTF-8?q?#1913:=20translate=20"Browse=20template?= =?UTF-8?q?s=E2=80=A6"=20in=20every=20interface=20catalog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The i18n audit failed on the new Backstage button. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/et.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sr-latn.tsv | 1 + crates/ui-egui/src/i18n/sr.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + 22 files changed, 22 insertions(+) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 66d02b6cf9..bfb5a10e33 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -938,6 +938,7 @@ {selected} of {words} words Думи: {selected} от {words} {words} words Думи: {words} Browse… Преглед… + Browse templates… Преглед на шаблони… Equation Уравнение Review Преглед Track\nChanges Проследяване\nна промените diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 02e380d826..382cd2daeb 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -158,6 +158,7 @@ Breaks Konce Bring Forward Přenést blíž Browse… Procházet… + Browse templates… Procházet šablony… Built-In Vestavěné Built-in style Vestavěný styl Built-in styles can't be deleted. Vestavěné styly nelze odstranit. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 6a9f286f88..6ec1035396 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -904,6 +904,7 @@ {group} settings {group}-Einstellungen {key}+Click to follow link {key}+Klick, um dem Link zu folgen Browse… Durchsuchen… + Browse templates… Vorlagen durchsuchen… {words} words Wörter: {words} {selected} of {words} words Wörter: {words}; ausgewählt: {selected} Direction: Richtung: diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 794cef7de7..fd8bf0c9a1 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1029,6 +1029,7 @@ {selected} of {words} words {selected} de {words} palabras {words} words {words} palabras Browse… Examinar… + Browse templates… Examinar plantillas… Equation Ecuación Review Revisar Track\nChanges Control de\ncambios diff --git a/crates/ui-egui/src/i18n/et.tsv b/crates/ui-egui/src/i18n/et.tsv index b37c9ac9d0..0b016c3709 100644 --- a/crates/ui-egui/src/i18n/et.tsv +++ b/crates/ui-egui/src/i18n/et.tsv @@ -1158,6 +1158,7 @@ Line breaking Reamurdmine Ungroup Tühista rühmitus Browse… Sirvi… + Browse templates… Sirvi malle… Draw Ink Joonista tindiga Erase Ink Kustuta tint Hide Ink Peida tint diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 78f281359a..91760a3b38 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -935,6 +935,7 @@ {group} settings Paramètres de {group} {key}+Click to follow link {key}+clic pour suivre le lien Browse… Parcourir… + Browse templates… Parcourir les modèles… {words} words {words} mots {selected} of {words} words {selected} mots sur {words} Apply Styles Appliquer les styles diff --git a/crates/ui-egui/src/i18n/hr.tsv b/crates/ui-egui/src/i18n/hr.tsv index 2fda6e1926..5c8e5f8009 100644 --- a/crates/ui-egui/src/i18n/hr.tsv +++ b/crates/ui-egui/src/i18n/hr.tsv @@ -298,6 +298,7 @@ Bring Forward Pomakni naprijed Browse in WordCraft… Pregledaj u programu WordCraft… Browse… Pregledaj… + Browse templates… Pregledaj predloške… Building Block Gallery Content Control Kontrola sadržaja galerije gradivnih blokova Built-In Ugrađeno Built-in style Ugrađeni stil diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 73d3f752ee..49444db56a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1092,6 +1092,7 @@ Preview Előnézet getartcraft.com/apps/wordcraft getartcraft.com/apps/wordcraft Browse… Tallózás… + Browse templates… Sablonok tallózása… AaBbYyZz AaBbYyZz ŐőŰű Align Top Left Igazítás balra fel Align Top Center Igazítás középre fel diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 0edbd298a2..33a586c124 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -925,6 +925,7 @@ {selected} of {words} words Parole: {words}; selezionate: {selected} {words} words Parole: {words} Browse… Sfoglia… + Browse templates… Sfoglia modelli… Equation Equazione Review Revisione Track\nChanges Revisioni diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9c92f9fcfd..7be0575d56 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -977,6 +977,7 @@ {group} settings {group} の設定 {key}+Click to follow link {key} キーを押しながらクリックしてリンク先を表示 Browse… 参照… + Browse templates… テンプレートを参照… {words} words {words} 語 {selected} of {words} words {selected}/{words} 語 Direction: 方向: diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 96002d803a..a9df0f1bc7 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -983,6 +983,7 @@ {group} settings {group} 설정 {key}+Click to follow link {key}+클릭하여 링크 열기 Browse… 찾아보기… + Browse templates… 서식 파일 찾아보기… {words} words 단어 {words}개 {selected} of {words} words 전체 {words}개 중 {selected}개 선택 Apply Styles 스타일 적용 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index dd9969a3b6..ffbe1d6778 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1088,6 +1088,7 @@ AutoSave only keeps .docx, .odt and .rtf files; {name} can't keep all formatting. Save as .docx to turn on AutoSave. Autozapis obsługuje tylko pliki .docx, .odt i .rtf; plik {name} nie zachowa całego formatowania. Zapisz jako .docx, aby włączyć Autozapis. Based on: {style} Na podstawie: {style} Browse… Przeglądaj… + Browse templates… Przeglądaj szablony… Built-in style Styl wbudowany Built-in styles can't be deleted. Nie można usuwać stylów wbudowanych. Change Password… Zmień hasło… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 5e44995910..735f9c34ea 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -977,6 +977,7 @@ {group} settings Configurações de {group} {key}+Click to follow link {key}+clique para seguir o link Browse… Procurar… + Browse templates… Procurar modelos… {words} words Palavras: {words} {selected} of {words} words Palavras: {words}; seleção: {selected} Dark page (white text on black) Página escura (texto branco sobre preto) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index a9c41168b7..33e9235512 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1102,6 +1102,7 @@ preview Title Пример Preview Предварительный просмотр getartcraft.com/apps/wordcraft getartcraft.com/apps/wordcraft Browse… Обзор… + Browse templates… Обзор шаблонов… # Equation gallery, themes, watermarks, paper sizes, table styles and other strings the # interface audit (`i18n/audit.rs`) found without a Russian entry. diff --git a/crates/ui-egui/src/i18n/sr-latn.tsv b/crates/ui-egui/src/i18n/sr-latn.tsv index 81d9f4f4af..976039325a 100644 --- a/crates/ui-egui/src/i18n/sr-latn.tsv +++ b/crates/ui-egui/src/i18n/sr-latn.tsv @@ -1039,6 +1039,7 @@ {name} is protected with a password. {name} je zaštićen lozinkom. {size} pt {size} pt Browse… Potraži… + Browse templates… Potraži šablone… {words} words {words} reči {selected} of {words} words {selected} od {words} reči Direction: Smer: diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 42bbeaf7b6..50630caa7c 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -1043,6 +1043,7 @@ {name} is protected with a password. {name} је заштићен лозинком. {size} pt {size} пт Browse… Потражи… + Browse templates… Потражи шаблоне… {words} words {words} речи {selected} of {words} words {selected} од {words} речи Direction: Смер: diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 6052c9a231..b2c0d1d094 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1019,6 +1019,7 @@ {selected} of {words} words {selected} av {words} ord {words} words {words} ord Browse… Bläddra… + Browse templates… Bläddra bland mallar… Equation Ekvation Review Granska Track\nChanges Spåra\nändringar diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 8ace2dd7b6..b15687d148 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1102,6 +1102,7 @@ preview Title Örnek Preview Önizleme getartcraft.com/apps/wordcraft getartcraft.com/apps/wordcraft Browse… Gözat… + Browse templates… Şablonlara gözat… # Equation gallery, themes, watermarks, paper sizes, table styles and other strings the # interface audit (`i18n/audit.rs`) found without a Russian entry. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index ca2070d95d..e64cf7991b 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1005,6 +1005,7 @@ {group} settings Параметри групи «{group}» {key}+Click to follow link {key}+клацання, щоб перейти за посиланням Browse… Огляд… + Browse templates… Огляд шаблонів… {words} words Слів: {words} {selected} of {words} words Слів: {words}; виділено: {selected} Apply Styles Застосувати стилі diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index c1d28add3d..0867ed5260 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -930,6 +930,7 @@ {selected} of {words} words Từ: {selected} trên {words} {words} words Từ: {words} Browse… Duyệt… + Browse templates… Duyệt mẫu… Equation Phương trình Review Xem lại Track\nChanges Theo dõi\nthay đổi diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 07b0861daa..9cb2ff4967 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -989,6 +989,7 @@ {group} settings {group}设置 {key}+Click to follow link 按住 {key} 并单击可访问链接 Browse… 浏览… + Browse templates… 浏览模板… {words} words {words} 个字 {selected} of {words} words {selected}/{words} 个字 Direction: 方向: diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 7b75dc9783..331b9cbbf9 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -978,6 +978,7 @@ {group} settings {group}設定 {key}+Click to follow link 按住 {key} 並按一下以追蹤連結 Browse… 瀏覽… + Browse templates… 瀏覽範本… {words} words {words} 個字 {selected} of {words} words {selected}/{words} 個字 Direction: 方向: From 62bf70beb301f3992dcb320d133e153082adea52 Mon Sep 17 00:00:00 2001 From: Diego Guerini Date: Sun, 18 Oct 2026 11:25:41 +0200 Subject: [PATCH 006/609] #2150: neutrals inside an explicit embedding keep the embedding's level Co-Authored-By: Claude Opus 5.5 --- crates/layout/src/para.rs | 18 +++++++++++++++++- crates/layout/src/tests_bidi.rs | 6 ++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/layout/src/para.rs b/crates/layout/src/para.rs index 72484f4e04..60732a2cc3 100644 --- a/crates/layout/src/para.rs +++ b/crates/layout/src/para.rs @@ -645,6 +645,22 @@ fn keep_latin_text_together(text: &str, base: u8, levels: &mut [u8]) { let chars: Vec<(usize, char, unicode_bidi::BidiClass)> = text.char_indices().map(|(i, c)| (i, c, unicode_bidi::bidi_class(c))).collect(); let stop = |c: &unicode_bidi::BidiClass| matches!(c, R | AL | B | S | LRE | RLE | LRO | RLO | PDF | LRI | RLI | FSI | PDI); let sentence_end = |c: char| matches!(c, '.' | ',' | ';' | ':' | '!' | '?' | '…' | '،' | '؛' | '؟'); + // Whether each byte is inside an explicit embedding, override or isolate: the paragraph's + // level isn't the neutrals' one there. The marks split the segments, so a segment is all in + // or all out. + let mut embedded = vec![false; text.len()]; + let mut depth = 0u32; + for &(i, c, class) in &chars { + match class { + LRE | RLE | LRO | RLO | LRI | RLI | FSI => depth = depth.saturating_add(1), + PDF | PDI => depth = depth.saturating_sub(1), + B => depth = 0, + _ => {} + } + if let Some(e) = embedded.get_mut(i..i + c.len_utf8()) { + e.fill(depth > 0); + } + } for seg in chars.split(|(_, _, c)| stop(c)) { let Some(first) = seg.iter().position(|(_, _, c)| *c == L) else { continue }; let Some(last) = seg.iter().rposition(|(_, _, c)| matches!(c, L | EN | AN)) else { continue }; @@ -665,7 +681,7 @@ fn keep_latin_text_together(text: &str, base: u8, levels: &mut [u8]) { }; span.iter().for_each(|ch| set(ch, lv)); // Inside an explicit embedding the paragraph's level isn't the neutrals' one: leave them. - if lv > base.saturating_add(1) { + if lv > base.saturating_add(1) || seg.first().is_some_and(|&(i, _, _)| embedded.get(i).copied().unwrap_or(false)) { continue; } let neutral = |ch: &&(usize, char, unicode_bidi::BidiClass)| matches!(ch.2, WS | ON | CS | ES | ET | BN | NSM); diff --git a/crates/layout/src/tests_bidi.rs b/crates/layout/src/tests_bidi.rs index cddd6c65a7..6ed32f13cd 100644 --- a/crates/layout/src/tests_bidi.rs +++ b/crates/layout/src/tests_bidi.rs @@ -134,6 +134,12 @@ fn latin_text_keeps_its_digits_spaces_and_punctuation_in_order() { // Inside an explicit isolate the Latin text is one run at the isolate's level. let s = "سلام \u{2067}2-x\u{2069}"; assert_eq!(&bidi_levels(s, true)[at(s, 6)..at(s, 9)], &[4, 4, 4]); + // Inside an explicit left-to-right embedding (LRE) one level above the paragraph's, the + // space before the Latin text keeps the embedding's level, so it stays before "foo". + let s = "سلام \u{202A} foo\u{202C}"; + let lv = bidi_levels(s, true); + assert_eq!(&lv[at(s, 6)..at(s, 10)], &[2, 2, 2, 2], "{lv:?}"); + assert_eq!(lv, unicode_levels(s, true)); // Numbers alone and text across a tab are left to UAX #9. for s in ["سال 5-10", "سال 2 و 3", "سلام 2\tx"] { assert_eq!(bidi_levels(s, true), unicode_levels(s, true), "{s:?}"); From 213b75ce02ad54c5cfd444608039d8dd0e796d4a Mon Sep 17 00:00:00 2001 From: Diego Guerini Date: Sun, 18 Oct 2026 12:37:08 +0200 Subject: [PATCH 007/609] #2150: a combining mark ending the right-to-left word keeps its level Co-Authored-By: Claude Opus 5.5 --- crates/layout/src/para.rs | 6 ++++-- crates/layout/src/tests_bidi.rs | 6 ++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/layout/src/para.rs b/crates/layout/src/para.rs index f8d8b59550..3d2232468d 100644 --- a/crates/layout/src/para.rs +++ b/crates/layout/src/para.rs @@ -732,7 +732,7 @@ pub fn bidi_levels(text: &str, rtl_para: bool) -> Vec { /// opposite directions and take the paragraph's level (rule N2), so a space after a Persian word /// stays between the two. fn keep_latin_text_together(text: &str, base: u8, levels: &mut [u8]) { - use unicode_bidi::BidiClass::{AL, AN, B, BN, CS, EN, ES, ET, FSI, L, LRE, LRI, LRO, NSM, ON, PDF, PDI, R, RLE, RLI, RLO, S, WS}; + use unicode_bidi::BidiClass::{AL, AN, B, BN, CS, EN, ES, ET, FSI, L, LRE, LRI, LRO, ON, PDF, PDI, R, RLE, RLI, RLO, S, WS}; let chars: Vec<(usize, char, unicode_bidi::BidiClass)> = text.char_indices().map(|(i, c)| (i, c, unicode_bidi::bidi_class(c))).collect(); let stop = |c: &unicode_bidi::BidiClass| matches!(c, R | AL | B | S | LRE | RLE | LRO | RLO | PDF | LRI | RLI | FSI | PDI); let sentence_end = |c: char| matches!(c, '.' | ',' | ';' | ':' | '!' | '?' | '…' | '،' | '؛' | '؟'); @@ -775,7 +775,9 @@ fn keep_latin_text_together(text: &str, base: u8, levels: &mut [u8]) { if lv > base.saturating_add(1) || seg.first().is_some_and(|&(i, _, _)| embedded.get(i).copied().unwrap_or(false)) { continue; } - let neutral = |ch: &&(usize, char, unicode_bidi::BidiClass)| matches!(ch.2, WS | ON | CS | ES | ET | BN | NSM); + // A combining mark at the edge belongs to the right-to-left letter before it (rule W1): + // it keeps that letter's level, so the word is shaped as one run. + let neutral = |ch: &&(usize, char, unicode_bidi::BidiClass)| matches!(ch.2, WS | ON | CS | ES | ET | BN); let before = seg.get(..start).unwrap_or_default().iter().rev().take_while(neutral); let after = seg.get(end..).unwrap_or_default().iter().take_while(neutral); before.chain(after).for_each(|ch| set(ch, base)); diff --git a/crates/layout/src/tests_bidi.rs b/crates/layout/src/tests_bidi.rs index 6ed32f13cd..c3766ca82b 100644 --- a/crates/layout/src/tests_bidi.rs +++ b/crates/layout/src/tests_bidi.rs @@ -140,6 +140,12 @@ fn latin_text_keeps_its_digits_spaces_and_punctuation_in_order() { let lv = bidi_levels(s, true); assert_eq!(&lv[at(s, 6)..at(s, 10)], &[2, 2, 2, 2], "{lv:?}"); assert_eq!(lv, unicode_levels(s, true)); + // A combining mark ending the Persian word before the Latin text (ٔ, U+0654) keeps the + // word's level, so the word is shaped in one run; only the space takes the paragraph's. + let s = "نسخهٔ Windows"; + let lv = bidi_levels(s, false); + assert_eq!(lv[at(s, 4)], 1, "{lv:?}"); + assert_eq!(lv[at(s, 5)], 0, "{lv:?}"); // Numbers alone and text across a tab are left to UAX #9. for s in ["سال 5-10", "سال 2 و 3", "سلام 2\tx"] { assert_eq!(bidi_levels(s, true), unicode_levels(s, true), "{s:?}"); From 71d341fcfb1c24cdefd837b1b455e1bccd14b46b Mon Sep 17 00:00:00 2001 From: Diego Guerini Date: Sun, 18 Oct 2026 23:25:30 +0200 Subject: [PATCH 008/609] #2150: a combining mark between a right-to-left letter and Latin text keeps its letter's level CodeRabbit: with no space between them, an Arabic or Persian letter's combining mark (NSM) began the segment the Latin span is found in, so the span gave it the Latin level and the mark was shaped apart from its letter. The marks the span starts with are left at their own level. Co-Authored-By: Claude Opus 5.5 --- crates/layout/src/para.rs | 6 ++++-- crates/layout/src/tests_bidi.rs | 8 ++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/layout/src/para.rs b/crates/layout/src/para.rs index ff2a496d8a..d47ebcfc96 100644 --- a/crates/layout/src/para.rs +++ b/crates/layout/src/para.rs @@ -746,7 +746,7 @@ pub fn bidi_levels(text: &str, rtl_para: bool) -> Vec { /// opposite directions and take the paragraph's level (rule N2), so a space after a Persian word /// stays between the two. fn keep_latin_text_together(text: &str, base: u8, levels: &mut [u8]) { - use unicode_bidi::BidiClass::{AL, AN, B, BN, CS, EN, ES, ET, FSI, L, LRE, LRI, LRO, ON, PDF, PDI, R, RLE, RLI, RLO, S, WS}; + use unicode_bidi::BidiClass::{AL, AN, B, BN, CS, EN, ES, ET, FSI, L, LRE, LRI, LRO, NSM, ON, PDF, PDI, R, RLE, RLI, RLO, S, WS}; let chars: Vec<(usize, char, unicode_bidi::BidiClass)> = text.char_indices().map(|(i, c)| (i, c, unicode_bidi::bidi_class(c))).collect(); let stop = |c: &unicode_bidi::BidiClass| matches!(c, R | AL | B | S | LRE | RLE | LRO | RLO | PDF | LRI | RLI | FSI | PDI); let sentence_end = |c: char| matches!(c, '.' | ',' | ';' | ':' | '!' | '?' | '…' | '،' | '؛' | '؟'); @@ -784,7 +784,9 @@ fn keep_latin_text_together(text: &str, base: u8, levels: &mut [u8]) { l.fill(to); } }; - span.iter().for_each(|ch| set(ch, lv)); + // Combining marks the span starts with belong to the right-to-left letter just before the + // segment (rule W1): they keep its level, so that letter is shaped with them. + span.iter().skip_while(|(_, _, c)| *c == NSM).for_each(|ch| set(ch, lv)); // Inside an explicit embedding the paragraph's level isn't the neutrals' one: leave them. if lv > base.saturating_add(1) || seg.first().is_some_and(|&(i, _, _)| embedded.get(i).copied().unwrap_or(false)) { continue; diff --git a/crates/layout/src/tests_bidi.rs b/crates/layout/src/tests_bidi.rs index c3766ca82b..7f04df3731 100644 --- a/crates/layout/src/tests_bidi.rs +++ b/crates/layout/src/tests_bidi.rs @@ -146,6 +146,14 @@ fn latin_text_keeps_its_digits_spaces_and_punctuation_in_order() { let lv = bidi_levels(s, false); assert_eq!(lv[at(s, 4)], 1, "{lv:?}"); assert_eq!(lv[at(s, 5)], 0, "{lv:?}"); + // With no space between them the mark still keeps the Persian word's level, in either + // paragraph direction; the Latin text after it is its own run. + let s = "نسخهٔWindows"; + for rtl in [true, false] { + let lv = bidi_levels(s, rtl); + assert_eq!(lv[at(s, 4)], lv[at(s, 3)], "rtl {rtl}: {lv:?}"); + assert_eq!(lv[at(s, 5)] % 2, 0, "rtl {rtl}: {lv:?}"); + } // Numbers alone and text across a tab are left to UAX #9. for s in ["سال 5-10", "سال 2 و 3", "سلام 2\tx"] { assert_eq!(bidi_levels(s, true), unicode_levels(s, true), "{s:?}"); From 0d75ca3bf67a37090102990bab339faa4fca1dc4 Mon Sep 17 00:00:00 2001 From: Diego Guerini Date: Mon, 19 Oct 2026 07:25:54 +0200 Subject: [PATCH 009/609] #2150: gap #16 and the progress log record Latin text kept in order in right-to-left lines CodeRabbit: `docs/gaps.md` still listed the right-to-left gap without this change and `ROADMAP.md` had no progress entry. Both are added, with their status lines and revision histories. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 4 +++- docs/gaps.md | 5 +++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index bda7581e50..aadf502a84 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **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-18 · **Change:** 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-19 · **Change:** trivial (progress log: Latin text in right-to-left lines keeps its order, #2150; 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-18 · **Change:** 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. @@ -139,6 +139,7 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target - 2026-10-15: Find opens Navigation on Results; editing the query restores Results after manual Headings/Pages navigation. Typed and selected-text searches retain document contents (#2096). | Date | What landed | +| 2026-10-19 | Mixed-direction lines: Latin text with digits, hyphens, spaces, full stops and commas after a Persian or Arabic word reads as typed ("2-naphthol", "Windows 11"), as in Word, in right-to-left and left-to-right paragraphs; a combining mark at the end of the Persian or Arabic word stays with its letter (#2150). | | 2026-10-18 | Clearing a font query with no matches keeps Recently Used Fonts visible at the top of a scrollable list. The initial scroll position no longer skips its heading; measured keyboard scrolling is unchanged (#2068). | | 2026-10-17 | Edit Recipient List finds records (#1576): a Find in list box hides rows with no cell containing the text (any case) and counts the matches, and "Show only records that will be merged" hides the rows the filter leaves out; both only change the view. Rows are striped, and edits and removes go to the right record however the grid is narrowed | | 2026-10-14 | DOCX row table border exceptions render and survive saving. Explicit cell borders win; a row exception does not change other rows. | @@ -501,6 +502,7 @@ Footer page-table height and body wrapping are corrected. Other pagination gaps | Date | Change | Summary | |---|---|---| +| 2026-10-19 | trivial | Progress log: Latin text in right-to-left lines keeps its order (#2150) | | 2026-10-18 | trivial | Font list starts at its first row after clearing a no-match query; recent heading remains visible (#2068) | | 2026-10-18 | trivial | A word after a slash wraps whole, like Word (#2963) | | 2026-10-17 | trivial | Progress log: recipient list search and merged-only view (#1576) | diff --git a/docs/gaps.md b/docs/gaps.md index fbadfe74bf..d3159454d6 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where WordCraft falls short of Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** 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-19 · **Change:** trivial (#16 narrowed: Latin text in right-to-left lines keeps its order, #2150; 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 > **Printing update:** 2026-10-12 · direct desktop printing through craft-print; details below. @@ -50,7 +50,7 @@ Active footnote and endnote text stays readable while editing (#2545). This fixe | 13 | **Charts and SmartArt editing** (editing charts and SmartArt from Word, more chart types and formatting) | | `insert.chart` and Chart Design basics landed (#409): WordCraft's own charts are editable; charts from Word stay read-only (no embedded-workbook editing), no combo/3D/radar/stock charts (charts of those types show a placeholder with their title and type, #998), axis or series formatting; Insert › SmartArt landed (#497) for graphics WordCraft makes | Reports and business documents | 35–55 | [target-app-parity.md](target-app-parity.md) | | 14 | **`.doc` can't be written; Word 6/95 files refused** | | `crates/docbin` is read-only | Users exchanging files with old Word or legacy systems | 25–40 | [file-format-parity.md](file-format-parity.md) | | 15 | **References depth**: no EndNote/Mendeley desktop integration (bibliography sources are saved in DOCX, #790; Zotero landed, #189; Word's own `Sources.xml` master list imports into Manage Sources, #2640) | | #790 stores sources in `customXml` and reads them back; `crates/zotero`; `references.sources` `import` reads a Word bibliography file (`b:Sources`) | Students and researchers | 3–6 | [target-app-parity.md](target-app-parity.md) | -| 16 | **Right-to-left completeness**: kashida, RTL in HTML/ODT/RTF; six still-open older RTL bug reports to re-verify after #207 (#211, #199, #66, #63, #48, #19; #215 is closed). RTL tables and sections landed (#362); PDF export's Hebrew and Arabic text copies and searches as whole words (#1383) | | [layout-parity.md](layout-parity.md) | Arabic, Persian, Hebrew writers | 7–11 | [layout-parity.md](layout-parity.md) | +| 16 | **Right-to-left completeness**: kashida, RTL in HTML/ODT/RTF; six still-open older RTL bug reports to re-verify after #207 (#211, #199, #66, #63, #48, #19; #215 is closed). RTL tables and sections landed (#362); PDF export's Hebrew and Arabic text copies and searches as whole words (#1383); Latin text with digits, spaces and punctuation after a Persian or Arabic word keeps its order ("2-naphthol", "Windows 11"), as in Word (#2150) | | [layout-parity.md](layout-parity.md) | Arabic, Persian, Hebrew writers | 7–11 | [layout-parity.md](layout-parity.md) | | 17 | **East Asian typography**: hint-reliant DFKai-SB contours repaired (local Windows regression; no readiness estimate change); Asian Typography options (Phonetic Guide landed, #288; Enclose Characters landed, #297; document grid landed, #391; vertical text landed, #491) | | `para.asianTypography` is live (Paragraph dialog Asian Typography tab, #323), automatic Asian/Latin and Asian/number spacing is laid out (#2358), and no East Asian item is left in the catalog's missing list; the remaining depth is not measured | Chinese, Japanese and Korean documents | 11–19 | [layout-parity.md](layout-parity.md) | | 19 | **RTF and ODT depth**: notes, comments, revisions (RTF and ODT insertions and deletions done; RTF paragraph-mark and character/paragraph formatting revisions done; RTF section/table and ODT formatting revisions left), sections (RTF import done, #1378; RTF export left; ODT export done), RTL. ODT sections landed on import (#1379): page-style changes and columned `text:section`s | | ~2,100 (RTF) and ~1,600 (ODT) lines in `crates/formats`; RTF code pages (#896) and page setup (#902), ODT page setup (#829) landed; open PRs: RTF notes and comments (#1056), ODT notes and comments (#1057), ODT headers and footers (#873) | Users exchanging with LibreOffice or older tools | 18–27 | [file-format-parity.md](file-format-parity.md) | | 18 | **Screen-reader access** to the document canvas: exposed, not yet tried with real screen readers | | The canvas describes paragraphs, headings, lists, tables, links, pictures and the caret to AccessKit (#488), tested headlessly; Windows Magnifier follows the caret, onto a new line too (#1119); no NVDA, VoiceOver or Orca run yet | Blind and low-vision users; public-sector procurement | 3–6 | [ui-parity.md](ui-parity.md) | @@ -106,6 +106,7 @@ Footer page-table height and body wrapping are corrected. Other pagination gaps | Date | Change | Summary | |---|---|---| +| 2026-10-19 | trivial | #16 narrowed: Latin text with digits, spaces and punctuation after a Persian or Arabic word keeps its order (#2150) | | 2026-10-18 | trivial | Font list starts at its first row after clearing a no-match query; recent heading remains visible (#2068) | | 2026-10-17 | trivial | #1327: Restrict Editing exceptions no longer let table, row or cell formatting change protected tables; formatting-only protection refuses Paste Formatting, table shading/borders/alignment/margins/text direction, table-style edits and locked table styles; recipient-list commands no longer rewrite merge-field results in a protected document. No gap row (enforcement fix); estimates unchanged | | 2026-10-17 | trivial | #21: Find in list and "Show only records that will be merged" in Edit Recipient List (#1576) | From 913d9fa5ab9a0de830ed5149efd3edac831b320a Mon Sep 17 00:00:00 2001 From: SlavenDj Date: Mon, 19 Oct 2026 23:43:49 +0200 Subject: [PATCH 010/609] =?UTF-8?q?Offer=20Blank=20document,=20Browse?= =?UTF-8?q?=E2=80=A6=20and=20Home=20in=20the=20empty=20window=20(#3126)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With no document open (Esc on the Start screen, File › Close) the page area was blank while the ribbon was greyed out, so the only way back to the Start screen was the account button. It now says no document is open and offers Blank document, Browse… and Home; Home returns to the Start screen without creating a document, and Blank document opens one ready for typing. --- ROADMAP.md | 3 ++- crates/ui-egui/src/canvas.rs | 32 ++++++++++++++++++++++++- crates/ui-egui/src/lib.rs | 46 ++++++++++++++++++++++++++++++++++-- docs/ui-parity.md | 5 ++-- 4 files changed, 80 insertions(+), 6 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 5a9fbf09fe..70f49dc55d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **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-19 · **Change:** 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-19 · **Change:** trivial (the empty window says no document is open and offers Blank document, Browse… and Home, #3126; 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-18 · **Change:** 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. @@ -141,6 +141,7 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target - 2026-10-15: Find opens Navigation on Results; editing the query restores Results after manual Headings/Pages navigation. Typed and selected-text searches retain document contents (#2096). | Date | What landed | +| 2026-10-19 | The empty window (no document, as after Esc on the Start screen or File › Close) says no document is open in the page area and offers Blank document, Browse… and Home; Home returns to the Start screen without making a document (#3126). | | 2026-10-19 | Save As, Export and Open no longer do nothing on Linux desktops whose file chooser portal fails to show its dialog (#2999): a "cancel" quicker than anyone could make one asks again without the parent window, then opens the built-in file browser. | | 2026-10-18 | Long navigation headings wrap onto further lines inside the resizable pane instead of ending in an ellipsis: the row grows with the text and the pane keeps its width (#759, #3015). | | 2026-10-18 | Clearing a font query with no matches keeps Recently Used Fonts visible at the top of a scrollable list. The initial scroll position no longer skips its heading; measured keyboard scrolling is unchanged (#2068). | diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index fabe1d43dc..1745f49cf1 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -12,7 +12,7 @@ use wordcraft_layout::display::CommentDisplay; use wordcraft_layout::{DocLayout, Page, Placed}; use crate::WordApp; -use crate::theme::{Tokens, regular, semibold}; +use crate::theme::{Tokens, medium, regular, semibold}; /// Points on screen per document point at 100% (96 px per inch, like a word processor). pub const PX_PER_PT: f32 = 96.0 / 72.0; @@ -899,6 +899,36 @@ fn drawing_grid_step(spacing: f32, scale: f32) -> f32 { step } +/// The page area with no document open (#3126): what to do next, so Esc on the Start screen or +/// File › Close leaves the ways to make or open a document in sight instead of just a greyed-out +/// ribbon that looks broken. The page itself stays empty until one is made or opened, as #1129 +/// has it; Home goes back to the Start screen. +pub(crate) fn empty_state(app: &mut WordApp, ui: &mut Ui) { + let t = Tokens::get(ui.ctx()); + let full = ui.available_rect_before_wrap(); + // Centred in the page area, but never pushed off the top of a short window. + ui.add_space(((full.height() - 100.0) * 0.5).max(24.0)); + ui.vertical_centered(|ui| { + ui.label(egui::RichText::new(tl!("No document is open. Create a document or open one first.")).font(regular(15.0)).color(t.text_dim)); + ui.add_space(16.0); + if ui.button(egui::RichText::new(tl!("Blank document")).font(medium(14.0))).clicked() { + let _ = app.run("file.new", json!({"template": "blank"})); + app.canvas.want_focus = true; + } + ui.add_space(2.0); + if ui.button(egui::RichText::new(tl!("Browse…")).font(medium(14.0))).clicked() { + let _ = app.run("ui.openFileDialog", json!({})); + } + ui.add_space(8.0); + // A frame-less button, so it reads as a link beside the two actions; the ribbon's Home tab + // is a button above it, so the test takes the lower one with the label. + let home = ui.add(egui::Button::new(egui::RichText::new(tl!("Home")).font(medium(13.5)).color(t.accent)).frame(false)); + if home.clicked() { + let _ = app.run("ui.backstage", json!({"value": true, "page": "home"})); + } + }); +} + pub fn show(app: &mut WordApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let full = ui.available_rect_before_wrap(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c7f687a4e8..40376262b4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2215,11 +2215,14 @@ impl WordApp { if self.ui.backstage { backstage::show(self, ui); } else if !self.has_document() { - // No document open (#1129): the ribbon greyed out but for Help, and no page. + // No document open (#1129): the ribbon greyed out but for Help, and no page. The page + // area says how to make or open one, the ways out of the empty window (#3126). chrome::title_bar(self, ui); ribbon::show(self, ui); chrome::status_bar(self, ui); - egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.canvas)).show(ui, |_| {}); + egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.canvas)).show(ui, |ui| { + canvas::empty_state(self, ui); + }); } else { chrome::title_bar(self, ui); if !self.session.view.focus_mode { @@ -3027,6 +3030,45 @@ mod tests { assert!(h.query_by_label("Blank document").is_some(), "where a document can be made"); } + /// #3126: the empty window (Esc on the Start screen, File › Close) is not a dead end: its + /// page area offers Blank document, Browse… and Home. Home returns to the Start screen and + /// makes nothing; Blank document makes one and the empty state gives way to the page. + #[test] + fn empty_window_offers_ways_to_make_or_open_a_document() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut a = app(); + a.start_screen(); + let mut h = harness(a); + h.run_steps(4); + h.key_press(egui::Key::Escape); + h.run_steps(4); + assert!(!h.state().has_document() && !h.state().ui.backstage, "the empty window"); + assert!(h.query_by_label("No document is open. Create a document or open one first.").is_some(), "the page area says what to do"); + assert!(h.query_by_role_and_label(Role::Button, "Blank document").is_some(), "Blank document is offered"); + assert!(h.query_by_role_and_label(Role::Button, "Browse…").is_some(), "Browse… is offered"); + // Home in the page area (the ribbon's Home tab shares the label but sits above it) goes + // back to the Start screen and creates no document. + let home = h + .get_all_by_role_and_label(Role::Button, "Home") + .max_by(|a, b| a.rect().top().total_cmp(&b.rect().top())) + .expect("a Home button in the page area"); + home.click(); + h.run_steps(4); + assert!(h.state().ui.backstage && h.state().ui.backstage_page == "home", "Home reaches the Start screen"); + assert!(!h.state().has_document(), "Home alone makes no document"); + h.key_press(egui::Key::Escape); + h.run_steps(4); + // Blank document makes one, ready for typing, and the empty state is gone. + h.get_by_role_and_label(Role::Button, "Blank document").click(); + h.run_steps(4); + assert!(h.query_by_label("No document is open. Create a document or open one first.").is_none(), "the page takes over"); + let a = h.state_mut(); + assert!(a.has_document() && !a.ui.backstage, "Blank document opens one"); + a.run("text.insert", json!({"text": "Hello"})).unwrap(); + assert_eq!(a.session.doc.plain_text(wordcraft_doc::StoryRef::Body).trim(), "Hello"); + } + /// #1908: with no document open the Home ribbon's split buttons grey out like the plain /// buttons beside them, and their drop-down arrow opens no menu. #[test] diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d4948067e1..c604e7c853 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity with Microsoft Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** 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: dragging the vertical scrollbar names the page at the top of the window, #2551; previously trivial: Add Font imports every selected font file, #1789); previously trivial (File › Close keeps the window, #1712; previously trivial: the Spike: Ctrl+F3 and Ctrl+Shift+F3; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: the tab strip never draws tabs over Comments / Editing / Share, #2026; previously trivial: Columns on selected text, #2024; previously trivial: Different First Page headers reachable from page 1, #2826; previously trivial: a copied equation also goes in the clipboard's MathML formats, #1297; previously trivial: Read Mode keeps the keyboard, shows whole columns and keeps text clear of the page-turn bar, #1772); previously trivial: font list entries of tall-ascent fonts sit in their row, not cut off, #2570); previously trivial: Split Cells and Convert Text to Table dialogs follow Word's merged-cell limits and Initial column width, #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 text fills the window width, #1876; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717)); previously trivial: comment balloons readable in the dark theme, #2045; previously trivial: Recently Used Fonts section at the top of the font list, #2068; previously trivial: web preferences kept between visits, #2132; previously trivial: dialog close control: a Windows-style box at the title bar's right end, the whole box clickable, red on hover, #1885); previously trivial (Modify Table Style formats every table style part, #714); previously trivial: a click on the ribbon chrome hands the keyboard to the page in the same frame, #1093 follow-up; previously trivial: Page Setup vertical alignment, #1320; previously trivial: the app opens on the Home tab every launch, as in Word; previously trivial: no document behind the Start screen, #1129; previously trivial: equation pictures share a few textures, #1002; previously trivial: selection bar in the left margin, #856; 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 major: first version; ribbon, dialogs, shortcuts and on-canvas interaction measured from `crates/ui-egui` and the command registry) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** trivial (the empty window says no document is open and offers Blank document, Browse… and Home, #3126; 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: dragging the vertical scrollbar names the page at the top of the window, #2551; previously trivial: Add Font imports every selected font file, #1789); previously trivial (File › Close keeps the window, #1712; previously trivial: the Spike: Ctrl+F3 and Ctrl+Shift+F3; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: the tab strip never draws tabs over Comments / Editing / Share, #2026; previously trivial: Columns on selected text, #2024; previously trivial: Different First Page headers reachable from page 1, #2826; previously trivial: a copied equation also goes in the clipboard's MathML formats, #1297; previously trivial: Read Mode keeps the keyboard, shows whole columns and keeps text clear of the page-turn bar, #1772); previously trivial: font list entries of tall-ascent fonts sit in their row, not cut off, #2570); previously trivial: Split Cells and Convert Text to Table dialogs follow Word's merged-cell limits and Initial column width, #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 text fills the window width, #1876; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717)); previously trivial: comment balloons readable in the dark theme, #2045; previously trivial: Recently Used Fonts section at the top of the font list, #2068; previously trivial: web preferences kept between visits, #2132; previously trivial: dialog close control: a Windows-style box at the title bar's right end, the whole box clickable, red on hover, #1885); previously trivial (Modify Table Style formats every table style part, #714); previously trivial: a click on the ribbon chrome hands the keyboard to the page in the same frame, #1093 follow-up; previously trivial: Page Setup vertical alignment, #1320; previously trivial: the app opens on the Home tab every launch, as in Word; previously trivial: no document behind the Start screen, #1129; previously trivial: equation pictures share a few textures, #1002; previously trivial: selection bar in the left margin, #856; 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 major: first version; ribbon, dialogs, shortcuts and on-canvas interaction measured from `crates/ui-egui` and the command registry) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 How WordCraft looks and feels next to Word: ribbon, dialogs, panes, keyboard, mouse and touch. Typing behaviour has its own checklist ([`typing-parity.md`](typing-parity.md)). All assets are our @@ -33,7 +33,7 @@ Document title opens Rename Document; the account badge opens Options › Genera | Task panes (Navigation, Styles, Comments, Reviewing, Format Picture/Shape, Thesaurus, Accessibility, Clipboard, Selection) | Navigation (long headings wrap onto further lines within the pane instead of expanding it, #759, #3015), Styles, Comments (balloons and cards read in both themes, #2045), Thesaurus, Restrict Editing, Accessibility (grouped findings, jump-to, fixes) and Alt Text (#386), Read Aloud, Zotero; Style Inspector (#236); Clipboard pane (#264) open | all | 70% | 4–6 | | Context menus (right-click) | text, spelling suggestions, fields (Update Field, Edit Field…, Toggle Field Codes, #339; Update Field on a table of contents entry updates the table, #1197, and after a save and reopen, #2182); right-click selects a picture, shape or text box and offers Insert Caption… (#1230) and Wrap Text (styles, Move with Text / Fix Position on Page, #513); tables, the items following the selection as in Word (Insert, Delete › Cells, Columns, Rows or Table whatever is selected (#1198), Merge and Split Cells, Distribute, AutoFit, Text Direction, Insert Caption…, Table Properties…; no Border Styles yet) | rich per context | 65% | 2–4 | | Task panes (Navigation, Styles, Comments, Reviewing, Format Picture/Shape, Thesaurus, Accessibility, Clipboard, Selection) | Navigation (long headings wrap onto further lines within the pane instead of expanding it, #759, #3015), Styles, Comments (typed comment and reply text stays with its document, is written before Save, Export, Print, Close, New or Open, Escape discards it, and the fields are read-only where comments can't change, #1348), Thesaurus, Restrict Editing, Accessibility (grouped findings, jump-to, fixes) and Alt Text (#386), Read Aloud, Zotero; Style Inspector (#236); Clipboard pane (#264) open | all | 70% | 4–6 | -| Backstage (Home, New, Open, Info, Save As, Print, Share, Export, Options) | Home and New separate (#254), Info properties kept (#268), Options in Word's panes with working settings (#485), Print page with preview, page range and copies (#641); launched with nothing to open, the app starts on Home (the Start screen: Blank document, templates, Recent; no document is open until one is picked or opened, so Esc or Back shows an empty window with the ribbon greyed out but for Help, #1129), with File › Options › General › Start-up to turn it off (#766); Info › Inspect Document finds and removes hidden text by its effective formatting (direct, character or paragraph style) in every story: body, headers, footers, notes, comments and text boxes, and lists what it couldn't reach (#1344); File › Close (Mod+W, Mod+F4) closes the document and keeps the window, showing no page, as Word does; the window's close button quits (#1712); each side-menu item has an icon, drawn in code (#1714) | | 68% | 4–6 | +| Backstage (Home, New, Open, Info, Save As, Print, Share, Export, Options) | Home and New separate (#254), Info properties kept (#268), Options in Word's panes with working settings (#485), Print page with preview, page range and copies (#641); launched with nothing to open, the app starts on Home (the Start screen: Blank document, templates, Recent; no document is open until one is picked or opened, so Esc or Back shows an empty window with the ribbon greyed out but for Help, #1129), whose page area says no document is open and offers Blank document, Browse… and Home; Home returns to the Start screen without making one (#3126), with File › Options › General › Start-up to turn it off (#766); Info › Inspect Document finds and removes hidden text by its effective formatting (direct, character or paragraph style) in every story: body, headers, footers, notes, comments and text boxes, and lists what it couldn't reach (#1344); File › Close (Mod+W, Mod+F4) closes the document and keeps the window, showing no page, as Word does; the window's close button quits (#1712); each side-menu item has an icon, drawn in code (#1714) | | 68% | 4–6 | | Rulers: indents, tabs, margins, table columns | indents draggable (one undo, #62); tab stops: corner selector (Left/Center/Right/Decimal/Bar), click to set, drag to move, drag off to clear, per-kind markers, Alt skips the snap, one undo step per gesture, double-click opens the Tabs dialog (#320); table column and row markers drag their borders (one undo) and in a cell the indents are measured from it (#700); the numbers thin out as the page shrinks on screen (every 1, 2, 4… units, never closer than 30 px, the small ticks never closer than 4 px, the text keeps its size), give way to an indent, tab or column marker on them, and the margins get ticks only; both rulers span the caret's page at its own scale in every layout (one column, One Page, Multiple Pages) and follow the caret to another page (#1878) | ✅ | 92% | 1 | | On-canvas objects: select, drag, resize handles, nudge | ✅ tested (#228); a picture or shape behind text can be dragged across the overlapping text (body and header/footer), whether or not it was selected first, while a click without movement still edits that text | ✅ | 75% | — | | On-canvas objects: select, drag, Ctrl+drag to copy, resize handles, nudge | ✅ tested (#228, #1014) | ✅ | 75% | — | @@ -74,6 +74,7 @@ Footnote and endnote editing keeps body and note text at normal opacity, on ligh | Date | Change | Summary | |---|---|---| +| 2026-10-19 | trivial | Empty window (#3126): with no document open (Esc on the Start screen, File › Close), the page area says no document is open and offers Blank document, Browse… and Home; Home goes back to the Start screen without making a document | | 2026-10-18 | trivial | Long navigation headings wrap onto further lines inside the pane instead of ending in an ellipsis; the row grows with the text and the pane still resizes (#759, #3015) | | 2026-10-18 | trivial | Font list starts at its first row after clearing a no-match query; recent heading remains visible (#2068) | | 2026-10-16 | trivial | Dragging the vertical scrollbar shows a tip beside the pointer with the page at the top of the window ("Page 7 of 10"); nothing said where the drag would land (#2551) | From a552c4bdda303f0e3058b8d74dc0800ed5605efd Mon Sep 17 00:00:00 2001 From: Michael Date: Tue, 20 Oct 2026 12:50:47 +0800 Subject: [PATCH 011/609] TOC: leave the caret after the table, not inside its own title MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit insert_toc builds the title paragraph, the field, and the entries, but never moves the selection afterward — whatever it was before the command (the document's original, now-displaced paragraph) stays put, which after a brand-new TOC on an otherwise-empty document is offset 0 of the TOCHeading paragraph itself, right before "Contents". Confirmed against real Word (16.0.20527.20054): Insert > Table of Contents leaves the caret in a fresh paragraph right after the table, ready to keep typing. Anyone following that same natural workflow in WordCraft today - insert a TOC placeholder, write headings and body text, call Update Table once done - ends up typing inside the TOC's own title paragraph instead, and the later Update Table call then splices "Contents" out of its own paragraph and onto whatever body paragraph happened to end up right before the entries, leaving the title blank. Move the selection to a paragraph right after the table once it's built (reusing one that's already there, or adding an empty one if the table ends the document), matching Word's placement and keeping the title and entries intact however the user continues from there. Fixes #3227. Co-Authored-By: Claude Sonnet 5 --- crates/engine/src/cmd/references.rs | 34 +++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/crates/engine/src/cmd/references.rs b/crates/engine/src/cmd/references.rs index 1d8edb6bc1..87569aa4aa 100644 --- a/crates/engine/src/cmd/references.rs +++ b/crates/engine/src/cmd/references.rs @@ -501,6 +501,15 @@ fn insert_toc(s: &mut Session, v: &Value) -> CmdResult { s.doc.insert_block(StoryRef::Body, &Path::top(i), Block::Para(head))?; let leader = leader(p::str(v, "tabLeader").unwrap_or("dot")); regenerate_toc(s, Some(leader), &tabs)?; + // Like Word, the caret lands in a paragraph right after the table, ready to keep typing — + // not inside the table's own title or entries, where typing (or Enter) would corrupt them. + if let Some((_, end)) = toc_range(s) { + let after = end + 1; + if s.doc.body.get(after).is_none() { + s.doc.insert_block(StoryRef::Body, &Path::top(after), Block::Para(Paragraph::new()))?; + } + s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(after), off: 0 }); + } s.clamp_selection(); sel_result(s) } @@ -1237,6 +1246,31 @@ mod tests { assert!(s.doc.bookmarks().iter().any(|(n, _)| format!("#{n}") == link), "{link}"); } + /// Inserting a table of contents (Word itself warns when there's no heading yet, but still + /// creates an empty one) must leave the caret in a fresh paragraph just after it, like Word + /// does — not inside the table's own title, where typing the rest of the document (and later + /// updating the table) would splice stray text into unrelated paragraphs and blank the title. + #[test] + fn a_toc_inserted_before_any_headings_exist_leaves_the_caret_after_it() { + let mut s = Session::new(wordcraft_doc::Document::new()); + s.run("references.toc", &json!({"levels": 2})).unwrap(); + assert_eq!(s.sel.focus.path, Path::top(1), "the caret must land right after the table, not inside it"); + s.run("text.insert", &json!({"text": "\r"})).unwrap(); + s.run("para.style", &json!({"style": "Heading 1"})).unwrap(); + s.run("text.insert", &json!({"text": "Kilns\r"})).unwrap(); + s.run("para.style", &json!({"style": "Normal"})).unwrap(); + s.run("text.insert", &json!({"text": "Body text."})).unwrap(); + s.run("references.updateToc", &json!({})).unwrap(); + assert_eq!( + s.doc.plain_text(StoryRef::Body).matches("Contents").count(), + 1, + "the title stays where it was, it doesn't vanish and reappear elsewhere" + ); + assert!(s.doc.plain_text(StoryRef::Body).contains("Body text."), "typed body content survives untouched"); + let heading = s.doc.body.iter().filter_map(|b| b.as_para()).find(|p| p.props.style.as_deref() == Some("Heading1")); + assert_eq!(heading.map(|p| p.plain_text()), Some("Kilns".to_string())); + } + /// #402: Caption numbering — a custom label above the paragraph, letters, and chapter /// numbers that restart after each Heading 1 (`STYLEREF 1 \s`, `SEQ … \s 1`). #[test] From c08be77357dcd41bd23eddeab041937b69a5c900 Mon Sep 17 00:00:00 2001 From: Michael Date: Tue, 20 Oct 2026 13:02:31 +0800 Subject: [PATCH 012/609] TOC: check the block after the table is a paragraph, not just present CodeRabbit found a real edge case: when a table of contents already has entries, is immediately followed by a table (nothing paragraph-shaped in between), and gets replaced in place by a settings change, the "does a block already exist after the table" check used Option::is_none, so it reused that existing block's path as the caret's position regardless of its type - landing the selection at the table's own top-level path. clamp_selection then silently snaps that invalid position back to the nearest *preceding* paragraph, i.e. back inside the table's own entries, reproducing a milder form of the very bug this PR fixes. Check the block is actually a paragraph before reusing it; insert one otherwise, same as when nothing is there at all. Co-Authored-By: Claude Sonnet 5 --- crates/engine/src/cmd/references.rs | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/references.rs b/crates/engine/src/cmd/references.rs index 87569aa4aa..5574e6d9a8 100644 --- a/crates/engine/src/cmd/references.rs +++ b/crates/engine/src/cmd/references.rs @@ -505,7 +505,8 @@ fn insert_toc(s: &mut Session, v: &Value) -> CmdResult { // not inside the table's own title or entries, where typing (or Enter) would corrupt them. if let Some((_, end)) = toc_range(s) { let after = end + 1; - if s.doc.body.get(after).is_none() { + let is_para = s.doc.body.get(after).is_some_and(|b| b.as_para().is_some()); + if !is_para { s.doc.insert_block(StoryRef::Body, &Path::top(after), Block::Para(Paragraph::new()))?; } s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(after), off: 0 }); @@ -1271,6 +1272,29 @@ mod tests { assert_eq!(heading.map(|p| p.plain_text()), Some("Kilns".to_string())); } + /// A settings-based replacement of a table whose last entry is directly followed by a table + /// (nothing paragraph-shaped in between) must still land the caret in a real paragraph: the + /// block "after" the table isn't always a paragraph just because it exists. + #[test] + fn a_toc_replaced_right_before_a_table_still_lands_the_caret_in_a_paragraph() { + let mut s = Session::new(wordcraft_doc::Document::new()); + s.run("references.toc", &json!({"levels": 2})).unwrap(); + s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap(); + let (_, end) = toc_range(&s).unwrap(); + while s.doc.body.get(end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())) { + s.doc.remove_block(StoryRef::Body, &Path::top(end + 1)).unwrap(); + } + assert!(matches!(&*s.doc.body[end + 1], Block::Table(_)), "test setup: a table must directly follow the table's entries"); + // Replacing the table's settings must still land the caret in a fresh paragraph right + // after the table, not snap back into the table's own entries (a bogus position pointing + // at the table gets silently corrected by `clamp_selection` to the nearest *preceding* + // paragraph, so a weaker "is this some paragraph" check wouldn't catch the regression). + s.run("references.toc", &json!({"levels": 3})).unwrap(); + let (_, new_end) = toc_range(&s).unwrap(); + assert_eq!(s.sel.focus.path, Path::top(new_end + 1), "the caret must land right after the table, not snap back into the table"); + assert!(matches!(&*s.doc.body[new_end + 1], Block::Para(_))); + } + /// #402: Caption numbering — a custom label above the paragraph, letters, and chapter /// numbers that restart after each Heading 1 (`STYLEREF 1 \s`, `SEQ … \s 1`). #[test] From aea58b38b8a97160b42b81b5b29f1dccbd8ab9c6 Mon Sep 17 00:00:00 2001 From: Divyanshu Gupta Date: Wed, 21 Oct 2026 23:49:45 +0530 Subject: [PATCH 013/609] fix(engine): apply Turkic case mapping in Change Case for Turkish, Azerbaijani, and Crimean Tatar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In Change Case, resolve the effective run language and apply language-aware casing for Turkish, Azerbaijani, and Crimean Tatar (mapping i <-> İ and ı <-> I). Non-Turkic languages continue to use default Unicode casing. Closes #3479 --- crates/engine/src/cmd/format.rs | 28 +++++++++---- crates/engine/src/cmd/tools.rs | 8 ++-- crates/engine/src/tests.rs | 71 +++++++++++++++++++++++++++++++++ docs/typing-parity.md | 3 +- 4 files changed, 96 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index 021e24baf4..cefee613e5 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -422,7 +422,15 @@ fn change_case(s: &mut Session, v: &Value) -> CmdResult { let to = if path == b.path { b.off } else { p.len() }; let chars = live_chars(p, from, to); let src: String = chars.iter().map(|(_, c)| c).collect(); - case_groups(p, &chars, &convert_chars(&src, &mode, from == 0)) + let turkic: Vec = chars + .iter() + .map(|&(off, _)| { + let rc = s.doc.styles.resolve_char(p.props.style.as_deref(), p.props_of_char(off)); + let lang = rc.lang.or_else(|| s.editing_lang.clone()); + super::tools::is_turkic(lang.as_deref()) + }) + .collect(); + case_groups(p, &chars, &convert_chars(&src, &turkic, &mode, from == 0)) }; if groups.is_empty() { continue; @@ -556,37 +564,41 @@ fn is_title(t: &str) -> bool { #[cfg(test)] fn convert(src: &str, mode: &str, para_start: bool) -> String { - convert_chars(src, mode, para_start).concat() + let non_turkic = vec![false; src.chars().count()]; + convert_chars(src, &non_turkic, mode, para_start).concat() } /// The case-converted form of each character of `src`, in order (one entry per char, so a /// change of length such as ß → SS or İ → i̇ can be applied run by run). -fn convert_chars(src: &str, mode: &str, para_start: bool) -> Vec { +fn convert_chars(src: &str, turkic: &[bool], mode: &str, para_start: bool) -> Vec { let chars: Vec = src.chars().collect(); + let is_tr = |i: usize| turkic.get(i).copied().unwrap_or(false); + let upper = |i: usize, c: char| -> String { super::tools::upper_char(c, is_tr(i)) }; // Greek capital sigma lowers to the final form at the end of a word (as `str::to_lowercase`). let lower = |i: usize, c: char| -> String { + let tr = is_tr(i); let prev = i.checked_sub(1).and_then(|j| chars.get(j)).is_some_and(|p| p.is_alphabetic()); let next = chars.get(i + 1).is_some_and(|n| n.is_alphabetic()); - if c == 'Σ' && prev && !next { "ς".to_string() } else { c.to_lowercase().collect() } + if !tr && c == 'Σ' && prev && !next { "ς".to_string() } else { super::tools::lower_char(c, tr) } }; // Title case capitalises the first word of any selection; sentence case only at a paragraph start. let mut up = mode == "title" || para_start; let mut out = Vec::with_capacity(chars.len()); for (i, &c) in chars.iter().enumerate() { let new = match mode { - "upper" => c.to_uppercase().collect(), + "upper" => upper(i, c), "lower" => lower(i, c), "toggle" => { if c.is_uppercase() { lower(i, c) } else { - c.to_uppercase().collect() + upper(i, c) } } "title" => { let n = if up && c.is_alphabetic() { up = false; - c.to_uppercase().collect() + upper(i, c) } else { lower(i, c) }; @@ -599,7 +611,7 @@ fn convert_chars(src: &str, mode: &str, para_start: bool) -> Vec { // Sentence case. let n = if up && c.is_alphabetic() { up = false; - c.to_uppercase().collect() + upper(i, c) } else { lower(i, c) }; diff --git a/crates/engine/src/cmd/tools.rs b/crates/engine/src/cmd/tools.rs index b02408dd21..d289587289 100644 --- a/crates/engine/src/cmd/tools.rs +++ b/crates/engine/src/cmd/tools.rs @@ -1002,7 +1002,7 @@ fn prev_token(before: &str) -> String { } /// Turkish, Azerbaijani (and Crimean Tatar) map `i`/`İ` and `ı`/`I` as pairs (#1923). -fn is_turkic(lang: Option<&str>) -> bool { +pub(crate) fn is_turkic(lang: Option<&str>) -> bool { if wordcraft_proof::ProofLang::from_tag(lang) == wordcraft_proof::ProofLang::Tr { return true; // tr, tur, any region, same normalisation as proofing } @@ -1012,7 +1012,7 @@ fn is_turkic(lang: Option<&str>) -> bool { } /// A letter in capitals: `i` → `İ` in Turkic languages, otherwise the Unicode default. -fn upper_char(c: char, turkic: bool) -> String { +pub(crate) fn upper_char(c: char, turkic: bool) -> String { if turkic && c == 'i' { return "\u{130}".to_string(); } @@ -1021,10 +1021,10 @@ fn upper_char(c: char, turkic: bool) -> String { /// A letter in lowercase: `I` → `ı` in Turkic languages. `İ` is always the single letter `i`, /// never `i` plus a combining dot. -fn lower_char(c: char, turkic: bool) -> String { +pub(crate) fn lower_char(c: char, turkic: bool) -> String { match c { 'I' if turkic => "\u{131}".to_string(), - '\u{130}' => "i".to_string(), + '\u{130}' if turkic => "i".to_string(), _ => c.to_lowercase().collect(), } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 4031e230a1..27a1ea78de 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5372,6 +5372,77 @@ fn change_case_keeps_each_runs_formatting_when_lengths_change() { assert_eq!(text(&s), "Q"); } +/// #3479: Change Case follows language-aware mapping for Turkish, Azerbaijani, and Crimean Tatar (i↔İ, ı↔I). +#[test] +fn change_case_follows_turkic_language_mapping() { + // 1. Turkish (tr-TR): all 5 modes + // Capitalize Each Word (title) + let mut s = s(); + run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true})); + run(&mut s, "text.insert", json!({"text": "istanbul ışık", "raw": true})); + run(&mut s, "select.all", json!({})); + run(&mut s, "format.changeCase", json!({"mode": "title"})); + assert_eq!(text(&s), "İstanbul Işık"); + + // UPPERCASE + run(&mut s, "format.changeCase", json!({"mode": "upper"})); + assert_eq!(text(&s), "İSTANBUL IŞIK"); + + // lowercase + run(&mut s, "format.changeCase", json!({"mode": "lower"})); + assert_eq!(text(&s), "istanbul ışık"); + + // sentence case + let mut s = self::s(); + run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true})); + run(&mut s, "text.insert", json!({"text": "istanbul. ışık.", "raw": true})); + run(&mut s, "select.all", json!({})); + run(&mut s, "format.changeCase", json!({"mode": "sentence"})); + assert_eq!(text(&s), "İstanbul. Işık."); + + // toggle case + let mut s = self::s(); + run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true})); + run(&mut s, "text.insert", json!({"text": "İstanbul Işık", "raw": true})); + run(&mut s, "select.all", json!({})); + run(&mut s, "format.changeCase", json!({"mode": "toggle"})); + assert_eq!(text(&s), "iSTANBUL ıŞIK"); + + // 2. Azerbaijani (az-AZ) + let mut s = self::s(); + run(&mut s, "review.language", json!({"lang": "az-AZ", "default": true})); + run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true})); + run(&mut s, "select.all", json!({})); + run(&mut s, "format.changeCase", json!({"mode": "title"})); + assert_eq!(text(&s), "İstanbul"); + + // 3. Crimean Tatar (crh) + let mut s = self::s(); + run(&mut s, "review.language", json!({"lang": "crh", "default": true})); + run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true})); + run(&mut s, "select.all", json!({})); + run(&mut s, "format.changeCase", json!({"mode": "title"})); + assert_eq!(text(&s), "İstanbul"); + + // 4. English control (en-US): unchanged Unicode default + let mut s = self::s(); + run(&mut s, "review.language", json!({"lang": "en-US", "default": true})); + run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true})); + run(&mut s, "select.all", json!({})); + run(&mut s, "format.changeCase", json!({"mode": "title"})); + assert_eq!(text(&s), "Istanbul"); + + // 5. Mixed-language selection: Turkish run followed by English run + let mut s = self::s(); + run(&mut s, "review.language", json!({"lang": "tr-TR"})); + run(&mut s, "text.insert", json!({"text": "istanbul ", "raw": true})); + run(&mut s, "review.language", json!({"lang": "en-US"})); + run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true})); + run(&mut s, "select.all", json!({})); + run(&mut s, "format.changeCase", json!({"mode": "title"})); + assert_eq!(text(&s), "İstanbul Istanbul"); +} + #[test] fn document_grid_sets_lines_and_characters_in_one_undo_step() { // #391: Layout › Page Setup › Document Grid. diff --git a/docs/typing-parity.md b/docs/typing-parity.md index 289ab6dea4..ddd48866a5 100644 --- a/docs/typing-parity.md +++ b/docs/typing-parity.md @@ -183,8 +183,7 @@ Applied when a word is finished by a space, punctuation **or Enter** (`enter_fin `İngilizce`, `ılık` → `Ilık`; observed in Word for Mac with Turkish proofing). Lowercasing `İ` gives the single letter `i` in every language, never `i` + combining dot. Other languages keep the Unicode default (`istanbul` → `Istanbul` in English) - (`autocorrect_capitalisation_follows_turkic_case_mapping`). Format > Change Case is not yet - Turkish-aware. + (`autocorrect_capitalisation_follows_turkic_case_mapping`). - Names of days are capitalised (`monday` → `Monday`). AutoCorrect Options (#412, `tools.autocorrect`, saved per user) switch each of these off: replacements, sentence and table-cell capitals, days, smart quotes, fractions, ordinals, dashes, links, bulleted and From c2cb17cb364a4a48ee9e9bafe19034aec4d71503 Mon Sep 17 00:00:00 2001 From: Divyanshu Gupta Date: Thu, 22 Oct 2026 00:19:56 +0530 Subject: [PATCH 014/609] fix(engine): support quoted literals and preserve bare 'a' in date pictures In format_date_parts, strip single quotes around literal text sections, preserve bare 'a'/'A' characters instead of treating them as AM/PM tokens, and zero-pad 12-hour clock hours when 'hh' is specified. Closes #3488 --- crates/engine/src/cmd/insert.rs | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index cf59390ade..b724be0311 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -831,6 +831,25 @@ pub fn format_date_parts(fmt: &str, y: i64, m: usize, d: u32, (hh, mm, ss): (u32 let mut i = 0; while i < chars.len() { let c = chars.get(i).copied().unwrap_or(' '); + // Literal text enclosed in single quotes: `'...'` (#3488). + if c == '\'' { + i += 1; + while i < chars.len() { + if chars[i] == '\'' { + if chars.get(i + 1) == Some(&'\'') { + out.push('\''); + i += 2; + } else { + i += 1; + break; + } + } else { + out.push(chars[i]); + i += 1; + } + } + continue; + } // `am/pm` (any case) is one token: AM or PM. if chars.get(i..i + 5).is_some_and(|w| w.iter().collect::().eq_ignore_ascii_case("am/pm")) { out.push_str(if hh < 12 { "AM" } else { "PM" }); @@ -854,12 +873,12 @@ pub fn format_date_parts(fmt: &str, y: i64, m: usize, d: u32, (hh, mm, ss): (u32 ('d', 1) => out.push_str(&d.to_string()), ('H', 2..) => out.push_str(&format!("{hh:02}")), ('H', _) => out.push_str(&hh.to_string()), + ('h', 2..) => out.push_str(&format!("{:02}", if hh.is_multiple_of(12) { 12 } else { hh % 12 })), ('h', _) => out.push_str(&(if hh.is_multiple_of(12) { 12 } else { hh % 12 }).to_string()), ('m', 2..) => out.push_str(&format!("{mm:02}")), ('m', _) => out.push_str(&mm.to_string()), ('s', 2..) => out.push_str(&format!("{ss:02}")), ('s', _) => out.push_str(&ss.to_string()), - ('a' | 'A', _) => out.push_str(if hh < 12 { "AM" } else { "PM" }), _ => { for _ in 0..n { out.push(c); @@ -1220,6 +1239,15 @@ mod tests { assert_eq!(date_picture(r#"DATE \@ "MMMM d, yyyy" \* MERGEFORMAT"#).as_deref(), Some("MMMM d, yyyy")); assert_eq!(date_picture(r#"TIME \@ HH:mm"#).as_deref(), Some("HH:mm")); assert_eq!(date_picture("DATE"), None); + + // #3488: Quoted literals and bare 'a' + use super::format_date_parts; + assert_eq!(format_date_parts("yyyy 'Q'", 2026, 10, 21, (14, 30, 0), 0), "2026 Q"); + assert_eq!(format_date_parts("yyyy 'at' h:mm", 2026, 10, 21, (9, 5, 0), 0), "2026 at 9:05"); + assert_eq!(format_date_parts("yyyy 'O''clock'", 2026, 10, 21, (14, 30, 0), 0), "2026 O'clock"); + assert_eq!(format_date_parts("yyyy a", 2026, 10, 21, (14, 30, 0), 0), "2026 a"); + assert_eq!(format_date_parts("hh:mm", 2026, 10, 21, (9, 5, 0), 0), "09:05"); + assert_eq!(format_date_parts("h:mm", 2026, 10, 21, (9, 5, 0), 0), "9:05"); } } From 6e783bdc6eb1b3b4b54579aaa62deda525b620ad Mon Sep 17 00:00:00 2001 From: Divyanshu Gupta Date: Thu, 22 Oct 2026 00:43:17 +0530 Subject: [PATCH 015/609] =?UTF-8?q?fix(engine):=20preserve=20AutoCorrect?= =?UTF-8?q?=20=C4=B0=20lowering=20for=20non-Turkic=20languages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep AutoCorrect's specific mapping of İ -> i for non-Turkic languages while allowing Change Case to use Unicode-default lowering, and add regression tests for English two-initial-capitals and caps-lock. --- crates/engine/src/cmd/format.rs | 14 +++++++++++--- crates/engine/src/cmd/tools.rs | 4 ++-- crates/engine/src/tests_typing.rs | 10 ++++++++++ 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index cefee613e5..7b104dba83 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -577,9 +577,17 @@ fn convert_chars(src: &str, turkic: &[bool], mode: &str, para_start: bool) -> Ve // Greek capital sigma lowers to the final form at the end of a word (as `str::to_lowercase`). let lower = |i: usize, c: char| -> String { let tr = is_tr(i); - let prev = i.checked_sub(1).and_then(|j| chars.get(j)).is_some_and(|p| p.is_alphabetic()); - let next = chars.get(i + 1).is_some_and(|n| n.is_alphabetic()); - if !tr && c == 'Σ' && prev && !next { "ς".to_string() } else { super::tools::lower_char(c, tr) } + if tr { + match c { + 'I' => "\u{131}".to_string(), + '\u{130}' => "i".to_string(), + _ => c.to_lowercase().collect(), + } + } else { + let prev = i.checked_sub(1).and_then(|j| chars.get(j)).is_some_and(|p| p.is_alphabetic()); + let next = chars.get(i + 1).is_some_and(|n| n.is_alphabetic()); + if c == 'Σ' && prev && !next { "ς".to_string() } else { c.to_lowercase().collect() } + } }; // Title case capitalises the first word of any selection; sentence case only at a paragraph start. let mut up = mode == "title" || para_start; diff --git a/crates/engine/src/cmd/tools.rs b/crates/engine/src/cmd/tools.rs index d289587289..edad68ec00 100644 --- a/crates/engine/src/cmd/tools.rs +++ b/crates/engine/src/cmd/tools.rs @@ -1021,10 +1021,10 @@ pub(crate) fn upper_char(c: char, turkic: bool) -> String { /// A letter in lowercase: `I` → `ı` in Turkic languages. `İ` is always the single letter `i`, /// never `i` plus a combining dot. -pub(crate) fn lower_char(c: char, turkic: bool) -> String { +fn lower_char(c: char, turkic: bool) -> String { match c { 'I' if turkic => "\u{131}".to_string(), - '\u{130}' if turkic => "i".to_string(), + '\u{130}' => "i".to_string(), _ => c.to_lowercase().collect(), } } diff --git a/crates/engine/src/tests_typing.rs b/crates/engine/src/tests_typing.rs index c610fd34c2..3918444384 100644 --- a/crates/engine/src/tests_typing.rs +++ b/crates/engine/src/tests_typing.rs @@ -1956,6 +1956,16 @@ fn autocorrect_capitalisation_follows_turkic_case_mapping() { run(&mut s, "review.language", json!({"lang": "en-US", "default": true})); typ(&mut s, "İNgilizce "); assert_eq!(s.doc.plain_text(StoryRef::Body), "İngilizce ", "no combining dot in any language"); + + // Regression check (#3503): Two initial capitals and caps-lock with stray İ in English + let mut s = self::s(); + run(&mut s, "review.language", json!({"lang": "en-US", "default": true})); + typ(&mut s, "Wİrd "); + assert_eq!(s.doc.plain_text(StoryRef::Body), "Wird ", "two initial capitals lowercases İ to i in English"); + let mut s = self::s(); + run(&mut s, "review.language", json!({"lang": "en-US", "default": true})); + typ(&mut s, "wİRD "); + assert_eq!(s.doc.plain_text(StoryRef::Body), "Wird ", "caps-lock slip fixes wİRD to Wird in English"); } // Spelling as you type (#1552): the word being typed gets no red squiggle until the caret leaves From 7c1792867dfeb5595ea82fe01159e39cff6ef517 Mon Sep 17 00:00:00 2001 From: Jayesh Prajapati Date: Fri, 23 Oct 2026 13:44:17 +0530 Subject: [PATCH 016/609] #3639: Header and footer commands change the section of the header the caret is in With the caret in a header or footer, Link to Previous, Header/Footer Position, Insert Header/Footer, Edit Header/Footer and Page Borders read the header's paragraph index as a body paragraph index, so section 2's header changed section 1. They now find the caret's section with section_index_of_focus, as Page Setup already does (#2072). --- ROADMAP.md | 4 +++- crates/engine/src/cmd/design.rs | 2 +- crates/engine/src/cmd/insert.rs | 6 ++--- crates/engine/src/cmd/page.rs | 8 +++++++ crates/engine/src/cmd/tools.rs | 4 ++-- crates/engine/src/tests.rs | 39 +++++++++++++++++++++++++++++++++ docs/ui-parity.md | 5 +++-- 7 files changed, 59 insertions(+), 9 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index e899cf6a00..1f63f4ee19 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **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-22 · **Change:** 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-23 · **Change:** trivial (progress log: header and footer commands change the section of the header the caret is in, #3639; 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-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. @@ -136,6 +136,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm ## Progress log +- 2026-10-23: Headers and footers: with the caret in a later section's header or footer, Link to Previous, Header/Footer Position, Insert › Header/Footer and Page Borders change that section. They counted the header's paragraphs as body paragraphs, so section 2's header changed section 1 (#3639). - 2026-10-22: Headers and footers: while editing the header, a single click in the footer edits the footer with the caret where clicked (and the reverse, and another page's own header or footer). The click went to the header being edited and the view scrolled back up to it, so a double-click on the footer rarely landed unless both were on screen. - 2026-10-21: 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). @@ -902,3 +903,4 @@ Footer page-table height and body wrapping are corrected. Other pagination gaps | 2026-10-17 | trivial | Progress log: saving into a folder that refuses a temporary file (#2138) | | 2026-10-19 | trivial | Progress log: personal templates in File › New, Save as Word Template (#2852) | | 2026-10-20 | trivial | Progress log: saving to a NAS share mounted by GVFS (#3003) | +| 2026-10-23 | trivial | Progress log: header and footer commands change the section of the header the caret is in (#3639) | diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index d1fedc1602..259a17e8a8 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -229,7 +229,7 @@ fn page_borders(s: &mut Session, v: &Value) -> CmdResult { }; let blocks: Vec = match p::str(v, "applyTo") { Some("document") => s.doc.sections().iter().map(|(end, _)| *end).collect(), - Some("section") | None => vec![s.sel.focus.path.0.first().copied().unwrap_or(0) as usize], + Some("section") | None => vec![super::page::section_end_of_focus(s)], Some(x) => return Err(CmdError::Params(format!("unknown `applyTo` `{x}`"))), }; for block in blocks { diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index a381f3bdaa..173b32b122 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -562,7 +562,7 @@ fn bookmark(s: &mut Session, v: &Value) -> CmdResult { /// even page or the default), made when there is none: with Different First Page on, a header /// inserted on page 1 is the one page 1 shows (#2826). fn hf_part(s: &mut Session, header: bool) -> u32 { - let block = s.sel.focus.path.0.first().copied().unwrap_or(0) as usize; + let block = super::page::section_end_of_focus(s); let layout = s.layout(); let page = if s.sel.focus.story == StoryRef::Body { layout.page_of(&s.sel.focus) } else { Some(s.page_hint) }; let slot = page.and_then(|pg| layout.pages.get(pg)).map(|pg| pg.hf_slot).unwrap_or_default(); @@ -629,12 +629,12 @@ fn edit_hf(s: &mut Session, v: &Value, header: bool) -> CmdResult { let shown = match page { Some(page) => shown_hf(s, page, header)?, None => { - let block = s.sel.focus.path.0.first().copied().unwrap_or(0) as usize; + let section = super::page::section_index_of_focus(s); let set = s .doc .sections() .into_iter() - .find(|(end, _)| block <= *end) + .nth(section) .or_else(|| s.doc.sections().pop()) .map(|(_, sp)| if header { sp.headers.default } else { sp.footers.default }); set.flatten().filter(|id| s.doc.parts.contains_key(id)) diff --git a/crates/engine/src/cmd/page.rs b/crates/engine/src/cmd/page.rs index 5d8055a729..1800122eec 100644 --- a/crates/engine/src/cmd/page.rs +++ b/crates/engine/src/cmd/page.rs @@ -247,6 +247,14 @@ pub fn section_index_of_focus(s: &Session) -> usize { } } +/// The last body block of the caret's section, the block [`wordcraft_doc::Document::section_mut`] +/// takes. In a header or footer the caret's block index counts that story's paragraphs, not the +/// body's, so it would name another section (#3639). +pub fn section_end_of_focus(s: &Session) -> usize { + let i = section_index_of_focus(s); + s.doc.sections().get(i).map(|(end, _)| *end).unwrap_or(0) +} + pub fn sect(s: &Session) -> SectionProps { let i = section_index_of_focus(s); s.doc.sections().get(i).map(|(_, x)| (*x).clone()).unwrap_or_default() diff --git a/crates/engine/src/cmd/tools.rs b/crates/engine/src/cmd/tools.rs index 2de3cfb97d..f71132dd6f 100644 --- a/crates/engine/src/cmd/tools.rs +++ b/crates/engine/src/cmd/tools.rs @@ -617,7 +617,7 @@ pub fn specs() -> Vec { .params(r#"{"csv"?: string}"#), CommandSpec::new("layout.linkToPrevious", "Link to Previous", "Header & Footer › Navigation", |s, v| { let header = p::bool(v, "footer").map(|f| !f).unwrap_or(true); - let block = s.sel.focus.path.0.first().copied().unwrap_or(0) as usize; + let block = super::page::section_end_of_focus(s); let sect = s.doc.section_mut(block); if header { sect.headers = Default::default(); @@ -632,7 +632,7 @@ pub fn specs() -> Vec { CommandSpec::new("hf.previous", "Previous Section", "Header & Footer › Navigation", |s, _| hf_nav(s, -1)).pure(), CommandSpec::new("hf.position", "Header/Footer Position", "Header & Footer › Position", |s, v| { let (h, f) = (p::f32(v, "header"), p::f32(v, "footer")); - let block = s.sel.focus.path.0.first().copied().unwrap_or(0) as usize; + let block = super::page::section_end_of_focus(s); let sect = s.doc.section_mut(block); if let Some(h) = h { sect.header = h.clamp(0.0, 300.0); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6a8b3d6b5b..6e4b4a9daf 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2275,6 +2275,45 @@ fn layout_size_when_focus_is_in_header_updates_correct_section() { assert_eq!((s0.page_w, s0.page_h), (612.0, 792.0)); } +/// #3639: with the caret in section 2's header, the header and footer commands change section 2. +/// The caret's block index counts the header's paragraphs, and block 0 of the body is in section 1. +#[test] +fn header_and_footer_commands_change_the_section_of_the_header_the_caret_is_in() { + use wordcraft_doc::{Block, Paragraph, PartKind, StoryRef}; + let mut s = s(); + run(&mut s, "text.insert", json!({"text": "section 1"})); + run(&mut s, "layout.break", json!({"kind": "nextPage"})); + run(&mut s, "text.insert", json!({"text": "section 2"})); + assert_eq!(s.doc.sections().len(), 2); + let header = |s: &mut Session, text: &str| { + s.doc.add_part(PartKind::Header, vec![std::sync::Arc::new(Block::Para(Paragraph::with_text(text, Default::default())))]) + }; + let (h1, h2) = (header(&mut s, "H1"), header(&mut s, "H2")); + s.doc.section_mut(0).headers.default = Some(h1); + s.doc.last_section.headers.default = Some(h2); + let first = s.doc.sections()[0].1.clone(); + let in_h2 = |s: &mut Session| s.sel = crate::Selection::caret(s.doc.start_of(StoryRef::Part(h2))); + + in_h2(&mut s); + run(&mut s, "hf.position", json!({"header": 50})); + assert_eq!(s.doc.last_section.header, 50.0); + in_h2(&mut s); + run(&mut s, "design.pageBorders", json!({"kind": "box"})); + assert!(s.doc.last_section.page_borders.is_some()); + in_h2(&mut s); + run(&mut s, "insert.footer", json!({"text": "F2"})); + let f2 = s.doc.last_section.footers.default.expect("section 2 has the new footer"); + assert_eq!(s.doc.plain_text(StoryRef::Part(f2)), "F2"); + in_h2(&mut s); + assert_eq!(run(&mut s, "insert.editFooter", json!({}))["story"], f2, "Edit Footer opens section 2's footer"); + in_h2(&mut s); + run(&mut s, "layout.linkToPrevious", json!({})); + assert_eq!(s.doc.last_section.headers.default, None, "section 2 is linked to section 1"); + + assert_eq!(*s.doc.sections()[0].1, first, "section 1 is untouched"); + assert_eq!(s.doc.plain_text(StoryRef::Part(h1)), "H1"); +} + /// #1433: the smallest page there can be (0.1" wide, no margins, set straight through Page /// Setup's section) still lays out and exports text, a table and two columns. #[test] diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 88685b2f79..02cd9a5056 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity with Microsoft Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** trivial (File › Options disables the User name field while Restrict Editing is active; previously trivial: while editing a header or footer, a click in the other one edits it there without scrolling; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Insert Table of Figures dialog: any caption label, #3013; previously trivial: Home › Underline drop-down shows its lines, #2738; previously trivial: the text context menu includes the formatting mini toolbar, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: the scrollbar page tip stays on one line as the page number grows, #3341; previously trivial: File › Home and New: templates and recent documents are buttons named for screen readers, #3176; previously trivial: forms protection greys out the Developer tab's control buttons and Properties; previously trivial: AltGr doesn't open KeyTips, #2388; previously trivial: closing the header or footer puts the caret back where it was in the body, #3331; previously trivial: Format Page Numbers dialog: number format and Continue from previous section / Start at, #1113; previously trivial: inline pictures drag to a dashed insertion cursor and stay inline, #2233, #2234; previously trivial: Save Changes prompt: a text file saved over itself closes, #2376; previously trivial: the equation being edited is framed as in Word: an outline as tall as its line, a grip, an options strip that opens its menu, and its current argument shaded; previously trivial: the table handles show while the caret is in the table, #2428; previously trivial: legacy menu keys, #1697; previously trivial: Shape Fill › Gradient and the Format Shape pane, #1500; previously trivial: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: the text pointer over the page is drawn black or white on Windows, #1746; previously trivial: a click in the header/footer band from the body no longer scrolls to the body text, #2103; previously trivial: File › Recover follows the app theme, #3243; 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: dragging the vertical scrollbar names the page at the top of the window, #2551; previously trivial: Add Font imports every selected font file, #1789); previously trivial (File › Close keeps the window, #1712; previously trivial: the Spike: Ctrl+F3 and Ctrl+Shift+F3; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: the tab strip never draws tabs over Comments / Editing / Share, #2026; previously trivial: Columns on selected text, #2024; previously trivial: Different First Page headers reachable from page 1, #2826; previously trivial: a copied equation also goes in the clipboard's MathML formats, #1297; previously trivial: Read Mode keeps the keyboard, shows whole columns and keeps text clear of the page-turn bar, #1772); previously trivial: font list entries of tall-ascent fonts sit in their row, not cut off, #2570); previously trivial: Split Cells and Convert Text to Table dialogs follow Word's merged-cell limits and Initial column width, #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 text fills the window width, #1876; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717)); previously trivial: comment balloons readable in the dark theme, #2045; previously trivial: Recently Used Fonts section at the top of the font list, #2068; previously trivial: web preferences kept between visits, #2132; previously trivial: dialog close control: a Windows-style box at the title bar's right end, the whole box clickable, red on hover, #1885); previously trivial (Modify Table Style formats every table style part, #714); previously trivial: a click on the ribbon chrome hands the keyboard to the page in the same frame, #1093 follow-up; previously trivial: Page Setup vertical alignment, #1320; previously trivial: the app opens on the Home tab every launch, as in Word; previously trivial: no document behind the Start screen, #1129; previously trivial: equation pictures share a few textures, #1002; previously trivial: selection bar in the left margin, #856; 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 major: first version; ribbon, dialogs, shortcuts and on-canvas interaction measured from `crates/ui-egui` and the command registry) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** trivial (header and footer commands change the section of the header the caret is in, #3639; previously trivial: File › Options disables the User name field while Restrict Editing is active; previously trivial: while editing a header or footer, a click in the other one edits it there without scrolling; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Insert Table of Figures dialog: any caption label, #3013; previously trivial: Home › Underline drop-down shows its lines, #2738; previously trivial: the text context menu includes the formatting mini toolbar, #2959; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: the scrollbar page tip stays on one line as the page number grows, #3341; previously trivial: File › Home and New: templates and recent documents are buttons named for screen readers, #3176; previously trivial: forms protection greys out the Developer tab's control buttons and Properties; previously trivial: AltGr doesn't open KeyTips, #2388; previously trivial: closing the header or footer puts the caret back where it was in the body, #3331; previously trivial: Format Page Numbers dialog: number format and Continue from previous section / Start at, #1113; previously trivial: inline pictures drag to a dashed insertion cursor and stay inline, #2233, #2234; previously trivial: Save Changes prompt: a text file saved over itself closes, #2376; previously trivial: the equation being edited is framed as in Word: an outline as tall as its line, a grip, an options strip that opens its menu, and its current argument shaded; previously trivial: the table handles show while the caret is in the table, #2428; previously trivial: legacy menu keys, #1697; previously trivial: Shape Fill › Gradient and the Format Shape pane, #1500; previously trivial: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: the text pointer over the page is drawn black or white on Windows, #1746; previously trivial: a click in the header/footer band from the body no longer scrolls to the body text, #2103; previously trivial: File › Recover follows the app theme, #3243; 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: dragging the vertical scrollbar names the page at the top of the window, #2551; previously trivial: Add Font imports every selected font file, #1789); previously trivial (File › Close keeps the window, #1712; previously trivial: the Spike: Ctrl+F3 and Ctrl+Shift+F3; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: the tab strip never draws tabs over Comments / Editing / Share, #2026; previously trivial: Columns on selected text, #2024; previously trivial: Different First Page headers reachable from page 1, #2826; previously trivial: a copied equation also goes in the clipboard's MathML formats, #1297; previously trivial: Read Mode keeps the keyboard, shows whole columns and keeps text clear of the page-turn bar, #1772); previously trivial: font list entries of tall-ascent fonts sit in their row, not cut off, #2570); previously trivial: Split Cells and Convert Text to Table dialogs follow Word's merged-cell limits and Initial column width, #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 text fills the window width, #1876; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717)); previously trivial: comment balloons readable in the dark theme, #2045; previously trivial: Recently Used Fonts section at the top of the font list, #2068; previously trivial: web preferences kept between visits, #2132; previously trivial: dialog close control: a Windows-style box at the title bar's right end, the whole box clickable, red on hover, #1885); previously trivial (Modify Table Style formats every table style part, #714); previously trivial: a click on the ribbon chrome hands the keyboard to the page in the same frame, #1093 follow-up; previously trivial: Page Setup vertical alignment, #1320; previously trivial: the app opens on the Home tab every launch, as in Word; previously trivial: no document behind the Start screen, #1129; previously trivial: equation pictures share a few textures, #1002; previously trivial: selection bar in the left margin, #856; 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 major: first version; ribbon, dialogs, shortcuts and on-canvas interaction measured from `crates/ui-egui` and the command registry) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 Recovery discovery no longer interrupts an explicitly created or opened document. Older copies remain in File › Recover, whose buttons use the interface palette. See [local recovery](recovery.md). @@ -44,7 +44,7 @@ Document title opens Rename Document; the account badge opens Options › Genera | Selection: word/sentence/paragraph clicks, dragging after a double-click/triple-click/Ctrl+click extends by whole words/paragraphs/sentences (#549), Shift extend, F8 extend mode, column (Alt+drag, #237) | ✅ | ✅ | 90% | 1 | | Zoom: Ctrl+scroll (only zooms; a coast or notch still gliding stops, #1743), pinch (#179), zoom buttons (#232), pages side by side when zoomed out (#251), still one per row after One Page or Page Width (#768) | ✅ | ✅ | 85% | — | | Selection: word/sentence/paragraph clicks, dragging after a double-click/triple-click/Ctrl+click extends by whole words/paragraphs/sentences (#549), Shift extend, F8 extend mode, column (Alt+drag, #237), selection bar in the left margin (click a line, double-click a paragraph, triple-click or Ctrl+click everything, drag by lines, Shift+click extends; #856) | ✅ Missing: the selection bar in the right margin for right-to-left paragraphs, beside table rows, and Word's right-pointing arrow cursor (egui has none; the plain arrow shows) | ✅ | 92% | 1 | -| Headers and footers on the page: double-click the top or bottom margin to edit them, the body to leave | ✅ in Print Layout, also on a page with none yet: the header or footer that page shows is created (first page, even page or the default) and the caret put in it; one left empty is taken away again on leaving and is never saved (#960). Making one is an undo step, refused in a protected document. On a later section's page with no header anywhere it goes in the first section and shows on every section linked to it, as Word links to the previous section by default. With Different First Page (or Odd & Even) on, a double-click goes into the header that page shows even from another header being edited, and Insert › Header/Footer and Edit Header with the caret on page 1 use page 1's own (#2826). Closing it (Esc, Close Header and Footer) puts the caret back where it was in the body, as Word does, instead of on page 1 (#3331); a double-click on the body puts it where clicked. While one is being edited, a single click in the other (the footer while editing the header, or another page's own) edits that one with the caret where clicked, and the view stays put. Web Layout, Draft and Read Mode show no margins and leave it alone. A click in the margin band from the body leaves the caret and the view where they are, so double-clicking a later page's footer opens it there (#2103) | ✅ | 95% | 0.5 | +| Headers and footers on the page: double-click the top or bottom margin to edit them, the body to leave | ✅ in Print Layout, also on a page with none yet: the header or footer that page shows is created (first page, even page or the default) and the caret put in it; one left empty is taken away again on leaving and is never saved (#960). Making one is an undo step, refused in a protected document. On a later section's page with no header anywhere it goes in the first section and shows on every section linked to it, as Word links to the previous section by default. With Different First Page (or Odd & Even) on, a double-click goes into the header that page shows even from another header being edited, and Insert › Header/Footer and Edit Header with the caret on page 1 use page 1's own (#2826). Closing it (Esc, Close Header and Footer) puts the caret back where it was in the body, as Word does, instead of on page 1 (#3331); a double-click on the body puts it where clicked. While one is being edited, a single click in the other (the footer while editing the header, or another page's own) edits that one with the caret where clicked, and the view stays put. Web Layout, Draft and Read Mode show no margins and leave it alone. A click in the margin band from the body leaves the caret and the view where they are, so double-clicking a later page's footer opens it there (#2103). Link to Previous, Header/Footer Position, Insert › Header/Footer and Page Borders change the section of the header or footer the caret is in (#3639) | ✅ | 95% | 0.5 | | Zoom: Ctrl+scroll (only zooms; a coast or notch still gliding stops, #1743), pinch (#179), zoom buttons (#232), pages side by side when zoomed out (#251) | ✅ | ✅ | 85% | — | | Touchpad smooth/inertial scroll | ✅ (#252) | ✅ | 90% | — | | Web Layout width | Text wraps to the whole work area (window width at the current zoom, 144–20,000 pt) and re-wraps once a window resize has settled (not on every frame of a drag) or at once on a zoom, keeping the caret in view; the sheet runs edge to edge with no centred page. Draft and Outline keep their 800 pt column; headless sessions keep 800 pt (#1876) | text across the window | 95% | — | @@ -287,3 +287,4 @@ labels unambiguous. Those extra-number assignments have not been compared with W | 2026-10-19 | trivial | Personal templates (#2852): File › New › Personal lists the user templates folder (`/Templates`, or File › Options › Advanced › File locations › User templates), subfolders as categories, searchable; a template opens as an untitled document attached to it; Save As › Save as Word Template starts there (`file.listTemplates`, `ui.saveAsTemplate`) | | 2026-10-15 | trivial | Double-clicking a page number in a later page's footer opens the footer there: the first click no longer moves the caret to the body text and scrolls the view up to it (#2103) | | 2026-10-20 | trivial | File › Home and New: each template (thumbnail and caption) and each recent document is one button named by its caption or file name (with the path when two recent file names are the same), so a screen reader announces it instead of unnamed text (#3176) | +| 2026-10-23 | trivial | Link to Previous, Header/Footer Position, Insert › Header/Footer and Page Borders, with the caret in a later section's header or footer, change that section instead of the first (#3639) | From 85ad49db32fc951974b8bafce9e18479559464fd Mon Sep 17 00:00:00 2001 From: Jayesh Prajapati Date: Fri, 23 Oct 2026 18:17:16 +0530 Subject: [PATCH 017/609] #3639: Edit Header/Footer from a header opens the one the section is linked to With no page given and the caret in a header or footer, Edit Footer took only the caret's section's own footer, so a section linked to the previous one got a new footer of its own and lost the link. It now walks back to the footer the section shows, as layout does. --- crates/engine/src/cmd/insert.rs | 13 +++++-------- crates/engine/src/tests.rs | 7 +++++++ 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index 173b32b122..f2143cac26 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -629,15 +629,12 @@ fn edit_hf(s: &mut Session, v: &Value, header: bool) -> CmdResult { let shown = match page { Some(page) => shown_hf(s, page, header)?, None => { + // The caret's section's own, else the one it is linked to from a section before it, as + // layout shows it (#3639): editing that one keeps the link. let section = super::page::section_index_of_focus(s); - let set = s - .doc - .sections() - .into_iter() - .nth(section) - .or_else(|| s.doc.sections().pop()) - .map(|(_, sp)| if header { sp.headers.default } else { sp.footers.default }); - set.flatten().filter(|id| s.doc.parts.contains_key(id)) + let sections = s.doc.sections(); + let set = sections.iter().take(section + 1).rev().find_map(|(_, sp)| if header { sp.headers.default } else { sp.footers.default }); + set.filter(|id| s.doc.parts.contains_key(id)) } }; let Some(id) = shown else { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6e4b4a9daf..068a30b32e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2289,7 +2289,9 @@ fn header_and_footer_commands_change_the_section_of_the_header_the_caret_is_in() s.doc.add_part(PartKind::Header, vec![std::sync::Arc::new(Block::Para(Paragraph::with_text(text, Default::default())))]) }; let (h1, h2) = (header(&mut s, "H1"), header(&mut s, "H2")); + let f1 = s.doc.add_part(PartKind::Footer, vec![std::sync::Arc::new(Block::Para(Paragraph::with_text("F1", Default::default())))]); s.doc.section_mut(0).headers.default = Some(h1); + s.doc.section_mut(0).footers.default = Some(f1); s.doc.last_section.headers.default = Some(h2); let first = s.doc.sections()[0].1.clone(); let in_h2 = |s: &mut Session| s.sel = crate::Selection::caret(s.doc.start_of(StoryRef::Part(h2))); @@ -2300,6 +2302,11 @@ fn header_and_footer_commands_change_the_section_of_the_header_the_caret_is_in() in_h2(&mut s); run(&mut s, "design.pageBorders", json!({"kind": "box"})); assert!(s.doc.last_section.page_borders.is_some()); + // Section 2 has no footer of its own and shows section 1's: Edit Footer opens that one and + // keeps the link. + in_h2(&mut s); + assert_eq!(run(&mut s, "insert.editFooter", json!({}))["story"], f1); + assert_eq!(s.doc.last_section.footers.default, None, "section 2 stays linked"); in_h2(&mut s); run(&mut s, "insert.footer", json!({"text": "F2"})); let f2 = s.doc.last_section.footers.default.expect("section 2 has the new footer"); From 96eddcfe695e54c6d97204528fea417b19eec8ef Mon Sep 17 00:00:00 2001 From: Jayesh Prajapati Date: Sat, 24 Oct 2026 11:02:42 +0530 Subject: [PATCH 018/609] #3639: Header and footer commands use the section of the caret's page in a linked header --- crates/engine/src/cmd/insert.rs | 2 +- crates/engine/src/cmd/page.rs | 22 +++++++++++++++++----- crates/engine/src/tests.rs | 22 ++++++++++++++++++++++ 3 files changed, 40 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index f2143cac26..9e768650c2 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -631,7 +631,7 @@ fn edit_hf(s: &mut Session, v: &Value, header: bool) -> CmdResult { None => { // The caret's section's own, else the one it is linked to from a section before it, as // layout shows it (#3639): editing that one keeps the link. - let section = super::page::section_index_of_focus(s); + let section = super::page::hf_section_of_focus(s); let sections = s.doc.sections(); let set = sections.iter().take(section + 1).rev().find_map(|(_, sp)| if header { sp.headers.default } else { sp.footers.default }); set.filter(|id| s.doc.parts.contains_key(id)) diff --git a/crates/engine/src/cmd/page.rs b/crates/engine/src/cmd/page.rs index 1800122eec..5e2d2fef92 100644 --- a/crates/engine/src/cmd/page.rs +++ b/crates/engine/src/cmd/page.rs @@ -247,11 +247,23 @@ pub fn section_index_of_focus(s: &Session) -> usize { } } -/// The last body block of the caret's section, the block [`wordcraft_doc::Document::section_mut`] -/// takes. In a header or footer the caret's block index counts that story's paragraphs, not the -/// body's, so it would name another section (#3639). -pub fn section_end_of_focus(s: &Session) -> usize { - let i = section_index_of_focus(s); +/// The caret's section, for the header and footer commands. In a header or footer it is the +/// section of the caret's page when that page shows it: a section linked to the previous one +/// shows that section's header, so the header alone names the earlier section (#3639). +pub fn hf_section_of_focus(s: &mut Session) -> usize { + let wordcraft_doc::StoryRef::Part(id) = s.sel.focus.story else { return section_index_of_focus(s) }; + let layout = s.layout(); + match layout.pages.get(s.page_hint) { + Some(pg) if pg.header_story == Some(id) || pg.footer_story == Some(id) => pg.section, + _ => section_of_part(s, id), + } +} + +/// The last body block of the caret's section ([`hf_section_of_focus`]), the block +/// [`wordcraft_doc::Document::section_mut`] takes. In a header or footer the caret's block index +/// counts that story's paragraphs, not the body's, so it would name another section (#3639). +pub fn section_end_of_focus(s: &mut Session) -> usize { + let i = hf_section_of_focus(s); s.doc.sections().get(i).map(|(end, _)| *end).unwrap_or(0) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 068a30b32e..1008831872 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2319,6 +2319,28 @@ fn header_and_footer_commands_change_the_section_of_the_header_the_caret_is_in() assert_eq!(*s.doc.sections()[0].1, first, "section 1 is untouched"); assert_eq!(s.doc.plain_text(StoryRef::Part(h1)), "H1"); + + // Section 2 now shows section 1's header and has its own footer. With the caret in that + // header on section 2's page, the commands change section 2, not section 1 that owns it. + let page2 = s.layout().pages.iter().position(|pg| pg.section == 1).expect("section 2 has a page"); + assert_eq!(s.layout().pages[page2].header_story, Some(h1)); + let in_h1 = |s: &mut Session, page: usize| { + s.sel = crate::Selection::caret(s.doc.start_of(StoryRef::Part(h1))); + s.page_hint = page; + }; + in_h1(&mut s, page2); + assert_eq!(run(&mut s, "insert.editFooter", json!({}))["story"], f2, "Edit Footer opens the footer section 2 shows"); + in_h1(&mut s, page2); + run(&mut s, "hf.position", json!({"header": 40})); + assert_eq!(s.doc.last_section.header, 40.0); + assert_eq!(*s.doc.sections()[0].1, first, "section 1 is untouched"); + // On section 1's own page the same header is section 1's. + in_h1(&mut s, 0); + assert_eq!(run(&mut s, "insert.editFooter", json!({}))["story"], f1); + in_h1(&mut s, 0); + run(&mut s, "hf.position", json!({"header": 30})); + assert_eq!(s.doc.sections()[0].1.header, 30.0); + assert_eq!(s.doc.last_section.header, 40.0); } /// #1433: the smallest page there can be (0.1" wide, no margins, set straight through Page From dd20b23d4d85334e49632cc801dc22f4312a19f0 Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Sat, 24 Oct 2026 20:44:17 -0100 Subject: [PATCH 019/609] Engine tests: the command fuzz fails on a panic Session::run caught hostile_params_never_panic runs every command with junk parameters, but it threw the result away. Session::run turns a panic inside a command into Err(Failed(" panicked: ...")) and restores the document, so a command that panicked on junk passed the test: the one check the never-crash rule points to could not see the panics it exists for. The Outline view fuzz in outline_level_changes_are_undoable had the same gap. Both now go through run_junk, which fails on that error. Today no command panics there (611 commands, 8 junk inputs each), so nothing else changes. Tests: making edit.repeat panic on null params fails the fuzz with "edit.repeat panicked: mutation"; before this change the same mutation passed. --- crates/engine/src/tests.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 7c6ad50e71..2a0716000b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3408,6 +3408,13 @@ fn failed_command_leaves_document_unchanged() { assert_eq!(text(&s), before); } +/// Runs a command on junk; `Session::run` turns a panic into an error, which fails the test. +fn run_junk(s: &mut Session, id: &str, params: &serde_json::Value) { + if let Err(crate::CmdError::Failed(m)) = s.run(id, params) { + assert!(!m.starts_with(&format!("{id} panicked: ")), "{m}"); + } +} + #[test] fn hostile_params_never_panic() { let reg = cmd::registry(); @@ -3430,7 +3437,7 @@ fn hostile_params_never_panic() { for j in &junk { let mut s = Session::new(crate::sample::sample_document()); assert_ne!(s.read_aloud.backend, crate::speech::Backend::System, "tests must never start real speech"); - let _ = s.run(spec.id, j); + run_junk(&mut s, spec.id, j); s.clamp_selection(); let _ = s.layout(); } @@ -7861,7 +7868,7 @@ fn outline_level_changes_are_undoable() { for spec in cmd::registry().all().iter().filter(|c| c.id.starts_with("outline.")) { for j in [json!(null), json!({"block": 99999, "level": "x", "value": 5}), json!({"block": -1, "level": 0})] { let mut s = outline_doc(); - let _ = s.run(spec.id, &j); + run_junk(&mut s, spec.id, &j); let _ = s.layout(); } } From fe692315441f0e0c565176431eac24025d3ff687 Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Sat, 24 Oct 2026 20:44:19 -0100 Subject: [PATCH 020/609] AutoSave: the switch turns it on for a file you opened (#3307) Opening a saved .docx greyed the AutoSave switch out. Clicking it asked for Save As, so a file you work on every day needed a save before each session's AutoSave would cover it. The rule behind it stays. #151 stopped AutoSave from rewriting a file that was only opened, because a save drops what the readers don't model (content controls, charts, SmartArt), and that loss should follow the user's own choice. Clicking the switch is such a choice. So a file opened in this window now shows the switch off, not greyed out, and clicking it (or file.autosave from a script) turns AutoSave on for that file. Opening alone never rewrites anything. The browser and lossy-format blocks are unchanged. Tests: turning_autosave_on_covers_a_file_only_opened_here (open, type, nothing written; switch on, file written) and clicking_autosave_on_an_opened_file_turns_it_on (the real title bar, no Save As). Dropping the go-ahead in set_autosave fails both; keeping the switch greyed fails the second. --- crates/ui-egui/src/chrome.rs | 30 +++++++++++++++++++++++++----- crates/ui-egui/src/lib.rs | 31 +++++++++++++++++++++++++++++-- 2 files changed, 54 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 60053a871d..188e841d68 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -303,7 +303,8 @@ pub fn title_bar(app: &mut WordApp, ui: &mut Ui) { ui.spacing_mut().item_spacing = vec2(2.0, 0.0); // AutoSave switch: greyed out, with the reason as its tooltip, when AutoSave can't // cover the document (#196, #176); clicking it then offers Save As where that helps. - let block = app.autosave_block(); + // A file only opened here is off, not blocked: the switch turns it on (#3307). + let block = app.autosave_block().filter(|b| *b != crate::AutoSaveBlock::NotSavedHere); let on = app.autosaves(); let color = if block.is_some() { t.text_dim.gamma_multiply(0.6) } else { t.text_dim }; // The text is part of the switch (#3370): clicking it toggles AutoSave, and chrome @@ -1028,9 +1029,10 @@ mod tests { assert!(a.session.undo_history().is_empty(), "the step was undone"); } - /// A saved .docx (so AutoSave can cover it) with the title bar drawn over it. - fn autosave_harness() -> (egui_kittest::Harness<'static, WordApp>, std::path::PathBuf) { - let dir = std::env::temp_dir().join(format!("wordcraft-ui-autosave-label-{}", std::process::id())); + /// A saved .docx (so AutoSave can cover it), or with `reopened` the same file opened in a + /// fresh window, with the title bar drawn over it. + fn autosave_harness(reopened: bool) -> (egui_kittest::Harness<'static, WordApp>, std::path::PathBuf) { + let dir = std::env::temp_dir().join(format!("wordcraft-ui-autosave-label-{}-{reopened}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("draft.docx"); @@ -1038,6 +1040,11 @@ mod tests { a.run("text.insert", json!({"text": "Hello"})).unwrap(); a.run("file.save", json!({"path": path.to_string_lossy()})).unwrap(); assert!(a.autosaves(), "a saved .docx is covered by AutoSave"); + if reopened { + a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default()); + a.run("file.open", json!({"path": path.to_string_lossy()})).unwrap(); + assert!(!a.autosaves(), "an opened file waits for the user's go-ahead"); + } let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state( |ui, app: &mut WordApp| { let ctx = ui.ctx().clone(); @@ -1060,7 +1067,7 @@ mod tests { #[test] fn clicking_the_autosave_label_toggles_autosave() { use egui_kittest::kittest::Queryable; - let (mut h, dir) = autosave_harness(); + let (mut h, dir) = autosave_harness(false); assert!(h.state().autosaves()); h.get_by_label("AutoSave").click(); h.run_steps(2); @@ -1070,4 +1077,17 @@ mod tests { assert!(h.state().autosaves(), "and clicking it again turns it back on"); let _ = std::fs::remove_dir_all(dir); } + + /// #3307: a file opened, not saved, in this window had the switch greyed out, and clicking it + /// asked for Save As. Clicking it now turns AutoSave on for that file. + #[test] + fn clicking_autosave_on_an_opened_file_turns_it_on() { + use egui_kittest::kittest::Queryable; + let (mut h, dir) = autosave_harness(true); + h.get_by_label("AutoSave").click(); + h.run_steps(2); + assert!(h.state().autosaves(), "the switch turned AutoSave on"); + assert!(h.state().dialog.is_none() && h.state().file_dialog.is_none(), "without Save As"); + let _ = std::fs::remove_dir_all(dir); + } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ed49611fe2..9a94c3e29f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2355,10 +2355,14 @@ impl WordApp { /// `file.autosave` (the AutoSave switch, and scripts): `value` turns AutoSave on or off; /// without it, it toggles what the switch shows. Turning it on for a document AutoSave can't /// cover is an error that says why, instead of a switch that is on but saves nothing (#196). + /// Turning it on for a file only opened here is the go-ahead a save gives (#3307). fn set_autosave(&mut self, params: &Value) -> Result { let on = params.get("value").and_then(Value::as_bool).unwrap_or(!self.autosaves()); if on && let Some(block) = self.autosave_block() { - return Err(block.reason()); + if block != AutoSaveBlock::NotSavedHere { + return Err(block.reason()); + } + self.autosave_path = self.session.path.clone(); } self.autosave = on; self.session.autosave = on; @@ -2692,7 +2696,7 @@ pub enum AutoSaveBlock { Unsaved, /// A file in a format that can't keep everything (Markdown, plain text, HTML…), by file name. Format { name: String }, - /// A file that was opened but not yet saved in this session. + /// A file that was opened but not yet saved in this session; the switch shows off and lifts it. NotSavedHere, } @@ -7500,6 +7504,29 @@ mod tests { assert!(err.contains("browser"), "{err}"); } + /// #3307: an opened file isn't rewritten until the user says so, but the switch says so + /// without Save As: turning it on lets AutoSave write the file. + #[test] + fn turning_autosave_on_covers_a_file_only_opened_here() { + let dir = scratch("autosave-opened"); + let path = dir.join("report.docx"); + let mut a = typed(); + a.run("file.save", json!({"path": path.to_string_lossy()})).unwrap(); + let mut b = app(); + b.run("file.open", json!({"path": path.to_string_lossy()})).unwrap(); + assert_eq!(b.autosave_block(), Some(AutoSaveBlock::NotSavedHere)); + b.run("text.insert", json!({"text": "Opened "})).unwrap(); + b.autosave_tick(now_ms() + 10_000.0); + assert!(b.session.dirty, "opening alone never rewrites the file"); + assert_eq!(b.run("file.autosave", json!({})).unwrap(), json!({"value": true})); + assert!(b.autosaves()); + b.autosave_tick(now_ms() + 20_000.0); + assert!(!b.session.dirty, "AutoSave wrote the opened file"); + assert!(b.run("file.autosave", json!({"value": false})).is_ok()); + assert!(!b.autosaves()); + let _ = std::fs::remove_dir_all(&dir); + } + /// Cancelling the Open picker (Mod+O) left the document as it was but turned AutoSave off. #[test] fn cancelling_open_keeps_autosave() { From 6d51d93bb67318b78782910d5703be69d120d19b Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Sat, 24 Oct 2026 21:28:50 -0100 Subject: [PATCH 021/609] AutoSave: a value that isn't true or false is an error (#3307) `file.autosave` read `value` with as_bool and toggled when that gave nothing. Since the switch can now turn AutoSave on for a file only opened here, `{"value":"false"}` on such a file turned it on and gave AutoSave the go-ahead to rewrite it. A missing value still toggles; anything other than a bool is now refused, the way the focus ribbon and other ui commands already do it. Found in review. Test: turning_autosave_on_covers_a_file_only_opened_here sends "false" as a string and checks AutoSave stays off; it fails with the old parsing. --- crates/ui-egui/src/lib.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9a94c3e29f..8bde3d3b32 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2357,7 +2357,11 @@ impl WordApp { /// cover is an error that says why, instead of a switch that is on but saves nothing (#196). /// Turning it on for a file only opened here is the go-ahead a save gives (#3307). fn set_autosave(&mut self, params: &Value) -> Result { - let on = params.get("value").and_then(Value::as_bool).unwrap_or(!self.autosaves()); + let on = match params.get("value") { + None => !self.autosaves(), + Some(Value::Bool(on)) => *on, + Some(_) => return Err("`value` must be true or false".into()), + }; if on && let Some(block) = self.autosave_block() { if block != AutoSaveBlock::NotSavedHere { return Err(block.reason()); @@ -7518,6 +7522,8 @@ mod tests { b.run("text.insert", json!({"text": "Opened "})).unwrap(); b.autosave_tick(now_ms() + 10_000.0); assert!(b.session.dirty, "opening alone never rewrites the file"); + assert!(b.run("file.autosave", json!({"value": "false"})).is_err()); + assert!(!b.autosaves(), "a value that isn't a bool grants nothing"); assert_eq!(b.run("file.autosave", json!({})).unwrap(), json!({"value": true})); assert!(b.autosaves()); b.autosave_tick(now_ms() + 20_000.0); From dd7b12f5046149d9e1f22348b201c153cc99ec7a Mon Sep 17 00:00:00 2001 From: ratko Date: Sat, 24 Oct 2026 23:08:14 +0200 Subject: [PATCH 022/609] A selected picture survives Enter and breaks (#4126) Enter on a selected picture or shape deleted it, like selected text. In Word for Mac, Enter does nothing there, inline or floating, however many times it is pressed. Shift+Enter and a page break go in front of the picture and keep it selected, so it moves down a line or to the next page; a column break does the same. A break on a picture inside a Picture content control goes in front of the control, and the picture stays selected. A selected text box is unchanged: in the app, Enter puts the caret in its text. Tested by the developer in the app. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/objects.rs | 2 +- crates/engine/src/cmd/text.rs | 25 ++++++++--- crates/engine/src/tests.rs | 2 +- crates/engine/src/tests_typing.rs | 71 +++++++++++++++++++++++++++++++ docs/typing-parity.md | 5 ++- 5 files changed, 97 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/objects.rs b/crates/engine/src/cmd/objects.rs index b99c302522..f1234b3aae 100644 --- a/crates/engine/src/cmd/objects.rs +++ b/crates/engine/src/cmd/objects.rs @@ -694,7 +694,7 @@ fn bounds(s: &mut Session, v: &Value) -> CmdResult { } /// Select the object whose character is at `pos`. -fn select_object(s: &mut Session, pos: &Pos) { +pub(super) fn select_object(s: &mut Session, pos: &Pos) { s.sel = Selection { anchor: pos.clone(), focus: Pos { off: pos.off + wordcraft_doc::para::OBJ.len_utf8(), ..pos.clone() } }; } diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 6db399d8d0..2adda02de0 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -12,9 +12,9 @@ pub fn specs() -> Vec { vec![ CommandSpec::new("text.insert", "Type Text", "Editing", insert).params(r#"{"text": string}"#), CommandSpec::new("text.newParagraph", "New Paragraph", "Editing", new_paragraph).key("Enter"), - CommandSpec::new("text.lineBreak", "Line Break", "Editing", |s, _| ins_char(s, '\n')).key("Shift+Enter"), - CommandSpec::new("text.pageBreak", "Page Break", "Insert › Pages", |s, _| ins_char(s, PAGE_BREAK)).key("Mod+Enter"), - CommandSpec::new("text.columnBreak", "Column Break", "Layout › Breaks", |s, _| ins_char(s, COLUMN_BREAK)).key("Mod+Shift+Enter"), + CommandSpec::new("text.lineBreak", "Line Break", "Editing", |s, _| insert_break(s, '\n')).key("Shift+Enter"), + CommandSpec::new("text.pageBreak", "Page Break", "Insert › Pages", |s, _| insert_break(s, PAGE_BREAK)).key("Mod+Enter"), + CommandSpec::new("text.columnBreak", "Column Break", "Layout › Breaks", |s, _| insert_break(s, COLUMN_BREAK)).key("Mod+Shift+Enter"), CommandSpec::new("text.tab", "Tab", "Editing", tab).key("Tab"), CommandSpec::new("text.backTab", "Shift+Tab", "Editing", back_tab).key("Shift+Tab"), // A tab character even in a table cell, where Tab moves to the next cell (#3137); ⌥Tab on macOS. @@ -611,6 +611,20 @@ fn ins_char(s: &mut Session, c: char) -> CmdResult { sel_result(s) } +/// A line, page or column break. On a selected picture or shape, Word puts the break in front of +/// it and keeps it selected, rather than replacing it (#4126). +fn insert_break(s: &mut Session, c: char) -> CmdResult { + let Some(at) = super::objects::object_selection(s).map(|(p, _)| p) else { return ins_char(s, c) }; + s.sel = Selection::caret(at.clone()); + ins_char(s, c)?; + // The break goes in front of the object, or of the content control around it. + let at = Pos { off: at.off + c.len_utf8(), ..at }; + if s.doc.para_at(&at).and_then(|p| p.object_at(at.off)).is_some_and(|o| o.is_drawing()) { + super::objects::select_object(s, &at); + } + sel_result(s) +} + /// Exact sample-text formulas; bounded counts keep typed input from allocating without limit. fn sample_text(s: &Session) -> Option { let at = &s.sel.focus; @@ -664,8 +678,9 @@ fn sample_text(s: &Session) -> Option { } fn new_paragraph(s: &mut Session, _: &Value) -> CmdResult { - // Enter in a one-line plain text control (or a check box or list) does nothing, as in Word. - if super::controls::refuses_paragraph(s) { + // Enter in a one-line plain text control (or a check box or list), or on a selected picture or + // shape, does nothing, as in Word (#4126). + if super::controls::refuses_paragraph(s) || super::objects::object_selection(s).is_some() { return sel_result(s); } super::controls::prepare_edit(s)?; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 3dbd4082c5..84c350c810 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4593,7 +4593,7 @@ fn scratch_dir(name: &str) -> std::path::PathBuf { } #[cfg(not(target_arch = "wasm32"))] -fn tiny_png() -> Vec { +pub(crate) fn tiny_png() -> Vec { let mut png = Vec::new(); image::RgbaImage::from_pixel(2, 2, image::Rgba([200, 30, 30, 255])) .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) diff --git a/crates/engine/src/tests_typing.rs b/crates/engine/src/tests_typing.rs index c9a2c434d9..b8beb9888b 100644 --- a/crates/engine/src/tests_typing.rs +++ b/crates/engine/src/tests_typing.rs @@ -2846,6 +2846,77 @@ fn typing_over_backward_selection_keeps_its_font() { } } +/// `One`, a picture (floating with Square wrapping when `floating`), `Two`; the picture selected, +/// right to left when floating. +fn picture_between_paragraphs(floating: bool) -> Session { + let mut s = s(); + typ(&mut s, "One\n"); + run(&mut s, "insert.picture", json!({"data": crate::cmd::insert::base64_encode(&crate::tests::tiny_png()), "width": 50})); + typ(&mut s, "\nTwo"); + let pic = Pos::body(1, 0); + let end = Pos { off: pic.off + wordcraft_doc::para::OBJ.len_utf8(), ..pic.clone() }; + run(&mut s, "select.range", json!({"anchor": pic, "focus": end})); + if floating { + run(&mut s, "arrange.wrap", json!({"wrap": "square"})); + s.sel = crate::Selection { anchor: s.sel.focus.clone(), focus: s.sel.anchor.clone() }; + } + assert!(crate::cmd::objects::object_selection(&s).is_some_and(|(_, o)| o.is_floating() == floating)); + s +} + +#[test] +fn enter_on_a_selected_picture_does_nothing() { + // Word for Mac: with a picture selected, inline or floating, Enter (any number of times) + // leaves it alone (#4126). + for floating in [false, true] { + let mut s = picture_between_paragraphs(floating); + let (doc, sel) = (s.doc.clone(), s.sel.clone()); + typ(&mut s, "\n\n\n"); + assert_eq!(s.doc, doc, "the picture and the paragraphs stay as they were (floating: {floating})"); + assert_eq!(s.sel, sel, "the picture stays selected (floating: {floating})"); + } +} + +#[test] +fn a_break_on_a_selected_picture_goes_in_front_of_it() { + // Word for Mac: Shift+Enter or a page break on a selected picture puts the break in front of + // it (an inline picture moves down a line or to the next page; a floating one's anchor does) + // and keeps it selected (#4126). A column break is treated the same way. + use wordcraft_doc::para::{COLUMN_BREAK, OBJ, PAGE_BREAK}; + for (id, c) in [("text.lineBreak", '\n'), ("text.pageBreak", PAGE_BREAK), ("text.columnBreak", COLUMN_BREAK)] { + for floating in [false, true] { + let mut s = picture_between_paragraphs(floating); + let (doc, sel) = (s.doc.clone(), s.sel.clone()); + let (at, before) = crate::cmd::objects::object_selection(&s).map(|(p, o)| (p, o.clone())).unwrap(); + run(&mut s, id, json!({})); + run(&mut s, id, json!({})); + let text: Vec<_> = paras(&s).into_iter().map(|p| p.0).collect(); + assert_eq!(text, ["One".to_string(), format!("{c}{c}{OBJ}"), "Two".to_string()], "{id}, floating: {floating}"); + let (pos, o) = crate::cmd::objects::object_selection(&s).expect("the picture stays selected"); + assert_eq!((pos.off, o), (at.off + 2 * c.len_utf8(), &before), "{id}, floating: {floating}"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!((&s.doc, &s.sel), (&doc, &sel), "{id}, floating: {floating}"); + } + } +} + +#[test] +fn a_break_on_a_picture_in_a_picture_control_keeps_the_picture_selected() { + // The break goes in front of the control, and the picture (not the control's start) stays + // selected (#4126). + let mut s = picture_between_paragraphs(false); + run(&mut s, "developer.picture", json!({})); + let obj = wordcraft_doc::para::OBJ.len_utf8(); + let pic = Pos::body(1, obj); + run(&mut s, "select.range", json!({"anchor": pic, "focus": Pos { off: obj * 2, ..pic.clone() }})); + let before = crate::cmd::objects::object_selection(&s).map(|(_, o)| o.clone()).expect("the picture is selected"); + run(&mut s, "text.lineBreak", json!({})); + assert!(paras(&s)[1].0.starts_with('\n'), "{:?}", paras(&s)[1].0); + let (_, o) = crate::cmd::objects::object_selection(&s).expect("the picture stays selected"); + assert_eq!(o, &before); +} + #[test] fn right_arrow_moves_through_a_ligature_one_letter_at_a_time() { // A font that draws "ffi" as one glyph (bundled, so the test doesn't depend on the installed diff --git a/docs/typing-parity.md b/docs/typing-parity.md index 5120306827..086ee582a8 100644 --- a/docs/typing-parity.md +++ b/docs/typing-parity.md @@ -1,6 +1,6 @@ # Typing parity with Word -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-25 · **Change:** trivial (`*Bold* and _italic_ as real formatting` in AutoFormat As You Type; previously trivial: highlight target includes selected paragraph marks, #4085; previously trivial: full-target highlight check beyond 10,000 runs, #4085; previously trivial: AutoCorrect finds the word after a no-break space or an ideographic space; 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 trivial: while an input method composes, the caret and its candidate window sit at the input method's cursor inside the composition; previously trivial: Ctrl+Tab types a tab in a table cell, #3137; previously trivial: List AutoFormat triggers in front of an already-written paragraph, not only a fresh empty one, checked in Word for Windows, #3352; previously trivial: AltGr types its characters without opening KeyTips on Linux, #2388; previously trivial: Delete on whole selected cells leaves one empty paragraph in each, with the cell's last paragraph's formatting; nested tables go too, #2802; 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: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: a slash opening a word travels whole to the next line, #2963; previously trivial: typing over a selection takes the first selected character's formatting, also when the selection was made right to left, #2879; previously trivial: Turkish and Azerbaijani case mapping in AutoCorrect, #1923; previously trivial: smart quotes in Hebrew pinned: logical order, ” in acronyms as in Word, #1670; previously trivial: Backspace on a selected table, rows or columns deletes them, Delete clears them, #1844; previously trivial: typed text takes its direction from its own letters, #1543; previously trivial: an input method's request to erase text around the caret is honoured, so web typing in Cyrillic and other non-Latin text no longer repeats, #1480; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: a heading-list preset keeps Heading styles and makes other paragraphs Heading 1, as in Word, #1793; previously trivial: numbered headings: a heading-linked Multilevel List numbers new headings by their style; numbering keeps a heading a heading, #1793; previously trivial: reversing an automatic capital adds an exception, #1857; previously trivial: smart quotes open after guillemets and low quotes and nest; previously trivial: Enter on an empty list item numbered by its paragraph style moves it up a level, #2143; previously trivial: Backspace after a section break and Delete before it remove the break, also on the last paragraph, #2127; previously trivial: a table inserted in right-to-left text is right to left, so Tab moves left, #2634; previously trivial: Shift+Delete cuts the selection on every platform, #1669; previously trivial: Select All then Delete removes a table the document starts with, #1198; previously trivial: Alt+numpad character codes, #961; previously trivial: Down and Up from a line start beside a table go into it, #1007; previously trivial: sample-text formulas on Enter, #1067; previously trivial: Track Changes: Accept All after a tracked delete from a paragraph end keeps the next paragraph; Reject All after typing into an empty paragraph keeps it (#864); previously minor: Correct TWo INitial CApitals, cAPS LOCK and table-cell capitals, #544; previously trivial: complex-script caret and Backspace, #604; Move Paragraph Up/Down, Promote/Demote, Go Back and Alt+X keys, #343) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-25 · **Change:** trivial (Enter on a selected picture or shape does nothing; Shift+Enter and a page break go in front of it, #4126; previously trivial: `*Bold* and _italic_ as real formatting` in AutoFormat As You Type; previously trivial: highlight target includes selected paragraph marks, #4085; previously trivial: full-target highlight check beyond 10,000 runs, #4085; previously trivial: AutoCorrect finds the word after a no-break space or an ideographic space; 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 trivial: while an input method composes, the caret and its candidate window sit at the input method's cursor inside the composition; previously trivial: Ctrl+Tab types a tab in a table cell, #3137; previously trivial: List AutoFormat triggers in front of an already-written paragraph, not only a fresh empty one, checked in Word for Windows, #3352; previously trivial: AltGr types its characters without opening KeyTips on Linux, #2388; previously trivial: Delete on whole selected cells leaves one empty paragraph in each, with the cell's last paragraph's formatting; nested tables go too, #2802; 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: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: a slash opening a word travels whole to the next line, #2963; previously trivial: typing over a selection takes the first selected character's formatting, also when the selection was made right to left, #2879; previously trivial: Turkish and Azerbaijani case mapping in AutoCorrect, #1923; previously trivial: smart quotes in Hebrew pinned: logical order, ” in acronyms as in Word, #1670; previously trivial: Backspace on a selected table, rows or columns deletes them, Delete clears them, #1844; previously trivial: typed text takes its direction from its own letters, #1543; previously trivial: an input method's request to erase text around the caret is honoured, so web typing in Cyrillic and other non-Latin text no longer repeats, #1480; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: a heading-list preset keeps Heading styles and makes other paragraphs Heading 1, as in Word, #1793; previously trivial: numbered headings: a heading-linked Multilevel List numbers new headings by their style; numbering keeps a heading a heading, #1793; previously trivial: reversing an automatic capital adds an exception, #1857; previously trivial: smart quotes open after guillemets and low quotes and nest; previously trivial: Enter on an empty list item numbered by its paragraph style moves it up a level, #2143; previously trivial: Backspace after a section break and Delete before it remove the break, also on the last paragraph, #2127; previously trivial: a table inserted in right-to-left text is right to left, so Tab moves left, #2634; previously trivial: Shift+Delete cuts the selection on every platform, #1669; previously trivial: Select All then Delete removes a table the document starts with, #1198; previously trivial: Alt+numpad character codes, #961; previously trivial: Down and Up from a line start beside a table go into it, #1007; previously trivial: sample-text formulas on Enter, #1067; previously trivial: Track Changes: Accept All after a tracked delete from a paragraph end keeps the next paragraph; Reject All after typing into an empty paragraph keeps it (#864); previously minor: Correct TWo INitial CApitals, cAPS LOCK and table-cell capitals, #544; previously trivial: complex-script caret and Backspace, #604; Move Paragraph Up/Down, Promote/Demote, Go Back and Alt+X keys, #343) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 What Word does when you type, observed black-box (same keystrokes typed into Word and WordCraft, results read back paragraph by paragraph) and pinned by tests in @@ -120,6 +120,8 @@ Windows/Linux keys are given first, macOS second. | Keys | Word's result | Test | |---|---|---| +| Enter (Return) on a selected picture or shape, inline or floating | nothing: the object stays, still selected, and no paragraph is added, however many times it is pressed (Word for Mac, observed 2026-10-24; #4126). On a selected text box, Enter puts the caret in its text | `enter_on_a_selected_picture_does_nothing` | +| Shift+Enter (⇧Return), Insert › Page Break (⌘Return) on a selected picture or shape | the break goes in front of it (in front of a content control around it) and the object stays selected: each Shift+Enter moves an inline picture down a line (with a floating picture, the text after its anchor), and a page break moves it to the next page (Word for Mac, observed 2026-10-24; #4126). A column break does the same (not observed) | `a_break_on_a_selected_picture_goes_in_front_of_it`, `a_break_on_a_picture_in_a_picture_control_keeps_the_picture_selected` | | select text right to left (from its end), type | the new text takes the first selected character's formatting (font, size…), as with a selection made left to right; not the text's before it (#2879) | `typing_over_backward_selection_keeps_its_font` | | Down / Up (↓ / ↑) from a line beside a table | into the table's nearest row: the cell under the caret, or the nearest one when the caret is left or right of the cells' text (the start of the line above a table is left of the first cell's text); never past the table to the paragraph beyond it | `down_and_up_from_a_line_start_beside_a_table_go_into_it` | | Alt+Shift+Up / Down (⌃⇧↑ / ⌃⇧↓) | the paragraphs the selection touches swap with the paragraph above / below, keeping style and list membership; the selection moves with them; one undo step. A selection ending at the start of a paragraph doesn't take it along. Refused at the top or bottom of the story or cell, next to a table and across a section break | `alt_shift_down_then_up_moves_a_paragraph_and_back_and_undoes` | @@ -414,6 +416,7 @@ again. | Date | Change | Summary | |---|---|---| +| 2026-10-24 | trivial | Enter on a selected picture or shape does nothing, and Shift+Enter, page and column breaks go in front of it, instead of deleting it (#4126) | | 2026-10-24 | trivial | AutoCorrect: a word typed after a no-break space or an ideographic space is corrected as after a plain space | | 2026-10-25 | trivial | Highlight decisions include fully selected paragraph marks in whole cells and ordinary ranges, including empty paragraphs; partial text columns exclude unselected marks (#4085). | | 2026-10-25 | trivial | Highlight toggle checks the full target beyond 10,000 runs without collecting resolved formatting; mixed and inherited tails and Undo/Redo covered (#4085). | From af4608d7f0efdb51843403c93139247a3f790e2d Mon Sep 17 00:00:00 2001 From: Florent Siegenthaler <64897087+Atalantis@users.noreply.github.com> Date: Mon, 26 Oct 2026 09:24:47 +0100 Subject: [PATCH 023/609] Declare the UI languages to AppKit so the open and save panels are translated --- packaging/macos/Info.plist.in | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/packaging/macos/Info.plist.in b/packaging/macos/Info.plist.in index 1dce256c49..a86176ba7b 100644 --- a/packaging/macos/Info.plist.in +++ b/packaging/macos/Info.plist.in @@ -6,6 +6,39 @@ CFBundleDevelopmentRegion en + + CFBundleLocalizations + + en + bg + cs + da + de + es + et + fr + hr + hu + it + ja + ka + ko + nl + pl + pt-BR + ro + ru + sl + sr-Latn + sr + sv + tr + uk + vi + zh-Hans + zh-Hant + CFBundleDisplayName WordCraft CFBundleName From 0e96d0abd012184172151dc269b71da68a02be56 Mon Sep 17 00:00:00 2001 From: OPUZZLES <109076338+OPUZZLES@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:34:06 +0100 Subject: [PATCH 024/609] M12: reuse PDF figure object lookups (#3614) --- ROADMAP.md | 5 +- crates/pdf/src/export.rs | 1 + crates/pdf/src/exporter.rs | 9 +- crates/pdf/src/exporter/objects.rs | 93 ++++++++++++++++++++ crates/pdf/src/tests.rs | 134 +++++++++++++++++++++++++++++ docs/file-format-parity.md | 12 ++- docs/gaps.md | 5 +- docs/target-app-parity.md | 3 +- 8 files changed, 253 insertions(+), 9 deletions(-) create mode 100644 crates/pdf/src/exporter/objects.rs diff --git a/ROADMAP.md b/ROADMAP.md index 477dfb3cdc..40a5999795 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -4,8 +4,8 @@ **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-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 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** trivial (PDF figure lookup work, #3614; previously 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-29 · **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. WordCraft aims for complete parity with Microsoft Word, then goes further on speed, openness and @@ -312,6 +312,7 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target | 2026-10-17 | Non-overlapping body floating tables clear header tables. Original native controls distinguish never-overlap from allowed overlap. | | 2026-10-14 | Comment text being typed is no longer lost or misplaced (#1348): an edit or reply the document refuses (for example read-only protection) keeps the typed text in its field and says why on the status line; drafts belong to their document, so after New or Open a comment with the same number shows its own text; Save, Export, Print, Close, New and Open write pending comment text first; if the document refuses it, Save, Export and Print carry on with the stored comments and show why on the status line (a refused draft is dropped when Save is the only change), while Close, New and Open show the Save Changes prompt (Don't Save drops text the document refuses); Escape discards what was typed; in a document protected as read only or for forms the comment fields can't be typed in | |---|---| +| 2026-10-29 | PDF figure tagging reuses requested paragraph prefixes within each export (#3614); alternative text, decorative roles and drawing/page order stay unchanged. Synthetic export scaling and tag/persistence controls; readiness estimates unchanged. | | 2026-10-18 | Explicit New/Open keeps the requested document visible when startup recovery discovery finishes; older copies stay available. Recover uses the regular theme. See docs/recovery.md. | | 2026-10-15 | A floating picture or shape in a table cell set to align centre or bottom no longer lands half its height above its line (#1887); it starts at the anchor line | | 2026-10-18 | Picture Format › Size (#2573): width and height in the interface unit, and a size typed in any unit works, pixels too (`300 px` keeps the picture's proportions, #1901), applied once typed (Enter, Tab or a click elsewhere; Esc cancels) in one undo step. The group's launcher opens a Size dialog: height and width, scale of the original size (or of the size it opened with), Lock aspect ratio, the original size with its pixels, and Reset. `picture.size {"original": true, "scale"?}` sizes from the original; sizes past 4000 pt that keep the proportions shrink as a whole. | diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index a6f6abf81e..99987773dd 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -79,6 +79,7 @@ fn write_attempt(doc: &Document, lay: &DocLayout, opts: &PdfOptions, pages: &[us vectors: HashMap::new(), tags: Vec::new(), tag_index: HashMap::new(), + objects: crate::exporter::ObjectLookup::new(doc), links: Vec::new(), bookmarks: std::cell::OnceCell::new(), }; diff --git a/crates/pdf/src/exporter.rs b/crates/pdf/src/exporter.rs index 4d184f8663..11baf721a3 100644 --- a/crates/pdf/src/exporter.rs +++ b/crates/pdf/src/exporter.rs @@ -13,6 +13,8 @@ use super::{ mod draw; mod nav; +mod objects; +pub(crate) use objects::ObjectLookup; mod text; pub(crate) struct Exporter<'a> { @@ -32,6 +34,9 @@ pub(crate) struct Exporter<'a> { pub(crate) vectors: HashMap>>, pub(crate) tags: Vec, pub(crate) tag_index: HashMap<(StoryRef, DocPath), usize>, + /// Object offsets of paragraphs whose floating figures are tagged, shared across pages for + /// this export only. Repeated `object_at` calls would recount each paragraph prefix. + pub(crate) objects: ObjectLookup<'a>, /// Link rectangles on the current page: (x0, y0, x1, y1, target). pub(crate) links: Vec<(f32, f32, f32, f32, String)>, /// Bookmark positions by name (the first of a name wins), gathered once: looking each internal @@ -234,7 +239,7 @@ impl Exporter<'_> { } } Placed::Image { story, path, off, .. } => { - let obj = self.doc.para(*story, path).and_then(|p| p.object_at(*off)); + let obj = self.objects.get(*story, path, *off); let role = if obj.is_some_and(InlineObject::is_decorative) { Role::Artifact(ArtifactType::Other) } else { Role::Figure }; let alt = match obj { Some(InlineObject::Image { alt, .. }) => alt.clone(), @@ -253,7 +258,7 @@ impl Exporter<'_> { } }), Placed::Graphic { story, path, off, graphic, .. } => { - let alt = match self.doc.para(*story, path).and_then(|p| p.object_at(*off)) { + let alt = match self.objects.get(*story, path, *off) { Some(InlineObject::Graphic { alt, .. }) => graphic_alt(alt, graphic.kind).to_string(), _ => graphic.kind.noun().to_string(), }; diff --git a/crates/pdf/src/exporter/objects.rs b/crates/pdf/src/exporter/objects.rs new file mode 100644 index 0000000000..914f9fb313 --- /dev/null +++ b/crates/pdf/src/exporter/objects.rs @@ -0,0 +1,93 @@ +//! Per-export figure lookups in drawing order, which can revisit paragraph offsets out of order. +//! Scan only the requested prefixes, once, and borrow objects without copying their contents. + +use std::collections::HashMap; +use wordcraft_doc::para::OBJ; +use wordcraft_doc::{Document, InlineObject, Path, StoryRef}; + +#[derive(Default)] +struct ParagraphObjects<'a> { + scanned: usize, + ordinal: usize, + objects: Vec<(usize, &'a InlineObject)>, +} + +pub(crate) struct ObjectLookup<'a> { + doc: &'a Document, + paragraphs: HashMap<(StoryRef, Path), ParagraphObjects<'a>>, +} + +impl<'a> ObjectLookup<'a> { + pub(crate) fn new(doc: &'a Document) -> Self { + Self { doc, paragraphs: HashMap::new() } + } + + pub(crate) fn get(&mut self, story: StoryRef, path: &Path, off: usize) -> Option<&'a InlineObject> { + let p = self.doc.para(story, path)?; + if !p.text.get(off..)?.starts_with(OBJ) { + return None; + } + let end = off.checked_add(OBJ.len_utf8())?; + let cached = self.paragraphs.entry((story, path.clone())).or_default(); + if end > cached.scanned { + // A lone early figure must not index a long unused suffix. Later figures extend + // this prefix; repeated/reordered pages and drawing order reuse previous entries. + for (at, c) in p.text.get(cached.scanned..end)?.char_indices() { + if c == OBJ { + if let Some(object) = p.objects.get(cached.ordinal) { + cached.objects.push((cached.scanned + at, object)); + } + cached.ordinal += 1; + } + } + cached.scanned = end; + } + let i = cached.objects.binary_search_by_key(&off, |(at, _)| *at).ok()?; + cached.objects.get(i).map(|(_, object)| *object) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use wordcraft_doc::{CharProps, Paragraph, Part, PartKind, Table, para_block}; + + #[test] + fn lookups_keep_utf8_offsets_story_paths_and_missing_storage() { + let para = |name: &str| { + let mut p = Paragraph::with_text("éβ", CharProps::default()); + p.insert_object(2, InlineObject::BookmarkStart { name: name.into() }, &Default::default()).unwrap(); + p.insert_object(p.len(), InlineObject::BookmarkEnd { name: name.into() }, &Default::default()).unwrap(); + p + }; + let mut d = Document::new(); + let mut table = Table::new(1, 1, 200.0); + table.rows[0].cells[0].blocks = vec![para_block(para("cell"))]; + d.body = vec![para_block(para("body")), std::sync::Arc::new(wordcraft_doc::Block::Table(table))]; + d.parts.insert(7, Part { kind: PartKind::Header, blocks: vec![para_block(para("header"))], ..Default::default() }); + let mut lookup = ObjectLookup::new(&d); + for (story, path, name) in + [(StoryRef::Body, Path::top(0), "body"), (StoryRef::Body, Path(vec![1, 0, 0, 0]), "cell"), (StoryRef::Part(7), Path::top(0), "header")] + { + // The later marker first, then the earlier one, including duplicates. + for off in [7, 2, 7, 2] { + let obj = lookup.get(story, &path, off).unwrap(); + assert!(matches!(obj, InlineObject::BookmarkStart { name: n } | InlineObject::BookmarkEnd { name: n } if n == name)); + } + for off in [0, 1, 3, 5, 6, 8, 10, usize::MAX] { + assert!(lookup.get(story, &path, off).is_none(), "{off}"); + } + } + assert!(lookup.get(StoryRef::Part(99), &Path::top(0), 2).is_none()); + assert!(lookup.get(StoryRef::Body, &Path::top(99), 2).is_none()); + drop(lookup); + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + p.objects.truncate(1); + p.text.push_str(&"x".repeat(100_000)); + let mut lookup = ObjectLookup::new(&d); + assert!(lookup.get(StoryRef::Body, &Path::top(0), 2).is_some()); + assert_eq!(lookup.paragraphs[&(StoryRef::Body, Path::top(0))].scanned, 5, "unused suffix scanned"); + assert!(lookup.get(StoryRef::Body, &Path::top(0), 7).is_none()); + assert!(lookup.get(StoryRef::Body, &Path::top(0), 2).is_some()); + } +} diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index c8f1bec54c..e741dabe67 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -1343,6 +1343,7 @@ fn bookmark_destination_is_the_page_of_its_start() { vectors: HashMap::new(), tags: Vec::new(), tag_index: HashMap::new(), + objects: crate::exporter::ObjectLookup::new(&d), links: Vec::new(), bookmarks: std::cell::OnceCell::new(), }; @@ -2462,3 +2463,136 @@ fn baseline_is_the_most_shared_y() { assert_eq!(baseline(&[(1, 0.0, 9.0), (2, 3.0, 4.0)]), Some(4.0)); assert_eq!(baseline(&[(1, 0.0, -0.0), (2, 3.0, 0.0)]), Some(0.0)); } + +/// #3614: tagging separately placed pictures must not count every preceding object again. +#[test] +fn figure_tag_lookups_do_not_rescan_long_paragraphs() { + use wordcraft_doc::para::{AltText, Float, OBJ, Run}; + use wordcraft_geom::{Rect, Spin}; + let fixture = |n: usize| { + let mut d = Document::new(); + let media = d.add_media(png(), "png"); + let mut p = Paragraph::new(); + // Invisible markers dominate the paragraph, not drawing or PDF compression work. + p.text = OBJ.to_string().repeat(16 * n); + p.objects = (0..16 * n).map(|_| InlineObject::BookmarkEnd { name: "absent".into() }).collect(); + let mut items = Vec::new(); + for i in 0..n { + let off = p.len(); + p.text.push(OBJ); + p.objects.push(InlineObject::Image { + media: media.clone(), + w: 1.0, + h: 1.0, + alt: format!("Figure {i}"), + float: Float { alt: AltText { decorative: i % 2 == 0, ..Default::default() }, ..Default::default() }, + crop: [0.0; 4], + ole: None, + }); + items.push(Placed::Image { + rect: Rect::new(72.0, 72.0, 1.0, 1.0), + media: media.clone(), + crop: [0.0; 4], + story: StoryRef::Body, + path: DocPath::top(0), + off, + spin: Spin::default(), + }); + } + p.runs = vec![Run { len: p.len(), props: CharProps::default() }]; + // Reuse a real empty page to isolate PDF export from pagination cost. + let mut lay = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default()); + lay.pages[0].items = items; + d.body = vec![para_block(p)]; + (d, lay) + }; + let ((small, small_lay), (big, big_lay)) = (fixture(1_000), fixture(8_000)); + let opts = PdfOptions { compress: false, tagged: true, ..Default::default() }; + let (t1, t8, ratio) = cost_ratio( + 8, + || { + std::hint::black_box(export_layout(&small, &small_lay, &opts).unwrap()); + }, + || { + std::hint::black_box(export_layout(&big, &big_lay, &opts).unwrap()); + }, + ); + eprintln!("figure tagging n {t1:.4}s, 8n {t8:.4}s, ratio {ratio:.2}"); + assert!(ratio < 24.0, "8x the figures cost {ratio:.2}x CPU ({t1:.4}s -> {t8:.4}s)"); + let raw = String::from_utf8_lossy(&export_layout(&small, &small_lay, &opts).unwrap()).into_owned(); + assert_eq!(raw.matches("/Alt(").count(), 500); + assert!(raw.contains("/Alt(Figure 1)")); + assert!(!raw.contains("/Alt(Figure 0)")); +} + +/// The lookup key includes the story and table path; selected/repeated pages retain each alt. +#[test] +fn figure_tags_keep_story_paths_and_reordered_pages() { + use wordcraft_doc::graphic::{Graphic, GraphicKind}; + use wordcraft_doc::para::{AltText, Float}; + use wordcraft_doc::{Part, PartKind}; + use wordcraft_geom::{Rect, Spin}; + let mut d = Document::new(); + let media = d.add_media(png(), "png"); + let image = |alt: &str, decorative: bool| InlineObject::Image { + media: media.clone(), + w: 5.0, + h: 5.0, + alt: alt.into(), + float: Float { alt: AltText { decorative, ..Default::default() }, ..Default::default() }, + crop: [0.0; 4], + ole: None, + }; + let para = |object| { + let mut p = Paragraph::with_text("é", CharProps::default()); + p.insert_object(2, object, &Default::default()).unwrap(); + p + }; + let mut lay = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default()); + let mut body = para(image("Body picture", false)); + body.insert_object(body.len(), image("Decorative", true), &Default::default()).unwrap(); + let graphic = Arc::new(Graphic { kind: GraphicKind::Diagram, ..Default::default() }); + let mut table = Table::new(1, 1, 200.0); + table.rows[0].cells[0].blocks = vec![para_block(para(InlineObject::Graphic { + w: 5.0, + h: 5.0, + alt: "Cell diagram".into(), + float: Default::default(), + graphic: graphic.clone(), + }))]; + d.body = vec![para_block(body), Arc::new(Block::Table(table))]; + d.parts.insert(7, Part { kind: PartKind::Endnote, blocks: vec![para_block(para(image("Part picture", false)))], ..Default::default() }); + let placed = |story, path, off| Placed::Image { + rect: Rect::new(72.0, 72.0, 5.0, 5.0), + media: media.clone(), + crop: [0.0; 4], + story, + path, + off, + spin: Spin::default(), + }; + lay.pages[0].items = vec![ + placed(StoryRef::Body, DocPath::top(0), 5), + Placed::Graphic { + rect: Rect::new(80.0, 72.0, 5.0, 5.0), + graphic, + story: StoryRef::Body, + path: DocPath(vec![1, 0, 0, 0]), + off: 2, + spin: Spin::default(), + }, + placed(StoryRef::Body, DocPath::top(0), 2), + ]; + let mut second = lay.pages[0].clone(); + second.items = vec![placed(StoryRef::Part(7), DocPath::top(0), 2), placed(StoryRef::Body, DocPath::top(0), 2)]; + lay.pages.push(second); + for tagged in [true, false] { + let bytes = export_layout(&d, &lay, &PdfOptions { tagged, compress: false, pages: Some(vec![1, 0, 1]), ..Default::default() }).unwrap(); + let raw = String::from_utf8_lossy(&bytes); + assert_eq!(hayro_syntax::Pdf::new(bytes.clone()).unwrap().pages().len(), 3); + assert_eq!(raw.matches("/Alt(Body picture)").count(), if tagged { 3 } else { 0 }); + assert_eq!(raw.matches("/Alt(Part picture)").count(), if tagged { 2 } else { 0 }); + assert_eq!(raw.matches("/Alt(Cell diagram)").count(), usize::from(tagged)); + assert!(!raw.contains("/Alt(Decorative)")); + } +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6b38552f56..54409723c0 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # 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 `
` 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-29 · **Change:** trivial (PDF figure lookup work, #3614; previously 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 `
` 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 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; @@ -12,6 +12,13 @@ gives ~64%; we discount it to ~60% because DOCX fidelity has never been checked files. DOCX dominates the weight: a Word user sends and receives .docx; everything else is occasional. +## PDF figure lookup work + +Floating picture and graphic tags reuse each requested paragraph prefix within one PDF export. +Reordered or repeated pages retain their Figure/Artifact roles and alternative text; a lone early +figure does not scan the unused paragraph suffix. Original synthetic scaling and tag regressions +cover this part of #3614. PDF layout, saved content and format-readiness estimates are unchanged. + ## Drawing payloads DOCX textboxes retain their own frame and story when they contain an inline picture. @@ -264,12 +271,13 @@ Repeated DOCX style IDs use the last complete definition. The original regressio | Date | Change | Summary | |---|---|---| +| 2026-10-29 | trivial | PDF figure tagging reuses requested paragraph prefixes within each export (#3614); alternative text, decorative roles and drawing/page order stay unchanged; synthetic controls, readiness estimates unchanged. | | 2026-10-17 | trivial | Encryption rows: Standard (Word 2007, AES-ECB) encrypted packages open with a password, also when named `.doc`/`.dot`; AES headers in Word 97-2003 files are outside the public spec and refused (gap 9). The duplicate combined `.docx`/`.doc` row is removed; the `.doc` row reads 🟡 ~60% (it opens XOR/RC4/RC4 CryptoAPI); hours 2–4 → 1–2 and 4–6 → 1–2 (left: checks against Word-written files); total re-summed from the rows, 175–287 h | | 2026-10-25 | trivial | Repeated DOCX style IDs: repeated save/reopen regression for whole-definition replacement. | | 2026-10-25 | 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`) | | 2026-10-26 | trivial | DOCX: a package spelling `WORD/FONTTABLE.XML` and its fonts in another casing than the relationships still loads and saves its embedded fonts (the font table is found by its stored spelling), and a save that removes personal information escapes the attribute values of a kept glossary (`w:val='Say "hi"'` stays well-formed) (#3872 review) | | 2026-10-23 | trivial | cu20we: preserve and render outline caps across DOCX/VML, screen and PDF; synthetic regressions; readiness estimates unchanged | -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-25 · **Change:** trivial (the `.doc` reader logs what its copy budget leaves out, once a kind per document; 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 `
` 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-29 · **Change:** trivial (the `.doc` reader logs what its copy budget leaves out, once a kind per document; 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 `
` 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-23 | trivial | `.doc` reader logs what its copy budget leaves out (floating objects, link targets, alt text, Prm formatting), once a kind per document (#3692) | | 2026-10-22 | trivial | `.doc` reader bounds hostile files: oversized sector tables refused, per-character re-reads removed, copy and decode budgets (#3642, #3692, #3708-#3712) | | 2026-10-22 | trivial | Hostile input: DOCX package, comment, font, chart and Flat OPC hardening (#3692, #3723, #3704, #3742, #3648) | diff --git a/docs/gaps.md b/docs/gaps.md index dd16596f79..b4df162eb8 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,8 +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-29 · **Change:** trivial (PDF figure lookup work, #3614; previously 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 > **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 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **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 Recovery discovery no longer interrupts an explicitly created or opened document. Older copies remain in File › Recover, whose buttons use the interface palette. See [local recovery](recovery.md). @@ -150,6 +150,7 @@ Small follow-ups from the 2026-10-25 field, table and AutoFormat batch (#4232): | Date | Change | Summary | |---|---|---| +| 2026-10-29 | trivial | PDF figure tagging reuses requested paragraph prefixes within each export (#3614); alternative text, decorative roles and drawing/page order stay unchanged; synthetic controls, readiness estimates unchanged. | | 2026-10-22 | trivial | View windows: several open documents and Switch Windows in the engine | | 2026-10-25 | trivial | egui 0.37 migration: interface catalogs remain pinned by `craft-i18n.rev` (`9205108…`; 27 languages, English fallback); IME surrounding deletions and composition resets are implemented with regressions, but managed CI passed; native IME acceptance and native-speaker catalog review remain open; no gap or readiness change | | 2026-10-17 | trivial | Gap 9 narrowed: Standard (Word 2007, AES-ECB) encrypted packages open with a password under any Word extension; AES headers in Word 97-2003 files are outside the public spec and refused with a clear message; estimate 3–5 → 0 h, since the remaining AES-in-`.doc` case is refused by design | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index dd73f73075..50f0753907 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # WordCraft parity with Microsoft Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** trivial (Insert Table of Figures lists any caption label, #3013; previously trivial: Performance row: typing no longer starts render threads on every repaint, #3027; previously trivial: shapes inserted in a row are all kept, #2019; previously trivial: East Asian typography: `w:eastAsianLayout` kept on save, not laid out; previously trivial: Ink to Shape recognises arrows; previously trivial: Windows Magnifier follows the caret onto a new line, #1119; previously trivial: table border drags with Ctrl and Alt, from the left edge and of selected cells, #711; 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: all 12 bibliography styles, #383; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; 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; replaces the parity tables that lived in ROADMAP.md) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** trivial (PDF figure lookup work, #3614; previously trivial: Insert Table of Figures lists any caption label, #3013; previously trivial: Performance row: typing no longer starts render threads on every repaint, #3027; previously trivial: shapes inserted in a row are all kept, #2019; previously trivial: East Asian typography: `w:eastAsianLayout` kept on save, not laid out; previously trivial: Ink to Shape recognises arrows; previously trivial: Windows Magnifier follows the caret onto a new line, #1119; previously trivial: table border drags with Ctrl and Alt, from the left edge and of selected cells, #711; 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: all 12 bibliography styles, #383; previously trivial: formatting revisions landed, #41; previously trivial: Draw Table and Eraser landed, #303; 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; replaces the parity tables that lived in ROADMAP.md) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 The authoritative assessment of how close WordCraft is to Microsoft Word. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) itemizes every shortfall; the deep checklists are @@ -251,6 +251,7 @@ can be used without committing Word output. | Date | Change | Summary | |---|---|---| +| 2026-10-29 | trivial | PDF figure tagging reuses requested paragraph prefixes within each export (#3614); alternative text, decorative roles and drawing/page order stay unchanged; synthetic controls, readiness estimates unchanged. | | 2026-10-18 | trivial | References: Insert Table of Figures dialog; a table of figures lists any caption label (`TOC \c`), without label and number (`\a`), without page numbers (`\n`) or with them after the text (`\p`); Word's switch order is recognised and the leader kept on update (#3013); no percentage change | | 2026-10-15 | trivial | Pictures, shapes, text boxes: Insert › Shapes adds the new shape beside the selection, as Word draws it, so a second shape no longer replaces the first (still selected after its insert) and selected text stays; a picture still replaces a selected picture, as in Word (#2019) | | 2026-10-19 | trivial | Performance row: render threads reused while typing (#3027) | From 6b3555e831298f645004c3003c7fe1196f7c52bd Mon Sep 17 00:00:00 2001 From: OPUZZLES <109076338+OPUZZLES@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:03:58 +0100 Subject: [PATCH 025/609] M12: assert PDF figure roles and selected page order (#3614) --- crates/pdf/src/tests.rs | 49 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index e741dabe67..476bf3837a 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -2586,6 +2586,19 @@ fn figure_tags_keep_story_paths_and_reordered_pages() { let mut second = lay.pages[0].clone(); second.items = vec![placed(StoryRef::Part(7), DocPath::top(0), 2), placed(StoryRef::Body, DocPath::top(0), 2)]; lay.pages.push(second); + use hayro_syntax::content::ops::TypedInstruction; + use hayro_syntax::object::{Array, Dict, Name, String as PdfString}; + // Read serialized structure elements rather than inferring their role from an alt string. + fn described<'a>(dict: Dict<'a>, out: &mut Vec>) { + if dict.get::>(b"Alt").is_some() { + out.push(dict.clone()); + } + if let Some(kids) = dict.get::>(b"K") { + for child in kids.iter::>() { + described(child, out); + } + } + } for tagged in [true, false] { let bytes = export_layout(&d, &lay, &PdfOptions { tagged, compress: false, pages: Some(vec![1, 0, 1]), ..Default::default() }).unwrap(); let raw = String::from_utf8_lossy(&bytes); @@ -2594,5 +2607,41 @@ fn figure_tags_keep_story_paths_and_reordered_pages() { assert_eq!(raw.matches("/Alt(Part picture)").count(), if tagged { 2 } else { 0 }); assert_eq!(raw.matches("/Alt(Cell diagram)").count(), usize::from(tagged)); assert!(!raw.contains("/Alt(Decorative)")); + let pdf = hayro_syntax::Pdf::new(bytes.clone()).unwrap(); + let catalog = pdf.xref().get::>(pdf.xref().root_id()).unwrap(); + let tree = catalog.get::>(b"StructTreeRoot"); + assert_eq!(tree.is_some(), tagged); + let mut figures = Vec::new(); + if let Some(tree) = tree { + described(tree, &mut figures); + } + let expected = [["Part picture", "Body picture"], ["Cell diagram", "Body picture"], ["Part picture", "Body picture"]]; + for (i, page) in pdf.pages().iter().enumerate() { + let alts: Vec<_> = figures + .iter() + .filter(|f| f.get::>(b"Pg").as_ref() == Some(page.raw())) + .map(|f| { + assert_eq!(f.get::>(b"S").as_deref(), Some(b"Figure".as_slice()), "described image/graphic role"); + pdf_text_string(f.get::>(b"Alt").unwrap().as_bytes()) + }) + .collect(); + assert_eq!(alts, if tagged { expected[i].to_vec() } else { Vec::new() }, "output page {i} alt sequence"); + let mut marked = Vec::new(); + let mut pictures = Vec::new(); + let mut ops = page.typed_operations(); + while let Some(op) = ops.next() { + match op { + TypedInstruction::BeginMarkedContent(bmc) => marked.push(bmc.0.as_ref() == b"Artifact"), + TypedInstruction::BeginMarkedContentWithProperties(bdc) => marked.push(bdc.0.as_ref() == b"Artifact"), + TypedInstruction::EndMarkedContent(_) => { + marked.pop(); + } + TypedInstruction::XObject(_) => pictures.push(marked.contains(&true)), + _ => {} + } + } + // Only output page 1 has the cached decorative picture, painted before the body figure. + assert_eq!(pictures, vec![tagged && i == 1, false], "cached picture Artifact roles on output page {i}"); + } } } From 0f84914edcfd0cc1ec7b25f7cb3138c3a9bd9272 Mon Sep 17 00:00:00 2001 From: Mat Strange Date: Thu, 29 Oct 2026 14:00:45 +0000 Subject: [PATCH 026/609] #4053: A recipient list over what it keeps is refused while it is read MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The CSV reader had no field cap: every comma became a String, so a 38 MB file of commas was forty million of them — a gigabyte of memory for a list that came back empty. The field cap that did exist was applied afterwards, to a list that had already been built, and every record of a wide header is padded to its width, so 605 KB of CSV grew to 4.7 GB. The reader now keeps its limits while it reads: at most 1,000 columns in a record, 2,000,000 cells (the records times the widest record, which is what a list costs once every record is padded to the header's width) and 64 MiB of cell text. A list over them is refused with a message that says which limit it is over, rather than built and cut. Those are the numbers the spreadsheet path already keeps (crates/formats/src/sheet.rs), so a list read as a CSV and the same list read as a workbook are held to one budget. Measured through the file route (wordcraft-cli), before and after: 40,000,000 commas (38 MB): 1,003 MB → 128 MB, refused 1,000 columns over 100,000 records (605 KB): 4,610 MB → 13 MB, refused 100,000 records of 10 columns: 0.16 s, the same peak memory, before and after The reader keeps the separator detection main has (the separator is counted outside quotes) and the record limit of 100,000 is untouched: that line is #1927's, and it changes the same function. The spreadsheet path and the typed `rows` list are untouched, and a list is still stored twice and cloned on every filter; those are the auditor's #3616, which stays open. --- ROADMAP.md | 4 +- crates/engine/src/cmd/mailings.rs | 2 +- crates/engine/src/cmd/mailings/recipients.rs | 91 ++++++++++++++++---- crates/engine/src/cmd/mailings/tests.rs | 51 ++++++++++- docs/file-format-parity.md | 6 +- docs/gaps.md | 3 +- 6 files changed, 132 insertions(+), 25 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 477dfb3cdc..eabe0b44c2 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -4,7 +4,7 @@ **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-29 · **Change:** trivial (a recipient list over what it keeps is refused while it is read: 1,000 columns, 2 M cells (its records times its widest record) and 64 MiB of cell text; previously 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-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. @@ -201,6 +201,7 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target - 2026-10-15: Find opens Navigation on Results; editing the query restores Results after manual Headings/Pages navigation. Typed and selected-text searches retain document contents (#2096). | Date | What landed | +| 2026-10-23 | A recipient list over what it keeps is refused while it is read: 1,000 columns, 2 M cells (its records times its widest record) and 64 MiB of cell text. A CSV with a record wider than a list keeps, or a wide header over many records, was built whole and then cut, so a 38 MB file of commas cost about a gigabyte and a 605 KB file cost gigabytes more once every record was padded to the header's width. | | 2026-10-17 | Password-protected Word files from Word 2007 (Standard encryption: AES-128/192/256, SHA-1) open with their password, also when named `.doc` or `.dot`; a wrong or missing password is reported as for newer files. Word 97-2003 files with an AES header, which the public spec doesn't define, are refused with a clear message (gap 9) | | 2026-10-23 | A command that changes nothing is not an edit: it adds no undo step, marks no unsaved changes and forces no relayout, so the redo stack survives it and five hundred of them can no longer push the user's own edits out of the undo history. | | 2026-10-23 | Interface translations come from storytold/craft-i18n, shared with the other Crafting Apps: the catalogs are embedded at build time from the commit in `craft-i18n.rev` and looked up through craft-libs' `craft-i18n` crate; `crates/ui-egui/src/i18n/*.tsv` are gone (translations now go to craft-i18n). Strings other apps already translate show translated; a build without `CRAFT_I18N_DIR` is English only | @@ -644,6 +645,7 @@ Footer page-table height and body wrapping are corrected. Other pagination gaps | Date | Change | Summary | |---|---|---| +| 2026-10-23 | trivial | Progress log: a recipient list over what it keeps is refused while it is read, so a hostile CSV is never built and then cut | | 2026-10-22 | trivial | Progress log: one native window per open document | | 2026-10-22 | trivial | Progress log: every open document keeps its own recovery copy | | 2026-10-22 | trivial | Progress log: several open documents in the desktop window | diff --git a/crates/engine/src/cmd/mailings.rs b/crates/engine/src/cmd/mailings.rs index 832842471f..a64df4b1a3 100644 --- a/crates/engine/src/cmd/mailings.rs +++ b/crates/engine/src/cmd/mailings.rs @@ -26,7 +26,7 @@ pub use merge::{merge_range, refresh}; #[cfg(test)] use merge::{mergefield_name, placeholder}; use recipients::recipients; -pub use recipients::{RECIPIENT_EXTENSIONS, is_spreadsheet_name, parse_csv}; +pub use recipients::{CsvLimits, MAX_CELLS, MAX_FIELDS, MAX_TEXT_BYTES, RECIPIENT_EXTENSIONS, RECIPIENT_LIMITS, is_spreadsheet_name, parse_csv}; /// The mail-merge data source and preview state (lives in the session, not the document). #[derive(Clone, Debug, Default)] diff --git a/crates/engine/src/cmd/mailings/recipients.rs b/crates/engine/src/cmd/mailings/recipients.rs index 0d8f051124..0bb9425200 100644 --- a/crates/engine/src/cmd/mailings/recipients.rs +++ b/crates/engine/src/cmd/mailings/recipients.rs @@ -17,21 +17,32 @@ fn csv_separator(text: &str) -> char { [',', ';', '\t'].into_iter().max_by_key(|c| unquoted.matches(*c).count()).unwrap_or(',') } -/// Ends the current row: kept when it has any non-empty field, otherwise dropped. -fn push_csv_row(rows: &mut Vec>, row: &mut Vec) { - if row.iter().any(|x| !x.is_empty()) { - rows.push(std::mem::take(row)); - } else { - row.clear(); - } +/// What a CSV may hold while it is read: the parser refuses a list that is over these, so a +/// hostile file is never built and then cut. +#[derive(Clone, Copy)] +pub struct CsvLimits { + /// Most columns in a record. + pub fields: usize, + /// Most cells in the list: its records times its widest record. + pub cells: usize, + /// Most bytes of cell text in all. + pub text: usize, } -pub fn parse_csv(text: &str) -> Vec> { +/// Parse CSV (RFC 4180-ish: quotes, doubled quotes, commas/semicolons/tabs). +/// +/// The limits are kept while the list is read, not after it: a record wider than +/// `limits.fields`, a list of more than `limits.cells` cells, or more than `limits.text` bytes +/// of cell text is refused, rather than built and then cut. +pub fn parse_csv(text: &str, limits: &CsvLimits) -> Result>, CmdError> { let sep = csv_separator(text); let mut rows = Vec::new(); let mut row = Vec::new(); let mut cell = String::new(); let mut q = false; + // The widest record read so far, and the bytes of cell text read so far. + let mut widest = 0usize; + let mut text_bytes = 0usize; let mut chars = text.chars().peekable(); while let Some(c) = chars.next() { if q { @@ -48,29 +59,75 @@ pub fn parse_csv(text: &str) -> Vec> { } else if c == '"' { q = true; } else if c == sep { - row.push(std::mem::take(&mut cell)); + end_cell(&mut row, &mut cell, &mut text_bytes, limits)?; } else if c == '\n' || c == '\r' { if c == '\r' && chars.peek() == Some(&'\n') { chars.next(); } - row.push(std::mem::take(&mut cell)); - push_csv_row(&mut rows, &mut row); + end_cell(&mut row, &mut cell, &mut text_bytes, limits)?; + end_row(&mut rows, &mut row, &mut widest, limits)?; } else { cell.push(c); } + // The text read so far: the finished cells and the one being read. + if text_bytes.saturating_add(cell.len()) > limits.text { + return Err(CmdError::Failed(format!("the CSV can't have more than {} of text", text_size(limits.text)))); + } if rows.len() > 100_000 { break; } } - row.push(cell); - push_csv_row(&mut rows, &mut row); - rows + // The last cell, when the file doesn't end with a line break. + end_cell(&mut row, &mut cell, &mut text_bytes, limits)?; + end_row(&mut rows, &mut row, &mut widest, limits)?; + Ok(rows) +} + +/// A finished cell joins the record: the record's width stays inside the limit. +fn end_cell(row: &mut Vec, cell: &mut String, text_bytes: &mut usize, limits: &CsvLimits) -> Result<(), CmdError> { + *text_bytes = text_bytes.saturating_add(cell.len()); + row.push(std::mem::take(cell)); + if row.len() > limits.fields { + return Err(CmdError::Failed(format!("the CSV can't have more than {} columns", limits.fields))); + } + Ok(()) +} + +/// A finished record joins the list (an empty one is dropped). The list costs its records times +/// its widest record — a recipient list pads every record to the header's width — so a list +/// over the limit is refused here, while it is read. +fn end_row(rows: &mut Vec>, row: &mut Vec, widest: &mut usize, limits: &CsvLimits) -> Result<(), CmdError> { + if row.iter().any(|x| !x.is_empty()) { + *widest = (*widest).max(row.len()); + rows.push(std::mem::take(row)); + } else { + row.clear(); + } + if rows.len().saturating_mul(*widest) > limits.cells { + return Err(CmdError::Failed(format!("the CSV can't have more than {} cells (its records times its widest record)", limits.cells))); + } + Ok(()) +} + +/// A byte budget, said the way a reader says it. +fn text_size(bytes: usize) -> String { + if bytes >= 1 << 20 { format!("{} MB", bytes >> 20) } else { format!("{bytes} bytes") } } /// Most records and fields a recipient list keeps. const MAX_RECORDS: usize = 100_000; -const MAX_FIELDS: usize = 1_000; +pub const MAX_FIELDS: usize = 1_000; + +/// Most cells a recipient list keeps: its records times its fields. A recipient list pads every +/// record to the header's width, so this is what a list costs, not how many values it says. +pub const MAX_CELLS: usize = 2_000_000; + +/// Most bytes of cell text a recipient list keeps. The table path keeps the same budget. +pub const MAX_TEXT_BYTES: usize = 64 << 20; + +/// The limits a recipient list keeps. +pub const RECIPIENT_LIMITS: CsvLimits = CsvLimits { fields: MAX_FIELDS, cells: MAX_CELLS, text: MAX_TEXT_BYTES }; pub(super) fn cell(x: &Value) -> String { match x { @@ -118,7 +175,7 @@ pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult { table_from_rows(v.get("fields").and_then(Value::as_array), arr)? } else { let all = if let Some(c) = p::str(v, "csv") { - parse_csv(c) + parse_csv(c, &RECIPIENT_LIMITS)? } else { let (bytes, ext) = if let Some(d) = p::str(v, "data") { let b = crate::cmd::insert::base64_decode(d.trim()).ok_or_else(|| CmdError::Params("`data` isn't valid base64".into()))?; @@ -175,7 +232,7 @@ pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult { sheet = json!(chosen); rows } else { - parse_csv(&decode(&bytes, v)?) + parse_csv(&decode(&bytes, v)?, &RECIPIENT_LIMITS)? } }; header_split(all, p::bool(v, "headers").unwrap_or(true))? diff --git a/crates/engine/src/cmd/mailings/tests.rs b/crates/engine/src/cmd/mailings/tests.rs index c7a721594a..bb46b2feb7 100644 --- a/crates/engine/src/cmd/mailings/tests.rs +++ b/crates/engine/src/cmd/mailings/tests.rs @@ -2,9 +2,54 @@ use super::*; #[test] fn csv_parsing() { - let r = parse_csv("Name,City\n\"Smith, Ann\",Paris\r\nBo,\"Oslo \"\"N\"\"\"\n\n"); + let r = parse_csv("Name,City\n\"Smith, Ann\",Paris\r\nBo,\"Oslo \"\"N\"\"\"\n\n", &RECIPIENT_LIMITS).unwrap(); assert_eq!(r, vec![vec!["Name", "City"], vec!["Smith, Ann", "Paris"], vec!["Bo", "Oslo \"N\""]]); - assert_eq!(parse_csv("a;b\n1;2")[1], vec!["1", "2"]); + assert_eq!(parse_csv("a;b\n1;2", &RECIPIENT_LIMITS).unwrap()[1], vec!["1", "2"]); +} + +/// The parser keeps its limits while it reads the list, so a hostile list is refused +/// instead of being built and then cut. +#[test] +fn csv_parsing_refuses_a_list_over_its_limits() { + // A record wider than the limit. + let e = parse_csv("a,b,c,d,e", &CsvLimits { fields: 4, cells: 100, text: 1_000 }).unwrap_err(); + assert!(e.to_string().contains("4 columns"), "{e}"); + // More cells than the list keeps. + let e = parse_csv("a,b\nc,d\ne,f\ng,h\ni,j\nk,l", &CsvLimits { fields: 10, cells: 10, text: 1_000 }).unwrap_err(); + assert!(e.to_string().contains("10 cells"), "{e}"); + // More text than the list keeps. + let e = parse_csv("abcdefghij", &CsvLimits { fields: 10, cells: 100, text: 8 }).unwrap_err(); + assert!(e.to_string().contains("of text"), "{e}"); + // A list inside the limits still parses. + let limits = CsvLimits { fields: 4, cells: 10, text: 1_000 }; + assert_eq!(parse_csv("a,b\nc,d", &limits).unwrap(), vec![vec!["a", "b"], vec!["c", "d"]]); +} + +/// A recipient list over its limits is refused, not built. +#[test] +fn a_recipient_list_over_its_limits_is_refused() { + // A record wider than the list's fields. + let wide = format!("{}\nvalue", "f,".repeat(MAX_FIELDS + 1)); + let e = parse_csv(&wide, &RECIPIENT_LIMITS).unwrap_err(); + assert!(e.to_string().contains(&format!("{MAX_FIELDS} columns")), "{e}"); + + // A record of exactly the limit's width is kept. + let exact = format!("{}\nvalue", "f,".repeat(MAX_FIELDS - 1)); + assert_eq!(parse_csv(&exact, &RECIPIENT_LIMITS).unwrap()[0].len(), MAX_FIELDS); + + // A wide header over many records: the list would cost more cells than it keeps, and + // every record is padded to the header's width. + let mut csv = format!("{}\n", (0..MAX_FIELDS).map(|i| format!("f{i}")).collect::>().join(",")); + for _ in 0..=MAX_CELLS / MAX_FIELDS { + csv.push_str("value\n"); + } + let e = parse_csv(&csv, &RECIPIENT_LIMITS).unwrap_err(); + assert!(e.to_string().contains(&format!("{MAX_CELLS} cells")), "{e}"); + + // The command refuses it too, with a message of its own. + let mut s = Session::new(Document::new()); + let e = s.run("mailings.recipients", &json!({"csv": wide})).unwrap_err(); + assert!(e.to_string().contains("columns"), "{e}"); } /// #4001: finishing a merge opens a new document, with a new undo history. It is not an @@ -48,7 +93,7 @@ fn finishing_a_merge_to_a_file_is_not_an_edit() { #[test] fn csv_delimiter_ignores_quoted_text() { - let r = parse_csv("\"Name, first, last\";City\nAnn;Paris\n"); + let r = parse_csv("\"Name, first, last\";City\nAnn;Paris\n", &RECIPIENT_LIMITS).unwrap(); assert_eq!(r, vec![vec!["Name, first, last", "City"], vec!["Ann", "Paris"]]); } diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6b38552f56..9f57455af4 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # 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 `
` 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-29 · **Change:** trivial (a recipient list over what it keeps is refused while it is read: 1,000 columns, 2 M cells (its records times its widest record) and 64 MiB of cell text; previously 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 `
` 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 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; @@ -60,7 +60,7 @@ Weights are the share of a Word user's file traffic (estimate). Read/write: ✅ | `.xml` Word XML Document (Flat OPC) | <1% | R/W | ✅ | ✅ | ~65% | — | `crates/docx/tests/it/word_xml.rs`, `roundtrip.rs` (`flat_opc_round_trip_equals_docx`) | The DOCX package in one XML file, read and written by the DOCX code (#548); File › Export › Word XML Document. `.xml` files are told apart by their root element | | `.xml` Word 2003 XML (WordprocessingML 2003) | <1% | R/W | 🟡 | 🟡 | ~55% | 1–2 | `crates/docx/tests/it/word_xml.rs` | Opened by rewriting it as a package for the DOCX reader (#548): styles, default fonts, lists, tables, sections, headers/footers, footnotes/endnotes, comments, bookmarks, tracked insertions/deletions, hyperlinks, `w:binData` pictures, document properties. Not read: formatting changes, `w:docPr` settings, smart tags. Written (#1081) by rewriting the DOCX writer's package into the 2003 vocabulary (`crates/docx/src/wordml2003_write.rs`, `crates/docx/tests/it/wordml2003_write.rs`): core properties, styles (document defaults folded into Normal), lists, text and paragraph/character formatting, tables, hyperlinks, footnotes/endnotes inline, headers/footers in the section properties, bookmarks, comments and tracked insertions/deletions as `aml:annotation`, section page setup, and PNG/JPEG/GIF/BMP/EMF/WMF pictures as `w:pict` with `w:binData`. **Dropped on write:** shapes, text boxes, groups, charts, SmartArt, ink, equations, OLE objects, picture crop, rotation and floating position (pictures become inline), content-control wrappers (their content stays), formatting-change tracking, theme colours/fonts, custom XML, macros, even/odd header setting. File › Export › Word 2003 XML Document, `file.save`/`file.saveAs` with `format: "wordml2003"`, `wordcraft-cli convert … --format wordml2003`; a plain save over a 2003 file keeps that format. Never opened in Word yet (written from the published schemas; needs a tester) | | `.wps` Works 6–9, WordPerfect `.wpd` (Windows) | <1% | R | ❌ | — | 0% | 10–20 | — | Windows-only converters; low value | -| `.xlsx`/`.xlsm`/`.xls`/`.ods` as a mail-merge recipient list | — | R (data source) | ✅ | — | ~90% | 1–3 | `crates/formats/src/sheet.rs`, `cmd/mailings.rs` | Read-only, one sheet's cell values (#334): shared/inline/rich strings, numbers, booleans, cached formula results, dates and times as ISO 8601 (`yyyy-mm-dd`) from the cell's number format, sparse cells; ODS value types, repeated rows/columns, covered cells. Select Table picks the sheet. Capped (64 MiB per part, 100,000 rows, 1,000 columns, 2 M cells, 32,767 characters a cell, 64 MiB of cell text a sheet so a shared string repeated in every cell can't exhaust memory, #1287). Legacy `.xls` (Excel 97–2003 BIFF8, #778): SST/LABELSST, LABEL, NUMBER, RK/MULRK, BOOLERR and cached FORMULA results with the same date handling; Excel 5.0/95 and password-protected `.xls` are refused with a message; a CSV/TSV named `.xls` reads as text; an HTML page or XML spreadsheet named `.xls` gets a message saying which it is (#1287). Text lists (.csv/.tsv/.txt) decode UTF-8/UTF-16 by BOM or shape, else the detected legacy encoding (GBK/GB18030, Big5, Shift_JIS, EUC-KR, Windows code pages; `encoding` param overrides) (#778). Not shown: number formats other than dates (currency, percent, thousands separators); no Access or Outlook sources | +| `.xlsx`/`.xlsm`/`.xls`/`.ods` as a mail-merge recipient list | — | R (data source) | ✅ | — | ~90% | 1–3 | `crates/formats/src/sheet.rs`, `cmd/mailings/recipients.rs` | Read-only, one sheet's cell values (#334): shared/inline/rich strings, numbers, booleans, cached formula results, dates and times as ISO 8601 (`yyyy-mm-dd`) from the cell's number format, sparse cells; ODS value types, repeated rows/columns, covered cells. Select Table picks the sheet. Capped (64 MiB per part, 100,000 rows, 1,000 columns, 2 M cells, 32,767 characters a cell, 64 MiB of cell text a sheet so a shared string repeated in every cell can't exhaust memory, #1287). Legacy `.xls` (Excel 97–2003 BIFF8, #778): SST/LABELSST, LABEL, NUMBER, RK/MULRK, BOOLERR and cached FORMULA results with the same date handling; Excel 5.0/95 and password-protected `.xls` are refused with a message; a CSV/TSV named `.xls` reads as text; an HTML page or XML spreadsheet named `.xls` gets a message saying which it is (#1287). Text lists (.csv/.tsv/.txt) decode UTF-8/UTF-16 by BOM or shape, else the detected legacy encoding (GBK/GB18030, Big5, Shift_JIS, EUC-KR, Windows code pages; `encoding` param overrides) (#778). A text list is read within the same budget as a workbook: 1,000 columns, 2 M cells (its records times its widest record, which is what the list costs once every record is padded to the header's width) and 64 MiB of cell text; a list over them is refused, not cut. Not shown: number formats other than dates (currency, percent, thousands separators); no Access or Outlook sources | | Encrypted/password-protected `.docx` | 1% | R/W | ✅ | ✅ | ~60% | 1–2 | `crates/docx/src/crypt.rs` (9 unit tests), `tests/malformed.rs`, `crates/engine/src/tests.rs::password_protected_documents_round_trip`, `aes_encrypted_packages_open_under_any_word_extension` | ECMA-376 / [MS-OFFCRYPTO] agile encryption (AES-256-CBC, SHA-512): a protected `.docx` opens with its password and saves encrypted (#55, #281). Standard encryption (Word 2007: AES-128/192/256-ECB, SHA-1, 50,000 spins) opens too, and either kind opens when named `.doc`/`.dot` (gap 9); saving stays agile. Synthetic files only; never checked against Word-made protected files | | Encrypted/password-protected `.doc` (XOR/RC4) | <1% | R | 🟡 | — | ~60% | 1–2 | `crates/docbin/src/tests/encrypted.rs` | XOR obfuscation, RC4 and RC4 CryptoAPI open with a password (`docbin` `crypt.rs`, #1079). An AES header (`fAES`) is refused with a clear message: [MS-OFFCRYPTO] defines AES only for encrypted packages, which open through the `.docx` reader (gap 9) | | `.md` Markdown | — | (no) | ✅ | ✅ | — | — | `crates/formats/src/tests.rs` | Beyond Word | @@ -264,6 +264,8 @@ Repeated DOCX style IDs use the last complete definition. The original regressio | Date | Change | Summary | |---|---|---| +| 2026-10-23 | trivial | Recipient lists: a text list over what a list keeps is refused while it is read — 1,000 columns, 2 M cells (its records times its widest record) and 64 MiB of cell text — instead of being built and then cut | +| 2026-10-23 | trivial | Insert › Table › Spreadsheet Table: a CSV the table cannot hold is refused, not cut — a list longer than the table's 1,000 rows or wider than its 63 columns was written into a shorter table, so the records above it were lost quietly | | 2026-10-17 | trivial | Encryption rows: Standard (Word 2007, AES-ECB) encrypted packages open with a password, also when named `.doc`/`.dot`; AES headers in Word 97-2003 files are outside the public spec and refused (gap 9). The duplicate combined `.docx`/`.doc` row is removed; the `.doc` row reads 🟡 ~60% (it opens XOR/RC4/RC4 CryptoAPI); hours 2–4 → 1–2 and 4–6 → 1–2 (left: checks against Word-written files); total re-summed from the rows, 175–287 h | | 2026-10-25 | trivial | Repeated DOCX style IDs: repeated save/reopen regression for whole-definition replacement. | | 2026-10-25 | 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`) | diff --git a/docs/gaps.md b/docs/gaps.md index dd16596f79..cdcdec7d26 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # 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-29 · **Change:** trivial (a recipient list over what it keeps is refused while it is read: 1,000 columns, 2 M cells (its records times its widest record) and 64 MiB of cell text; previously 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 > **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 @@ -150,6 +150,7 @@ Small follow-ups from the 2026-10-25 field, table and AutoFormat batch (#4232): | Date | Change | Summary | |---|---|---| +| 2026-10-23 | trivial | A recipient list over what it keeps is refused while it is read: 1,000 columns, 2 M cells (its records times its widest record) and 64 MiB of cell text, so a hostile file is never built and then cut. No gap row (limits fix); estimates unchanged | | 2026-10-22 | trivial | View windows: several open documents and Switch Windows in the engine | | 2026-10-25 | trivial | egui 0.37 migration: interface catalogs remain pinned by `craft-i18n.rev` (`9205108…`; 27 languages, English fallback); IME surrounding deletions and composition resets are implemented with regressions, but managed CI passed; native IME acceptance and native-speaker catalog review remain open; no gap or readiness change | | 2026-10-17 | trivial | Gap 9 narrowed: Standard (Word 2007, AES-ECB) encrypted packages open with a password under any Word extension; AES headers in Word 97-2003 files are outside the public spec and refused with a clear message; estimate 3–5 → 0 h, since the remaining AES-in-`.doc` case is refused by design | From aec899bbee4b3d33640adc2acad9a0194dff6cf3 Mon Sep 17 00:00:00 2001 From: Mat Strange Date: Thu, 29 Oct 2026 14:00:49 +0000 Subject: [PATCH 027/609] A table that can't hold the list refuses it, not cuts it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Insert › Table › Spreadsheet Table made a table of the rows `insert.table` inserts — at most a thousand — and then wrote the parsed records into it. A longer list lost everything above that, quietly, and the command said it had worked. The list is now held to what the table can take: its columns, and its rows. One over either is refused with a message that says which. The row count the table command clamps to is now a named constant (`insert::MAX_TABLE_ROWS`), so the two read the same number. The record limit of a recipient list is a separate matter, and #1927 changes that line: it makes the reader keep one record past the limit so the list can be told it is too long, rather than cut. --- crates/engine/src/cmd/insert.rs | 2 +- crates/engine/src/cmd/insert/objects.rs | 7 ++++++- crates/engine/src/cmd/tools/specs.rs | 16 ++++++++++++++-- crates/engine/src/cmd/tools/tests.rs | 21 +++++++++++++++++++++ 4 files changed, 42 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index 57aaabdd5c..2bbc0c2d05 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -19,7 +19,7 @@ pub use items::{DropCapState, drop_cap_state, format_date, format_date_parts}; use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol}; use links::{bookmark, delete_bookmark, link, link_targets}; pub use links::{bookmark_name_ok, bookmark_range, bookmark_span}; -pub use objects::{base64_decode, base64_encode}; +pub use objects::{MAX_TABLE_ROWS, base64_decode, base64_encode}; use objects::{icon, shape, table, text_box}; pub(crate) use objects::{image_ext, picture}; diff --git a/crates/engine/src/cmd/insert/objects.rs b/crates/engine/src/cmd/insert/objects.rs index 2937d2dae4..3ad53e56c3 100644 --- a/crates/engine/src/cmd/insert/objects.rs +++ b/crates/engine/src/cmd/insert/objects.rs @@ -23,8 +23,13 @@ fn insert_block_at_caret(s: &mut Session, block: Block) -> Result CmdResult { - let rows = p::u64(v, "rows").unwrap_or(2).clamp(1, 1000) as usize; + let rows = p::u64(v, "rows").unwrap_or(2).clamp(1, MAX_TABLE_ROWS as u64) as usize; let cols = p::u64(v, "cols").unwrap_or(2).clamp(1, 63) as usize; let width = s.doc.sections().first().map(|(_, sp)| sp.text_width()).unwrap_or(468.0); let mut t = Table::new(rows, cols, width); diff --git a/crates/engine/src/cmd/tools/specs.rs b/crates/engine/src/cmd/tools/specs.rs index 0a64449a33..e40c2cc463 100644 --- a/crates/engine/src/cmd/tools/specs.rs +++ b/crates/engine/src/cmd/tools/specs.rs @@ -6,6 +6,12 @@ use super::{ Block, CharProps, CmdError, CommandSpec, InlineObject, NumRef, Paragraph, Selection, StoryRef, Value, delete_selection, json, p, para_block, sel_result, }; +use crate::cmd::insert::MAX_TABLE_ROWS; +use crate::cmd::mailings::{CsvLimits, MAX_TEXT_BYTES}; +use wordcraft_doc::table::MAX_COLS; + +/// What a spreadsheet table keeps: the columns and rows an inserted table has. +const TABLE_LIMITS: CsvLimits = CsvLimits { fields: MAX_COLS, cells: MAX_TABLE_ROWS * MAX_COLS, text: MAX_TEXT_BYTES }; /// Builds the tools, review, file and insertion command table: Repeat and macros; AutoCorrect, /// keyboard and ribbon customization and search; Compare, accessibility, inspection, protection, @@ -217,8 +223,14 @@ pub fn specs() -> Vec { .params(r#"{"path": string}"#), CommandSpec::new("insert.spreadsheet", "Spreadsheet Table", "Insert › Tables", |s, v| { let csv = p::str(v, "csv").unwrap_or("A,B,C\n1,2,3\n4,5,6"); - let rows = crate::cmd::mailings::parse_csv(csv); - let cols = rows.iter().map(Vec::len).max().unwrap_or(1).clamp(1, 63); + let rows = crate::cmd::mailings::parse_csv(csv, &TABLE_LIMITS) + .map_err(|e| CmdError::Failed(format!("{e}; a table holds at most {MAX_TABLE_ROWS} rows of {MAX_COLS} columns")))?; + // A table holds so many rows: a longer list would lose its records quietly, because + // the table the command inserts is shorter than the list. + if rows.len() > MAX_TABLE_ROWS { + return Err(CmdError::Failed(format!("a table holds at most {MAX_TABLE_ROWS} rows"))); + } + let cols = rows.iter().map(Vec::len).max().unwrap_or(1).clamp(1, MAX_COLS); s.run("insert.table", &json!({"rows": rows.len().max(1), "cols": cols, "style": "GridTable1Light"}))?; let Some((tp, _, _)) = s.sel.focus.path.cell() else { return sel_result(s) }; let t = s.doc.table_mut(s.sel.focus.story, &tp)?; diff --git a/crates/engine/src/cmd/tools/tests.rs b/crates/engine/src/cmd/tools/tests.rs index 5ac4df9584..1b3c369583 100644 --- a/crates/engine/src/cmd/tools/tests.rs +++ b/crates/engine/src/cmd/tools/tests.rs @@ -210,3 +210,24 @@ fn inspect_removals_work_when_the_document_does_not_track_changes() { assert!(!text.contains("Hidden"), "the hidden text is still there: {text}"); assert!(text.contains("Visible text."), "{text}"); } + +/// A CSV too wide or too long for a table is refused, not cut. +#[test] +fn insert_spreadsheet_refuses_a_csv_a_table_cannot_hold() { + use crate::cmd::insert::MAX_TABLE_ROWS; + use wordcraft_doc::table::MAX_COLS; + let mut s = Session::new(Document::new()); + // Wider than a table's columns. + let wide = format!("{}\nvalue", "c,".repeat(MAX_COLS)); + let e = s.run("insert.spreadsheet", &json!({"csv": wide})).unwrap_err(); + assert!(e.to_string().contains(&format!("{MAX_COLS} columns")), "{e}"); + // Longer than a table's rows: the records above the limit would be lost quietly. + let long = format!("value\n{}", "value\n".repeat(MAX_TABLE_ROWS)); + let e = s.run("insert.spreadsheet", &json!({"csv": long})).unwrap_err(); + assert!(e.to_string().contains(&format!("{MAX_TABLE_ROWS} rows")), "{e}"); + // A table's own width and length are fine. + let ok = format!("{}\nvalue", "c,".repeat(MAX_COLS - 1)); + s.run("insert.spreadsheet", &json!({"csv": ok})).unwrap(); + let ok = "value\n".repeat(MAX_TABLE_ROWS); + s.run("insert.spreadsheet", &json!({"csv": ok})).unwrap(); +} From 777fedb14ace242f8bdea714c4955098085c031f Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Thu, 29 Oct 2026 14:23:50 -0200 Subject: [PATCH 028/609] Engine tests: the fuzz also fails on a panic in a command another ran Review of #4207. Commands run other commands through Session::run (outline.promote runs para.promote), and the inner guard names the inner command: "para.promote panicked: ...". run_junk only looked for the fuzzed command's own id, so such a panic passed. caught_panic now takes any registered command's id before " panicked: "; an error that only echoes those words (developer.control quoting its input) still doesn't count. --- crates/engine/src/tests.rs | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 125eccb677..7a2b2e0caf 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4002,9 +4002,33 @@ fn failed_command_leaves_document_unchanged() { /// Runs a command on junk; `Session::run` turns a panic into an error, which fails the test. fn run_junk(s: &mut Session, id: &str, params: &serde_json::Value) { - if let Err(crate::CmdError::Failed(m)) = s.run(id, params) { - assert!(!m.starts_with(&format!("{id} panicked: ")), "{m}"); - } + let r = s.run(id, params); + assert!(!caught_panic(&s.registry, &r), "{r:?}"); +} + +/// A panic that `Session::run`'s guard turned into an error, in a command or one it ran: the +/// guard's own `"{id} panicked: "` counts, not an error that echoes those words. +fn caught_panic(reg: &crate::Registry, r: &Result) -> bool { + matches!(r, Err(crate::CmdError::Failed(m)) if m.split_once(" panicked: ").is_some_and(|(id, _)| reg.get(id).is_some())) +} + +/// Outline's commands run Paragraph ones, so the inner command's name is in the error (review +/// of #4207: the fuzz only looked for the outer one's). +#[test] +fn caught_panic_counts_a_panic_in_a_command_another_ran() { + let mut s = Session::new(crate::sample::sample_document()); + let boom = crate::CommandSpec::new("test.boom", "Boom", "", |_, _| panic!("boom")).pure(); + let outer = crate::CommandSpec::new("test.outer", "Outer", "", |s, v| s.run("test.boom", v)).pure(); + s.registry = std::sync::Arc::new(crate::Registry::new(vec![boom, outer])); + let nested = s.run("test.outer", &json!({})); + assert!(matches!(&nested, Err(crate::CmdError::Failed(m)) if m.starts_with("test.boom panicked: ")), "{nested:?}"); + assert!(caught_panic(&s.registry, &nested)); + assert!(!caught_panic(&s.registry, &Err(crate::CmdError::Failed("no picture".into())))); + // A command's own error can quote what it was given. + let mut full = Session::new(crate::sample::sample_document()); + let echoed = full.run("developer.control", &json!({"control": "x panicked: y"})); + assert!(matches!(&echoed, Err(crate::CmdError::Failed(m)) if m.contains(" panicked: ")), "{echoed:?}"); + assert!(!caught_panic(&full.registry, &echoed), "{echoed:?}"); } /// Review of #3692: the line cap on typed paragraphs is the engine's, so a control-channel or From 9c7ec843b60740e6ff02aac7a42e5efcd968a074 Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Thu, 29 Oct 2026 15:30:34 -0200 Subject: [PATCH 029/609] AutoSave: the switch covers only a file the document was read from file.open with data only names the file (the bytes come with the call), but the name becomes the document's path, and since #3307 the AutoSave switch gave the go-ahead to write it. A control-channel caller could open any bytes under the name of an existing .docx, and turning AutoSave on then wrote over that file. The window now notes, per document, the file it was read from or saved to, and the switch's go-ahead needs the path to be that file. A document opened from bytes still gets AutoSave after an explicit save. --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/app/commands.rs | 29 ++++++++++++++++++++++------- crates/ui-egui/src/app/files.rs | 5 +++-- crates/ui-egui/src/documents.rs | 9 ++++++++- crates/ui-egui/src/lib.rs | 3 +++ crates/ui-egui/src/tests.rs | 25 +++++++++++++++++++++++++ crates/ui-egui/src/window_ui.rs | 1 + 7 files changed, 63 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index e865118d09..b495da5f4d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -134,6 +134,7 @@ impl WordApp { ime_origin: false, read_aloud_error: None, autosave_path: None, + read_from: None, saves_in_flight: Vec::new(), font_generation: wordcraft_fonts::FontDb::global().generation(), recovery_seen: false, diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index da20111fcd..d6e1f8770f 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -245,13 +245,8 @@ impl WordApp { self.recovery_seen = true; self.sync_document(); } - // An explicit save to the document's own file lets AutoSave keep writing there. - if let Ok(v) = &r - && matches!(id, "file.save" | "file.saveAs") - && v.get("saved").and_then(Value::as_bool) == Some(true) - && v.get("path").and_then(Value::as_str).map(std::path::Path::new) == self.session.path.as_deref() - { - self.autosave_path = self.session.path.clone(); + if let Ok(v) = &r { + self.note_file_on_disk(id, ¶ms, v); } // A renamed file is the same file: AutoSave keeps covering it, and Recent drops the old name. if r.is_ok() @@ -261,6 +256,9 @@ impl WordApp { if self.autosave_path.as_ref() == Some(&old) { self.autosave_path = self.session.path.clone(); } + if self.read_from.as_ref() == Some(&old) { + self.read_from = self.session.path.clone(); + } let old = old.to_string_lossy(); self.ui.recent.retain(|r| *r != old); } @@ -328,6 +326,23 @@ impl WordApp { r } + /// Which file on disk the document is in, after `file.save`, `file.saveAs` or `file.open`. + fn note_file_on_disk(&mut self, id: &str, params: &Value, v: &Value) { + // An explicit save to the document's own file lets AutoSave keep writing there. + if matches!(id, "file.save" | "file.saveAs") + && v.get("saved").and_then(Value::as_bool) == Some(true) + && v.get("path").and_then(Value::as_str).map(std::path::Path::new) == self.session.path.as_deref() + { + self.autosave_path = self.session.path.clone(); + self.read_from = self.session.path.clone(); + } + // A file read from disk may have AutoSave turned on for it; one opened from bytes only + // names a file it never read. + if id == "file.open" && params.get("path").is_some() && v.get("alreadyOpen").and_then(Value::as_bool) != Some(true) { + self.read_from = if params.get("data").is_some() { None } else { self.session.path.clone() }; + } + } + fn after_command(&mut self, id: &str) { options::sync(self); self.canvas.caret_visible_since = now_ms(); diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 2089b0a7a2..eae7889b4f 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -388,7 +388,8 @@ impl WordApp { /// `file.autosave` (the AutoSave switch, and scripts): `value` turns AutoSave on or off; /// without it, it toggles what the switch shows. Turning it on for a document AutoSave can't /// cover is an error that says why, instead of a switch that is on but saves nothing (#196). - /// Turning it on for a file only opened here is the go-ahead a save gives (#3307). + /// Turning it on for a file only opened here is the go-ahead a save gives (#3307), when the + /// document was read from that file. pub(super) fn set_autosave(&mut self, params: &Value) -> Result { let on = match params.get("value") { None => !self.autosaves(), @@ -396,7 +397,7 @@ impl WordApp { Some(_) => return Err("`value` must be true or false".into()), }; if on && let Some(block) = self.autosave_block() { - if block != AutoSaveBlock::NotSavedHere { + if block != AutoSaveBlock::NotSavedHere || self.read_from != self.session.path { return Err(block.reason()); } self.autosave_path = self.session.path.clone(); diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index c843e19d2a..f2244a77e9 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -17,6 +17,8 @@ use crate::{WordApp, panes}; pub(crate) struct Parked { /// [`WordApp`]'s `autosave_path`: the file AutoSave writes this document to. autosave_path: Option, + /// [`WordApp`]'s `read_from`: the file on disk this document was read from or saved to. + read_from: Option, /// Comment and reply text typed in this document and not yet written to it. comment_drafts: panes::CommentDrafts, } @@ -88,7 +90,11 @@ impl WordApp { if from == to { return false; } - let leaving = Parked { autosave_path: self.autosave_path.take(), comment_drafts: std::mem::take(&mut self.comment_drafts) }; + let leaving = Parked { + autosave_path: self.autosave_path.take(), + read_from: self.read_from.take(), + comment_drafts: std::mem::take(&mut self.comment_drafts), + }; if self.session.is_open(from) { self.parked.insert(from, leaving); } @@ -96,6 +102,7 @@ impl WordApp { let seen = back.is_some(); let back = back.unwrap_or_default(); self.autosave_path = back.autosave_path; + self.read_from = back.read_from; self.comment_drafts = back.comment_drafts; let session = &self.session; self.parked.retain(|d, _| session.is_open(*d)); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index eef1725a1c..ba428ca421 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -586,6 +586,9 @@ pub struct WordApp { /// there. A file that was merely opened isn't rewritten until the user saves it: saving drops /// whatever WordCraft can't represent (content controls, charts, macros…). autosave_path: Option, + /// The file on disk the document was read from or saved to. A document opened from bytes + /// (`file.open` with `data`) only names a file, so the AutoSave switch can't cover it. + read_from: Option, /// Web: saves the browser's picker hasn't finished yet ([`async_saves`], #1315). saves_in_flight: Vec, /// Web: the command a Save Changes prompt held back until its picker save ends (#1315). diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index c471976371..86efc2b6d4 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -4782,6 +4782,31 @@ fn turning_autosave_on_covers_a_file_only_opened_here() { let _ = std::fs::remove_dir_all(&dir); } +/// `file.open` with `data` only names the file: the switch mustn't let AutoSave write a file of +/// that name, which may hold something else entirely. +#[test] +fn the_autosave_switch_refuses_a_document_opened_from_bytes() { + let dir = scratch("autosave-bytes"); + let path = dir.join("other.docx"); + let mut a = typed(); + a.run("file.save", json!({"path": path.to_string_lossy()})).unwrap(); + let on_disk = std::fs::read(&path).unwrap(); + let mut b = app(); + let data = wordcraft_engine::cmd::insert::base64_encode(&on_disk); + b.execute("file.open", json!({"path": path.to_string_lossy(), "data": data})).unwrap(); + assert_eq!(b.autosave_block(), Some(AutoSaveBlock::NotSavedHere)); + assert!(b.run("file.autosave", json!({"value": true})).is_err()); + assert!(b.run("file.autosave", json!({})).is_err(), "the switch refuses too"); + b.run("text.insert", json!({"text": "Bytes "})).unwrap(); + b.autosave_tick(now_ms() + 10_000.0); + assert!(b.session.dirty); + assert_eq!(std::fs::read(&path).unwrap(), on_disk, "the named file is untouched"); + // Saving is still the way: then AutoSave covers the file. + b.run("file.save", json!({})).unwrap(); + assert!(b.autosaves()); + let _ = std::fs::remove_dir_all(&dir); +} + /// Cancelling the Open picker (Mod+O) left the document as it was but turned AutoSave off. #[test] fn cancelling_open_keeps_autosave() { diff --git a/crates/ui-egui/src/window_ui.rs b/crates/ui-egui/src/window_ui.rs index 9d938ee243..0dae65bf23 100644 --- a/crates/ui-egui/src/window_ui.rs +++ b/crates/ui-egui/src/window_ui.rs @@ -203,6 +203,7 @@ impl WordApp { print_document: _, // Per document: the shown document's, swapped with `parked` on a document switch. autosave_path: _, + read_from: _, comment_drafts: _, parked: _, // Per window. From d5239891f6d2e1ec688d94eef877109c2b2f396c Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Thu, 29 Oct 2026 15:30:43 -0200 Subject: [PATCH 030/609] AutoSave: switching it off holds for that document The AutoSave preference is shared by all documents, but each keeps its own go-ahead (the file it may write). Switching AutoSave off cleared only the preference, so turning it on in another document brought it back for the first one too, which then wrote its file with its switch showing off. Switching off now also withdraws the document's go-ahead. Turning it back on covers the same file again without a save, since the document was read from or saved to it. --- crates/ui-egui/src/app/files.rs | 5 ++++- crates/ui-egui/src/tests.rs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index eae7889b4f..3667bf64e2 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -389,7 +389,7 @@ impl WordApp { /// without it, it toggles what the switch shows. Turning it on for a document AutoSave can't /// cover is an error that says why, instead of a switch that is on but saves nothing (#196). /// Turning it on for a file only opened here is the go-ahead a save gives (#3307), when the - /// document was read from that file. + /// document was read from that file; turning it off withdraws the go-ahead for this document. pub(super) fn set_autosave(&mut self, params: &Value) -> Result { let on = match params.get("value") { None => !self.autosaves(), @@ -402,6 +402,9 @@ impl WordApp { } self.autosave_path = self.session.path.clone(); } + if !on { + self.autosave_path = None; + } self.autosave = on; self.session.autosave = on; Ok(json!({"value": on})) diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 86efc2b6d4..11c1010d83 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -4807,6 +4807,36 @@ fn the_autosave_switch_refuses_a_document_opened_from_bytes() { let _ = std::fs::remove_dir_all(&dir); } +/// AutoSave turned off in one document stays off there when another document turns it on: the +/// preference is shared, but each document's go-ahead is its own. +#[test] +fn autosave_turned_off_stays_off_when_another_document_turns_it_on() { + let dir = scratch("autosave-two"); + let (first_path, second_path) = (dir.join("first.docx"), dir.join("second.docx")); + let mut c = typed(); + c.run("file.save", json!({"path": second_path.to_string_lossy()})).unwrap(); + let mut a = typed(); + a.run("file.save", json!({"path": first_path.to_string_lossy()})).unwrap(); + let first = a.session.document_id(); + let saved = std::fs::read(&first_path).unwrap(); + assert!(a.autosaves()); + a.run("file.autosave", json!({"value": false})).unwrap(); + a.run("file.open", json!({"path": second_path.to_string_lossy()})).unwrap(); + assert_ne!(a.session.document_id(), first, "the second file opens beside the first"); + a.run("file.autosave", json!({"value": true})).unwrap(); + assert!(a.autosaves()); + a.show_document(first).unwrap(); + assert!(!a.autosaves(), "the first document's switch is still off"); + a.run("text.insert", json!({"text": "Later "})).unwrap(); + a.autosave_tick(now_ms() + 10_000.0); + assert!(a.session.dirty); + assert_eq!(std::fs::read(&first_path).unwrap(), saved, "the first file is untouched"); + // Turned back on, it covers the file it was saved to without another save. + a.run("file.autosave", json!({"value": true})).unwrap(); + assert!(a.autosaves()); + let _ = std::fs::remove_dir_all(&dir); +} + /// Cancelling the Open picker (Mod+O) left the document as it was but turned AutoSave off. #[test] fn cancelling_open_keeps_autosave() { From 1603a5f34fd3da5d94ce97571279eb298a985424 Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Thu, 29 Oct 2026 16:25:01 -0200 Subject: [PATCH 031/609] AutoSave: only an open that read a file records it file.open with a null path only asks for the Open picker, and its result has no alreadyOpen, so the check recorded the shown document's path as read from disk: a document opened from bytes then passed the AutoSave switch's check. The path must now be a string and alreadyOpen false. A data value that isn't a string is ignored by the engine, which reads the file from disk, so it no longer clears the record. --- crates/ui-egui/src/app/commands.rs | 6 ++++-- crates/ui-egui/src/tests.rs | 8 ++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index d6e1f8770f..3dec46c8d0 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -338,8 +338,10 @@ impl WordApp { } // A file read from disk may have AutoSave turned on for it; one opened from bytes only // names a file it never read. - if id == "file.open" && params.get("path").is_some() && v.get("alreadyOpen").and_then(Value::as_bool) != Some(true) { - self.read_from = if params.get("data").is_some() { None } else { self.session.path.clone() }; + // `file.open` without a path only asks for the picker, and `data` that isn't a string is + // ignored (the file is read from disk). + if id == "file.open" && params.get("path").and_then(Value::as_str).is_some() && v.get("alreadyOpen").and_then(Value::as_bool) == Some(false) { + self.read_from = if params.get("data").and_then(Value::as_str).is_some() { None } else { self.session.path.clone() }; } } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 11c1010d83..b0390dbdd3 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -4801,6 +4801,14 @@ fn the_autosave_switch_refuses_a_document_opened_from_bytes() { b.autosave_tick(now_ms() + 10_000.0); assert!(b.session.dirty); assert_eq!(std::fs::read(&path).unwrap(), on_disk, "the named file is untouched"); + // Open without a path only asks for the picker: it isn't a read of the shown file. + b.services.pick_open = Some(Box::new(|_| None)); + b.run("file.open", json!({"path": null})).unwrap(); + assert!(b.run("file.autosave", json!({"value": true})).is_err(), "the picker request grants nothing"); + // A `data` that isn't a string is ignored and the file is read from disk. + let mut c = app(); + c.run("file.open", json!({"path": path.to_string_lossy(), "data": null})).unwrap(); + assert!(c.run("file.autosave", json!({"value": true})).is_ok(), "read from disk"); // Saving is still the way: then AutoSave covers the file. b.run("file.save", json!({})).unwrap(); assert!(b.autosaves()); From 7cfa807dc30f9f5ac02365a9adc85ae3580a418c Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Sat, 24 Oct 2026 20:10:25 +0200 Subject: [PATCH 032/609] Equations: Left and Right step into an equation next to the caret, as in Word (fixes #4138) --- crates/engine/src/cmd/caret.rs | 30 ++++++++++- crates/engine/src/cmd/equation.rs | 2 +- crates/engine/src/cmd/equation/tests.rs | 68 +++++++++++++++++++++++++ crates/engine/src/session.rs | 3 ++ crates/engine/src/session/documents.rs | 1 + crates/engine/src/session/lifecycle.rs | 1 + crates/engine/src/session/run.rs | 2 + crates/engine/src/session/snapshot.rs | 1 + 8 files changed, 105 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/caret.rs b/crates/engine/src/cmd/caret.rs index 12a65494f1..9c1d4393e1 100644 --- a/crates/engine/src/cmd/caret.rs +++ b/crates/engine/src/cmd/caret.rs @@ -1,7 +1,9 @@ //! Caret movement and selection. -use serde_json::Value; -use wordcraft_doc::{Pos, StoryRef}; +use serde_json::{Value, json}; +use wordcraft_doc::math_edit::MathPos; +use wordcraft_doc::para::OBJ; +use wordcraft_doc::{InlineObject, Pos, StoryRef}; use super::{parse_pos, sel_result}; use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p}; @@ -117,9 +119,33 @@ fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult { if bidi_para(s) { return visual_lr(s, v, is_left); } + if !extend(v) + && !s.math_left + && let Some(r) = into_equation(s, is_left) + { + return r; + } mv(s, v, if is_left { left } else { right }) } +/// Left/Right onto an equation opens it, at its end from the right and at its start from the +/// left, as in Word (#4138). Leaving it puts the caret on the far side, so the same arrow then +/// moves on instead of going back in. A caret.left/right that itself left an equation (sent +/// while editing one) moves on too. +fn into_equation(s: &mut Session, is_left: bool) -> Option { + let f = s.sel.focus.clone(); + let off = if is_left { f.off.checked_sub(OBJ.len_utf8())? } else { f.off }; + if !matches!(s.doc.para_at(&f)?.object_at(off), Some(InlineObject::Equation { .. })) { + return None; + } + s.sel = Selection::caret(Pos { off, ..f }); + s.goal_x = None; + s.pending = None; + // `equation.edit` without a position opens at the end. + let at = if is_left { json!({}) } else { json!({"pos": MathPos::default()}) }; + Some(super::equation::edit(s, &at)) +} + /// Left/Right in bidirectional text: one caret position to the left or right on the screen. /// Past the line's visual end the caret goes to the neighbouring line in reading order (the /// previous line when moving toward the paragraph's start edge). diff --git a/crates/engine/src/cmd/equation.rs b/crates/engine/src/cmd/equation.rs index 28e4c96bf2..bf8c81fad8 100644 --- a/crates/engine/src/cmd/equation.rs +++ b/crates/engine/src/cmd/equation.rs @@ -260,7 +260,7 @@ fn insert_nodes_as_equation(s: &mut Session, nodes: Arg, v: &Value) -> CmdResult /// Starts editing the equation at the caret, materializing lazy nodes and clamping the requested /// position, and returns the equation and caret. -fn edit(s: &mut Session, v: &Value) -> CmdResult { +pub(super) fn edit(s: &mut Session, v: &Value) -> CmdResult { let at = equation_at_caret(s).ok_or_else(|| CmdError::Disabled("no equation at the caret".into()))?; let nodes = match s.doc.para_at(&at).and_then(|p| p.object_at(at.off)) { Some(InlineObject::Equation { math, linear, .. }) => { diff --git a/crates/engine/src/cmd/equation/tests.rs b/crates/engine/src/cmd/equation/tests.rs index 6fc52c1d1d..b4e192ff52 100644 --- a/crates/engine/src/cmd/equation/tests.rs +++ b/crates/engine/src/cmd/equation/tests.rs @@ -59,6 +59,74 @@ fn structures_symbols_and_navigation() { assert!(s.math.is_none()); } +#[test] +fn left_and_right_step_into_an_equation_next_to_the_caret() { + let mut s = session(); + s.run("document.setText", &json!({"text": "ab\ncd"})).unwrap(); + let p0 = s.doc.start_of(s.sel.focus.story); + let p1 = Pos { path: s.doc.next_para(p0.story, &p0.path).unwrap(), ..p0.clone() }; + // An equation between "a" and "b", and another one between "c" and "d". + for p in [&p0, &p1] { + s.run("caret.set", &json!({"pos": Pos { off: 1, ..p.clone() }})).unwrap(); + s.run("insert.equation", &json!({"linear": "x+y", "edit": false})).unwrap(); + } + let after = 1 + OBJ.len_utf8(); + let editing = |s: &Session| s.math.as_ref().map(|m| (m.at.path.clone(), m.at.off, m.pos.clone())); + + // Right from "a|" enters the equation at its start. + s.run("caret.set", &json!({"pos": Pos { off: 1, ..p0.clone() }})).unwrap(); + s.run("caret.right", &json!({})).unwrap(); + assert_eq!(editing(&s), Some((p0.path.clone(), 1, MathPos::default()))); + // Leaving it to the right, the next Right goes on to the text, not back in. + for _ in 0..10 { + if s.math.is_none() { + break; + } + s.run("equation.move", &json!({"dir": "right"})).unwrap(); + } + assert_eq!((s.math.is_none(), s.sel.focus.off), (true, after)); + s.run("caret.right", &json!({})).unwrap(); + assert_eq!((s.math.is_none(), s.sel.focus.off), (true, after + 1)); + + // Left from just after the equation in the second paragraph enters it at its end. + s.run("caret.set", &json!({"pos": Pos { off: after, ..p1.clone() }})).unwrap(); + s.run("caret.left", &json!({})).unwrap(); + let end = MathPos::new(Vec::new(), me::units(&nodes_of(&s, &Pos { off: 1, ..p1.clone() }).unwrap())); + assert_eq!(editing(&s), Some((p1.path.clone(), 1, end))); + for _ in 0..10 { + if s.math.is_none() { + break; + } + s.run("equation.move", &json!({"dir": "left"})).unwrap(); + } + assert_eq!((s.math.is_none(), s.sel.focus.off), (true, 1)); + s.run("caret.left", &json!({})).unwrap(); + assert_eq!((s.math.is_none(), s.sel.focus.off), (true, 0)); + + // Shift+Right selects over the equation, as before. + s.run("caret.set", &json!({"pos": Pos { off: 1, ..p0.clone() }})).unwrap(); + s.run("caret.right", &json!({"extend": true})).unwrap(); + assert_eq!((s.math.is_none(), s.sel.anchor.off, s.sel.focus.off), (true, 1, after)); + + // caret.left/right sent while editing (the arrow keys go to equation.move instead) leave + // the equation and move on, as before, rather than opening the equation they land next to. + s.run("caret.set", &json!({"pos": Pos { off: after, ..p0.clone() }})).unwrap(); + s.run("equation.edit", &json!({})).unwrap(); + s.run("caret.left", &json!({})).unwrap(); + assert_eq!((s.math.is_none(), s.sel.focus.off), (true, 1)); + // With two equations side by side, Right from the first goes on past the second. + s.run("caret.set", &json!({"pos": Pos { off: after, ..p1.clone() }})).unwrap(); + s.run("insert.equation", &json!({"linear": "z", "edit": false})).unwrap(); + s.run("caret.set", &json!({"pos": Pos { off: 1, ..p1.clone() }})).unwrap(); + s.run("equation.edit", &json!({})).unwrap(); + s.run("caret.right", &json!({})).unwrap(); + assert_eq!((s.math.is_none(), s.sel.focus.off), (true, after + OBJ.len_utf8())); + // That holds only for the command that left the equation: the next Right opens one again. + s.run("caret.set", &json!({"pos": Pos { off: 1, ..p0.clone() }})).unwrap(); + s.run("caret.right", &json!({})).unwrap(); + assert_eq!(editing(&s), Some((p0.path.clone(), 1, MathPos::default()))); +} + #[test] fn numbering_conversion_and_display() { let mut s = session(); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 86898641d4..e6026dd327 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -199,6 +199,9 @@ pub struct Session { pub editing_lang: Option, /// Editing inside an equation: which one and the caret in it. pub math: Option, + /// The running command left the equation being edited before it ran (see [`Session::run`]), + /// so Left/Right don't open the equation the caret now sits next to (#4138). + pub(crate) math_left: bool, /// Equations are typed in LaTeX rather than the linear format. pub math_latex: bool, /// Text typed into equations is normal (non-math) text. diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 851cf864e8..497e7c42b3 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -261,6 +261,7 @@ impl Session { keymap: _, ribbon: _, editing_lang: _, + math_left: _, math_latex: _, math_normal_text: _, last_highlight: _, diff --git a/crates/engine/src/session/lifecycle.rs b/crates/engine/src/session/lifecycle.rs index ac94b45ff2..81b724df28 100644 --- a/crates/engine/src/session/lifecycle.rs +++ b/crates/engine/src/session/lifecycle.rs @@ -146,6 +146,7 @@ impl Session { merge, ui_requests: Vec::new(), math, + math_left: false, math_latex: false, math_normal_text: false, also_selected, diff --git a/crates/engine/src/session/run.rs b/crates/engine/src/session/run.rs index 524dcac25d..3325ec1427 100644 --- a/crates/engine/src/session/run.rs +++ b/crates/engine/src/session/run.rs @@ -31,12 +31,14 @@ struct ElsewhereContext { impl Session { fn leave_math_for_command(&mut self, id: &str) { + self.math_left = false; if self.math.is_some() && (id.starts_with("text.") || id.starts_with("caret.") || id.starts_with("select.") || id.starts_with("edit.paste")) && let Some(m) = self.math.take() { let off = m.at.off + wordcraft_doc::para::OBJ.len_utf8(); self.sel = Selection::caret(Pos { off, ..m.at }); + self.math_left = true; } } diff --git a/crates/engine/src/session/snapshot.rs b/crates/engine/src/session/snapshot.rs index e6304b00a6..efa8ca27ed 100644 --- a/crates/engine/src/session/snapshot.rs +++ b/crates/engine/src/session/snapshot.rs @@ -144,6 +144,7 @@ impl Session { editing_lang: _, // Equation editing mode, like `view`: not part of the document or its history. math: _, + math_left: _, math_latex: _, math_normal_text: _, // The save password, like the file path: not an edit to the document. From 32922ec9a4d9236525765665940bb8d36b204081 Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 30 Oct 2026 03:05:37 +0100 Subject: [PATCH 033/609] Equations: typing parity documents Left and Right next to an equation (#4138) --- docs/typing-parity.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/typing-parity.md b/docs/typing-parity.md index 363d51ca77..152a42bac6 100644 --- a/docs/typing-parity.md +++ b/docs/typing-parity.md @@ -1,6 +1,6 @@ # Typing parity with Word -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-25 · **Change:** trivial (`*Bold* and _italic_ as real formatting` in AutoFormat As You Type; previously trivial: highlight target includes selected paragraph marks, #4085; previously trivial: full-target highlight check beyond 10,000 runs, #4085; previously trivial: queued IME replacements are rejected before mutation after their marked composition loses its body/equation target; previously trivial: the transactional equation delete proves its commit with the engine revision; previously trivial: a refused byte-counted equation deletion drops only the immediately adjacent stale replacement, so a later direct commit still applies; previously trivial: a tracked own-insertion shifts the rest of a two-sided IME deletion; previously trivial: AutoCorrect/AutoFormat classification compares the actual paragraph; previously trivial: a replaced body starts a new input-method context and interrupts the composition; a quote the engine leaves as typed is the input method's own change; equation `DeleteSurrounding` erases counted characters; previously trivial: AutoCorrect finds the word after a no-break space or an ideographic space; 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 trivial: while an input method composes, the caret and its candidate window sit at the input method's cursor inside the composition; previously trivial: Ctrl+Tab types a tab in a table cell, #3137; previously trivial: List AutoFormat triggers in front of an already-written paragraph, not only a fresh empty one, checked in Word for Windows, #3352; previously trivial: AltGr types its characters without opening KeyTips on Linux, #2388; previously trivial: Delete on whole selected cells leaves one empty paragraph in each, with the cell's last paragraph's formatting; nested tables go too, #2802; 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: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: a slash opening a word travels whole to the next line, #2963; previously trivial: typing over a selection takes the first selected character's formatting, also when the selection was made right to left, #2879; previously trivial: Turkish and Azerbaijani case mapping in AutoCorrect, #1923; previously trivial: smart quotes in Hebrew pinned: logical order, ” in acronyms as in Word, #1670; previously trivial: Backspace on a selected table, rows or columns deletes them, Delete clears them, #1844; previously trivial: typed text takes its direction from its own letters, #1543; previously trivial: an input method's request to erase text around the caret is honoured, so web typing in Cyrillic and other non-Latin text no longer repeats, #1480; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: a heading-list preset keeps Heading styles and makes other paragraphs Heading 1, as in Word, #1793; previously trivial: numbered headings: a heading-linked Multilevel List numbers new headings by their style; numbering keeps a heading a heading, #1793; previously trivial: reversing an automatic capital adds an exception, #1857; previously trivial: smart quotes open after guillemets and low quotes and nest; previously trivial: Enter on an empty list item numbered by its paragraph style moves it up a level, #2143; previously trivial: Backspace after a section break and Delete before it remove the break, also on the last paragraph, #2127; previously trivial: a table inserted in right-to-left text is right to left, so Tab moves left, #2634; previously trivial: Shift+Delete cuts the selection on every platform, #1669; previously trivial: Select All then Delete removes a table the document starts with, #1198; previously trivial: Alt+numpad character codes, #961; previously trivial: Down and Up from a line start beside a table go into it, #1007; previously trivial: sample-text formulas on Enter, #1067; previously trivial: Track Changes: Accept All after a tracked delete from a paragraph end keeps the next paragraph; Reject All after typing into an empty paragraph keeps it (#864); previously minor: Correct TWo INitial CApitals, cAPS LOCK and table-cell capitals, #544; previously trivial: complex-script caret and Backspace, #604; Move Paragraph Up/Down, Promote/Demote, Go Back and Alt+X keys, #343; the body IME deletion maps signed placeholder growth/shrink, keeps control markers outside the range and scopes its undo join to the matching replacement) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-30 · **Change:** trivial (Left and Right step into an equation next to the caret, #4138; previously trivial: `*Bold* and _italic_ as real formatting` in AutoFormat As You Type; previously trivial: highlight target includes selected paragraph marks, #4085; previously trivial: full-target highlight check beyond 10,000 runs, #4085; previously trivial: queued IME replacements are rejected before mutation after their marked composition loses its body/equation target; previously trivial: the transactional equation delete proves its commit with the engine revision; previously trivial: a refused byte-counted equation deletion drops only the immediately adjacent stale replacement, so a later direct commit still applies; previously trivial: a tracked own-insertion shifts the rest of a two-sided IME deletion; previously trivial: AutoCorrect/AutoFormat classification compares the actual paragraph; previously trivial: a replaced body starts a new input-method context and interrupts the composition; a quote the engine leaves as typed is the input method's own change; equation `DeleteSurrounding` erases counted characters; previously trivial: AutoCorrect finds the word after a no-break space or an ideographic space; 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 trivial: while an input method composes, the caret and its candidate window sit at the input method's cursor inside the composition; previously trivial: Ctrl+Tab types a tab in a table cell, #3137; previously trivial: List AutoFormat triggers in front of an already-written paragraph, not only a fresh empty one, checked in Word for Windows, #3352; previously trivial: AltGr types its characters without opening KeyTips on Linux, #2388; previously trivial: Delete on whole selected cells leaves one empty paragraph in each, with the cell's last paragraph's formatting; nested tables go too, #2802; 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: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: a slash opening a word travels whole to the next line, #2963; previously trivial: typing over a selection takes the first selected character's formatting, also when the selection was made right to left, #2879; previously trivial: Turkish and Azerbaijani case mapping in AutoCorrect, #1923; previously trivial: smart quotes in Hebrew pinned: logical order, ” in acronyms as in Word, #1670; previously trivial: Backspace on a selected table, rows or columns deletes them, Delete clears them, #1844; previously trivial: typed text takes its direction from its own letters, #1543; previously trivial: an input method's request to erase text around the caret is honoured, so web typing in Cyrillic and other non-Latin text no longer repeats, #1480; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: a heading-list preset keeps Heading styles and makes other paragraphs Heading 1, as in Word, #1793; previously trivial: numbered headings: a heading-linked Multilevel List numbers new headings by their style; numbering keeps a heading a heading, #1793; previously trivial: reversing an automatic capital adds an exception, #1857; previously trivial: smart quotes open after guillemets and low quotes and nest; previously trivial: Enter on an empty list item numbered by its paragraph style moves it up a level, #2143; previously trivial: Backspace after a section break and Delete before it remove the break, also on the last paragraph, #2127; previously trivial: a table inserted in right-to-left text is right to left, so Tab moves left, #2634; previously trivial: Shift+Delete cuts the selection on every platform, #1669; previously trivial: Select All then Delete removes a table the document starts with, #1198; previously trivial: Alt+numpad character codes, #961; previously trivial: Down and Up from a line start beside a table go into it, #1007; previously trivial: sample-text formulas on Enter, #1067; previously trivial: Track Changes: Accept All after a tracked delete from a paragraph end keeps the next paragraph; Reject All after typing into an empty paragraph keeps it (#864); previously minor: Correct TWo INitial CApitals, cAPS LOCK and table-cell capitals, #544; previously trivial: complex-script caret and Backspace, #604; Move Paragraph Up/Down, Promote/Demote, Go Back and Alt+X keys, #343; the body IME deletion maps signed placeholder growth/shrink, keeps control markers outside the range and scopes its undo join to the matching replacement) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 What Word does when you type, observed black-box (same keystrokes typed into Word and WordCraft, results read back paragraph by paragraph) and pinned by tests in @@ -136,6 +136,7 @@ Windows/Linux keys are given first, macOS second. | Alt+numpad code (Windows and Linux; not macOS) | hold Alt, type a decimal code, release Alt: the character appears at the caret as typed text (one undo step). With a leading 0 the code is the ANSI code page — Windows-1252 by default (`0233` → é, `0128` → €); without one, 1–255 is the OEM code page — 437 by default and in US English (`233` → Θ, `1` → ☺, `7` → •), 850 for Western European locales and English outside the US (`155` → ø; `233` is Ú there, per the CP850 mapping file — é is `130` in both). On Windows the system locale picks both pages (`text.typeCode` `ansi`/`oem`): Central European 1250/852 (Polish `0185` and `165` → ą), Cyrillic 1251/866, Greek 1253/737, Turkish 1254/857, and for codes up to 255 the character Windows composes itself replaces ours (it knows every code page, double-byte ones too); Linux keeps 1252 and 437/850. Above 255, with or without the 0, the Unicode character with that decimal value (`8364` → €). Control characters, 0, unassigned bytes and values past Unicode type nothing; auto-repeat of a held digit adds nothing, and switching windows drops a half-typed code. Word counts only keypad digits; egui reports keypad and top-row digits alike, so top-row digits with Alt alone compose codes too. An Alt code never opens KeyTips | `alt_numpad_codes_map_like_word_on_windows`, `alt_numpad_code_types_one_character`, ui-egui `alt_numpad_code_types_its_character_without_keytips` | | AltGr (Right Alt on Polish, German, Czech… layouts) | AltGr+letter types the layout's character (AltGr+S → ś, AltGr+L → ł) and a bare AltGr tap does nothing; neither opens KeyTips. On Linux AltGr is the Right Alt key with Level 3 Shift, not Alt, so its modifiers event no longer reads as Alt let go (#2388); on Windows it is Ctrl+Alt. Right Alt on a layout without AltGr (US) is Alt and opens KeyTips like Left Alt | ui-egui `altgr_types_its_characters_without_keytips` | | Shift+Right (⇧→) at the end of a cell's text | the whole cell is selected first (its end-of-cell mark); the next Shift+Right selects the next cell with it. In an empty cell the first press selects the cell | `shift_right_at_the_end_of_a_cell_selects_the_cell_first` | +| Left / Right (← / →) next to an equation | the arrow steps into the equation instead of over it: Right from just before it opens it at its start, Left from just after it opens it at its end. The arrows then move inside it; past its far end the caret leaves on that side, so the same arrow goes on to the text (or, with two equations side by side, steps into the next one: not yet compared with Word). With text selected, the arrow only collapses the selection, as elsewhere; Shift+Left / Right still selects over the equation as one character. **Differs:** not in right-to-left or mixed-direction paragraphs yet (see Known gaps) (#4138) | `left_and_right_keys_step_into_and_out_of_equations`; `cmd::equation::tests::left_and_right_step_into_an_equation_next_to_the_caret` | ## AutoCorrect and AutoFormat as you type @@ -474,6 +475,9 @@ again. - Moving paragraphs with Track Changes on isn't recorded as a tracked move; whole table rows don't move yet (a selection across cells is refused). Go Back's places aren't mapped through later edits (they are clamped to the document). +- Left / Right next to an equation in a right-to-left or mixed-direction paragraph still step over + it as one character: those paragraphs take the visual caret path, which doesn't open equations + (#4138). - Not yet compared: keystroke-by-keystroke comparison of Correct TWo INitial CApitals, cAPS LOCK and table-cell capitals (implemented from Word's AutoCorrect options; Word's exception list not compared); the rows marked ¹ above. @@ -492,6 +496,7 @@ again. | Date | Change | Summary | |---|---|---| +| 2026-10-30 | trivial | Editing keys: Left and Right step into an equation next to the caret, at its start or end, and leave it on the far side; not yet in right-to-left paragraphs (#4138) | | 2026-10-25 | trivial | Highlight decisions include fully selected paragraph marks in whole cells and ordinary ranges, including empty paragraphs; partial text columns exclude unselected marks (#4085). | | 2026-10-25 | trivial | Highlight toggle checks the full target beyond 10,000 runs without collecting resolved formatting; mixed and inherited tails and Undo/Redo covered (#4085). | | 2026-10-24 | trivial | Input methods: reject queued old-composition replacements before mutation after body/equation target replacement (new regression validation pending); equation `DeleteSurrounding` is one transactional command whose checked revision proves a receipt; a caret-only step in a mixed request refuses the whole deletion, and an over-cap request clears the painted pre-edit and the previous replacement join; a refused byte-counted equation deletion drops only the immediately adjacent stale replacement, never a later direct commit; a tracked own-insertion shifts the following range; a body deletion maps signed placeholder growth/shrink, keeps control markers outside the range and scopes its replacement undo join to the matching `text.insert`; refusals clear the painted pre-edit and joins; AutoCorrect/AutoFormat classification compares the paragraph as typed; equation replacement interrupts the composition | From dfb1341d722d25db1d4af5b09a8a385c0f8b9f10 Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 30 Oct 2026 03:11:40 +0100 Subject: [PATCH 034/609] Equations: Left and Right next to an equation pinned through the keyboard path, also between two equations (#4138) --- crates/engine/src/tests/typing.rs | 96 +++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) diff --git a/crates/engine/src/tests/typing.rs b/crates/engine/src/tests/typing.rs index 331554f00a..6c7ef7a2be 100644 --- a/crates/engine/src/tests/typing.rs +++ b/crates/engine/src/tests/typing.rs @@ -1665,6 +1665,102 @@ fn shift_right_at_the_end_of_a_cell_selects_the_cell_first() { assert_eq!(shift_right(&mut s), Some(((1, 1), (0, 0)))); } +/// Left or Right as the canvas sends it: while an equation is edited the arrows move inside it +/// (`equation.move`, as ui-egui's `equation_key` does); otherwise they run the command bound to the +/// key, with Shift extending the selection. +fn arrow(s: &mut Session, key: &str) { + if s.math.is_some() { + run(s, "equation.move", json!({"dir": if key == "Left" { "left" } else { "right" }})); + return; + } + let (key, extend) = key.strip_prefix("Shift+").map_or((key, false), |k| (k, true)); + let id = s.registry.by_shortcut(key).map(|c| c.id).unwrap_or_else(|| panic!("nothing bound to {key}")); + run(s, id, if extend { json!({"extend": true}) } else { json!({}) }); +} + +/// The equation being edited and the caret in it. +fn editing(s: &Session) -> Option<(Pos, wordcraft_doc::math_edit::MathPos)> { + s.math.as_ref().map(|m| (m.at.clone(), m.pos.clone())) +} + +/// Presses `key` until the caret is out of the equation (at most 10 times). +fn arrow_out(s: &mut Session, key: &str) { + for _ in 0..10 { + if s.math.is_none() { + return; + } + arrow(s, key); + } + panic!("{key} didn't leave the equation"); +} + +/// "a", an equation `x+y`, "b"; or with `n` equations side by side. +fn equations_between_a_and_b(n: usize) -> Session { + let mut s = typed("ab"); + for _ in 0..n { + run(&mut s, "caret.set", json!({"pos": Pos::body(0, 1)})); + run(&mut s, "insert.equation", json!({"linear": "x+y", "edit": false})); + } + s +} + +#[test] +fn left_and_right_keys_step_into_and_out_of_an_equation() { + use wordcraft_doc::math_edit::{MathPos, units}; + let e = wordcraft_doc::para::OBJ.len_utf8(); + let end = MathPos::new(Vec::new(), units(&wordcraft_doc::math::parse_linear("x+y"))); + let mut s = equations_between_a_and_b(1); + // Right from "a|" opens the equation at its start; leaving it past its end puts the caret + // after it, so the next Right goes on over "b". + run(&mut s, "caret.set", json!({"pos": Pos::body(0, 1)})); + arrow(&mut s, "Right"); + assert_eq!(editing(&s), Some((Pos::body(0, 1), MathPos::default()))); + arrow_out(&mut s, "Right"); + assert_eq!(s.sel.focus, Pos::body(0, 1 + e)); + arrow(&mut s, "Right"); + assert_eq!((editing(&s), s.sel.focus.clone()), (None, Pos::body(0, 2 + e))); + // Left over "b", then into the equation at its end; out past its start, then on over "a". + arrow(&mut s, "Left"); + assert_eq!((editing(&s), s.sel.focus.clone()), (None, Pos::body(0, 1 + e))); + arrow(&mut s, "Left"); + assert_eq!(editing(&s), Some((Pos::body(0, 1), end))); + arrow_out(&mut s, "Left"); + assert_eq!(s.sel.focus, Pos::body(0, 1)); + arrow(&mut s, "Left"); + assert_eq!((editing(&s), s.sel.focus.clone()), (None, Pos::body(0, 0))); + // Shift+Right selects over the equation as one character, as before. + run(&mut s, "caret.set", json!({"pos": Pos::body(0, 1)})); + arrow(&mut s, "Shift+Right"); + assert_eq!((editing(&s), s.sel.anchor.clone(), s.sel.focus.clone()), (None, Pos::body(0, 1), Pos::body(0, 1 + e))); + // With text selected, Left and Right only collapse the selection, even when its moving end is + // next to the equation. + arrow(&mut s, "Left"); + assert_eq!((editing(&s), s.sel.anchor.clone(), s.sel.focus.clone()), (None, Pos::body(0, 1), Pos::body(0, 1))); + run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)})); + arrow(&mut s, "Shift+Right"); + arrow(&mut s, "Right"); + assert_eq!((editing(&s), s.sel.anchor.clone(), s.sel.focus.clone()), (None, Pos::body(0, 1), Pos::body(0, 1))); +} + +#[test] +fn right_out_of_an_equation_steps_into_the_one_beside_it() { + let e = wordcraft_doc::para::OBJ.len_utf8(); + let mut s = equations_between_a_and_b(2); + run(&mut s, "caret.set", json!({"pos": Pos::body(0, 1)})); + arrow(&mut s, "Right"); + assert_eq!(editing(&s).map(|(at, _)| at), Some(Pos::body(0, 1)), "into the first one"); + arrow_out(&mut s, "Right"); + assert_eq!(s.sel.focus, Pos::body(0, 1 + e), "between the two equations"); + arrow(&mut s, "Right"); + assert_eq!(editing(&s), Some((Pos::body(0, 1 + e), wordcraft_doc::math_edit::MathPos::default())), "into the second one"); + arrow_out(&mut s, "Right"); + arrow(&mut s, "Left"); + assert_eq!(editing(&s).map(|(at, _)| at), Some(Pos::body(0, 1 + e)), "Left goes back into the second one"); + arrow_out(&mut s, "Left"); + arrow(&mut s, "Left"); + assert_eq!(editing(&s).map(|(at, _)| at), Some(Pos::body(0, 1)), "then into the first"); +} + #[test] fn two_initial_capitals_are_corrected() { let s = typed("the WOrd and THe end, not IDs or CDs. TV is fine "); From 57427c7b983653a1a37b2e30ab12fd1f9de0f6c4 Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 30 Oct 2026 03:11:45 +0100 Subject: [PATCH 035/609] Equations: progress docs for Left and Right next to an equation (#4138) --- ROADMAP.md | 6 ++++-- docs/gaps.md | 7 ++++--- docs/typing-parity.md | 2 +- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 2ab3a1a164..f093cf386c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -4,8 +4,8 @@ **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-29 · **Change:** trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously 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-29 · **Change:** trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously 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 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** trivial (progress log: Left and Right step into an equation next to the caret, as in Word (#4138)); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet, #4880; previously 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-30 · **Change:** trivial (progress log: Left and Right step into an equation next to the caret, as in Word (#4138)); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet, #4880; previously 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. WordCraft aims for complete parity with Microsoft Word, then goes further on speed, openness and @@ -140,6 +140,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm ## Progress log +- 2026-10-30: Left and Right step into an equation next to the caret, as in Word: Right from just before it opens it at its start, Left from just after it at its end, and past its far end the caret leaves on that side, so the same arrow goes on (#4138). With text selected the arrows only collapse the selection; Shift still selects over the equation. Right-to-left paragraphs keep the old behaviour for now. - 2026-10-29: Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880). Labels → New Document with one label per recipient includes every selected address, with unused labels blank on the final sheet. Fixed-text and single-label output remain one sheet. Finish & Merge template expansion is separate. - 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. @@ -648,6 +649,7 @@ Footer page-table height and body wrapping are corrected. Other pagination gaps | Date | Change | Summary | |---|---|---| +| 2026-10-30 | trivial | Progress log: Left and Right step into an equation next to the caret (#4138); readiness estimates unchanged | | 2026-10-29 | trivial | Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880). Filtered/sorted order, product geometry and single-label mode retained; readiness estimates unchanged. | | 2026-10-22 | trivial | Progress log: one native window per open document | | 2026-10-22 | trivial | Progress log: every open document keeps its own recovery copy | diff --git a/docs/gaps.md b/docs/gaps.md index 5b082dc6f3..087292b7fe 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,8 +1,8 @@ # Where WordCraft falls short of Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously 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-30 · **Change:** trivial (Left and Right step into an equation next to the caret, as in Word (#4138)); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet, #4880; previously 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 > **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-29 · **Change:** trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously 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 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** trivial (Left and Right step into an equation next to the caret, as in Word (#4138)); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet, #4880; previously 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 Recovery discovery no longer interrupts an explicitly created or opened document. Older copies remain in File › Recover, whose buttons use the interface palette. See [local recovery](recovery.md). @@ -92,7 +92,7 @@ Text context menus now include the existing formatting mini toolbar (#2959), inc | 27 | **View windows**: Side by Side, Synchronous Scrolling, Arrange All; a window per open document (the engine holds several open documents and Switch Windows lists and switches them) | | [parity-checklist.md](parity-checklist.md) (View 26/29); PR #331 open | Comparing documents | 3–5 | [ui-parity.md](ui-parity.md) | | 26 | **Minor formats**: MHT, Works/WordPerfect | | Word XML Document (Flat OPC) opens and saves, Word 2003 XML opens (#548) and saves (#1081, not yet checked in Word) | Rare | 14–26 | [file-format-parity.md](file-format-parity.md) | | 28 | **Dictate** | | `tools.dictate` missing | Dictation users | 8–15 + owner (speech model) | [hardware-parity.md](hardware-parity.md) | -| 29 | **Equations**: ink equations; a copied equation pasting into Word as an editable equation, still to be confirmed (#816, #1297) | | #191 notes; long display equations wrap at operators (#326); a copy holding an equation puts MathML in HTML on the clipboard (#816), and a copy of one equation alone also its MathML in the "MathML" clipboard formats Word reads first (Windows, macOS; #1297; Word/LibreOffice paste not yet verified) | Maths-heavy documents | 2–3 | [layout-parity.md](layout-parity.md) | +| 29 | **Equations**: ink equations; a copied equation pasting into Word as an editable equation, still to be confirmed (#816, #1297) | | #191 notes; long display equations wrap at operators (#326); a copy holding an equation puts MathML in HTML on the clipboard (#816), and a copy of one equation alone also its MathML in the "MathML" clipboard formats Word reads first (Windows, macOS; #1297; Word/LibreOffice paste not yet verified); Left and Right step into an equation next to the caret (#4138), not yet in right-to-left paragraphs | Maths-heavy documents | 2–3 | [layout-parity.md](layout-parity.md) | **Beta needs #1–#7** (~150–230 h with the stability and layout work they imply): they are the blocking gaps, and closing them lifts file formats, layout, stability and UI enough to take the @@ -152,6 +152,7 @@ Recipient label generation (#4880) now includes all selected recipients across a | Date | Change | Summary | |---|---|---| +| 2026-10-30 | trivial | #29: Left and Right step into an equation next to the caret and leave it on the far side (#4138); right-to-left paragraphs stay open in typing-parity's known gaps; readiness estimates unchanged | | 2026-10-29 | trivial | Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880). Filtered/sorted order, product geometry and single-label mode retained; readiness estimates unchanged. | | 2026-10-22 | trivial | View windows: several open documents and Switch Windows in the engine | | 2026-10-25 | trivial | egui 0.37 migration: interface catalogs remain pinned by `craft-i18n.rev` (`9205108…`; 27 languages, English fallback); IME surrounding deletions and composition resets are implemented with regressions, but managed CI passed; native IME acceptance and native-speaker catalog review remain open; no gap or readiness change | diff --git a/docs/typing-parity.md b/docs/typing-parity.md index 152a42bac6..b6db15c7fe 100644 --- a/docs/typing-parity.md +++ b/docs/typing-parity.md @@ -136,7 +136,7 @@ Windows/Linux keys are given first, macOS second. | Alt+numpad code (Windows and Linux; not macOS) | hold Alt, type a decimal code, release Alt: the character appears at the caret as typed text (one undo step). With a leading 0 the code is the ANSI code page — Windows-1252 by default (`0233` → é, `0128` → €); without one, 1–255 is the OEM code page — 437 by default and in US English (`233` → Θ, `1` → ☺, `7` → •), 850 for Western European locales and English outside the US (`155` → ø; `233` is Ú there, per the CP850 mapping file — é is `130` in both). On Windows the system locale picks both pages (`text.typeCode` `ansi`/`oem`): Central European 1250/852 (Polish `0185` and `165` → ą), Cyrillic 1251/866, Greek 1253/737, Turkish 1254/857, and for codes up to 255 the character Windows composes itself replaces ours (it knows every code page, double-byte ones too); Linux keeps 1252 and 437/850. Above 255, with or without the 0, the Unicode character with that decimal value (`8364` → €). Control characters, 0, unassigned bytes and values past Unicode type nothing; auto-repeat of a held digit adds nothing, and switching windows drops a half-typed code. Word counts only keypad digits; egui reports keypad and top-row digits alike, so top-row digits with Alt alone compose codes too. An Alt code never opens KeyTips | `alt_numpad_codes_map_like_word_on_windows`, `alt_numpad_code_types_one_character`, ui-egui `alt_numpad_code_types_its_character_without_keytips` | | AltGr (Right Alt on Polish, German, Czech… layouts) | AltGr+letter types the layout's character (AltGr+S → ś, AltGr+L → ł) and a bare AltGr tap does nothing; neither opens KeyTips. On Linux AltGr is the Right Alt key with Level 3 Shift, not Alt, so its modifiers event no longer reads as Alt let go (#2388); on Windows it is Ctrl+Alt. Right Alt on a layout without AltGr (US) is Alt and opens KeyTips like Left Alt | ui-egui `altgr_types_its_characters_without_keytips` | | Shift+Right (⇧→) at the end of a cell's text | the whole cell is selected first (its end-of-cell mark); the next Shift+Right selects the next cell with it. In an empty cell the first press selects the cell | `shift_right_at_the_end_of_a_cell_selects_the_cell_first` | -| Left / Right (← / →) next to an equation | the arrow steps into the equation instead of over it: Right from just before it opens it at its start, Left from just after it opens it at its end. The arrows then move inside it; past its far end the caret leaves on that side, so the same arrow goes on to the text (or, with two equations side by side, steps into the next one: not yet compared with Word). With text selected, the arrow only collapses the selection, as elsewhere; Shift+Left / Right still selects over the equation as one character. **Differs:** not in right-to-left or mixed-direction paragraphs yet (see Known gaps) (#4138) | `left_and_right_keys_step_into_and_out_of_equations`; `cmd::equation::tests::left_and_right_step_into_an_equation_next_to_the_caret` | +| Left / Right (← / →) next to an equation | the arrow steps into the equation instead of over it: Right from just before it opens it at its start, Left from just after it opens it at its end. The arrows then move inside it; past its far end the caret leaves on that side, so the same arrow goes on to the text (or, with two equations side by side, steps into the next one: not yet compared with Word). With text selected, the arrow only collapses the selection, as elsewhere; Shift+Left / Right still selects over the equation as one character. **Differs:** not in right-to-left or mixed-direction paragraphs yet (see Known gaps) (#4138) | `left_and_right_keys_step_into_and_out_of_an_equation`, `right_out_of_an_equation_steps_into_the_one_beside_it`; `cmd::equation::tests::left_and_right_step_into_an_equation_next_to_the_caret` | ## AutoCorrect and AutoFormat as you type From ce1f7ecb631cd104378e120209357dbb81bd78eb Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 30 Oct 2026 03:14:45 +0100 Subject: [PATCH 036/609] Equations: Left and Right open the equation through edit_at, not a JSON round trip (#4138) --- crates/engine/src/cmd/caret.rs | 6 ++---- crates/engine/src/cmd/equation.rs | 10 +++++++--- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/caret.rs b/crates/engine/src/cmd/caret.rs index 9c1d4393e1..1e66c6b025 100644 --- a/crates/engine/src/cmd/caret.rs +++ b/crates/engine/src/cmd/caret.rs @@ -1,6 +1,6 @@ //! Caret movement and selection. -use serde_json::{Value, json}; +use serde_json::Value; use wordcraft_doc::math_edit::MathPos; use wordcraft_doc::para::OBJ; use wordcraft_doc::{InlineObject, Pos, StoryRef}; @@ -141,9 +141,7 @@ fn into_equation(s: &mut Session, is_left: bool) -> Option { s.sel = Selection::caret(Pos { off, ..f }); s.goal_x = None; s.pending = None; - // `equation.edit` without a position opens at the end. - let at = if is_left { json!({}) } else { json!({"pos": MathPos::default()}) }; - Some(super::equation::edit(s, &at)) + Some(super::equation::edit_at(s, (!is_left).then(MathPos::default))) } /// Left/Right in bidirectional text: one caret position to the left or right on the screen. diff --git a/crates/engine/src/cmd/equation.rs b/crates/engine/src/cmd/equation.rs index bf8c81fad8..d3df73dcdc 100644 --- a/crates/engine/src/cmd/equation.rs +++ b/crates/engine/src/cmd/equation.rs @@ -260,7 +260,12 @@ fn insert_nodes_as_equation(s: &mut Session, nodes: Arg, v: &Value) -> CmdResult /// Starts editing the equation at the caret, materializing lazy nodes and clamping the requested /// position, and returns the equation and caret. -pub(super) fn edit(s: &mut Session, v: &Value) -> CmdResult { +fn edit(s: &mut Session, v: &Value) -> CmdResult { + edit_at(s, v.get("pos").and_then(|p| serde_json::from_value::(p.clone()).ok())) +} + +/// [`edit`] at `pos` in the equation, or at its end without one. +pub(super) fn edit_at(s: &mut Session, pos: Option) -> CmdResult { let at = equation_at_caret(s).ok_or_else(|| CmdError::Disabled("no equation at the caret".into()))?; let nodes = match s.doc.para_at(&at).and_then(|p| p.object_at(at.off)) { Some(InlineObject::Equation { math, linear, .. }) => { @@ -272,8 +277,7 @@ pub(super) fn edit(s: &mut Session, v: &Value) -> CmdResult { } _ => return Err(CmdError::Failed("no equation there".into())), }; - let pos = - v.get("pos").and_then(|p| serde_json::from_value::(p.clone()).ok()).unwrap_or_else(|| MathPos::new(Vec::new(), me::units(&nodes))); + let pos = pos.unwrap_or_else(|| MathPos::new(Vec::new(), me::units(&nodes))); let Some(session) = crate::next_math_session() else { return Err(CmdError::Failed("no equation editing session available".into())); }; From 47039c163f4b65365de442dfd5e6dad18559e250 Mon Sep 17 00:00:00 2001 From: Florent Siegenthaler <64897087+Atalantis@users.noreply.github.com> Date: Fri, 30 Oct 2026 21:18:40 +0100 Subject: [PATCH 037/609] Info.plist: say where the language list comes from, and that AppKit follows the macOS language --- packaging/macos/Info.plist.in | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/packaging/macos/Info.plist.in b/packaging/macos/Info.plist.in index a86176ba7b..14a446c975 100644 --- a/packaging/macos/Info.plist.in +++ b/packaging/macos/Info.plist.in @@ -6,8 +6,11 @@ CFBundleDevelopmentRegion en - + CFBundleLocalizations en From cee47681a3d29cfd0714d466c986d6172019bc39 Mon Sep 17 00:00:00 2001 From: Max Murphy Date: Sun, 18 Oct 2026 13:51:53 +0200 Subject: [PATCH 038/609] M15 #1: add opt-in DOCX corpus harness Adds cargo xtask docx-corpus: every .docx under a local corpus is opened and inspected, rendered to PNG (page 1 or all pages), saved to a temporary copy, reopened and compared by plain text and page count. Each stage runs in a bounded child wordcraft-cli process, failures are classified, and one bad file never stops the run. The JSON report is sorted and timestamp-free, with a Markdown summary and rendered pages beside it. Missing and empty corpora exit successfully. The harness is local-only: /corpus stays git-ignored, only corpus/docx/README.md is tracked, and no Word-produced file or Word-vs-WordCraft visual comparison is added. --- .gitignore | 5 +- Cargo.lock | 1 + ROADMAP.md | 4 +- corpus/docx/README.md | 98 ++++ xtask/Cargo.toml | 1 + xtask/src/docx_corpus.rs | 940 +++++++++++++++++++++++++++++++++++++++ xtask/src/main.rs | 4 + 7 files changed, 1051 insertions(+), 2 deletions(-) create mode 100644 corpus/docx/README.md create mode 100644 xtask/src/docx_corpus.rs diff --git a/.gitignore b/.gitignore index ab3202793a..8644fb7d1f 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,10 @@ plan/ /target /dist -/corpus +/corpus/* +!/corpus/docx/ +/corpus/docx/* +!/corpus/docx/README.md /log .DS_Store /.claude/ diff --git a/Cargo.lock b/Cargo.lock index 7bff2098d4..de67b4b4ab 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7127,6 +7127,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" name = "xtask" version = "0.14.0" dependencies = [ + "serde", "serde_json", ] diff --git a/ROADMAP.md b/ROADMAP.md index ee41c6059a..251f735862 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -47,7 +47,9 @@ discounts and the user evidence (120 issues from outside users, 4 praise, 0 "swi **Why alpha:** the core workflows (write, format, styles, lists, tables, references, review, mail merge, open and save .docx) work end to end and ship as signed builds on every desktop platform -and the web. **Why not beta:** DOCX has never been tested on real-world files; charts, SmartArt and +and the web. **Why not beta:** DOCX has not been tested on a real-world corpus yet (the opt-in +`cargo xtask docx-corpus` harness can now run one locally, but no corpus or Word comparison is +checked in); charts, SmartArt and OLE objects are dropped silently; pagination differs from Word (no Aptos-metric font, no column balancing or footnote continuation); content controls are lost; there is open field evidence of a startup crash and several hangs; no native printing. Gaps #1–#7 in [`docs/gaps.md`](docs/gaps.md) diff --git a/corpus/docx/README.md b/corpus/docx/README.md new file mode 100644 index 0000000000..37b51b035a --- /dev/null +++ b/corpus/docx/README.md @@ -0,0 +1,98 @@ +# DOCX corpus (local only) + +This directory is where a local, real-world DOCX corpus can live for the opt-in +`cargo xtask docx-corpus` harness. **The corpus is never committed.** `/corpus` is +git-ignored; only this README is tracked. Never commit Word-produced files, documents +you do not have the right to redistribute, or any proprietary template, theme, font +or image. Word-produced documents are useful locally, including ones you made +yourself, but they must stay untracked. + +## Populate it + +Put `.docx` files anywhere under this directory (subfolders are walked, symlinks are +skipped): + +```sh +mkdir -p corpus/docx/mine +cp ~/Documents/report.docx corpus/docx/mine/ +``` + +Useful sources for a local corpus: + +- documents you wrote yourself, exported from Word, Google Docs, LibreOffice or Pages; +- public-domain or openly licensed DOCX samples whose licence allows local testing; +- synthetic files generated by WordCraft (`wordcraft-cli run --template sample --save …`); +- deliberately broken files for the failure path (a text file renamed `.docx`, a + truncated ZIP, a package missing `word/document.xml`). + +Keep a note of where each file came from. If a corpus must be shared, share the +manifest and the harness report, not the documents. + +## Run it + +```sh +# Build wordcraft-cli once (the runner also does this automatically if it is absent) +cargo build -p wordcraft-cli + +cargo xtask docx-corpus --dir corpus/docx +cargo xtask docx-corpus --dir corpus/docx --out target/docx-corpus/report.json +cargo xtask docx-corpus --dir corpus/docx --all-pages +cargo xtask docx-corpus --dir corpus/docx --timeout 120 --cli target/debug/wordcraft-cli +``` + +Options: + +| Option | Meaning | +|---|---| +| `--dir ` | corpus directory (required) | +| `--out ` | JSON report path (default `target/docx-corpus/report.json`); the Markdown summary is written beside it with an `.md` extension | +| `--all-pages` | render every page instead of only page 1 (capped at 2,000 pages per file) | +| `--timeout ` | per-child-process timeout, default 60, maximum 3,600 | +| `--cli ` | use a specific `wordcraft-cli` binary | +| `-h`, `--help` | usage | + +A missing or empty corpus directory is not an error: the command explains what is +missing and exits successfully. + +## What each file goes through + +Every `.docx` is handled in child `wordcraft-cli` processes, each with the timeout +above, so one hostile or hanging file cannot stop the run: + +1. **Open + inspect** — `wordcraft-cli info` gives page and word counts; `wordcraft-cli text` + gives the plain text baseline. +2. **Render** — page 1 to PNG (`--all-pages` renders every page). Images go to + `-artifacts/-/page-NNNN.png` beside the report. +3. **Save** — `wordcraft-cli convert` writes a temporary `.docx` copy under the system + temporary directory. +4. **Reopen + compare** — the copy is opened again for page count and plain text. The + temporary copy is then deleted. + +The report records file name, bytes, open time, page count, word count, render time, +round-trip time, rendered images, and every failure. Failures are classified as: + +| Kind | Meaning | +|---|---| +| `open` | the file could not be opened or inspected (invalid package, encrypted, timeout, oversized, …) | +| `render` | page rendering failed | +| `save` | saving the temporary copy failed | +| `reopen` | the saved copy could not be opened or its text read | +| `text_mismatch` | reopened plain text differs from the original | +| `page_count_delta` | reopened page count differs from the original | + +The JSON report is deterministic for the same corpus and arguments apart from the +timing fields: files are sorted by relative path, failure counts are always present, +and there is no timestamp. The Markdown summary is a short human-readable table. + +## Limits + +- This harness measures open/render/save/reopen and text/page stability. It does **not** + compare with Word's own rendering or page count, and it does not fix document bugs. + A Word-vs-WordCraft visual comparison is a separate task. +- PNG rendering is a smoke test that the page can be produced, not a fidelity score. +- Files are treated as hostile: recursion depth, file count, file size, render pages and + child output are capped, and symlinks are skipped. The caps are deliberately generous + for normal documents; a file above them is reported as a failure rather than skipped + silently. +- The corpus and its reports stay local. `target/` is git-ignored too, so reports do not + enter commits. diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 6d935ae8fd..856ed96585 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -9,4 +9,5 @@ publish = false workspace = true [dependencies] +serde = { workspace = true } serde_json = { workspace = true } diff --git a/xtask/src/docx_corpus.rs b/xtask/src/docx_corpus.rs new file mode 100644 index 0000000000..b43fcfaf1b --- /dev/null +++ b/xtask/src/docx_corpus.rs @@ -0,0 +1,940 @@ +//! `cargo xtask docx-corpus --dir [--out ]`: an opt-in, reproducible +//! DOCX corpus runner. +//! +//! Every `.docx` under `--dir` is opened and inspected in a child `wordcraft-cli` process with a +//! bounded timeout, rendered to PNG (page 1, or every page with `--all-pages`), saved to a +//! temporary `.docx`, reopened and compared with its original plain text and page count. A +//! failure in one file is recorded and the run continues. The report is stable JSON plus a short +//! Markdown summary; renders live beside the report. +//! +//! The corpus itself is local only (see `corpus/docx/README.md`): `/corpus` is git-ignored and no +//! Word-produced or proprietary document may be committed. + +use std::ffi::OsString; +use std::fs; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::mpsc::{self, RecvTimeoutError}; +use std::thread; +use std::time::{Duration, Instant}; + +use serde::Serialize; +use serde_json::Value; + +const SCHEMA: &str = "wordcraft.docx-corpus/v1"; +const DEFAULT_TIMEOUT_SECS: u64 = 60; +const MAX_TIMEOUT_SECS: u64 = 3600; +const MAX_FILE_BYTES: u64 = 512 * 1024 * 1024; +const MAX_OUTPUT_BYTES: usize = 64 * 1024 * 1024; +const MAX_FILES: usize = 100_000; +const MAX_DEPTH: usize = 64; +const MAX_ALL_PAGES: u64 = 2_000; +const RENDER_SCALE: &str = "1.5"; +/// How long to wait for a finished child's pipes to close. +const OUTPUT_GRACE: Duration = Duration::from_secs(10); +/// How long to wait for pipes after killing a timed-out child. +const KILL_GRACE: Duration = Duration::from_secs(2); + +const USAGE: &str = "\ +usage: cargo xtask docx-corpus --dir [--out ] [options] + +Run every .docx under DIR through open/inspect, render, save, reopen and text/page compare. +The corpus is local only (never committed); see corpus/docx/README.md. + +options: + --dir corpus directory (required) + --out JSON report path (default: target/docx-corpus/report.json); + the Markdown summary is written beside it with an .md extension + --all-pages render every page, not only page 1 (capped at 2000 pages) + --timeout timeout for each child process (default: 60, max: 3600) + --cli wordcraft-cli binary (default: beside this xtask binary, building it if absent) + -h, --help this help +"; + +pub fn run(args: &[&str]) -> Result<(), String> { + if args.iter().any(|a| *a == "-h" || *a == "--help") { + print!("{USAGE}"); + return Ok(()); + } + let opts = Options::parse(args)?; + let out = opts.out.clone(); + let cli = ProcessCli { program: resolve_cli(opts.cli.as_deref())? }; + let Some(report) = execute(&opts, &cli)? else { + return Ok(()); + }; + write_outputs(&out, &report) +} + +struct Options { + dir: PathBuf, + out: PathBuf, + all_pages: bool, + timeout: Duration, + cli: Option, +} + +impl Options { + fn parse(args: &[&str]) -> Result { + let mut dir = None; + let mut out = None; + let mut all_pages = false; + let mut timeout_secs = DEFAULT_TIMEOUT_SECS; + let mut cli = None; + let mut it = args.iter().copied(); + while let Some(arg) = it.next() { + match arg { + "--dir" => dir = Some(PathBuf::from(it.next().ok_or("--dir requires a path")?)), + "--out" => out = Some(PathBuf::from(it.next().ok_or("--out requires a path")?)), + "--all-pages" => all_pages = true, + "--timeout" => { + let value = it.next().ok_or("--timeout requires seconds")?; + timeout_secs = value.parse::().map_err(|_| format!("--timeout `{value}` is not a whole number of seconds"))?; + if timeout_secs == 0 || timeout_secs > MAX_TIMEOUT_SECS { + return Err(format!("--timeout must be 1..={MAX_TIMEOUT_SECS} seconds")); + } + } + "--cli" => cli = Some(PathBuf::from(it.next().ok_or("--cli requires a path")?)), + other => return Err(format!("unknown option `{other}`\n\n{USAGE}")), + } + } + let dir = dir.ok_or_else(|| format!("--dir is required\n\n{USAGE}"))?; + let out = out.unwrap_or_else(|| crate::root().join("target/docx-corpus/report.json")); + Ok(Self { dir, out, all_pages, timeout: Duration::from_secs(timeout_secs), cli }) + } +} + +/// One child process result. +struct CliOutput { + success: bool, + code: Option, + stdout: Vec, + stderr: Vec, +} + +/// The seam between the runner and `wordcraft-cli`; tests supply an in-process fake. +trait Cli { + fn call(&self, args: &[OsString], timeout: Duration) -> Result; +} + +struct ProcessCli { + program: PathBuf, +} + +impl Cli for ProcessCli { + fn call(&self, args: &[OsString], timeout: Duration) -> Result { + let mut cmd = Command::new(&self.program); + cmd.args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); + let mut child = cmd.spawn().map_err(|e| format!("spawn {}: {e}", self.program.display()))?; + let stdout = child.stdout.take().map(Reader::spawn); + let stderr = child.stderr.take().map(Reader::spawn); + let start = Instant::now(); + let deadline = start.checked_add(timeout).unwrap_or(start); + let mut timed_out = false; + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break Some(status), + Ok(None) => { + if Instant::now() >= deadline { + timed_out = true; + break None; + } + thread::sleep(Duration::from_millis(10)); + } + Err(e) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(format!("wait for {}: {e}", self.program.display())); + } + } + }; + if timed_out || status.is_none() { + let _ = child.kill(); + let _ = child.wait(); + } + if timed_out { + // A killed child normally closes its pipes at once. If a grandchild still holds them, + // abandon the readers rather than letting one hostile file stall the run. + if let Some(reader) = stdout { + let _ = reader.take(KILL_GRACE, "stdout"); + } + if let Some(reader) = stderr { + let _ = reader.take(KILL_GRACE, "stderr"); + } + return Err(format!("timed out after {}s", timeout.as_secs())); + } + let (out, out_too_big) = match stdout { + Some(reader) => reader.take(OUTPUT_GRACE, "stdout")?, + None => (Vec::new(), false), + }; + let (err, err_too_big) = match stderr { + Some(reader) => reader.take(OUTPUT_GRACE, "stderr")?, + None => (Vec::new(), false), + }; + if out_too_big || err_too_big { + return Err(format!("output exceeds the {} MiB cap", MAX_OUTPUT_BYTES / (1024 * 1024))); + } + let (success, code) = match status { + Some(status) => (status.success(), status.code()), + None => (false, None), + }; + Ok(CliOutput { success, code, stdout: out, stderr: err }) + } +} + +type ReaderResult = io::Result<(Vec, bool)>; + +/// A pipe reader thread whose result is collected with a deadline. Dropping the receiver lets a +/// still-blocked thread finish (or exit) without the runner waiting for it. +struct Reader { + rx: mpsc::Receiver, +} + +impl Reader { + fn spawn(reader: R) -> Self { + let (tx, rx) = mpsc::channel(); + let _ = thread::spawn(move || { + let _ = tx.send(read_capped(reader, MAX_OUTPUT_BYTES)); + }); + Self { rx } + } + + fn take(self, grace: Duration, what: &str) -> Result<(Vec, bool), String> { + match self.rx.recv_timeout(grace) { + Ok(Ok(result)) => Ok(result), + Ok(Err(e)) => Err(format!("read child {what}: {e}")), + Err(RecvTimeoutError::Timeout) => Err(format!("child {what} did not close after the process exited")), + Err(RecvTimeoutError::Disconnected) => Err(format!("read child {what}: the reader stopped")), + } + } +} + +/// Read at most `cap` bytes. Past the cap the pipe is closed, so a child producing unbounded +/// output fails fast instead of filling memory; the caller reports the cap as the stage error. +fn read_capped(mut reader: R, cap: usize) -> io::Result<(Vec, bool)> { + let mut out = Vec::with_capacity(cap.min(64 * 1024)); + let mut buf = [0u8; 16 * 1024]; + loop { + let n = reader.read(&mut buf)?; + if n == 0 { + break; + } + let room = cap.saturating_sub(out.len()); + let take = n.min(room); + if let Some(chunk) = buf.get(..take) { + out.extend_from_slice(chunk); + } + if take < n { + return Ok((out, true)); + } + } + Ok((out, false)) +} + +fn resolve_cli(explicit: Option<&Path>) -> Result { + if let Some(path) = explicit { + if path.is_file() { + return Ok(path.to_path_buf()); + } + return Err(format!("--cli {} is not a file", path.display())); + } + let exe = std::env::current_exe().map_err(|e| format!("current exe: {e}"))?; + let dir = exe.parent().ok_or_else(|| format!("{} has no parent directory", exe.display()))?; + let name = if cfg!(windows) { "wordcraft-cli.exe" } else { "wordcraft-cli" }; + let candidate = dir.join(name); + if candidate.is_file() { + return Ok(candidate); + } + eprintln!("docx-corpus: building wordcraft-cli (once) ..."); + let mut cargo = crate::cargo(); + if dir.file_name().is_some_and(|n| n == "release") { + cargo.arg("--release"); + } + cargo.args(["build", "-p", "wordcraft-cli"]); + let status = cargo.status().map_err(|e| format!("build wordcraft-cli: {e}"))?; + if !status.success() { + return Err(format!("build wordcraft-cli failed ({status})")); + } + if candidate.is_file() { Ok(candidate) } else { Err(format!("{} was not built; pass --cli", candidate.display())) } +} + +/// Run one corpus. `None` means the directory is missing, which is not an error. +fn execute(opts: &Options, cli: &dyn Cli) -> Result, String> { + let meta = match fs::metadata(&opts.dir) { + Ok(meta) => meta, + Err(e) if e.kind() == io::ErrorKind::NotFound => { + println!( + "docx-corpus: no corpus directory at {} — populate one as described in corpus/docx/README.md; nothing to do.", + opts.dir.display() + ); + return Ok(None); + } + Err(e) => return Err(format!("{}: {e}", opts.dir.display())), + }; + if !meta.is_dir() { + return Err(format!("{} is not a directory", opts.dir.display())); + } + let files = collect_docx(&opts.dir)?; + if files.is_empty() { + println!("docx-corpus: no .docx files under {}; writing an empty report.", opts.dir.display()); + } + let temp = TempDir::new()?; + let out_parent = output_parent(&opts.out); + let artifacts_root = artifacts_dir(&opts.out); + let mut reports = Vec::with_capacity(files.len()); + for (index, path) in files.iter().enumerate() { + let relative = relative_name(&opts.dir, path); + eprintln!("docx-corpus: [{}/{}] {relative}", index + 1, files.len()); + let paths = ArtifactPaths { root: &artifacts_root, out_parent }; + reports.push(run_file(cli, opts, &temp, paths, index, path, &relative)); + } + Ok(Some(Report::new(opts.dir.display().to_string(), reports))) +} + +fn collect_docx(root: &Path) -> Result, String> { + let mut found = Vec::new(); + let mut stack = vec![(root.to_path_buf(), 0usize)]; + while let Some((dir, depth)) = stack.pop() { + if depth > MAX_DEPTH { + continue; + } + let entries = fs::read_dir(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + for entry in entries { + let entry = entry.map_err(|e| format!("{}: {e}", dir.display()))?; + let file_type = entry.file_type().map_err(|e| format!("{}: {e}", entry.path().display()))?; + if file_type.is_symlink() { + continue; + } + let path = entry.path(); + if file_type.is_dir() { + stack.push((path, depth + 1)); + } else if file_type.is_file() && path.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("docx")) { + found.push(path); + if found.len() > MAX_FILES { + return Err(format!("more than {MAX_FILES} .docx files under {}", root.display())); + } + } + } + } + found.sort(); + Ok(found) +} + +/// A per-run temporary directory, removed on drop (best effort). +struct TempDir { + path: PathBuf, +} + +impl TempDir { + fn new() -> Result { + let base = std::env::temp_dir(); + for n in 0..100u32 { + let path = base.join(format!("wordcraft-docx-corpus-{}-{n}", std::process::id())); + match fs::create_dir(&path) { + Ok(()) => return Ok(Self { path }), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(format!("{}: {e}", path.display())), + } + } + Err(format!("{}: could not create a temporary directory", base.display())) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum FailureKind { + Open, + Render, + Save, + Reopen, + TextMismatch, + PageCountDelta, +} + +impl FailureKind { + fn as_str(self) -> &'static str { + match self { + Self::Open => "open", + Self::Render => "render", + Self::Save => "save", + Self::Reopen => "reopen", + Self::TextMismatch => "text_mismatch", + Self::PageCountDelta => "page_count_delta", + } + } +} + +#[derive(Serialize, Clone)] +struct Failure { + kind: &'static str, + message: String, +} + +#[derive(Serialize)] +struct FileReport { + file: String, + bytes: u64, + status: String, + open_ms: u64, + pages: u64, + words: u64, + render_ms: u64, + round_trip_ms: u64, + round_trip_pages: Option, + page_delta: Option, + text_match: Option, + rendered: Vec, + failures: Vec, + error: Option, +} + +impl FileReport { + fn new(file: String, bytes: u64) -> Self { + Self { + file, + bytes, + status: "ok".into(), + open_ms: 0, + pages: 0, + words: 0, + render_ms: 0, + round_trip_ms: 0, + round_trip_pages: None, + page_delta: None, + text_match: None, + rendered: Vec::new(), + failures: Vec::new(), + error: None, + } + } + + fn fail(&mut self, kind: FailureKind, message: impl Into) { + self.failures.push(Failure { kind: kind.as_str(), message: message.into() }); + } + + fn finish(mut self) -> Self { + self.status = if self.failures.is_empty() { "ok" } else { "failed" }.into(); + self.error = if self.failures.is_empty() { + None + } else { + Some(self.failures.iter().map(|f| format!("{}: {}", f.kind, f.message)).collect::>().join("; ")) + }; + self + } +} + +#[derive(Serialize)] +struct Totals { + files: usize, + ok: usize, + failed: usize, + bytes: u64, + pages: u64, + words: u64, +} + +#[derive(Default, Serialize)] +struct FailureCounts { + open: u64, + render: u64, + save: u64, + reopen: u64, + text_mismatch: u64, + page_count_delta: u64, +} + +impl FailureCounts { + fn add(&mut self, kind: &str) { + match kind { + "open" => self.open = self.open.saturating_add(1), + "render" => self.render = self.render.saturating_add(1), + "save" => self.save = self.save.saturating_add(1), + "reopen" => self.reopen = self.reopen.saturating_add(1), + "text_mismatch" => self.text_mismatch = self.text_mismatch.saturating_add(1), + "page_count_delta" => self.page_count_delta = self.page_count_delta.saturating_add(1), + _ => {} + } + } +} + +#[derive(Serialize)] +struct Report { + schema: &'static str, + corpus: String, + files: Vec, + totals: Totals, + failures: FailureCounts, +} + +impl Report { + fn new(corpus: String, mut files: Vec) -> Self { + files.sort_by(|a, b| a.file.cmp(&b.file)); + let mut failures = FailureCounts::default(); + let mut totals = Totals { files: files.len(), ok: 0, failed: 0, bytes: 0, pages: 0, words: 0 }; + for file in &files { + if file.failures.is_empty() { + totals.ok = totals.ok.saturating_add(1); + } else { + totals.failed = totals.failed.saturating_add(1); + } + totals.bytes = totals.bytes.saturating_add(file.bytes); + totals.pages = totals.pages.saturating_add(file.pages); + totals.words = totals.words.saturating_add(file.words); + for failure in &file.failures { + failures.add(failure.kind); + } + } + Self { schema: SCHEMA, corpus, files, totals, failures } + } +} + +struct ArtifactPaths<'a> { + root: &'a Path, + out_parent: &'a Path, +} + +fn run_file(cli: &dyn Cli, opts: &Options, temp: &TempDir, paths: ArtifactPaths<'_>, index: usize, path: &Path, relative: &str) -> FileReport { + let bytes = fs::metadata(path).map(|m| m.len()).unwrap_or(0); + let mut report = FileReport::new(relative.to_string(), bytes); + if bytes > MAX_FILE_BYTES { + report.fail(FailureKind::Open, format!("file is {bytes} bytes, above the {} MiB cap", MAX_FILE_BYTES / (1024 * 1024))); + return report.finish(); + } + + let open_start = Instant::now(); + let info = match read_info(cli, path, opts.timeout) { + Ok(info) => info, + Err(e) => { + report.open_ms = millis(open_start); + report.fail(FailureKind::Open, e); + return report.finish(); + } + }; + report.pages = info.pages; + report.words = info.words; + let original_text = match read_text(cli, path, opts.timeout) { + Ok(text) => text, + Err(e) => { + report.open_ms = millis(open_start); + report.fail(FailureKind::Open, format!("plain text: {e}")); + return report.finish(); + } + }; + report.open_ms = millis(open_start); + + let render_start = Instant::now(); + let page_count = if opts.all_pages { info.pages.max(1) } else { 1 }; + if opts.all_pages && page_count > MAX_ALL_PAGES { + report.fail(FailureKind::Render, format!("{page_count} pages exceeds the {MAX_ALL_PAGES}-page render cap")); + } else { + let slug = format!("{index:04}-{}", slug(relative)); + let dir = paths.root.join(&slug); + if let Err(e) = fs::create_dir_all(&dir) { + report.fail(FailureKind::Render, format!("{}: {e}", dir.display())); + } else { + for page in 1..=page_count { + let target = dir.join(format!("page-{page:04}.png")); + let args = vec![ + OsString::from("render"), + path.as_os_str().to_os_string(), + target.as_os_str().to_os_string(), + OsString::from("--page"), + OsString::from(page.to_string()), + OsString::from("--scale"), + OsString::from(RENDER_SCALE), + ]; + if let Err(e) = run_ok(cli, &args, opts.timeout) { + report.fail(FailureKind::Render, format!("page {page}: {e}")); + break; + } + report.rendered.push(relative_name(paths.out_parent, &target)); + } + } + } + report.render_ms = millis(render_start); + + let round_trip_start = Instant::now(); + let copy = temp.path.join(format!("{index:04}-{}.docx", slug(relative))); + let save_args = vec![OsString::from("convert"), path.as_os_str().to_os_string(), copy.as_os_str().to_os_string()]; + let saved = match run_ok(cli, &save_args, opts.timeout) { + Ok(_) => true, + Err(e) => { + report.fail(FailureKind::Save, scrub_temp(&e, &temp.path)); + false + } + }; + if saved { + match read_info(cli, ©, opts.timeout) { + Ok(info) => { + report.round_trip_pages = Some(info.pages); + let delta = i64::try_from(info.pages).unwrap_or(i64::MAX).saturating_sub(i64::try_from(report.pages).unwrap_or(i64::MAX)); + report.page_delta = Some(delta); + if info.pages != report.pages { + report.fail(FailureKind::PageCountDelta, format!("page count {} → {} ({delta:+})", report.pages, info.pages)); + } + match read_text(cli, ©, opts.timeout) { + Ok(text) => { + let matches = text == original_text; + report.text_match = Some(matches); + if !matches { + report.fail(FailureKind::TextMismatch, text_mismatch_message(&original_text, &text)); + } + } + Err(e) => report.fail(FailureKind::Reopen, scrub_temp(&format!("plain text: {e}"), &temp.path)), + } + } + Err(e) => report.fail(FailureKind::Reopen, scrub_temp(&e, &temp.path)), + } + } + report.round_trip_ms = millis(round_trip_start); + let _ = fs::remove_file(©); + report.finish() +} + +struct Info { + pages: u64, + words: u64, +} + +fn read_info(cli: &dyn Cli, path: &Path, timeout: Duration) -> Result { + let args = vec![OsString::from("info"), path.as_os_str().to_os_string()]; + let output = run_ok(cli, &args, timeout)?; + let value: Value = serde_json::from_slice(&output.stdout).map_err(|e| format!("file.info returned invalid JSON: {e}"))?; + let pages = value.get("pages").and_then(Value::as_u64).ok_or("file.info has no integer pages")?; + let words = value.get("words").and_then(Value::as_u64).ok_or("file.info has no integer words")?; + Ok(Info { pages, words }) +} + +fn read_text(cli: &dyn Cli, path: &Path, timeout: Duration) -> Result, String> { + let args = vec![OsString::from("text"), path.as_os_str().to_os_string()]; + Ok(run_ok(cli, &args, timeout)?.stdout) +} + +fn run_ok(cli: &dyn Cli, args: &[OsString], timeout: Duration) -> Result { + let output = cli.call(args, timeout)?; + if output.success { + Ok(output) + } else { + let code = match output.code { + Some(code) => format!("code {code}"), + None => "no exit code".to_string(), + }; + let stderr = stderr_excerpt(&output.stderr); + if stderr.is_empty() { Err(format!("wordcraft-cli exited with {code}")) } else { Err(format!("wordcraft-cli exited with {code}: {stderr}")) } + } +} + +fn stderr_excerpt(bytes: &[u8]) -> String { + let text = String::from_utf8_lossy(bytes); + let text = text.trim().replace('\n', " "); + if text.chars().count() > 400 { + let mut short: String = text.chars().take(400).collect(); + short.push('…'); + short + } else { + text + } +} + +/// Keep the report reproducible: the temporary copy's random name is not part of the result. +fn scrub_temp(message: &str, temp: &Path) -> String { + let path = temp.to_string_lossy(); + if path.is_empty() { message.to_string() } else { message.replace(path.as_ref(), "") } +} + +fn text_mismatch_message(original: &[u8], reopened: &[u8]) -> String { + let at = original.iter().zip(reopened.iter()).position(|(a, b)| a != b); + match at { + Some(at) => format!("text differs at byte {at} (original {} bytes, reopened {} bytes)", original.len(), reopened.len()), + None => format!("text differs in length (original {} bytes, reopened {} bytes)", original.len(), reopened.len()), + } +} + +fn millis(start: Instant) -> u64 { + u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX) +} + +fn relative_name(root: &Path, path: &Path) -> String { + let relative = path.strip_prefix(root).unwrap_or(path); + relative.to_string_lossy().replace('\\', "/") +} + +fn slug(relative: &str) -> String { + relative.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).take(80).collect() +} + +fn output_parent(out: &Path) -> &Path { + out.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| Path::new("")) +} + +fn artifacts_dir(out: &Path) -> PathBuf { + let stem = out.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "report".into()); + output_parent(out).join(format!("{stem}-artifacts")) +} + +fn write_outputs(out: &Path, report: &Report) -> Result<(), String> { + if let Some(parent) = out.parent().filter(|p| !p.as_os_str().is_empty()) { + fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?; + } + let json = serde_json::to_string_pretty(report).map_err(|e| format!("report JSON: {e}"))?; + fs::write(out, format!("{json}\n")).map_err(|e| format!("{}: {e}", out.display()))?; + let summary = out.with_extension("md"); + fs::write(&summary, summary_markdown(report)).map_err(|e| format!("{}: {e}", summary.display()))?; + println!("docx-corpus: wrote {} and {}", out.display(), summary.display()); + Ok(()) +} + +fn summary_markdown(report: &Report) -> String { + let mut out = String::new(); + out.push_str("# DOCX corpus report\n\n"); + out.push_str(&format!("- Corpus: `{}`\n", report.corpus.replace('`', "'"))); + out.push_str(&format!("- Files: {} ({} ok, {} failed)\n", report.totals.files, report.totals.ok, report.totals.failed)); + out.push_str(&format!("- Pages: {} · Words: {} · Bytes: {}\n", report.totals.pages, report.totals.words, report.totals.bytes)); + out.push_str(&format!( + "- Failures: open {} · render {} · save {} · reopen {} · text mismatch {} · page-count delta {}\n\n", + report.failures.open, + report.failures.render, + report.failures.save, + report.failures.reopen, + report.failures.text_mismatch, + report.failures.page_count_delta + )); + if report.files.is_empty() { + out.push_str("No `.docx` files were found.\n"); + return out; + } + out.push_str("| File | Status | Pages | Words | Open ms | Render ms | Round-trip ms | Error |\n"); + out.push_str("|---|---|---:|---:|---:|---:|---:|---|\n"); + for file in &report.files { + let error = file.error.as_deref().map(escape_table).unwrap_or_default(); + out.push_str(&format!( + "| `{}` | {} | {} | {} | {} | {} | {} | {} |\n", + escape_table(&file.file), + file.status, + file.pages, + file.words, + file.open_ms, + file.render_ms, + file.round_trip_ms, + error + )); + } + out +} + +fn escape_table(text: &str) -> String { + let mut out: String = text + .chars() + .map(|c| { + if c == '|' { + '/' + } else if c == '\n' || c == '\r' { + ' ' + } else { + c + } + }) + .take(240) + .collect(); + if text.chars().count() > 240 { + out.push('…'); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + use std::cell::RefCell; + + struct FakeCli { + calls: RefCell>>, + copy_pages: u64, + copy_text: &'static str, + } + + impl FakeCli { + fn new() -> Self { + Self { calls: RefCell::new(Vec::new()), copy_pages: 1, copy_text: "Hello\n" } + } + } + + impl Cli for FakeCli { + fn call(&self, args: &[OsString], _timeout: Duration) -> Result { + let args: Vec = args.iter().map(|a| a.to_string_lossy().into_owned()).collect(); + self.calls.borrow_mut().push(args.clone()); + let command = args.first().map(String::as_str).unwrap_or(""); + let path = args.get(1).cloned().unwrap_or_default(); + if path.ends_with("bad.docx") { + return Err("invalid zip: not a DOCX package".into()); + } + // The runner's temporary copy is named `NNNN-.docx`. + let copy = Path::new(&path).file_name().and_then(|name| name.to_str()).is_some_and(|name| { + name.as_bytes().get(4) == Some(&b'-') && name.as_bytes().get(..4).is_some_and(|n| n.iter().all(u8::is_ascii_digit)) + }); + match command { + "info" => { + let pages = if copy { self.copy_pages } else { 1 }; + Ok(ok(json!({"pages": pages, "words": 2}).to_string())) + } + "text" => Ok(ok(if copy { self.copy_text.to_string() } else { "Hello\n".to_string() })), + "render" => { + if let Some(out) = args.get(2) { + if let Some(parent) = Path::new(out).parent() { + let _ = fs::create_dir_all(parent); + } + let _ = fs::write(out, b"png"); + } + Ok(ok(String::new())) + } + "convert" => { + if let Some(out) = args.get(2) { + let _ = fs::write(out, b"docx"); + } + Ok(ok(String::new())) + } + other => Err(format!("unexpected command {other}")), + } + } + } + + fn ok(stdout: String) -> CliOutput { + CliOutput { success: true, code: Some(0), stdout: stdout.into_bytes(), stderr: Vec::new() } + } + + fn temp_case(name: &str) -> PathBuf { + let path = std::env::temp_dir().join(format!("wordcraft-docx-corpus-test-{}-{name}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).unwrap(); + path + } + + fn opts(dir: PathBuf, out: PathBuf) -> Options { + Options { dir, out, all_pages: false, timeout: Duration::from_secs(5), cli: None } + } + + #[test] + fn report_schema_and_order_are_stable() { + let a = FileReport::new("b/second.docx".into(), 20).finish(); + let b = FileReport::new("a/first.docx".into(), 10).finish(); + let report = Report::new("corpus/docx".into(), vec![a, b]); + assert_eq!(report.schema, "wordcraft.docx-corpus/v1"); + assert_eq!(report.files.first().map(|f| f.file.as_str()), Some("a/first.docx")); + assert_eq!(report.files.get(1).map(|f| f.file.as_str()), Some("b/second.docx")); + assert_eq!(report.totals.files, 2); + assert_eq!(report.totals.bytes, 30); + let value = serde_json::to_value(&report).unwrap(); + assert_eq!(value["schema"], "wordcraft.docx-corpus/v1"); + for key in [ + "file", + "bytes", + "status", + "open_ms", + "pages", + "words", + "render_ms", + "round_trip_ms", + "round_trip_pages", + "page_delta", + "text_match", + "rendered", + "failures", + "error", + ] { + assert!(value["files"][0].get(key).is_some(), "missing report field {key}"); + } + let once = serde_json::to_string(&report).unwrap(); + let twice = serde_json::to_string(&report).unwrap(); + assert_eq!(once, twice); + } + + #[test] + fn aggregation_counts_statuses_and_failure_kinds() { + let mut bad = FileReport::new("bad.docx".into(), 7); + bad.pages = 2; + bad.words = 3; + bad.fail(FailureKind::Open, "broken"); + bad.fail(FailureKind::TextMismatch, "different"); + let bad = bad.finish(); + let mut good = FileReport::new("good.docx".into(), 5); + good.pages = 1; + good.words = 4; + let good = good.finish(); + let report = Report::new("corpus".into(), vec![good, bad]); + assert_eq!(report.totals.files, 2); + assert_eq!(report.totals.ok, 1); + assert_eq!(report.totals.failed, 1); + assert_eq!(report.totals.bytes, 12); + assert_eq!(report.totals.pages, 3); + assert_eq!(report.totals.words, 7); + assert_eq!(report.failures.open, 1); + assert_eq!(report.failures.text_mismatch, 1); + assert_eq!(report.failures.render, 0); + assert_eq!(report.failures.reopen, 0); + assert_eq!(report.failures.save, 0); + assert_eq!(report.failures.page_count_delta, 0); + } + + #[test] + fn missing_directory_is_not_an_error() { + let dir = std::env::temp_dir().join(format!("wordcraft-docx-corpus-missing-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + let cli = FakeCli::new(); + let out = dir.join("report.json"); + let report = execute(&opts(dir, out), &cli).unwrap(); + assert!(report.is_none()); + assert!(cli.calls.borrow().is_empty()); + } + + #[test] + fn corrupt_file_is_classified_and_the_run_continues() { + let dir = temp_case("corrupt"); + fs::write(dir.join("bad.docx"), b"not a zip").unwrap(); + fs::write(dir.join("good.docx"), b"PK\x03\x04synthetic").unwrap(); + let out = dir.join("report.json"); + let cli = FakeCli::new(); + let report = execute(&opts(dir.clone(), out), &cli).unwrap().unwrap(); + assert_eq!(report.files.len(), 2); + let bad = &report.files[0]; + assert_eq!(bad.file, "bad.docx"); + assert_eq!(bad.status, "failed"); + assert_eq!(bad.failures.first().map(|f| f.kind), Some("open")); + assert!(bad.error.as_deref().is_some_and(|e| e.contains("invalid zip"))); + let good = &report.files[1]; + assert_eq!(good.file, "good.docx"); + assert_eq!(good.status, "ok"); + assert_eq!(good.pages, 1); + assert_eq!(good.words, 2); + assert_eq!(good.text_match, Some(true)); + assert_eq!(report.totals.ok, 1); + assert_eq!(report.totals.failed, 1); + assert_eq!(report.failures.open, 1); + let calls = cli.calls.borrow(); + assert!(calls.iter().any(|c| c.get(1).is_some_and(|p| p.ends_with("good.docx"))), "the run continued after the corrupt file"); + drop(calls); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn text_mismatch_and_page_delta_are_classified() { + let dir = temp_case("mismatch"); + fs::write(dir.join("good.docx"), b"PK\x03\x04synthetic").unwrap(); + let out = dir.join("report.json"); + let cli = FakeCli { calls: RefCell::new(Vec::new()), copy_pages: 2, copy_text: "Bye\n" }; + let report = execute(&opts(dir.clone(), out), &cli).unwrap().unwrap(); + let file = &report.files[0]; + assert_eq!(file.status, "failed"); + assert_eq!(file.text_match, Some(false)); + assert_eq!(file.page_delta, Some(1)); + assert_eq!(file.round_trip_pages, Some(2)); + assert_eq!(report.failures.text_mismatch, 1); + assert_eq!(report.failures.page_count_delta, 1); + let _ = fs::remove_dir_all(&dir); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 647e07260d..d2967bf090 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -4,6 +4,7 @@ //! invoked through `std::process::Command`. mod assets; +mod docx_corpus; mod ico; mod layers; mod parity; @@ -29,6 +30,8 @@ commands: (stops at first failure) corpus [--download] show where test corpora live; --download fetches PngSuite into corpus/pngsuite + docx-corpus --dir [--out ] + open, render and round-trip every .docx under a local corpus; writes JSON + Markdown stats [--exact] count tests and lines per crate (--exact: ask the test harness via `-- --list`) parity recompute the Word feature-parity summary in docs/parity-checklist.md visual-diff [--private] [--dpi N] @@ -49,6 +52,7 @@ fn main() -> ExitCode { Some("i18n-report") => cmd_i18n_report(), Some("ci") => cmd_ci(), Some("corpus") => cmd_corpus(rest.contains(&"--download")), + Some("docx-corpus") => docx_corpus::run(&rest), Some("stats") => stats::run(&root(), rest.contains(&"--exact")), Some("parity") => parity::run(&root()), Some("ico") => ico::run(&rest), From 77060f63ab15c9f71a672a9c896fb6c5621cba83 Mon Sep 17 00:00:00 2001 From: Max Murphy Date: Mon, 19 Oct 2026 23:09:55 +0200 Subject: [PATCH 039/609] M15 #1: put --release after the cargo build subcommand Signed-off-by: Max Murphy --- xtask/src/docx_corpus.rs | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/xtask/src/docx_corpus.rs b/xtask/src/docx_corpus.rs index b43fcfaf1b..5a407f6b47 100644 --- a/xtask/src/docx_corpus.rs +++ b/xtask/src/docx_corpus.rs @@ -231,6 +231,17 @@ fn read_capped(mut reader: R, cap: usize) -> io::Result<(Vec, bool) Ok((out, false)) } +/// Cargo arguments that build `wordcraft-cli`. `--release` is a `build` option, not a cargo +/// global one, so it must follow the subcommand: `cargo build --release`, never +/// `cargo --release build`. +fn cli_build_args(release: bool) -> Vec<&'static str> { + let mut args = vec!["build", "-p", "wordcraft-cli"]; + if release { + args.push("--release"); + } + args +} + fn resolve_cli(explicit: Option<&Path>) -> Result { if let Some(path) = explicit { if path.is_file() { @@ -246,12 +257,8 @@ fn resolve_cli(explicit: Option<&Path>) -> Result { return Ok(candidate); } eprintln!("docx-corpus: building wordcraft-cli (once) ..."); - let mut cargo = crate::cargo(); - if dir.file_name().is_some_and(|n| n == "release") { - cargo.arg("--release"); - } - cargo.args(["build", "-p", "wordcraft-cli"]); - let status = cargo.status().map_err(|e| format!("build wordcraft-cli: {e}"))?; + let release = dir.file_name().is_some_and(|n| n == "release"); + let status = crate::cargo().args(cli_build_args(release)).status().map_err(|e| format!("build wordcraft-cli: {e}"))?; if !status.success() { return Err(format!("build wordcraft-cli failed ({status})")); } @@ -881,6 +888,17 @@ mod tests { assert_eq!(report.failures.page_count_delta, 0); } + #[test] + fn cli_build_args_put_the_subcommand_before_flags() { + // Regression: `--release` used to be appended first, producing the invalid + // `cargo --release build -p wordcraft-cli` and failing a release xtask run. + assert_eq!(cli_build_args(false), ["build", "-p", "wordcraft-cli"]); + assert_eq!(cli_build_args(true), ["build", "-p", "wordcraft-cli", "--release"]); + for release in [false, true] { + assert_eq!(cli_build_args(release).first().copied(), Some("build")); + } + } + #[test] fn missing_directory_is_not_an_error() { let dir = std::env::temp_dir().join(format!("wordcraft-docx-corpus-missing-{}", std::process::id())); From c2e4a05df1dd08d694737ca84cb7d828c1118354 Mon Sep 17 00:00:00 2001 From: Max Murphy Date: Tue, 20 Oct 2026 00:17:40 +0200 Subject: [PATCH 040/609] M15 #1: rebuild wordcraft-cli before every DOCX corpus run Signed-off-by: Max Murphy --- corpus/docx/README.md | 4 +-- xtask/src/docx_corpus.rs | 75 +++++++++++++++++++++++++++++++++++----- 2 files changed, 68 insertions(+), 11 deletions(-) diff --git a/corpus/docx/README.md b/corpus/docx/README.md index 37b51b035a..71456ae45e 100644 --- a/corpus/docx/README.md +++ b/corpus/docx/README.md @@ -31,9 +31,7 @@ manifest and the harness report, not the documents. ## Run it ```sh -# Build wordcraft-cli once (the runner also does this automatically if it is absent) -cargo build -p wordcraft-cli - +# The runner builds wordcraft-cli before every run (a no-op when it is current). cargo xtask docx-corpus --dir corpus/docx cargo xtask docx-corpus --dir corpus/docx --out target/docx-corpus/report.json cargo xtask docx-corpus --dir corpus/docx --all-pages diff --git a/xtask/src/docx_corpus.rs b/xtask/src/docx_corpus.rs index 5a407f6b47..349a2b1443 100644 --- a/xtask/src/docx_corpus.rs +++ b/xtask/src/docx_corpus.rs @@ -48,7 +48,7 @@ options: the Markdown summary is written beside it with an .md extension --all-pages render every page, not only page 1 (capped at 2000 pages) --timeout timeout for each child process (default: 60, max: 3600) - --cli wordcraft-cli binary (default: beside this xtask binary, building it if absent) + --cli wordcraft-cli binary (default: build it and use the one beside this xtask binary) -h, --help this help "; @@ -251,18 +251,32 @@ fn resolve_cli(explicit: Option<&Path>) -> Result { } let exe = std::env::current_exe().map_err(|e| format!("current exe: {e}"))?; let dir = exe.parent().ok_or_else(|| format!("{} has no parent directory", exe.display()))?; - let name = if cfg!(windows) { "wordcraft-cli.exe" } else { "wordcraft-cli" }; - let candidate = dir.join(name); - if candidate.is_file() { - return Ok(candidate); - } - eprintln!("docx-corpus: building wordcraft-cli (once) ..."); + resolve_cli_beside(dir, build_cli) +} + +/// Build `wordcraft-cli` beside the running xtask binary and return its path. +/// +/// The build runs on every invocation: cargo is a no-op when the binary is current, and +/// returning an existing candidate would let a stale binary produce a stale report. +fn resolve_cli_beside(dir: &Path, build: impl FnOnce(&Path) -> Result<(), String>) -> Result { + eprintln!("docx-corpus: building wordcraft-cli ..."); + build(dir)?; + let candidate = dir.join(cli_name()); + if candidate.is_file() { Ok(candidate) } else { Err(format!("{} was not built; pass --cli", candidate.display())) } +} + +fn cli_name() -> &'static str { + if cfg!(windows) { "wordcraft-cli.exe" } else { "wordcraft-cli" } +} + +/// Build `wordcraft-cli` in the xtask binary's directory (cargo is a no-op when it is current). +fn build_cli(dir: &Path) -> Result<(), String> { let release = dir.file_name().is_some_and(|n| n == "release"); let status = crate::cargo().args(cli_build_args(release)).status().map_err(|e| format!("build wordcraft-cli: {e}"))?; if !status.success() { return Err(format!("build wordcraft-cli failed ({status})")); } - if candidate.is_file() { Ok(candidate) } else { Err(format!("{} was not built; pass --cli", candidate.display())) } + Ok(()) } /// Run one corpus. `None` means the directory is missing, which is not an error. @@ -899,6 +913,51 @@ mod tests { } } + #[test] + fn resolve_cli_builds_every_run_even_when_the_binary_exists() { + // Regression: an existing binary used to be returned without rebuilding, so a report + // could describe stale code. + let dir = temp_case("resolve-cli-rebuild"); + let candidate = dir.join(cli_name()); + fs::write(&candidate, b"stale").unwrap(); + let builds = RefCell::new(Vec::new()); + let resolved = resolve_cli_beside(&dir, |dir| { + builds.borrow_mut().push(dir.to_path_buf()); + Ok(()) + }) + .unwrap(); + assert_eq!(resolved, candidate); + assert_eq!(builds.borrow().as_slice(), std::slice::from_ref(&dir)); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn resolve_cli_uses_an_explicit_binary_without_building() { + let dir = temp_case("resolve-cli-explicit"); + let binary = dir.join("my-cli"); + fs::write(&binary, b"cli").unwrap(); + assert_eq!(resolve_cli(Some(&binary)).unwrap(), binary); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn resolve_cli_rejects_a_missing_explicit_binary() { + let dir = temp_case("resolve-cli-missing"); + let err = resolve_cli(Some(&dir.join("absent"))).unwrap_err(); + assert!(err.contains("is not a file"), "{err}"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn resolve_cli_reports_build_problems() { + let dir = temp_case("resolve-cli-build-errors"); + let err = resolve_cli_beside(&dir, |_| Err("build wordcraft-cli failed (exit status: 1)".into())).unwrap_err(); + assert!(err.contains("build wordcraft-cli failed"), "{err}"); + let err = resolve_cli_beside(&dir, |_| Ok(())).unwrap_err(); + assert!(err.contains("pass --cli"), "{err}"); + let _ = fs::remove_dir_all(&dir); + } + #[test] fn missing_directory_is_not_an_error() { let dir = std::env::temp_dir().join(format!("wordcraft-docx-corpus-missing-{}", std::process::id())); From dc515b61285cf649ddbe76226fdb7990d93033cd Mon Sep 17 00:00:00 2001 From: Mauro Mazzieri Date: Tue, 3 Nov 2026 10:36:33 +0100 Subject: [PATCH 041/609] Different first page: no first-page header on a continuous section's second page A page is its section's first page, the one a different first page's header and footer go on, only if the section begins on it. A page's section is the one at its top, so a section that starts continuously part-way down a page was taken to begin on the next page, which then showed the section's first-page header. Word shows the earlier section's header on the page where the section starts and the section's default header from the next page on: the first-page header of such a section is never seen (checked in Word for Windows 365 on a synthetic file). begins_section compares the section's first block with the page's first block, and serves the drawn headers and footers, header-table obstacles and footer-table wraps alike. Co-Authored-By: Claude Opus 5.5 --- crates/layout/src/headers.rs | 27 +++++++++++++------- crates/layout/src/table_flow.rs | 6 ++--- crates/layout/src/tests.rs | 44 +++++++++++++++++++++++++++++++++ docs/layout-parity.md | 3 ++- 4 files changed, 67 insertions(+), 13 deletions(-) diff --git a/crates/layout/src/headers.rs b/crates/layout/src/headers.rs index e6c22dc061..8d906892cd 100644 --- a/crates/layout/src/headers.rs +++ b/crates/layout/src/headers.rs @@ -36,6 +36,19 @@ pub(crate) fn section_side(start: SectionStart, restart: Option, last: u32, } } +/// Whether `page` (after `prev`) is its section's first page, the one a different first page's +/// header and footer go on: the page where the section begins. A page's section is the one at its +/// top, so a section that starts continuously part-way down `prev` has no first page of its own: +/// Word shows the earlier section's header there and the section's default one from the next page +/// on. `sections` as [`Document::sections`] gives them (each with its last block). +pub(crate) fn begins_section(sections: &[(usize, &SectionProps)], prev: Option<&Page>, page: &Page) -> bool { + if prev.is_some_and(|p| p.section == page.section) { + return false; + } + let start = page.section.checked_sub(1).and_then(|k| sections.get(k)).map_or(0, |(end, _)| end.saturating_add(1)); + start >= page.first_block +} + /// The document's sections with their headers and footers (Word's "link to previous"), each /// section's resolved once for the whole layout in document order rather than by looking back /// over the sections before it whenever one is needed. @@ -121,12 +134,12 @@ pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec { return Vec::new(); } let Some(page) = pb.pages.last() else { return Vec::new() }; - let first = pb.pages.iter().rev().nth(1).is_none_or(|prev| prev.section != page.section); + let hf = Arc::clone(&ctx.hf); + let first = begins_section(&hf.sections, pb.pages.iter().rev().nth(1), page); let key = (page.section, page.number, first); if let Some(areas) = ctx.header_tables.get(&key) { return areas.clone(); } - let hf = Arc::clone(&ctx.hf); let Some((_, sect)) = hf.sections.get(page.section) else { return Vec::new() }; if sect.text_direction.is_turned() { return Vec::new(); @@ -250,13 +263,9 @@ pub(crate) fn headers_footers(ctx: &mut Ctx, pages: &mut [Page], sections: &[(us let hf = Arc::clone(&ctx.hf); let even_odd = ctx.doc.settings.even_odd_headers; let styles = styleref::headers_use_styleref(ctx.doc).then(|| ctx.cache.style_index(ctx.doc)); - let mut first_of_section: HashSet = HashSet::new(); - let mut seen = HashSet::new(); - for (i, p) in pages.iter().enumerate() { - if seen.insert(p.section) { - first_of_section.insert(i); - } - } + let first_of_section: HashSet = (0..pages.len()) + .filter(|&i| pages.get(i).is_some_and(|p| begins_section(sections, i.checked_sub(1).and_then(|k| pages.get(k)), p))) + .collect(); for (i, page) in pages.iter_mut().enumerate() { let Some((_, sect)) = sections.get(page.section) else { continue }; // Inherit header/footer references from earlier sections (Word's "link to previous"). diff --git a/crates/layout/src/table_flow.rs b/crates/layout/src/table_flow.rs index f866cd8bf8..d605f3d446 100644 --- a/crates/layout/src/table_flow.rs +++ b/crates/layout/src/table_flow.rs @@ -2,7 +2,7 @@ use super::boxes::{BoxInput, clear_of_float_tables, layout_box}; use super::ctx::{Ctx, with_pct_base}; use super::floats::{WrapArea, align_in, body_wraps}; use super::flow::again; -use super::headers::{MAX_HEADER_ITEMS, header_table_areas}; +use super::headers::{MAX_HEADER_ITEMS, begins_section, header_table_areas}; use super::notes::table_notes; use super::page::{PageBuilder, PageFrame, page_frame}; use super::placed::Placed; @@ -14,14 +14,14 @@ pub(crate) fn footer_table_wraps(ctx: &mut Ctx, pb: &PageBuilder) -> Vec>().join("\n"); + let mut d = Document::from_text(&text); + let part = |d: &mut Document, t: &str| { + d.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(Paragraph::with_text(t, Default::default()))]) + }; + let (one, first, two) = (part(&mut d, "ONE"), part(&mut d, "FIRST"), part(&mut d, "TWO")); + let mut s1 = d.last_section.clone(); + s1.headers.default = Some(one); + d.para_mut(StoryRef::Body, &Path::top(19)).unwrap().section = Some(Box::new(s1)); + d.last_section.start = start; + d.last_section.title_page = true; + d.last_section.headers.first = Some(first); + d.last_section.headers.default = Some(two); + let l = lay(&d); + let begins = l.caret(&Pos::body(20, 0)).unwrap().page; + let shown: Vec<_> = l.pages.iter().map(|p| p.header_story).collect(); + assert!(l.pages.len() > begins + 2, "{start:?}: the second section runs over several pages"); + match start { + SectionStart::Continuous => { + assert!(l.caret(&Pos::body(19, 0)).unwrap().page == begins, "the second section starts part-way down a page"); + assert_eq!(shown[begins], Some(one), "{start:?}: the page where it starts keeps the first section's header"); + assert!( + shown[begins + 1..].iter().all(|h| *h == Some(two)), + "{start:?}: then its default header, never its first-page one: {shown:?}" + ); + assert!(l.pages[begins + 1..].iter().all(|p| p.hf_slot == crate::HfSlot::Default), "{start:?}"); + } + _ => { + assert_eq!(shown[begins], Some(first), "{start:?}: a section on a new page shows its first-page header there"); + assert_eq!(l.pages[begins].hf_slot, crate::HfSlot::First); + assert!(shown[begins + 1..].iter().all(|h| *h == Some(two)), "{start:?}: {shown:?}"); + } + } + } +} + /// Sections starting continuously one after another still go onto new pages: a paragraph that /// doesn't fit below the text above it moves on rather than running off the page (#3907). A /// hundred one-line sections lay out like a hundred plain paragraphs. diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 0681502353..63169ad8a2 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -1,6 +1,6 @@ # Layout and pagination parity with Microsoft Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a table row that would leave a cell empty on a page that already holds something, its picture or first line not fitting there, moves on whole instead of leaving the other cells' text beside the empty cell, #4272); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (tab leader dots spaced and placed as in Word); previously trivial (a level above that hasn't counted yet takes its first number at the first deeper item); previously trivial (paragraph side borders lie beyond their distance from the text, #5036); previously trivial (with a header taller than the top margin, Margin-anchored drawings, header-cell pins and header-table obstacles use the rendered body top; TopMargin and InsideMargin keep their declared band, #2485; previously trivial: connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (field results take the `\* DollarText`, `\* Hex` and `\* ArabicDash` switches, #4226; previously trivial: a cell spanning columns shares its extra minimum width by the columns' preferred widths, equally in automatic tables, #1883; previously 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 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** trivial (a section with a different first page that starts continuously part-way down a page shows its first-page header nowhere: the page it starts on keeps the earlier section's header and the next shows its default one, as in Word for Windows); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a table row that would leave a cell empty on a page that already holds something, its picture or first line not fitting there, moves on whole instead of leaving the other cells' text beside the empty cell, #4272); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (tab leader dots spaced and placed as in Word); previously trivial (a level above that hasn't counted yet takes its first number at the first deeper item); previously trivial (paragraph side borders lie beyond their distance from the text, #5036); previously trivial (with a header taller than the top margin, Margin-anchored drawings, header-cell pins and header-table obstacles use the rendered body top; TopMargin and InsideMargin keep their declared band, #2485; previously trivial: connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (field results take the `\* DollarText`, `\* Hex` and `\* ArabicDash` switches, #4226; previously trivial: a cell spanning columns shares its extra minimum width by the columns' preferred widths, equally in automatic tables, #1883; previously 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 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, @@ -278,6 +278,7 @@ layout suite are pending; this is not a new Word/native-IME acceptance claim. | Date | Change | Summary | |---|---|---| +| 2026-11-03 | trivial | Different first page: a page is its section's first only if the section begins on it; a continuous section starting part-way down a page no longer shows its first-page header (and footer) on its second page, compared with Word for Windows 365 on a synthetic file. `layout::tests::continuous_section_first_page_header_is_not_shown_on_its_second_page` | | 2026-11-01 | trivial | Columns: the line between them runs from the section's top on the page to the bottom of its tallest column; a continuous section mid-page gets its line (#5178) | | 2026-10-31 | trivial | A table row that would leave a cell empty on a page that already holds something (its inline picture or first line runs past the room) moves on whole instead of leaving the other cells' text beside the empty cell; an at-least row grown by its picture no longer splits off the picture (#4272) | | 2026-11-01 | trivial | A cell aligned to the middle or bottom of a row split across pages is aligned within the part left on the page when its text fits there, and starts at the top of the cell otherwise, as measured in Word | From c7bb6f6da22050b52c9c1eff7d3ff0727e42df99 Mon Sep 17 00:00:00 2001 From: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:15:46 +0300 Subject: [PATCH 042/609] Layout: a picture line in multiple spacing takes the text's leading and fits at the page foot like Word Under multiple spacing above single, Word puts the text's extra leading, (m - 1) x its natural height, below an inline picture taller than the text instead of the descent, and lets a page's last line run that leading into the bottom margin as it does for text: only the picture has to fit. Measured in Word for Windows (compatibility mode 15) on a 64-page document with 1.5-spaced 12pt text (natural 12.59pt, descent 2.63pt): a 472pt picture stayed on its page with 1.7pt to spare above the bottom margin, and the lines after 438pt and 616pt pictures started 6.3pt below them. WordCraft needed the picture plus the descent to fit, moved the picture to the next page and ended with 65 pages; it now lays the document out on 64, the pictures on Word's pages. The descent stays the floor, so single and slightly-above-single spacing (1.08, 1.15) keep their line heights. --- crates/layout/src/flow.rs | 4 +-- crates/layout/src/para/lines.rs | 30 ++++++++++++++++++-- crates/layout/src/para/model.rs | 3 ++ crates/layout/src/tests.rs | 50 +++++++++++++++++++++++++++++++-- docs/layout-parity.md | 1 + 5 files changed, 81 insertions(+), 7 deletions(-) diff --git a/crates/layout/src/flow.rs b/crates/layout/src/flow.rs index f8b093b5ba..e616121cdc 100644 --- a/crates/layout/src/flow.rs +++ b/crates/layout/src/flow.rs @@ -632,8 +632,8 @@ fn notes_limit(pb: &PageBuilder, new_notes: &[NoteBox], line_notes: &[NoteBox]) fn fit_height(pb: &PageBuilder, l: ¶::Line, rp: &wordcraft_doc::resolve::ResolvedPara, free: bool) -> f32 { let at_margin = pb.bottom >= pb.sect.page_h - pb.sect.margin_bottom - 0.01; match rp.line_spacing { - // `baseline` is from the paragraph's top; the text ends a descent below it. - wordcraft_doc::props::LineSpacing::Multiple(m) if m > 1.0 && at_margin && free => (l.baseline - l.top + l.text_desc).clamp(0.0, l.height), + // The text (or a taller picture) ends `leading` above the line's bottom. + wordcraft_doc::props::LineSpacing::Multiple(m) if m > 1.0 && at_margin && free => (l.height - l.leading).clamp(0.0, l.height), _ => l.height, } } diff --git a/crates/layout/src/para/lines.rs b/crates/layout/src/para/lines.rs index fac5c940a4..9e0110b8e2 100644 --- a/crates/layout/src/para/lines.rs +++ b/crates/layout/src/para/lines.rs @@ -352,6 +352,7 @@ impl<'e> Breaker<'e> { baseline: v.baseline, text_asc: v.text_asc, text_desc: v.text_desc, + leading: v.leading, c0: sc.c0, c1, xs: sc.xs, @@ -475,12 +476,23 @@ impl<'e> Breaker<'e> { // no rule tried so far (none, only the text's descent) matched both; it needs Word probes. let natural = asc + desc; let pictures = if obj_asc > asc { obj_asc + desc } else { 0.0 }; + // Word puts the multiple's leading of the text, (m - 1) x its natural height, below a taller + // picture instead of the descent: a 472pt picture in 1.5-spaced 12pt text (natural 12.59pt, + // descent 2.63pt) takes 478.3pt in Word for Windows, its next line 6.3pt below it. Never + // less than the picture and the descent (single spacing). (height, leading) + let multiple_pictures = match rp.line_spacing { + LineSpacing::Multiple(m) if text_pictures > 0.0 && m > 1.0 => { + let leading = (m - 1.0) * text_natural; + Some((obj_asc + desc.max(leading), leading)) + } + _ => None, + }; // Document grid: the line takes whole line pitches, its text centred in them. let grid = self.grid.as_ref(); let (height, centred) = match (rp.line_spacing, grid) { (LineSpacing::Multiple(m), Some(g)) => ((g.snap_height(natural) * m).max(g.snap_height(pictures)), true), (LineSpacing::AtLeast(v), Some(g)) => (g.snap_height(natural.max(pictures)).max(v), true), - (LineSpacing::Multiple(m), None) => ((text_natural * m + label_extra).max(text_pictures), false), + (LineSpacing::Multiple(m), None) => ((text_natural * m + label_extra).max(multiple_pictures.map_or(text_pictures, |p| p.0)), false), (LineSpacing::AtLeast(v), None) => (natural.max(text_pictures).max(v), false), (LineSpacing::Exactly(v), _) => (v, false), }; @@ -490,7 +502,15 @@ impl<'e> Breaker<'e> { } else { self.top + baseline_offset(rp.line_spacing, asc, height, desc).max(obj_asc.min(height - desc)) }; - Measure { height, baseline, text_asc, text_desc } + // Below a picture that sets the line's height the leading is the multiple's, as below text: + // Word keeps such a line on the page when the picture fits above the bottom margin (with + // 1.7pt to spare, under the descent, in the same document). + let leading = if let Some((h, lead)) = multiple_pictures.filter(|p| !centred && height <= p.0) { + lead.min(self.top + h - baseline).max(0.0) + } else { + (self.top + height - baseline - text_desc).max(0.0) + }; + Measure { height, baseline, text_asc, text_desc, leading } } /// Alignment / justification of the line (trailing spaces hang). @@ -567,12 +587,14 @@ impl<'e> Breaker<'e> { }; let (width, x0) = (self.width, rp.indent_left); let (x0, left, right) = if self.rtl_para { (width - x0, width - self.base_right, width - x0) } else { (x0, x0, self.base_right) }; + let below = if grid.is_some() { h - desc } else { baseline_offset(rp.line_spacing, asc, h, desc) }; self.lines.push(Line { top: self.top, height: h, - baseline: self.top + if grid.is_some() { h - desc } else { baseline_offset(rp.line_spacing, asc, h, desc) }, + baseline: self.top + below, text_asc: asc, text_desc: desc, + leading: (h - below - desc).max(0.0), c0: self.n, c1: self.n, xs: vec![x0], @@ -642,6 +664,8 @@ struct Measure { baseline: f32, text_asc: f32, text_desc: f32, + /// Room at the bottom of the line below its text or picture (see `Line::leading`). + leading: f32, } /// Where the line's content ends: trailing spaces and markers hang. diff --git a/crates/layout/src/para/model.rs b/crates/layout/src/para/model.rs index 294350df11..5ec3f03aed 100644 --- a/crates/layout/src/para/model.rs +++ b/crates/layout/src/para/model.rs @@ -158,6 +158,9 @@ pub struct Line { /// The text's own ascent and descent on this line, without line-spacing leading (the caret's extent). pub text_asc: f32, pub text_desc: f32, + /// Room at the bottom of the line below its text or picture: multiple spacing's extra + /// leading, which Word lets a page's last line run into the bottom margin. + pub leading: f32, /// Cluster index range. pub c0: usize, pub c1: usize, diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 6879f5c378..e7c355b037 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -4967,6 +4967,50 @@ fn line_spacing_does_not_scale_pictures() { assert!((line.baseline - line.top - 144.0).abs() < 0.01, "the picture stands on the baseline"); } +#[test] +fn a_picture_in_one_and_a_half_spacing_takes_the_texts_leading_and_fits_at_the_page_bottom() { + // Word for Windows (a 472pt picture in 1.5-spaced 12pt text): the line is the picture plus + // half the text's natural height, and at the foot of a page the picture only has to fit above + // the bottom margin: it stayed with 1.7pt to spare, less than the descent. + use wordcraft_doc::props::LineSpacing; + let pic = 400.0; + let doc = |spare: f32| { + let mut d = Document::from_text("Text"); + let s = d.last_section.clone(); + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + p.props.line_spacing = Some(LineSpacing::Exactly(20.0)); + p.props.space_before = Some(0.0); + p.props.space_after = Some(s.page_h - s.margin_bottom - s.margin_top - 20.0 - pic - spare); + let mut q = wordcraft_doc::Paragraph::with_text("", Default::default()); + q.props.line_spacing = Some(LineSpacing::Multiple(1.5)); + q.props.space_before = Some(0.0); + q.insert_object(0, picture(100.0, pic, Default::default()), &Default::default()).unwrap(); + d.body.push(wordcraft_doc::para_block(q)); + d + }; + let l = lay(&doc(1.0)); + let lines = |l: &DocLayout, page: usize| { + l.pages[page] + .items + .iter() + .filter_map(|i| if let Placed::Lines { para, l0, .. } = i { Some((para.clone(), *l0)) } else { None }) + .collect::>() + }; + let on_first = lines(&l, 0); + let Some((para, l0)) = on_first.iter().find(|(p, _)| !p.lines.is_empty() && p.lines[0].text_asc >= pic) else { + panic!("the picture should stay on page 1 ({} pages)", l.pages.len()) + }; + let line = ¶.lines[*l0]; + let st = ¶.styles[para.clusters[0].style as usize]; + assert!(st.descent > 1.0, "the spare room is under the descent"); + let want = pic + 0.5 * (st.ascent + st.descent); + assert!((line.height - want).abs() < 0.01, "line {} for a {pic}pt picture, want {want}", line.height); + assert!((line.baseline - line.top - pic).abs() < 0.01, "the picture stands at the line top"); + // A picture that ends past the margin still goes to the next page. + let l = lay(&doc(-0.5)); + assert!(!lines(&l, 0).iter().any(|(p, _)| p.lines.first().is_some_and(|x| x.text_asc >= pic)), "the picture should move on"); +} + #[test] fn multiple_line_spacing_adds_its_leading_below_the_text() { use wordcraft_doc::props::LineSpacing; @@ -5015,8 +5059,10 @@ fn list_label_does_not_inflate_an_inline_picture_floor() { let l = lay(&d); let Some(Placed::Lines { para, .. }) = l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { .. })) else { panic!() }; let line = ¶.lines[0]; - let desc = para.styles[para.clusters[0].style as usize].descent; - assert!((line.height - (144.0 + desc)).abs() < 0.01, "{spacing:?}: {}", line.height); + let st = ¶.styles[para.clusters[0].style as usize]; + // Under the picture: the descent, or the text's own multiple leading when larger. + let below = if let LineSpacing::Multiple(m) = spacing { st.descent.max((m - 1.0) * (st.ascent + st.descent)) } else { st.descent }; + assert!((line.height - (144.0 + below)).abs() < 0.01, "{spacing:?}: {}", line.height); assert!((line.baseline - line.top - 144.0).abs() < 0.01); } } diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 0681502353..d90ff55612 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -290,6 +290,7 @@ layout suite are pending; this is not a new Word/native-IME acceptance claim. | 2026-10-27 | trivial | Connector rerouting indexes laid-out object positions once per batch, preserving page hints, first-match order and same-page glue; synthetic equivalence, geometry and scaling regressions (#3631); routing policy and readiness estimates unchanged | | 2026-10-29 | trivial | A cell spanning columns shares its extra minimum width by the columns' preferred widths (equally in automatic tables); nested tables are measured with the same weights (#1883) | | 2026-10-25 | trivial | Field results take the `\* DollarText`, `\* Hex` and `\* ArabicDash` switches in table formulas and in the page-number, SEQ, PAGEREF and count fields (#4226); readiness estimates unchanged | +| 2026-10-26 | trivial | A line set by an inline picture in multiple spacing above single takes the text's leading, (m - 1) x its natural height, below the picture instead of the descent (when larger), and at the foot of a page only the picture has to fit above the bottom margin, as for text. Word for Windows put a 472pt picture in 1.5-spaced 12pt text on the page with 1.7pt to spare and spaced the next line 6.3pt below it; the 64-page document now has 64 pages, not 65 (`layout::tests::a_picture_in_one_and_a_half_spacing_takes_the_texts_leading_and_fits_at_the_page_bottom`) | | 2026-10-25 | trivial | Header-cell pins and header-table obstacles share the rendered body-top override (#2485); model positioning and overlap controls, no new native comparison. | | 2026-10-19 | trivial | Header body-boundary adjustment applies only to the Margin anchor. TopMargin and InsideMargin keep their declared extent; synthetic alignment countercontrols are prepared, not yet executed. | | 2026-10-25 | 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`) | From ace8f18c5a8bd2379232183c2d7b42bbd35445cf Mon Sep 17 00:00:00 2001 From: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:12:26 +0300 Subject: [PATCH 043/609] Layout: a picture line in multiple spacing takes the leading of its text, or of the paragraph mark alone Measured in Word for Mac 16.93 (a 2cm picture, 1.15/2/3 spacing, Times New Roman and Arial text, 8-20pt runs and marks): under a picture taller than the text Word puts the text's descent plus (m - 1) x its natural height, and on a line of only pictures (m - 1) x the paragraph mark's natural height, with no descent floor and never from the picture's own run. The engine matches Word within 0.6pt in all 36 cases and keeps every page break. --- crates/layout/src/para/lines.rs | 38 ++++++++++++++++++------ crates/layout/src/tests.rs | 51 +++++++++++++++++++++++++++++++-- 2 files changed, 77 insertions(+), 12 deletions(-) diff --git a/crates/layout/src/para/lines.rs b/crates/layout/src/para/lines.rs index 9e0110b8e2..b13d7096be 100644 --- a/crates/layout/src/para/lines.rs +++ b/crates/layout/src/para/lines.rs @@ -405,7 +405,7 @@ impl<'e> Breaker<'e> { /// tallest picture on it (which sits on the baseline). fn extents(&self, pl: &ParaLayout, (c0, c1): (usize, usize)) -> Extents { let rp = &self.rp; - let mut ex = Extents { asc: 0.0, desc: 0.0, obj_asc: 0.0 }; + let mut ex = Extents { asc: 0.0, desc: 0.0, obj_asc: 0.0, tasc: 0.0, tdesc: 0.0 }; let mut any = false; let dropped = pl.drop_cap.map_or(0, |d| d.0); for (k, c) in pl.clusters.get(c0..c1).into_iter().flatten().enumerate() { @@ -432,6 +432,8 @@ impl<'e> Breaker<'e> { } else { // `obj_h` is set on text clusters only under ruby text, which the line grows to fit. let (a, d) = st.line_extent(); + ex.tasc = ex.tasc.max(a); + ex.tdesc = ex.tdesc.max(d); (a.max(c.obj_h + st.shift), d) }; ex.asc = ex.asc.max(a); @@ -450,7 +452,7 @@ impl<'e> Breaker<'e> { /// The line's height, baseline and text extent. fn measure(&self, pl: &ParaLayout, range: (usize, usize)) -> Measure { let rp = &self.rp; - let Extents { mut asc, mut desc, obj_asc } = self.extents(pl, range); + let Extents { mut asc, mut desc, obj_asc, tasc, tdesc } = self.extents(pl, range); let text_natural = asc + desc; let (text_asc, text_desc) = (asc.max(obj_asc), desc); let text_pictures = if obj_asc > asc { obj_asc + desc } else { 0.0 }; @@ -476,14 +478,26 @@ impl<'e> Breaker<'e> { // no rule tried so far (none, only the text's descent) matched both; it needs Word probes. let natural = asc + desc; let pictures = if obj_asc > asc { obj_asc + desc } else { 0.0 }; - // Word puts the multiple's leading of the text, (m - 1) x its natural height, below a taller - // picture instead of the descent: a 472pt picture in 1.5-spaced 12pt text (natural 12.59pt, - // descent 2.63pt) takes 478.3pt in Word for Windows, its next line 6.3pt below it. Never - // less than the picture and the descent (single spacing). (height, leading) + // Below a picture taller than the text Word puts the multiple's leading, (m - 1) x the + // natural height, of the line's text after its descent, or of the paragraph mark's font + // alone on a line of only pictures, never of a picture's own run. Word for Mac 16.93, + // a 2cm picture: next to 14pt Times New Roman text at double spacing 3.0 + 16.1pt below it, + // under a default 11pt Cambria mark 12.9pt, in a 20pt Arial run under an 8pt Times New + // Roman mark 9.2pt; at 1.15 spacing 0.15 x 12.9pt, less than the descent. Word for + // Windows: a 472pt picture in 1.5-spaced 12pt text takes 478.3pt. (height, leading) let multiple_pictures = match rp.line_spacing { LineSpacing::Multiple(m) if text_pictures > 0.0 && m > 1.0 => { - let leading = (m - 1.0) * text_natural; - Some((obj_asc + desc.max(leading), leading)) + let (below, leading) = if tasc + tdesc > 0.0 { + let leading = (m - 1.0) * (tasc + tdesc); + (tdesc + leading, leading) + } else { + let natural = pl.styles.get(self.mark_style as usize).map_or(text_natural, |st| { + let (a, d) = st.line_extent(); + a + d + }); + ((m - 1.0) * natural, (m - 1.0) * natural) + }; + Some((obj_asc + below, leading)) } _ => None, }; @@ -500,7 +514,10 @@ impl<'e> Breaker<'e> { let up = asc.max(obj_asc); self.top + ((height - up - desc) / 2.0).max(0.0) + up } else { - self.top + baseline_offset(rp.line_spacing, asc, height, desc).max(obj_asc.min(height - desc)) + // A picture that sets the line's height under multiple spacing stands at its top: the + // room below it may be less than the descent. + let floor = if multiple_pictures.is_some_and(|p| height <= p.0) { obj_asc } else { obj_asc.min(height - desc) }; + self.top + baseline_offset(rp.line_spacing, asc, height, desc).max(floor) }; // Below a picture that sets the line's height the leading is the multiple's, as below text: // Word keeps such a line on the page when the picture fits above the bottom margin (with @@ -656,6 +673,9 @@ struct Extents { asc: f32, desc: f32, obj_asc: f32, + /// The line's text alone, without its pictures' runs: the multiple's leading below a picture. + tasc: f32, + tdesc: f32, } /// A line's height and baseline, and the extent of its text. diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index e7c355b037..2a9cbe17f0 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -4961,12 +4961,57 @@ fn line_spacing_does_not_scale_pictures() { let l = lay(&d); let Some(Placed::Lines { para, .. }) = l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { .. })) else { panic!() }; let line = ¶.lines[0]; - let desc = para.styles[0].descent; - // Word: the picture plus the font's descent, not (picture + descent) x 1.15. - assert!((line.height - (144.0 + desc)).abs() < 0.01, "line {} for a 144pt picture (descent {desc})", line.height); + let st = ¶.styles[0]; + // Word: the picture plus 0.15 of the paragraph mark's natural height, not (picture + descent) + // x 1.15, and not the descent either (Word for Mac 16.93: 1.9pt under a 2cm picture, 11pt Cambria). + let want = 144.0 + 0.15 * (st.ascent + st.descent); + assert!((line.height - want).abs() < 0.01, "line {} for a 144pt picture, want {want}", line.height); assert!((line.baseline - line.top - 144.0).abs() < 0.01, "the picture stands on the baseline"); } +#[test] +fn a_picture_line_in_multiple_spacing_takes_the_leading_of_its_text_or_the_paragraph_mark() { + // Word for Mac 16.93, a 2cm picture at double spacing: alone on its line it gets the + // paragraph mark's natural height below it, whatever its own run's size (20pt run, 8pt mark: + // 9.2pt); next to text, the text's descent and natural height (20pt Arial: 4.2 + 23pt). + use wordcraft_doc::CharProps; + use wordcraft_doc::props::LineSpacing; + let pic = 56.7; + let size = |pt: f32| CharProps { size: Some(pt), ..Default::default() }; + let para = |m: f32, mark: f32, picture_run: Option, text: Option| { + let mut p = wordcraft_doc::Paragraph::with_text(if text.is_some() { "x" } else { "" }, size(text.unwrap_or(mark))); + p.mark = size(mark); + p.props.line_spacing = Some(LineSpacing::Multiple(m)); + p.props.space_before = Some(0.0); + p.props.space_after = Some(0.0); + if let Some(run) = picture_run { + p.insert_object(0, picture(40.0, pic, Default::default()), &size(run)).unwrap(); + } + wordcraft_doc::para_block(p) + }; + let mut d = Document::from_text(""); + d.body = vec![ + para(1.0, 8.0, None, Some(8.0)), + para(1.0, 8.0, None, Some(20.0)), + para(2.0, 8.0, Some(20.0), None), + para(2.0, 8.0, Some(14.0), Some(20.0)), + ] + .into(); + let l = lay(&d); + let lines: Vec = l.pages[0] + .items + .iter() + .filter_map(|i| if let Placed::Lines { para, l0, .. } = i { Some(para.lines[*l0].clone()) } else { None }) + .collect(); + let (small, big) = (&lines[0], &lines[1]); + let alone = lines[2].height; + assert!((alone - (pic + small.height)).abs() < 0.01, "alone: {alone}, want {pic} + the 8pt mark's {}", small.height); + let beside = lines[3].height; + let want = pic + big.text_desc + big.height; + assert!((beside - want).abs() < 0.01, "next to 20pt text: {beside}, want {want}"); + assert!((lines[3].baseline - lines[3].top - pic).abs() < 0.01, "the picture stands at the line top"); +} + #[test] fn a_picture_in_one_and_a_half_spacing_takes_the_texts_leading_and_fits_at_the_page_bottom() { // Word for Windows (a 472pt picture in 1.5-spaced 12pt text): the line is the picture plus From 5cac512cfad9d7e5ef5ef8e4a068244f2af675b7 Mon Sep 17 00:00:00 2001 From: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:58:17 +0300 Subject: [PATCH 044/609] Layout: rustfmt the picture line test --- crates/layout/src/tests.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 2a9cbe17f0..45e0d2b958 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -4998,11 +4998,8 @@ fn a_picture_line_in_multiple_spacing_takes_the_leading_of_its_text_or_the_parag ] .into(); let l = lay(&d); - let lines: Vec = l.pages[0] - .items - .iter() - .filter_map(|i| if let Placed::Lines { para, l0, .. } = i { Some(para.lines[*l0].clone()) } else { None }) - .collect(); + let lines: Vec = + l.pages[0].items.iter().filter_map(|i| if let Placed::Lines { para, l0, .. } = i { Some(para.lines[*l0].clone()) } else { None }).collect(); let (small, big) = (&lines[0], &lines[1]); let alone = lines[2].height; assert!((alone - (pic + small.height)).abs() < 0.01, "alone: {alone}, want {pic} + the 8pt mark's {}", small.height); From 431251e139fdd27b545de225b9f284fde16ace57 Mon Sep 17 00:00:00 2001 From: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:55:09 +0300 Subject: [PATCH 045/609] Layout: drop a needless conversion in the picture line test (clippy) --- crates/layout/src/tests.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 45e0d2b958..6f049749cd 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -4995,8 +4995,7 @@ fn a_picture_line_in_multiple_spacing_takes_the_leading_of_its_text_or_the_parag para(1.0, 8.0, None, Some(20.0)), para(2.0, 8.0, Some(20.0), None), para(2.0, 8.0, Some(14.0), Some(20.0)), - ] - .into(); + ]; let l = lay(&d); let lines: Vec = l.pages[0].items.iter().filter_map(|i| if let Placed::Lines { para, l0, .. } = i { Some(para.lines[*l0].clone()) } else { None }).collect(); From 3b73a84082cd006a54899b3e19fc9c0d984b1368 Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Tue, 3 Nov 2026 17:51:02 -0200 Subject: [PATCH 046/609] AutoSave: the switch shows a document opened from bytes as blocked The title bar lifted NotSavedHere whatever read_from said, while set_autosave refused unless the document was read from its path, so the switch of a document opened from bytes looked available and a click did nothing. Both now use autosave_switch_block: the switch shows the block and offers Save As. file.autosave also puts a refusal on the status line, as other commands do, instead of returning early without it. --- crates/ui-egui/src/app/commands.rs | 6 +++- crates/ui-egui/src/app/files.rs | 10 ++++-- crates/ui-egui/src/chrome.rs | 4 +-- crates/ui-egui/src/chrome/tests.rs | 49 +++++++++++++++++++++++++----- crates/ui-egui/src/tests.rs | 6 +++- 5 files changed, 61 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 3dec46c8d0..e526b859ef 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -123,7 +123,11 @@ impl WordApp { return self.close_document(¶ms); } if id == "file.autosave" { - return self.set_autosave(¶ms); + let r = self.set_autosave(¶ms); + if let Err(e) = &r { + self.status(e.clone()); + } + return r; } if let Some(r) = table_pen::toggle(self, id, ¶ms) { return r; diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 3667bf64e2..997d63156e 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -385,6 +385,12 @@ impl WordApp { self.autosave && self.autosave_block().is_none() } + /// What the AutoSave switch can't lift: [`Self::autosave_block`], less a file read from disk + /// here, which the switch turns on (#3307). A document opened from bytes stays blocked. + pub fn autosave_switch_block(&self) -> Option { + self.autosave_block().filter(|b| *b != AutoSaveBlock::NotSavedHere || self.read_from != self.session.path) + } + /// `file.autosave` (the AutoSave switch, and scripts): `value` turns AutoSave on or off; /// without it, it toggles what the switch shows. Turning it on for a document AutoSave can't /// cover is an error that says why, instead of a switch that is on but saves nothing (#196). @@ -396,8 +402,8 @@ impl WordApp { Some(Value::Bool(on)) => *on, Some(_) => return Err("`value` must be true or false".into()), }; - if on && let Some(block) = self.autosave_block() { - if block != AutoSaveBlock::NotSavedHere || self.read_from != self.session.path { + if on && self.autosave_block().is_some() { + if let Some(block) = self.autosave_switch_block() { return Err(block.reason()); } self.autosave_path = self.session.path.clone(); diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 2b3208bed7..fad0c172e7 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -305,8 +305,8 @@ pub fn title_bar(app: &mut WordApp, ui: &mut Ui) { ui.spacing_mut().item_spacing = vec2(2.0, 0.0); // AutoSave switch: greyed out, with the reason as its tooltip, when AutoSave can't // cover the document (#196, #176); clicking it then offers Save As where that helps. - // A file only opened here is off, not blocked: the switch turns it on (#3307). - let block = app.autosave_block().filter(|b| *b != crate::AutoSaveBlock::NotSavedHere); + // A file read from disk here is off, not blocked: the switch turns it on (#3307). + let block = app.autosave_switch_block(); let on = app.autosaves(); let color = if block.is_some() { t.text_dim.gamma_multiply(0.6) } else { t.text_dim }; // The text is part of the switch (#3370): clicking it toggles AutoSave, and chrome diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 3973a242b3..332e64cd52 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -265,10 +265,21 @@ fn undo_list_row_returns_focus_to_the_document() { assert!(a.session.undo_history().is_empty(), "the step was undone"); } -/// A saved .docx (so AutoSave can cover it), or with `reopened` the same file opened in a -/// fresh window, with the title bar drawn over it. -fn autosave_harness(reopened: bool) -> (egui_kittest::Harness<'static, WordApp>, std::path::PathBuf) { - let dir = std::env::temp_dir().join(format!("wordcraft-ui-autosave-label-{}-{reopened}", std::process::id())); +/// How [`autosave_harness`] has the saved file in its window. +#[derive(Debug, PartialEq)] +enum Reopen { + /// The window that saved it. + No, + /// Opened in a fresh window, read from disk. + FromDisk, + /// Opened in a fresh window from its bytes, which only names the file. + FromBytes, +} + +/// A saved .docx (so AutoSave can cover it), or the same file opened in a fresh window as +/// `reopen` says, with the title bar drawn over it. +fn autosave_harness(reopen: Reopen) -> (egui_kittest::Harness<'static, WordApp>, std::path::PathBuf) { + let dir = std::env::temp_dir().join(format!("wordcraft-ui-autosave-label-{}-{reopen:?}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("draft.docx"); @@ -276,9 +287,14 @@ fn autosave_harness(reopened: bool) -> (egui_kittest::Harness<'static, WordApp>, a.run("text.insert", json!({"text": "Hello"})).unwrap(); a.run("file.save", json!({"path": path.to_string_lossy()})).unwrap(); assert!(a.autosaves(), "a saved .docx is covered by AutoSave"); - if reopened { + if reopen != Reopen::No { a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default()); - a.run("file.open", json!({"path": path.to_string_lossy()})).unwrap(); + if reopen == Reopen::FromBytes { + let data = wordcraft_engine::cmd::insert::base64_encode(&std::fs::read(&path).unwrap()); + a.execute("file.open", json!({"path": path.to_string_lossy(), "data": data})).unwrap(); + } else { + a.run("file.open", json!({"path": path.to_string_lossy()})).unwrap(); + } assert!(!a.autosaves(), "an opened file waits for the user's go-ahead"); } let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state( @@ -303,7 +319,7 @@ fn autosave_harness(reopened: bool) -> (egui_kittest::Harness<'static, WordApp>, #[test] fn clicking_the_autosave_label_toggles_autosave() { use egui_kittest::kittest::Queryable; - let (mut h, dir) = autosave_harness(false); + let (mut h, dir) = autosave_harness(Reopen::No); assert!(h.state().autosaves()); h.get_by_label("AutoSave").click(); h.run_steps(2); @@ -319,10 +335,27 @@ fn clicking_the_autosave_label_toggles_autosave() { #[test] fn clicking_autosave_on_an_opened_file_turns_it_on() { use egui_kittest::kittest::Queryable; - let (mut h, dir) = autosave_harness(true); + let (mut h, dir) = autosave_harness(Reopen::FromDisk); h.get_by_label("AutoSave").click(); h.run_steps(2); assert!(h.state().autosaves(), "the switch turned AutoSave on"); assert!(h.state().dialog.is_none() && h.state().file_dialog.is_none(), "without Save As"); let _ = std::fs::remove_dir_all(dir); } + +/// A document opened from bytes only names its file, so the switch can't hand that file to +/// AutoSave: it shows the block and clicking it asks for Save As, after which AutoSave is on. +#[test] +fn clicking_autosave_on_a_document_opened_from_bytes_asks_for_save_as() { + use egui_kittest::kittest::Queryable; + let (mut h, dir) = autosave_harness(Reopen::FromBytes); + assert_eq!(h.state().autosave_switch_block(), Some(crate::AutoSaveBlock::NotSavedHere)); + let copy = dir.join("copy.docx"); + let picked = copy.to_string_lossy().to_string(); + h.state_mut().services.pick_save = Some(Box::new(move |_| Some(picked.clone()))); + h.get_by_label("AutoSave").click(); + h.run_steps(2); + assert!(copy.is_file(), "Save As saved a copy"); + assert!(h.state().autosaves(), "AutoSave covers the copy"); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index b0390dbdd3..3089275f57 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -4768,6 +4768,7 @@ fn turning_autosave_on_covers_a_file_only_opened_here() { let mut b = app(); b.run("file.open", json!({"path": path.to_string_lossy()})).unwrap(); assert_eq!(b.autosave_block(), Some(AutoSaveBlock::NotSavedHere)); + assert_eq!(b.autosave_switch_block(), None, "the switch lifts it itself"); b.run("text.insert", json!({"text": "Opened "})).unwrap(); b.autosave_tick(now_ms() + 10_000.0); assert!(b.session.dirty, "opening alone never rewrites the file"); @@ -4795,8 +4796,11 @@ fn the_autosave_switch_refuses_a_document_opened_from_bytes() { let data = wordcraft_engine::cmd::insert::base64_encode(&on_disk); b.execute("file.open", json!({"path": path.to_string_lossy(), "data": data})).unwrap(); assert_eq!(b.autosave_block(), Some(AutoSaveBlock::NotSavedHere)); + assert_eq!(b.autosave_switch_block(), Some(AutoSaveBlock::NotSavedHere), "the switch shows the block"); assert!(b.run("file.autosave", json!({"value": true})).is_err()); - assert!(b.run("file.autosave", json!({})).is_err(), "the switch refuses too"); + b.status_msg = None; + let err = b.run("file.autosave", json!({})).unwrap_err(); + assert!(b.status_msg.as_ref().is_some_and(|(m, _)| *m == err), "the status bar says why: {:?}", b.status_msg); b.run("text.insert", json!({"text": "Bytes "})).unwrap(); b.autosave_tick(now_ms() + 10_000.0); assert!(b.session.dirty); From 0d4717cea6c67338cec2e24deee1ba984da2770f Mon Sep 17 00:00:00 2001 From: Michael Date: Thu, 5 Nov 2026 07:08:23 +0800 Subject: [PATCH 047/609] TOC: the caret goes after a table replaced above a section break; page numbers count the added paragraph Review follow-up. Replacing Word's TOC whose title sits above a section break returned before the caret was placed, so a caret in the title stayed there and typing changed the title; that branch now places it after the table too. When a table follows the TOC, the paragraph added for the caret came after the entries were paginated; the entries are now rebuilt once it is there (with the tabs and leader they now have), so their page numbers count it. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/references/toc.rs | 24 ++++++++++++++++++------ crates/engine/src/tests.rs | 16 ++++++++++++++++ 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/references/toc.rs b/crates/engine/src/cmd/references/toc.rs index cd73028620..48511e04a9 100644 --- a/crates/engine/src/cmd/references/toc.rs +++ b/crates/engine/src/cmd/references/toc.rs @@ -392,6 +392,7 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult { // its paragraph ending the title's section, and the new entries follow in their columns. Some((start, _)) if title_above_break(s, start).is_some() => { replace_toc_above_break(s, v, start, &tabs)?; + caret_after_toc(s)?; return sel_result(s); } Some((start, end)) => { @@ -425,18 +426,29 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult { s.doc.insert_block(StoryRef::Body, &Path::top(i), Block::Para(head))?; let leader = leader(p::str(v, "tabLeader").unwrap_or("dot")); regenerate_toc(s, Some(leader), &tabs)?; - // Like Word, the caret lands in a paragraph right after the table, ready to keep typing — - // not inside the table's own title or entries, where typing (or Enter) would corrupt them. + caret_after_toc(s)?; + sel_result(s) +} + +/// Like Word, the caret lands in the paragraph right after the table, ready to keep typing — not +/// inside the table's own title or entries, where typing (or Enter) would corrupt them. When a +/// table (or nothing) follows, a paragraph is added there first, and the entries are rebuilt so +/// their page numbers count it. +fn caret_after_toc(s: &mut Session) -> Result<(), CmdError> { if let Some((_, end)) = toc_range(s) { let after = end + 1; - let is_para = s.doc.body.get(after).is_some_and(|b| b.as_para().is_some()); - if !is_para { + if !s.doc.body.get(after).is_some_and(|b| b.as_para().is_some()) { s.doc.insert_block(StoryRef::Body, &Path::top(after), Block::Para(Paragraph::new()))?; + // Rebuilt as they now are (their leader and tabs), only the page numbers can change. + let tabs = cached_toc_tabs(s); + regenerate_toc(s, None, &tabs)?; + } + if let Some((_, end)) = toc_range(s) { + s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(end + 1), off: 0 }); } - s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(after), off: 0 }); } s.clamp_selection(); - sel_result(s) + Ok(()) } /// Replaces a TOC whose title sits above the section break its field's paragraph ends diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 0792962d01..359d1b51ce 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4190,6 +4190,22 @@ fn replacing_a_toc_keeps_its_title_above_the_section_break() { assert_eq!(toc_layout(&s), before, "{}", text(&s)); } +/// Replacing Word's TOC whose title sits above a section break leaves the caret after the table, +/// as a plain replacement does: with the caret in the title, typing went into the title. +#[test] +fn replacing_a_toc_above_a_section_break_leaves_the_caret_after_it() { + let mut s = word_toc_above_a_section_break("TOCHeading"); + s.sel = crate::Selection::caret(Pos { story: StoryRef::Body, path: wordcraft_doc::Path::top(0), off: 2 }); + run(&mut s, "references.toc", json!({"levels": 1})); + // Past the last entry, not in the title or the entries. + let last_entry = s.doc.body.iter().rposition(|b| b.as_para().is_some_and(|p| p.props.style.as_deref().is_some_and(|st| st.starts_with("TOC")))); + assert!(last_entry.is_some_and(|e| s.sel.focus.path.last() > e), "{:?}: {}", s.sel.focus, text(&s)); + run(&mut s, "text.insert", json!({"text": "typed"})); + let (paras, _) = toc_layout(&s); + assert_eq!(paras.first().map(|(_, _, t)| t.as_str()), Some("Contents"), "the title is untouched: {paras:?}"); + assert!(paras.iter().any(|(st, _, t)| t == "typed" && !st.starts_with("TOC")), "{paras:?}"); +} + /// #4041: removing Word's TOC whose title sits above a section break takes the title, the blank /// paragraph ending its section and that break with the entries, as Word's Remove Table of /// Contents does (observed in Word for Mac): the empty paragraph after the table, ending the From 1a86fd08fee051f21730c7b0765768b56a68252f Mon Sep 17 00:00:00 2001 From: Michael Date: Thu, 5 Nov 2026 07:20:05 +0800 Subject: [PATCH 048/609] TOC: the caret after the table sits past the next heading's bookmark Review follow-up. When the paragraph after the table is a heading, the rebuilt entries give it a `_Toc` bookmark at offset zero, so the caret placed at offset zero sat before the bookmark and Delete removed it instead of the heading's first character, leaving the entry without its target. The caret now goes past the markers the paragraph starts with. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/references/tests.rs | 19 +++++++++++++++++++ crates/engine/src/cmd/references/toc.rs | 14 +++++++++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/references/tests.rs b/crates/engine/src/cmd/references/tests.rs index 369e7069d2..60b1cf5e85 100644 --- a/crates/engine/src/cmd/references/tests.rs +++ b/crates/engine/src/cmd/references/tests.rs @@ -548,6 +548,25 @@ fn caption_for_an_object_in_a_cell_stays_in_the_cell() { assert_eq!(texts.get(1).map(String::as_str), Some("Figure 1"), "{texts:?}"); } +/// A TOC inserted before a heading leaves the caret at the heading's first character, past the +/// `_Toc` bookmark its entry links to: Delete then deletes that character, and the entry still +/// finds its heading (Delete at offset zero took the bookmark). +#[test] +fn the_caret_after_a_toc_sits_past_the_headings_bookmark() { + let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns\nBody text.")); + s.run("para.style", &json!({"style": "Heading 1"})).unwrap(); + s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(0), off: 0 }); + s.run("references.toc", &json!({"levels": 2})).unwrap(); + let heading = s.doc.para_at(&s.sel.focus).cloned().unwrap(); + assert_eq!(heading.plain_text(), "Kilns"); + let marks = |p: &Paragraph| p.objects.iter().filter(|o| matches!(o, InlineObject::BookmarkStart { .. })).count(); + assert_eq!(marks(&heading), 1, "the heading has its bookmark"); + s.run("text.delete", &json!({})).unwrap(); + let heading = s.doc.para_at(&s.sel.focus).cloned().unwrap(); + assert_eq!(heading.plain_text(), "ilns", "Delete took the first character"); + assert_eq!(marks(&heading), 1, "the bookmark stays"); +} + /// Inserting a table of contents (Word itself warns when there's no heading yet, but still /// creates an empty one) must leave the caret in a fresh paragraph just after it, like Word /// does — not inside the table's own title, where typing the rest of the document (and later diff --git a/crates/engine/src/cmd/references/toc.rs b/crates/engine/src/cmd/references/toc.rs index 48511e04a9..17e08ab59e 100644 --- a/crates/engine/src/cmd/references/toc.rs +++ b/crates/engine/src/cmd/references/toc.rs @@ -444,7 +444,19 @@ fn caret_after_toc(s: &mut Session) -> Result<(), CmdError> { regenerate_toc(s, None, &tabs)?; } if let Some((_, end)) = toc_range(s) { - s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(end + 1), off: 0 }); + // Past the markers the paragraph starts with (a heading's `_Toc` bookmark, which its + // entry links to): Delete there takes the first character, not the bookmark. + let off = s.doc.body.get(end + 1).and_then(|b| b.as_para()).map_or(0, |p| { + let mut off = 0; + for (at, o) in p.objects_with_offsets() { + if at != off || !o.is_marker() { + break; + } + off += OBJ.len_utf8(); + } + off + }); + s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(end + 1), off }); } } s.clamp_selection(); From 3c44fc64434e9ac172593b53fe404747e4870efa Mon Sep 17 00:00:00 2001 From: Kevin Joseph Date: Mon, 9 Nov 2026 13:30:03 +0100 Subject: [PATCH 049/609] Layout: a continued footnote ends on the bottom margin; widow control in it When a footnote continues on the next page, Word for Mac 16.113.4 keeps the note area's last line on the page's bottom margin and leaves the room above the separator; WordCraft placed the notes right under the text. With widow control in the note's paragraph, Word takes one more line along rather than leave its last line alone on the next page; WordCraft left it alone. Measured with cargo xtask word-compare: a long footnote whose reference moves down the page one body line at a time (Georgia 11, notes 9, widow control on and off), 30 documents; all 30 now match Word's PDFs line for line (9 differed in the note area's position, 1 in its line breaks). Tests: a_footnote_continuing_on_the_next_page_ends_on_the_bottom_margin and widow_control_leaves_two_lines_of_a_split_footnote_on_the_next_page, each failing without its half of the fix. --- crates/layout/src/notes.rs | 13 +++++++++ crates/layout/src/page.rs | 25 ++++++++++++++-- crates/layout/src/tests.rs | 60 ++++++++++++++++++++++++++++++++++++++ docs/layout-parity.md | 5 ++-- 4 files changed, 98 insertions(+), 5 deletions(-) diff --git a/crates/layout/src/notes.rs b/crates/layout/src/notes.rs index e34f1aff30..0ac348ffa1 100644 --- a/crates/layout/src/notes.rs +++ b/crates/layout/src/notes.rs @@ -223,6 +223,19 @@ impl NoteBox { cuts } + /// Whether splitting at `cut` leaves the last line of a paragraph with widow control alone + /// on the next page. + pub(crate) fn leaves_widow(&self, cut: f32) -> bool { + self.items.iter().filter(|it| self.splittable(it)).any(|it| { + let Placed::Lines { para, l0, l1, y, .. } = it else { return false }; + let Some(first) = para.lines.get(*l0) else { return false }; + para.rp.widow_control + && *l1 == para.lines.len() + && *l1 >= 2 + && para.lines.get(*l1 - 2).is_some_and(|l| (y + l.top - first.top + l.height - cut).abs() < 0.01) + }) + } + /// The least of the note that must stay with its reference: its first line (all of it if it /// can't be split). pub(crate) fn first_piece(&self) -> f32 { diff --git a/crates/layout/src/page.rs b/crates/layout/src/page.rs index 14c611f2da..18d99ab5a5 100644 --- a/crates/layout/src/page.rs +++ b/crates/layout/src/page.rs @@ -155,7 +155,7 @@ impl PageBuilder<'_> { // The note area starts below the text (a page of continued notes alone: at its top). let area = self.bottom.max(self.body_floor()); let fits = total <= self.orig_bottom - area + 0.01; - let top = match (fits, self.beneath) { + let mut top = match (fits, self.beneath) { (false, _) => area, // Below the page's last line of text. (true, true) => self.body_floor().min(self.orig_bottom - total), @@ -168,12 +168,15 @@ impl PageBuilder<'_> { let mut placed = Vec::new(); // Where the continuation notice goes, below a note that continues on the next page. let mut notice_y = None; + // The bottom of what is placed (with the notice). + let mut end = y; let mut rest = notes.into_iter(); while let Some(n) = rest.next() { let room = self.orig_bottom - y; if fits || n.h <= room + 0.01 { let ny = y; y += n.h; + end = y; placed.push((n, ny)); continue; } @@ -183,19 +186,35 @@ impl PageBuilder<'_> { let first = placed.is_empty(); let cuts = n.cuts(); let room = room - self.seps.notice_h(); - match cuts.iter().rev().find(|&&c| c <= room + 0.01).or(cuts.first().filter(|_| first)).copied() { + // Widow control in the note leaves two of a paragraph's lines on the next page. + let ok = |c: &&f32| **c <= room + 0.01 && !n.leaves_widow(**c); + match cuts.iter().rev().find(ok).or(cuts.first().filter(|_| first)).copied() { Some(c) => { let (head, tail) = n.split(c); notice_y = Some(y + head.h); + end = y + head.h + self.seps.notice_h(); placed.push((head, y)); self.carry.push(tail); } - None if first => placed.push((n, y)), + None if first => { + end = y + n.h; + placed.push((n, y)); + } None => self.carry.push(n), } self.carry.extend(rest.by_ref()); break; } + // Notes that continue on the next page still end on the bottom margin, the room left + // going above the separator (Word for Mac 16.113.4), unless they go beneath the text. + if !fits && !self.beneath { + let shift = (self.orig_bottom - end).max(0.0); + top += shift; + notice_y = notice_y.map(|ny| ny + shift); + for (_, ny) in &mut placed { + *ny += shift; + } + } if let Some(pg) = self.pages.last_mut() { match if cont { &self.seps.cont } else { &self.seps.sep } { Some((items, _)) => pg.items.extend(items.iter().cloned().map(|mut it| { diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 6db3eaa84c..fbbdb272c1 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -8982,6 +8982,66 @@ fn long_footnotes_continue_on_the_next_page() { assert!(own_note.top > p1.3, "own note after the continued one: {own_note:?} {p1:?}"); } +/// A document of `body` one-line paragraphs, the last of them referencing a footnote of `note` +/// sentences, with widow control `widow` in the note; the note's id. +fn long_note_after(body: usize, note: usize, widow: bool) -> (Document, u32) { + let mut d = Document::from_text(&"Body text line.\n".repeat(body)); + let mut p = wordcraft_doc::Paragraph::with_text(&"A long footnote that runs on. ".repeat(note), Default::default()); + p.props.widow_control = Some(widow); + p.props.space_after = Some(0.0); + let id = d.add_part(wordcraft_doc::PartKind::Footnote, vec![wordcraft_doc::para_block(p)]); + d.insert_object( + &Pos::body(body.saturating_sub(1), 4), + InlineObject::NoteRef { kind: wordcraft_doc::para::NoteKind::Footnote, id, custom: String::new() }, + &Default::default(), + ) + .unwrap(); + (d, id) +} + +#[test] +fn a_footnote_continuing_on_the_next_page_ends_on_the_bottom_margin() { + crate::test_fonts(); + // Observed in Word for Mac 16.113.4: whatever room the split leaves goes above the + // separator, the note's last line on the page sitting on the bottom margin. + let bottom = Document::default().last_section.page_h - Document::default().last_section.margin_bottom; + let mut slack = Vec::new(); + for body in 11..24 { + let (d, id) = long_note_after(body, 60, false); + let l = lay(&d); + let pieces = note_pieces(&l, id); + assert!(pieces.len() >= 2 && pieces[0].0 == 0 && pieces[1].0 == 1, "{body}: {pieces:?}"); + let (para, l0, l1, y) = l.pages[0] + .items + .iter() + .find_map(|it| match it { + Placed::Lines { story: StoryRef::Part(s), para, l0, l1, y, .. } if *s == id => Some((para.clone(), *l0, *l1, *y)), + _ => None, + }) + .unwrap(); + let end = item_bottom(y, ¶, l0, l1).unwrap(); + slack.push(bottom - end); + } + assert!(slack.iter().all(|s| s.abs() < 0.05), "room left under the note: {slack:?}"); +} + +#[test] +fn widow_control_leaves_two_lines_of_a_split_footnote_on_the_next_page() { + crate::test_fonts(); + // Observed in Word for Mac 16.113.4: a note that would leave its last line alone on the next + // page takes one more line along when its paragraph has widow control. + let lines_after = |body: usize, widow: bool| { + let (d, id) = long_note_after(body, 60, widow); + let pieces = note_pieces(&lay(&d), id); + pieces.get(1).filter(|p| p.0 == 1).map(|p| p.2 - p.1) + }; + let widows: Vec = (9..26).filter(|&b| lines_after(b, false) == Some(1)).collect(); + assert!(!widows.is_empty(), "no body length leaves one line of the note on page 2"); + for b in widows { + assert_eq!(lines_after(b, true), Some(2), "body of {b} lines"); + } +} + #[test] fn short_footnotes_stay_whole() { crate::test_fonts(); diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 1f2f967632..9afcb11997 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -1,6 +1,6 @@ # Layout and pagination parity with Microsoft Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** trivial (a turned inline picture whose file keeps no room for the turn keeps its line to its frame, the frame turned a quarter in Word 2013+ layout); previously trivial (a picture lowered further than its own height lowers its line as far, its top on the baseline); previously trivial (a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a line of only pictures is as tall as they reach, never less than its font's height; a legacy check box sizes its line as text of its size, #3984); previously trivial (spaces before a line's first character keep their width in justified and distributed lines, as in Word); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (Times and Courier take their Windows counterparts' line spacing; 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 (a click just outside a floating table, by a cell whose text is turned, goes to the text beside or after it, #4181; 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 (PR #4545: eligible cell floats keep in-bounds offsets; overflow confinement retains the front-of-text, turned-cell and native-acceptance limits); previously trivial (MATH construction reuse, #3630; previously 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 (ODT documents: a line of only pictures keeps its font's height; no setting for it any more); previously trivial (ODT documents: padding is the standard's box model always; picture-only line height is an ODF interpretation setting); previously trivial (行頭禁則 also covers the small kana and the prolonged sound mark at ordinary break opportunities, as JIS X 4051 §4 specifies, inferred from the standard and synthetic tests rather than checked in Word); previously trivial (a missing font is drawn in an installed metric twin before any other substitute: Arial for Helvetica on Windows, Tinos before macOS Times for Times New Roman); previously trivial (ODT documents: padding without a border takes room); previously trivial (ODT documents: a line of only pictures is as tall as they are); previously trivial (ODT documents: a table's own space above and below; header and footer spacing kept past a tall header); previously trivial (a page break before a table's first row moves the table; emphasis marks drawn with room in the line); previously trivial (text in a turned text box turns with it; previously trivial: an in-line picture, shape or chart moves with its run's raise or lowering, Word's `w:position`; previously trivial (layout work bounds: header-row repeats budgeted per layout, cached picture outlines charged to the decode budget, linked-box chain widths exact up to a work cap, #3867); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a table row that would leave a cell empty on a page that already holds something, its picture or first line not fitting there, moves on whole instead of leaving the other cells' text beside the empty cell, #4272); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (tab leader dots spaced and placed as in Word); previously trivial (a level above that hasn't counted yet takes its first number at the first deeper item); previously trivial (paragraph side borders lie beyond their distance from the text, #5036); previously trivial (with a header taller than the top margin, Margin-anchored drawings, header-cell pins and header-table obstacles use the rendered body top; TopMargin and InsideMargin keep their declared band, #2485; previously trivial: connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (field results take the `\* DollarText`, `\* Hex` and `\* ArabicDash` switches, #4226; previously trivial: a cell spanning columns shares its extra minimum width by the columns' preferred widths, equally in automatic tables, #1883; previously 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 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** trivial (a footnote continuing on the next page ends on the bottom margin, and widow control in it leaves two lines for the next page); previously trivial (a turned inline picture whose file keeps no room for the turn keeps its line to its frame, the frame turned a quarter in Word 2013+ layout); previously trivial (a picture lowered further than its own height lowers its line as far, its top on the baseline); previously trivial (a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a line of only pictures is as tall as they reach, never less than its font's height; a legacy check box sizes its line as text of its size, #3984); previously trivial (spaces before a line's first character keep their width in justified and distributed lines, as in Word); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (Times and Courier take their Windows counterparts' line spacing; 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 (a click just outside a floating table, by a cell whose text is turned, goes to the text beside or after it, #4181; 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 (PR #4545: eligible cell floats keep in-bounds offsets; overflow confinement retains the front-of-text, turned-cell and native-acceptance limits); previously trivial (MATH construction reuse, #3630; previously 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 (ODT documents: a line of only pictures keeps its font's height; no setting for it any more); previously trivial (ODT documents: padding is the standard's box model always; picture-only line height is an ODF interpretation setting); previously trivial (行頭禁則 also covers the small kana and the prolonged sound mark at ordinary break opportunities, as JIS X 4051 §4 specifies, inferred from the standard and synthetic tests rather than checked in Word); previously trivial (a missing font is drawn in an installed metric twin before any other substitute: Arial for Helvetica on Windows, Tinos before macOS Times for Times New Roman); previously trivial (ODT documents: padding without a border takes room); previously trivial (ODT documents: a line of only pictures is as tall as they are); previously trivial (ODT documents: a table's own space above and below; header and footer spacing kept past a tall header); previously trivial (a page break before a table's first row moves the table; emphasis marks drawn with room in the line); previously trivial (text in a turned text box turns with it; previously trivial: an in-line picture, shape or chart moves with its run's raise or lowering, Word's `w:position`; previously trivial (layout work bounds: header-row repeats budgeted per layout, cached picture outlines charged to the decode budget, linked-box chain widths exact up to a work cap, #3867); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a table row that would leave a cell empty on a page that already holds something, its picture or first line not fitting there, moves on whole instead of leaving the other cells' text beside the empty cell, #4272); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (tab leader dots spaced and placed as in Word); previously trivial (a level above that hasn't counted yet takes its first number at the first deeper item); previously trivial (paragraph side borders lie beyond their distance from the text, #5036); previously trivial (with a header taller than the top margin, Margin-anchored drawings, header-cell pins and header-table obstacles use the rendered body top; TopMargin and InsideMargin keep their declared band, #2485; previously trivial: connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (field results take the `\* DollarText`, `\* Hex` and `\* ArabicDash` switches, #4226; previously trivial: a cell spanning columns shares its extra minimum width by the columns' preferred widths, equally in automatic tables, #1883; previously 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 > **Floating anchor row segments:** 2026-11-07 · A floating anchor after a manual page/column break counts visible content on the far side of the same wrapped row. Marker-only cover anchors retain their previous-page rule. Synthetic picture spacing, placement and history controls; no new native Word measurement. Readiness estimates unchanged. @@ -67,7 +67,7 @@ Exact line spacing keeps the run font baseline around tall equations; automatic | List labels: number formats (decimal, letters, Russian letters, roman, ordinal text, Chinese/Japanese/Korean counting and legal, 一〇一 digits, 甲乙丙, ①…⑳, full-width), `%n` text such as `第%1章` / `(%1)`, legal numbering | ✅ | a level above that hasn't counted yet takes its first number at the first deeper item, as measured in Word: after 10.1–10.4 the next level-1 item is 11 (`doc::numbering::tests::a_deeper_item_first_counts_the_levels_above_it`); `doc::cjk_numbers` tests, `doc::section::tests::russian_letters_follow_word`, `layout::tests::chinese_counting_list_labels_and_their_font_runs`, `layout::tests::russian_letter_list_labels_draw_cyrillic`; a label mixing faces (digit + CJK comma) is drawn run by run (#534); Russian letters skip ё, й, ъ and ь and then double (аа, бб), as observed in Word. Hebrew, Hindi, Thai and Vietnamese formats show decimal; `arabicAlpha` and `arabicAbjad` draw Arabic letters, then double (أأ, بب) (`doc::section::tests::arabic_letters_count_in_both_orders`). The label stays attached to the start of the text when the paragraph is centred or aligned to the end, as in Word (#1159). A level with number format `none` is an ordinary level whose own number reads as nothing, as in Word for Windows (Microsoft 365, checked by MeHail-02): its label is its text with that number empty (`RESPONSE:`; `Part` above `%1.%2` gives `.1`), it counts and restarts the levels below it, it stays empty in legal numbering, and an empty label still tabs the text to the indent unless it already ends there (Heading 2 of the Chapter 1 list stays at the margin) (#4985; `doc::numbering::tests::a_none_level_shows_its_text_and_still_counts`, `layout::tests::a_none_format_label_shows_its_text_and_tabs_to_the_indent`). | — | | Body top below a tall header, footer pushes body up | ✅ | #138; a footer taller than the bottom margin moves the body bottom up (#453), and a header or footer linked to the previous section takes its room too (#454) | — | | Tables: row border exceptions (`w:tblPrEx/w:tblBorders`) | ✅ | `row_borders_stay_on_row`, `row_nil_overrides_style`: explicit cell borders win; row exceptions precede table styles and table borders | — | -| Footnotes at the page bottom, endnotes at the end, note numbering | 🟡 | A long note continues onto the next page at a line boundary (its first line stays with the reference), first in that page's note area under a full-width continuation separator (#352); the document's own separator, continuation separator and continuation notice are drawn (the notice under a note that continues); on a page with footnotes a paragraph ending there keeps its space after above the separator, or its last lines go to the next page with the note (#1116); a long endnote continues on the next column or page at a line boundary (#456), and the caret finds note text on its continuation page (#457); each section's note options: footnotes below the text, endnotes at the end of each section, start at, numbering restarted each section or each page (counted from where the notes land, at most three passes) (#385) | 1–2 | +| Footnotes at the page bottom, endnotes at the end, note numbering | 🟡 | A long note continues onto the next page at a line boundary (its first line stays with the reference), first in that page's note area under a full-width continuation separator (#352); the page it starts on keeps its last line on the bottom margin, the room left going above the separator, and widow control in the note's paragraph takes one more line along rather than leave its last line alone on the next page (measured in Word for Mac 16.113.4 with `cargo xtask word-compare`: a note pushed down the page one body line at a time); the document's own separator, continuation separator and continuation notice are drawn (the notice under a note that continues); on a page with footnotes a paragraph ending there keeps its space after above the separator, or its last lines go to the next page with the note (#1116); a long endnote continues on the next column or page at a line boundary (#456), and the caret finds note text on its continuation page (#457); each section's note options: footnotes below the text, endnotes at the end of each section, start at, numbering restarted each section or each page (counted from where the notes land, at most three passes) (#385) | 1–2 | | Tables: row heights (at least/exact), rows split across pages, header rows repeat, Can't Split | ✅ | 2026-10-06, #138; omitted cell-margin edges inherit current table defaults; every cell in a row gets the row's largest top and bottom margin; an exact height covers the top border, top margin and text, the bottom margin comes on top, and an exact row never splits; a row split across pages keeps its cells' bottom margin, border and last space after on the first page, widow/orphan control applies in its cells, each cell continues at the top of the next page and an at-least row keeps its minimum; an at-least row with less room than its minimum on a page that already holds something starts the next page whole (Allow row to break on or off, vAlign centre too), as observed in Word for Mac 2026-10-15 (a row of about 2.6 cm), #1742; that repeated header rows go with it and that a row taller than a page splits from the top of the next page come from the issue and synthetic tests, not a Word check (`…_an_at_least_row_with_no_room_starts_the_next_page_whole_either_way_breaking_is_set`, `…_an_at_least_row_taller_than_a_page_splits_from_the_top_of_the_next_page`, `layout::tests::a_row_shares_its_largest_top_and_bottom_margins`, `…_a_split_row_keeps_its_bottom_margin_and_widow_control`, `…_split_row_cells_each_continue_at_the_top`); a row's `gridAfter` is bounded to 63 columns in native documents too, and repeated header rows stop after 500 000 copied items across a table (hostile documents, #3692); a cell aligned to the middle or bottom of a split row is aligned within the part left on the page when all its text fits there (as tall as the other cells' text there), and runs from the top of the cell otherwise, as measured in Word (`layout::tests::a_middle_or_bottom_cell_of_a_split_row_lines_up_on_the_first_page`); a row whose first part on a page that already holds something would leave a cell empty there, because that cell's first line or inline picture (one line, never split) runs past the room, moves on whole instead of leaving the other cells' text beside the empty cell, so an at-least row grown taller than its minimum by a picture no longer splits off its picture (#4272; inferred from the reporter's Word result and the earlier observation that Word doesn't leave a cell empty for widow control, not yet checked in Word for rows without a minimum; at the top of a page such a row still splits; `layout::tests::an_at_least_row_grown_by_its_picture_moves_on_whole_rather_than_leave_the_picture_behind`, `…_a_picture_row_that_fits_stays_and_text_rows_beside_a_short_picture_still_split`, `…_a_picture_row_too_tall_for_any_page_splits_from_the_top_of_the_next_one`); a row of a nested table marked Can't Split isn't split with its outer row: the outer row moves on whole when that row comes first in it (docxide-pdf `nested-first-row-*-cant1`) and otherwise splits above it (inferred, not yet checked in Word), and on a fresh page a nested row taller than the room still splits; `layout::tests::nested_cant_split::nested_cant_split_row_moves_on_with_its_outer_row`, `…::the_outer_row_splits_above_a_nested_cant_split_row`, `…::the_cut_moves_up_until_no_nested_cant_split_row_runs_through_it`, `…::the_outer_row_breaks_between_nested_cant_split_rows_above_its_bottom_band`, `…::a_bottom_aligned_cell_keeps_its_nested_cant_split_row_whole`, `…::header_rows_go_on_with_a_first_row_whose_nested_cant_split_row_comes_first`, `…::a_kept_row_goes_on_with_a_row_whose_nested_cant_split_row_cant_start_below_it`, `…::a_merged_cell_doesnt_stretch_its_cant_split_row`, `…::nested_cant_split_row_taller_than_a_page_still_splits` | — | | Tables: autofit to contents/window, fixed widths, Word 2013 edge | 🟡 | #137; #44: AutoFit Contents measures each column's narrowest and widest text and shares the width like Word, once (not live as you type); consistent a percentage width past 100% is kept, as Word does; a table with its own preferred width keeps it, however far past the margin, and only an automatic-width table over 1.5× the text width is squeezed to the margins (Word squeezes it as soon as it is wider) (#1721); cell widths override stale grid proportions when their totals agree (`cell_widths_override_grid`); conflicting widths and spans still differ | 3–5 | | Floating tables (`w:tblpPr`) | 🟡 | #137; one placed on the page or margin that would cover visible text before it and does not fit below it moves to the next page (#534); empty line-break lines do not count as text; a click below one, outside its cells, goes to the text beside or after it, not to its last row, as checked in Word (#2038); exact line-bottom contact counts for tables only (#3977), both in row-span selection and word skipping; exact-spacing table contact uses the specified height rather than paragraph-mark metrics, with original Source Sans 3 controls in modes 11/12/14/15; expected Word rule from [cyril265's Word for Mac 16.114.1 measurements](https://github.com/storytold/wordcraft/issues/3977#issuecomment-6374217574), not a new Word run of these originals; anchor-order replay remains #3790's scope; other overlap rules untested | 2–3 | @@ -307,6 +307,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | Date | Change | Summary | |---|---|---| +| 2026-11-09 | trivial | A footnote continuing on the next page ends on the bottom margin of the page it starts on, the room left going above the separator, and widow control in its paragraph leaves two of its lines for the next page, as measured in Word for Mac 16.113.4 (`layout::tests::a_footnote_continuing_on_the_next_page_ends_on_the_bottom_margin`, `widow_control_leaves_two_lines_of_a_split_footnote_on_the_next_page`) | | 2026-11-08 | trivial | Turned inline pictures with no recorded effect extent keep their line to the frame (exchanged near a quarter turn in Word 2013+ layout) and overhang it, cut at the line's top and bottom, as in Word | | 2026-11-08 | trivial | Contextual spacing drops the space after a table cell's last paragraph in the Normal style, the end-of-cell mark counting as a Normal paragraph; another style keeps it, and a middle or bottom cell of a split row lines up without the dropped space (#5450) (`layout::tests::contextual_spacing_drops_the_space_after_a_cells_last_normal_paragraph`, `a_bottom_cell_of_a_split_row_ignores_a_dropped_space_after_beside_it`). | | 2026-11-04 | trivial | Header table measurements and fitted text-box heights use the page section’s PAGE format; cache reuse follows the field context | From 0074cb6ac6015bec878427606941b176bdfd5b0e Mon Sep 17 00:00:00 2001 From: Kevin Joseph Date: Mon, 9 Nov 2026 13:49:31 +0100 Subject: [PATCH 050/609] Layout: orphan control in a footnote split across pages Rather than leave a note paragraph's first line alone at the bottom of a page, Word for Mac 16.113.4 moves the line holding the reference on to the next page with it. WordCraft kept the line and one note line on the page. The least of a note that stays with its reference is now two lines of a paragraph with widow/orphan control (or the paragraph whole); the page's first note still splits where it must rather than overrun the page. Found by the word-compare footnotes probe, which now matches Word line for line (it differed by up to 37.6 pt on page 1, one body line on the wrong page). The 30 footnote-split probes still match. Test: orphan_control_keeps_two_lines_of_a_split_footnote_with_its_reference, failing without the change. --- crates/layout/src/notes.rs | 28 ++++++++++++++++++---------- crates/layout/src/page.rs | 9 +++++---- crates/layout/src/tests.rs | 27 +++++++++++++++++++++++++++ docs/layout-parity.md | 6 +++--- 4 files changed, 53 insertions(+), 17 deletions(-) diff --git a/crates/layout/src/notes.rs b/crates/layout/src/notes.rs index 0ac348ffa1..5168a1f4b1 100644 --- a/crates/layout/src/notes.rs +++ b/crates/layout/src/notes.rs @@ -223,23 +223,31 @@ impl NoteBox { cuts } - /// Whether splitting at `cut` leaves the last line of a paragraph with widow control alone - /// on the next page. - pub(crate) fn leaves_widow(&self, cut: f32) -> bool { + /// Whether widow/orphan control in the note's paragraphs forbids splitting at `cut`: a + /// paragraph's first line alone above it (an orphan) or its last line alone below it (a + /// widow), as in Word for Mac 16.113.4. + pub(crate) fn breaks_widow_control(&self, cut: f32) -> bool { self.items.iter().filter(|it| self.splittable(it)).any(|it| { let Placed::Lines { para, l0, l1, y, .. } = it else { return false }; let Some(first) = para.lines.get(*l0) else { return false }; - para.rp.widow_control - && *l1 == para.lines.len() - && *l1 >= 2 - && para.lines.get(*l1 - 2).is_some_and(|l| (y + l.top - first.top + l.height - cut).abs() < 0.01) + let ends_at = |k: usize| para.lines.get(k).is_some_and(|l| (y + l.top - first.top + l.height - cut).abs() < 0.01); + let n = para.lines.len(); + para.rp.widow_control && n >= 2 && ((*l0 == 0 && *l1 >= 2 && ends_at(0)) || (*l1 == n && ends_at(n - 2))) }) } - /// The least of the note that must stay with its reference: its first line (all of it if it - /// can't be split). + /// Where the note may be split with its paragraphs' widow/orphan control kept, ascending. + pub(crate) fn kept_cuts(&self) -> Vec { + let mut cuts = self.cuts(); + cuts.retain(|&c| !self.breaks_widow_control(c)); + cuts + } + + /// The least of the note that must stay with its reference: its first line, or more under + /// widow/orphan control (all of it if it can't be split). pub(crate) fn first_piece(&self) -> f32 { - self.cuts().first().copied().unwrap_or(self.h).min(self.h) + // Widow/orphan control may keep more lines together (two, or a short paragraph whole). + self.kept_cuts().first().copied().unwrap_or(self.h).min(self.h) } /// Split the note at line bottom `cut`: the part above (`cut` tall) and the rest, moved up to diff --git a/crates/layout/src/page.rs b/crates/layout/src/page.rs index 18d99ab5a5..80123f214c 100644 --- a/crates/layout/src/page.rs +++ b/crates/layout/src/page.rs @@ -184,11 +184,12 @@ impl PageBuilder<'_> { // always leaves something here (its first line, or all of it if it can't be split), // so continuing ends. let first = placed.is_empty(); - let cuts = n.cuts(); + // Widow/orphan control in the note keeps two of a paragraph's lines on either side; + // the page's first note gives that up before it gives up the page's room. let room = room - self.seps.notice_h(); - // Widow control in the note leaves two of a paragraph's lines on the next page. - let ok = |c: &&f32| **c <= room + 0.01 && !n.leaves_widow(**c); - match cuts.iter().rev().find(ok).or(cuts.first().filter(|_| first)).copied() { + let fit = |cuts: Vec| cuts.into_iter().rev().find(|&c| c <= room + 0.01); + let cut = fit(n.kept_cuts()).or_else(|| if first { fit(n.cuts()).or(n.cuts().first().copied()) } else { None }); + match cut { Some(c) => { let (head, tail) = n.split(c); notice_y = Some(y + head.h); diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index fbbdb272c1..5b105c5dd7 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -9042,6 +9042,33 @@ fn widow_control_leaves_two_lines_of_a_split_footnote_on_the_next_page() { } } +#[test] +fn orphan_control_keeps_two_lines_of_a_split_footnote_with_its_reference() { + crate::test_fonts(); + // Observed in Word for Mac 16.113.4: rather than leave a note paragraph's first line alone at + // the bottom of the page, the line with the reference goes on to the next page with it. + let first_piece = |body: usize, widow: bool| { + let (mut d, id) = long_note_after(body, 60, widow); + // Body lines as tall as the note's, so the room under the text shrinks a note line at a time. + for block in &mut d.body { + if let Block::Para(para) = Arc::make_mut(block) { + para.props.space_after = Some(0.0); + } + } + let l = lay(&d); + let refs = l.caret(&Pos::body(body - 1, 4)).unwrap().page; + let pieces = note_pieces(&l, id); + (refs, pieces.first().map(|p| (p.0, p.2 - p.1))) + }; + let orphans: Vec = (20..60).filter(|&b| first_piece(b, false).1.is_some_and(|p| p.1 == 1)).collect(); + assert!(!orphans.is_empty(), "no body length leaves one line of the note with its reference"); + for b in orphans { + let (refs, piece) = first_piece(b, true); + assert_eq!(piece.map(|p| p.0), Some(refs), "body of {b} lines: the note starts on its reference's page"); + assert!(piece.is_some_and(|p| p.1 >= 2), "body of {b} lines: {piece:?}"); + } +} + #[test] fn short_footnotes_stay_whole() { crate::test_fonts(); diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 9afcb11997..b357e601e6 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -1,6 +1,6 @@ # Layout and pagination parity with Microsoft Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** trivial (a footnote continuing on the next page ends on the bottom margin, and widow control in it leaves two lines for the next page); previously trivial (a turned inline picture whose file keeps no room for the turn keeps its line to its frame, the frame turned a quarter in Word 2013+ layout); previously trivial (a picture lowered further than its own height lowers its line as far, its top on the baseline); previously trivial (a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a line of only pictures is as tall as they reach, never less than its font's height; a legacy check box sizes its line as text of its size, #3984); previously trivial (spaces before a line's first character keep their width in justified and distributed lines, as in Word); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (Times and Courier take their Windows counterparts' line spacing; 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 (a click just outside a floating table, by a cell whose text is turned, goes to the text beside or after it, #4181; 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 (PR #4545: eligible cell floats keep in-bounds offsets; overflow confinement retains the front-of-text, turned-cell and native-acceptance limits); previously trivial (MATH construction reuse, #3630; previously 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 (ODT documents: a line of only pictures keeps its font's height; no setting for it any more); previously trivial (ODT documents: padding is the standard's box model always; picture-only line height is an ODF interpretation setting); previously trivial (行頭禁則 also covers the small kana and the prolonged sound mark at ordinary break opportunities, as JIS X 4051 §4 specifies, inferred from the standard and synthetic tests rather than checked in Word); previously trivial (a missing font is drawn in an installed metric twin before any other substitute: Arial for Helvetica on Windows, Tinos before macOS Times for Times New Roman); previously trivial (ODT documents: padding without a border takes room); previously trivial (ODT documents: a line of only pictures is as tall as they are); previously trivial (ODT documents: a table's own space above and below; header and footer spacing kept past a tall header); previously trivial (a page break before a table's first row moves the table; emphasis marks drawn with room in the line); previously trivial (text in a turned text box turns with it; previously trivial: an in-line picture, shape or chart moves with its run's raise or lowering, Word's `w:position`; previously trivial (layout work bounds: header-row repeats budgeted per layout, cached picture outlines charged to the decode budget, linked-box chain widths exact up to a work cap, #3867); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a table row that would leave a cell empty on a page that already holds something, its picture or first line not fitting there, moves on whole instead of leaving the other cells' text beside the empty cell, #4272); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (tab leader dots spaced and placed as in Word); previously trivial (a level above that hasn't counted yet takes its first number at the first deeper item); previously trivial (paragraph side borders lie beyond their distance from the text, #5036); previously trivial (with a header taller than the top margin, Margin-anchored drawings, header-cell pins and header-table obstacles use the rendered body top; TopMargin and InsideMargin keep their declared band, #2485; previously trivial: connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (field results take the `\* DollarText`, `\* Hex` and `\* ArabicDash` switches, #4226; previously trivial: a cell spanning columns shares its extra minimum width by the columns' preferred widths, equally in automatic tables, #1883; previously 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 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** trivial (a footnote continuing on the next page ends on the bottom margin, and widow/orphan control in it keeps two lines on either side of the split); previously trivial (a turned inline picture whose file keeps no room for the turn keeps its line to its frame, the frame turned a quarter in Word 2013+ layout); previously trivial (a picture lowered further than its own height lowers its line as far, its top on the baseline); previously trivial (a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a line of only pictures is as tall as they reach, never less than its font's height; a legacy check box sizes its line as text of its size, #3984); previously trivial (spaces before a line's first character keep their width in justified and distributed lines, as in Word); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (Times and Courier take their Windows counterparts' line spacing; 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 (a click just outside a floating table, by a cell whose text is turned, goes to the text beside or after it, #4181; 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 (PR #4545: eligible cell floats keep in-bounds offsets; overflow confinement retains the front-of-text, turned-cell and native-acceptance limits); previously trivial (MATH construction reuse, #3630; previously 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 (ODT documents: a line of only pictures keeps its font's height; no setting for it any more); previously trivial (ODT documents: padding is the standard's box model always; picture-only line height is an ODF interpretation setting); previously trivial (行頭禁則 also covers the small kana and the prolonged sound mark at ordinary break opportunities, as JIS X 4051 §4 specifies, inferred from the standard and synthetic tests rather than checked in Word); previously trivial (a missing font is drawn in an installed metric twin before any other substitute: Arial for Helvetica on Windows, Tinos before macOS Times for Times New Roman); previously trivial (ODT documents: padding without a border takes room); previously trivial (ODT documents: a line of only pictures is as tall as they are); previously trivial (ODT documents: a table's own space above and below; header and footer spacing kept past a tall header); previously trivial (a page break before a table's first row moves the table; emphasis marks drawn with room in the line); previously trivial (text in a turned text box turns with it; previously trivial: an in-line picture, shape or chart moves with its run's raise or lowering, Word's `w:position`; previously trivial (layout work bounds: header-row repeats budgeted per layout, cached picture outlines charged to the decode budget, linked-box chain widths exact up to a work cap, #3867); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a table row that would leave a cell empty on a page that already holds something, its picture or first line not fitting there, moves on whole instead of leaving the other cells' text beside the empty cell, #4272); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (tab leader dots spaced and placed as in Word); previously trivial (a level above that hasn't counted yet takes its first number at the first deeper item); previously trivial (paragraph side borders lie beyond their distance from the text, #5036); previously trivial (with a header taller than the top margin, Margin-anchored drawings, header-cell pins and header-table obstacles use the rendered body top; TopMargin and InsideMargin keep their declared band, #2485; previously trivial: connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (field results take the `\* DollarText`, `\* Hex` and `\* ArabicDash` switches, #4226; previously trivial: a cell spanning columns shares its extra minimum width by the columns' preferred widths, equally in automatic tables, #1883; previously 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 > **Floating anchor row segments:** 2026-11-07 · A floating anchor after a manual page/column break counts visible content on the far side of the same wrapped row. Marker-only cover anchors retain their previous-page rule. Synthetic picture spacing, placement and history controls; no new native Word measurement. Readiness estimates unchanged. @@ -67,7 +67,7 @@ Exact line spacing keeps the run font baseline around tall equations; automatic | List labels: number formats (decimal, letters, Russian letters, roman, ordinal text, Chinese/Japanese/Korean counting and legal, 一〇一 digits, 甲乙丙, ①…⑳, full-width), `%n` text such as `第%1章` / `(%1)`, legal numbering | ✅ | a level above that hasn't counted yet takes its first number at the first deeper item, as measured in Word: after 10.1–10.4 the next level-1 item is 11 (`doc::numbering::tests::a_deeper_item_first_counts_the_levels_above_it`); `doc::cjk_numbers` tests, `doc::section::tests::russian_letters_follow_word`, `layout::tests::chinese_counting_list_labels_and_their_font_runs`, `layout::tests::russian_letter_list_labels_draw_cyrillic`; a label mixing faces (digit + CJK comma) is drawn run by run (#534); Russian letters skip ё, й, ъ and ь and then double (аа, бб), as observed in Word. Hebrew, Hindi, Thai and Vietnamese formats show decimal; `arabicAlpha` and `arabicAbjad` draw Arabic letters, then double (أأ, بب) (`doc::section::tests::arabic_letters_count_in_both_orders`). The label stays attached to the start of the text when the paragraph is centred or aligned to the end, as in Word (#1159). A level with number format `none` is an ordinary level whose own number reads as nothing, as in Word for Windows (Microsoft 365, checked by MeHail-02): its label is its text with that number empty (`RESPONSE:`; `Part` above `%1.%2` gives `.1`), it counts and restarts the levels below it, it stays empty in legal numbering, and an empty label still tabs the text to the indent unless it already ends there (Heading 2 of the Chapter 1 list stays at the margin) (#4985; `doc::numbering::tests::a_none_level_shows_its_text_and_still_counts`, `layout::tests::a_none_format_label_shows_its_text_and_tabs_to_the_indent`). | — | | Body top below a tall header, footer pushes body up | ✅ | #138; a footer taller than the bottom margin moves the body bottom up (#453), and a header or footer linked to the previous section takes its room too (#454) | — | | Tables: row border exceptions (`w:tblPrEx/w:tblBorders`) | ✅ | `row_borders_stay_on_row`, `row_nil_overrides_style`: explicit cell borders win; row exceptions precede table styles and table borders | — | -| Footnotes at the page bottom, endnotes at the end, note numbering | 🟡 | A long note continues onto the next page at a line boundary (its first line stays with the reference), first in that page's note area under a full-width continuation separator (#352); the page it starts on keeps its last line on the bottom margin, the room left going above the separator, and widow control in the note's paragraph takes one more line along rather than leave its last line alone on the next page (measured in Word for Mac 16.113.4 with `cargo xtask word-compare`: a note pushed down the page one body line at a time); the document's own separator, continuation separator and continuation notice are drawn (the notice under a note that continues); on a page with footnotes a paragraph ending there keeps its space after above the separator, or its last lines go to the next page with the note (#1116); a long endnote continues on the next column or page at a line boundary (#456), and the caret finds note text on its continuation page (#457); each section's note options: footnotes below the text, endnotes at the end of each section, start at, numbering restarted each section or each page (counted from where the notes land, at most three passes) (#385) | 1–2 | +| Footnotes at the page bottom, endnotes at the end, note numbering | 🟡 | A long note continues onto the next page at a line boundary (its first line stays with the reference), first in that page's note area under a full-width continuation separator (#352); the page it starts on keeps its last line on the bottom margin, the room left going above the separator, and widow/orphan control in the note's paragraph keeps two of its lines on either side: one more line goes along rather than leave its last line alone on the next page, and the line with the reference goes on to the next page rather than leave the note's first line alone under it (measured in Word for Mac 16.113.4 with `cargo xtask word-compare`: a note pushed down the page one body line at a time); the document's own separator, continuation separator and continuation notice are drawn (the notice under a note that continues); on a page with footnotes a paragraph ending there keeps its space after above the separator, or its last lines go to the next page with the note (#1116); a long endnote continues on the next column or page at a line boundary (#456), and the caret finds note text on its continuation page (#457); each section's note options: footnotes below the text, endnotes at the end of each section, start at, numbering restarted each section or each page (counted from where the notes land, at most three passes) (#385) | 1–2 | | Tables: row heights (at least/exact), rows split across pages, header rows repeat, Can't Split | ✅ | 2026-10-06, #138; omitted cell-margin edges inherit current table defaults; every cell in a row gets the row's largest top and bottom margin; an exact height covers the top border, top margin and text, the bottom margin comes on top, and an exact row never splits; a row split across pages keeps its cells' bottom margin, border and last space after on the first page, widow/orphan control applies in its cells, each cell continues at the top of the next page and an at-least row keeps its minimum; an at-least row with less room than its minimum on a page that already holds something starts the next page whole (Allow row to break on or off, vAlign centre too), as observed in Word for Mac 2026-10-15 (a row of about 2.6 cm), #1742; that repeated header rows go with it and that a row taller than a page splits from the top of the next page come from the issue and synthetic tests, not a Word check (`…_an_at_least_row_with_no_room_starts_the_next_page_whole_either_way_breaking_is_set`, `…_an_at_least_row_taller_than_a_page_splits_from_the_top_of_the_next_page`, `layout::tests::a_row_shares_its_largest_top_and_bottom_margins`, `…_a_split_row_keeps_its_bottom_margin_and_widow_control`, `…_split_row_cells_each_continue_at_the_top`); a row's `gridAfter` is bounded to 63 columns in native documents too, and repeated header rows stop after 500 000 copied items across a table (hostile documents, #3692); a cell aligned to the middle or bottom of a split row is aligned within the part left on the page when all its text fits there (as tall as the other cells' text there), and runs from the top of the cell otherwise, as measured in Word (`layout::tests::a_middle_or_bottom_cell_of_a_split_row_lines_up_on_the_first_page`); a row whose first part on a page that already holds something would leave a cell empty there, because that cell's first line or inline picture (one line, never split) runs past the room, moves on whole instead of leaving the other cells' text beside the empty cell, so an at-least row grown taller than its minimum by a picture no longer splits off its picture (#4272; inferred from the reporter's Word result and the earlier observation that Word doesn't leave a cell empty for widow control, not yet checked in Word for rows without a minimum; at the top of a page such a row still splits; `layout::tests::an_at_least_row_grown_by_its_picture_moves_on_whole_rather_than_leave_the_picture_behind`, `…_a_picture_row_that_fits_stays_and_text_rows_beside_a_short_picture_still_split`, `…_a_picture_row_too_tall_for_any_page_splits_from_the_top_of_the_next_one`); a row of a nested table marked Can't Split isn't split with its outer row: the outer row moves on whole when that row comes first in it (docxide-pdf `nested-first-row-*-cant1`) and otherwise splits above it (inferred, not yet checked in Word), and on a fresh page a nested row taller than the room still splits; `layout::tests::nested_cant_split::nested_cant_split_row_moves_on_with_its_outer_row`, `…::the_outer_row_splits_above_a_nested_cant_split_row`, `…::the_cut_moves_up_until_no_nested_cant_split_row_runs_through_it`, `…::the_outer_row_breaks_between_nested_cant_split_rows_above_its_bottom_band`, `…::a_bottom_aligned_cell_keeps_its_nested_cant_split_row_whole`, `…::header_rows_go_on_with_a_first_row_whose_nested_cant_split_row_comes_first`, `…::a_kept_row_goes_on_with_a_row_whose_nested_cant_split_row_cant_start_below_it`, `…::a_merged_cell_doesnt_stretch_its_cant_split_row`, `…::nested_cant_split_row_taller_than_a_page_still_splits` | — | | Tables: autofit to contents/window, fixed widths, Word 2013 edge | 🟡 | #137; #44: AutoFit Contents measures each column's narrowest and widest text and shares the width like Word, once (not live as you type); consistent a percentage width past 100% is kept, as Word does; a table with its own preferred width keeps it, however far past the margin, and only an automatic-width table over 1.5× the text width is squeezed to the margins (Word squeezes it as soon as it is wider) (#1721); cell widths override stale grid proportions when their totals agree (`cell_widths_override_grid`); conflicting widths and spans still differ | 3–5 | | Floating tables (`w:tblpPr`) | 🟡 | #137; one placed on the page or margin that would cover visible text before it and does not fit below it moves to the next page (#534); empty line-break lines do not count as text; a click below one, outside its cells, goes to the text beside or after it, not to its last row, as checked in Word (#2038); exact line-bottom contact counts for tables only (#3977), both in row-span selection and word skipping; exact-spacing table contact uses the specified height rather than paragraph-mark metrics, with original Source Sans 3 controls in modes 11/12/14/15; expected Word rule from [cyril265's Word for Mac 16.114.1 measurements](https://github.com/storytold/wordcraft/issues/3977#issuecomment-6374217574), not a new Word run of these originals; anchor-order replay remains #3790's scope; other overlap rules untested | 2–3 | @@ -307,7 +307,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | Date | Change | Summary | |---|---|---| -| 2026-11-09 | trivial | A footnote continuing on the next page ends on the bottom margin of the page it starts on, the room left going above the separator, and widow control in its paragraph leaves two of its lines for the next page, as measured in Word for Mac 16.113.4 (`layout::tests::a_footnote_continuing_on_the_next_page_ends_on_the_bottom_margin`, `widow_control_leaves_two_lines_of_a_split_footnote_on_the_next_page`) | +| 2026-11-09 | trivial | A footnote continuing on the next page ends on the bottom margin of the page it starts on, the room left going above the separator, and widow/orphan control in its paragraph keeps two of its lines on either side of the split (the line with the reference goes on to the next page rather than leave the note's first line alone under it), as measured in Word for Mac 16.113.4 (`layout::tests::a_footnote_continuing_on_the_next_page_ends_on_the_bottom_margin`, `widow_control_leaves_two_lines_of_a_split_footnote_on_the_next_page`, `orphan_control_keeps_two_lines_of_a_split_footnote_with_its_reference`) | | 2026-11-08 | trivial | Turned inline pictures with no recorded effect extent keep their line to the frame (exchanged near a quarter turn in Word 2013+ layout) and overhang it, cut at the line's top and bottom, as in Word | | 2026-11-08 | trivial | Contextual spacing drops the space after a table cell's last paragraph in the Normal style, the end-of-cell mark counting as a Normal paragraph; another style keeps it, and a middle or bottom cell of a split row lines up without the dropped space (#5450) (`layout::tests::contextual_spacing_drops_the_space_after_a_cells_last_normal_paragraph`, `a_bottom_cell_of_a_split_row_ignores_a_dropped_space_after_beside_it`). | | 2026-11-04 | trivial | Header table measurements and fitted text-box heights use the page section’s PAGE format; cache reuse follows the field context | From 6997afcc346e44c0990b1b5f7ef94b7e093e0e03 Mon Sep 17 00:00:00 2001 From: Kevin Joseph Date: Mon, 9 Nov 2026 16:11:28 +0100 Subject: [PATCH 051/609] Word for Mac 16.114.4 is the version these were measured in, not 16.113.4 The commit messages before this one name 16.113.4 too; the measurements were made in the Word for Mac installed here, which reports 16.114.4. --- crates/layout/src/notes.rs | 2 +- crates/layout/src/page.rs | 2 +- crates/layout/src/tests.rs | 6 +++--- docs/layout-parity.md | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/layout/src/notes.rs b/crates/layout/src/notes.rs index 5168a1f4b1..297fb92c80 100644 --- a/crates/layout/src/notes.rs +++ b/crates/layout/src/notes.rs @@ -225,7 +225,7 @@ impl NoteBox { /// Whether widow/orphan control in the note's paragraphs forbids splitting at `cut`: a /// paragraph's first line alone above it (an orphan) or its last line alone below it (a - /// widow), as in Word for Mac 16.113.4. + /// widow), as in Word for Mac 16.114.4. pub(crate) fn breaks_widow_control(&self, cut: f32) -> bool { self.items.iter().filter(|it| self.splittable(it)).any(|it| { let Placed::Lines { para, l0, l1, y, .. } = it else { return false }; diff --git a/crates/layout/src/page.rs b/crates/layout/src/page.rs index 80123f214c..2de191ecc8 100644 --- a/crates/layout/src/page.rs +++ b/crates/layout/src/page.rs @@ -207,7 +207,7 @@ impl PageBuilder<'_> { break; } // Notes that continue on the next page still end on the bottom margin, the room left - // going above the separator (Word for Mac 16.113.4), unless they go beneath the text. + // going above the separator (Word for Mac 16.114.4), unless they go beneath the text. if !fits && !self.beneath { let shift = (self.orig_bottom - end).max(0.0); top += shift; diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 5b105c5dd7..5284c44bf6 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -9002,7 +9002,7 @@ fn long_note_after(body: usize, note: usize, widow: bool) -> (Document, u32) { #[test] fn a_footnote_continuing_on_the_next_page_ends_on_the_bottom_margin() { crate::test_fonts(); - // Observed in Word for Mac 16.113.4: whatever room the split leaves goes above the + // Observed in Word for Mac 16.114.4: whatever room the split leaves goes above the // separator, the note's last line on the page sitting on the bottom margin. let bottom = Document::default().last_section.page_h - Document::default().last_section.margin_bottom; let mut slack = Vec::new(); @@ -9028,7 +9028,7 @@ fn a_footnote_continuing_on_the_next_page_ends_on_the_bottom_margin() { #[test] fn widow_control_leaves_two_lines_of_a_split_footnote_on_the_next_page() { crate::test_fonts(); - // Observed in Word for Mac 16.113.4: a note that would leave its last line alone on the next + // Observed in Word for Mac 16.114.4: a note that would leave its last line alone on the next // page takes one more line along when its paragraph has widow control. let lines_after = |body: usize, widow: bool| { let (d, id) = long_note_after(body, 60, widow); @@ -9045,7 +9045,7 @@ fn widow_control_leaves_two_lines_of_a_split_footnote_on_the_next_page() { #[test] fn orphan_control_keeps_two_lines_of_a_split_footnote_with_its_reference() { crate::test_fonts(); - // Observed in Word for Mac 16.113.4: rather than leave a note paragraph's first line alone at + // Observed in Word for Mac 16.114.4: rather than leave a note paragraph's first line alone at // the bottom of the page, the line with the reference goes on to the next page with it. let first_piece = |body: usize, widow: bool| { let (mut d, id) = long_note_after(body, 60, widow); diff --git a/docs/layout-parity.md b/docs/layout-parity.md index b357e601e6..96b1947d06 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -67,7 +67,7 @@ Exact line spacing keeps the run font baseline around tall equations; automatic | List labels: number formats (decimal, letters, Russian letters, roman, ordinal text, Chinese/Japanese/Korean counting and legal, 一〇一 digits, 甲乙丙, ①…⑳, full-width), `%n` text such as `第%1章` / `(%1)`, legal numbering | ✅ | a level above that hasn't counted yet takes its first number at the first deeper item, as measured in Word: after 10.1–10.4 the next level-1 item is 11 (`doc::numbering::tests::a_deeper_item_first_counts_the_levels_above_it`); `doc::cjk_numbers` tests, `doc::section::tests::russian_letters_follow_word`, `layout::tests::chinese_counting_list_labels_and_their_font_runs`, `layout::tests::russian_letter_list_labels_draw_cyrillic`; a label mixing faces (digit + CJK comma) is drawn run by run (#534); Russian letters skip ё, й, ъ and ь and then double (аа, бб), as observed in Word. Hebrew, Hindi, Thai and Vietnamese formats show decimal; `arabicAlpha` and `arabicAbjad` draw Arabic letters, then double (أأ, بب) (`doc::section::tests::arabic_letters_count_in_both_orders`). The label stays attached to the start of the text when the paragraph is centred or aligned to the end, as in Word (#1159). A level with number format `none` is an ordinary level whose own number reads as nothing, as in Word for Windows (Microsoft 365, checked by MeHail-02): its label is its text with that number empty (`RESPONSE:`; `Part` above `%1.%2` gives `.1`), it counts and restarts the levels below it, it stays empty in legal numbering, and an empty label still tabs the text to the indent unless it already ends there (Heading 2 of the Chapter 1 list stays at the margin) (#4985; `doc::numbering::tests::a_none_level_shows_its_text_and_still_counts`, `layout::tests::a_none_format_label_shows_its_text_and_tabs_to_the_indent`). | — | | Body top below a tall header, footer pushes body up | ✅ | #138; a footer taller than the bottom margin moves the body bottom up (#453), and a header or footer linked to the previous section takes its room too (#454) | — | | Tables: row border exceptions (`w:tblPrEx/w:tblBorders`) | ✅ | `row_borders_stay_on_row`, `row_nil_overrides_style`: explicit cell borders win; row exceptions precede table styles and table borders | — | -| Footnotes at the page bottom, endnotes at the end, note numbering | 🟡 | A long note continues onto the next page at a line boundary (its first line stays with the reference), first in that page's note area under a full-width continuation separator (#352); the page it starts on keeps its last line on the bottom margin, the room left going above the separator, and widow/orphan control in the note's paragraph keeps two of its lines on either side: one more line goes along rather than leave its last line alone on the next page, and the line with the reference goes on to the next page rather than leave the note's first line alone under it (measured in Word for Mac 16.113.4 with `cargo xtask word-compare`: a note pushed down the page one body line at a time); the document's own separator, continuation separator and continuation notice are drawn (the notice under a note that continues); on a page with footnotes a paragraph ending there keeps its space after above the separator, or its last lines go to the next page with the note (#1116); a long endnote continues on the next column or page at a line boundary (#456), and the caret finds note text on its continuation page (#457); each section's note options: footnotes below the text, endnotes at the end of each section, start at, numbering restarted each section or each page (counted from where the notes land, at most three passes) (#385) | 1–2 | +| Footnotes at the page bottom, endnotes at the end, note numbering | 🟡 | A long note continues onto the next page at a line boundary (its first line stays with the reference), first in that page's note area under a full-width continuation separator (#352); the page it starts on keeps its last line on the bottom margin, the room left going above the separator, and widow/orphan control in the note's paragraph keeps two of its lines on either side: one more line goes along rather than leave its last line alone on the next page, and the line with the reference goes on to the next page rather than leave the note's first line alone under it (measured in Word for Mac 16.114.4 with `cargo xtask word-compare`: a note pushed down the page one body line at a time); the document's own separator, continuation separator and continuation notice are drawn (the notice under a note that continues); on a page with footnotes a paragraph ending there keeps its space after above the separator, or its last lines go to the next page with the note (#1116); a long endnote continues on the next column or page at a line boundary (#456), and the caret finds note text on its continuation page (#457); each section's note options: footnotes below the text, endnotes at the end of each section, start at, numbering restarted each section or each page (counted from where the notes land, at most three passes) (#385) | 1–2 | | Tables: row heights (at least/exact), rows split across pages, header rows repeat, Can't Split | ✅ | 2026-10-06, #138; omitted cell-margin edges inherit current table defaults; every cell in a row gets the row's largest top and bottom margin; an exact height covers the top border, top margin and text, the bottom margin comes on top, and an exact row never splits; a row split across pages keeps its cells' bottom margin, border and last space after on the first page, widow/orphan control applies in its cells, each cell continues at the top of the next page and an at-least row keeps its minimum; an at-least row with less room than its minimum on a page that already holds something starts the next page whole (Allow row to break on or off, vAlign centre too), as observed in Word for Mac 2026-10-15 (a row of about 2.6 cm), #1742; that repeated header rows go with it and that a row taller than a page splits from the top of the next page come from the issue and synthetic tests, not a Word check (`…_an_at_least_row_with_no_room_starts_the_next_page_whole_either_way_breaking_is_set`, `…_an_at_least_row_taller_than_a_page_splits_from_the_top_of_the_next_page`, `layout::tests::a_row_shares_its_largest_top_and_bottom_margins`, `…_a_split_row_keeps_its_bottom_margin_and_widow_control`, `…_split_row_cells_each_continue_at_the_top`); a row's `gridAfter` is bounded to 63 columns in native documents too, and repeated header rows stop after 500 000 copied items across a table (hostile documents, #3692); a cell aligned to the middle or bottom of a split row is aligned within the part left on the page when all its text fits there (as tall as the other cells' text there), and runs from the top of the cell otherwise, as measured in Word (`layout::tests::a_middle_or_bottom_cell_of_a_split_row_lines_up_on_the_first_page`); a row whose first part on a page that already holds something would leave a cell empty there, because that cell's first line or inline picture (one line, never split) runs past the room, moves on whole instead of leaving the other cells' text beside the empty cell, so an at-least row grown taller than its minimum by a picture no longer splits off its picture (#4272; inferred from the reporter's Word result and the earlier observation that Word doesn't leave a cell empty for widow control, not yet checked in Word for rows without a minimum; at the top of a page such a row still splits; `layout::tests::an_at_least_row_grown_by_its_picture_moves_on_whole_rather_than_leave_the_picture_behind`, `…_a_picture_row_that_fits_stays_and_text_rows_beside_a_short_picture_still_split`, `…_a_picture_row_too_tall_for_any_page_splits_from_the_top_of_the_next_one`); a row of a nested table marked Can't Split isn't split with its outer row: the outer row moves on whole when that row comes first in it (docxide-pdf `nested-first-row-*-cant1`) and otherwise splits above it (inferred, not yet checked in Word), and on a fresh page a nested row taller than the room still splits; `layout::tests::nested_cant_split::nested_cant_split_row_moves_on_with_its_outer_row`, `…::the_outer_row_splits_above_a_nested_cant_split_row`, `…::the_cut_moves_up_until_no_nested_cant_split_row_runs_through_it`, `…::the_outer_row_breaks_between_nested_cant_split_rows_above_its_bottom_band`, `…::a_bottom_aligned_cell_keeps_its_nested_cant_split_row_whole`, `…::header_rows_go_on_with_a_first_row_whose_nested_cant_split_row_comes_first`, `…::a_kept_row_goes_on_with_a_row_whose_nested_cant_split_row_cant_start_below_it`, `…::a_merged_cell_doesnt_stretch_its_cant_split_row`, `…::nested_cant_split_row_taller_than_a_page_still_splits` | — | | Tables: autofit to contents/window, fixed widths, Word 2013 edge | 🟡 | #137; #44: AutoFit Contents measures each column's narrowest and widest text and shares the width like Word, once (not live as you type); consistent a percentage width past 100% is kept, as Word does; a table with its own preferred width keeps it, however far past the margin, and only an automatic-width table over 1.5× the text width is squeezed to the margins (Word squeezes it as soon as it is wider) (#1721); cell widths override stale grid proportions when their totals agree (`cell_widths_override_grid`); conflicting widths and spans still differ | 3–5 | | Floating tables (`w:tblpPr`) | 🟡 | #137; one placed on the page or margin that would cover visible text before it and does not fit below it moves to the next page (#534); empty line-break lines do not count as text; a click below one, outside its cells, goes to the text beside or after it, not to its last row, as checked in Word (#2038); exact line-bottom contact counts for tables only (#3977), both in row-span selection and word skipping; exact-spacing table contact uses the specified height rather than paragraph-mark metrics, with original Source Sans 3 controls in modes 11/12/14/15; expected Word rule from [cyril265's Word for Mac 16.114.1 measurements](https://github.com/storytold/wordcraft/issues/3977#issuecomment-6374217574), not a new Word run of these originals; anchor-order replay remains #3790's scope; other overlap rules untested | 2–3 | @@ -307,7 +307,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | Date | Change | Summary | |---|---|---| -| 2026-11-09 | trivial | A footnote continuing on the next page ends on the bottom margin of the page it starts on, the room left going above the separator, and widow/orphan control in its paragraph keeps two of its lines on either side of the split (the line with the reference goes on to the next page rather than leave the note's first line alone under it), as measured in Word for Mac 16.113.4 (`layout::tests::a_footnote_continuing_on_the_next_page_ends_on_the_bottom_margin`, `widow_control_leaves_two_lines_of_a_split_footnote_on_the_next_page`, `orphan_control_keeps_two_lines_of_a_split_footnote_with_its_reference`) | +| 2026-11-09 | trivial | A footnote continuing on the next page ends on the bottom margin of the page it starts on, the room left going above the separator, and widow/orphan control in its paragraph keeps two of its lines on either side of the split (the line with the reference goes on to the next page rather than leave the note's first line alone under it), as measured in Word for Mac 16.114.4 (`layout::tests::a_footnote_continuing_on_the_next_page_ends_on_the_bottom_margin`, `widow_control_leaves_two_lines_of_a_split_footnote_on_the_next_page`, `orphan_control_keeps_two_lines_of_a_split_footnote_with_its_reference`) | | 2026-11-08 | trivial | Turned inline pictures with no recorded effect extent keep their line to the frame (exchanged near a quarter turn in Word 2013+ layout) and overhang it, cut at the line's top and bottom, as in Word | | 2026-11-08 | trivial | Contextual spacing drops the space after a table cell's last paragraph in the Normal style, the end-of-cell mark counting as a Normal paragraph; another style keeps it, and a middle or bottom cell of a split row lines up without the dropped space (#5450) (`layout::tests::contextual_spacing_drops_the_space_after_a_cells_last_normal_paragraph`, `a_bottom_cell_of_a_split_row_ignores_a_dropped_space_after_beside_it`). | | 2026-11-04 | trivial | Header table measurements and fitted text-box heights use the page section’s PAGE format; cache reuse follows the field context | From f211d2914a34656381d6152f453be42de19d4914 Mon Sep 17 00:00:00 2001 From: Max Murphy Date: Tue, 10 Nov 2026 20:03:10 +0100 Subject: [PATCH 052/609] M15 #1: list every docx-corpus option in xtask help; record the harness in gap #1 The top-level help listed only --dir and --out, hiding --all-pages, --timeout and --cli. The ranked gap #1 row still said the DOCX fidelity corpus was not started; it now records that the runner is complete while the real-world corpus and the Word comparison remain, so the gap stays open. Status lines and revision histories follow the repo convention. Signed-off-by: Max Murphy --- ROADMAP.md | 2 +- docs/gaps.md | 6 ++++-- xtask/src/main.rs | 4 +++- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 0ba1319cb6..649c82a17b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,6 +1,6 @@ # WordCraft roadmap -> **Last reviewed:** 2026-10-31 · **Last updated:** 2026-10-31 · **Change:** minor (#3398: persistent screen paper colors; parity estimates unchanged); previously minor (#3693: additional Delete Previous Sentence command and shortcut; Word-parity estimates unchanged) +> **Last reviewed:** 2026-10-31 · **Last updated:** 2026-11-10 · **Change:** trivial (the opt-in `cargo xtask docx-corpus` harness can run a local DOCX corpus; no corpus or Word comparison is checked in, so readiness estimates are unchanged); previously minor (#3398: persistent screen paper colors; parity estimates unchanged); previously minor (#3693: additional Delete Previous Sentence command and shortcut; Word-parity estimates unchanged) > **CLI path update:** 2026-11-04 · Options before a non-Unicode input filename no longer make the CLI reject that filename; text option values still require Unicode; `run --file` and `run --script` retain native paths. No ranked gap or readiness estimate changes. > **Floating anchor row segments:** 2026-11-07 · A floating anchor after a manual page/column break counts visible content on the far side of the same wrapped row. Marker-only cover anchors retain their previous-page rule. Synthetic picture spacing, placement and history controls; no new native Word measurement. Readiness estimates unchanged. diff --git a/docs/gaps.md b/docs/gaps.md index 80d2e148a8..238d7aac68 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -2,7 +2,7 @@ > **CLI path update:** 2026-11-04 · Options before a non-Unicode input filename no longer make the CLI reject that filename; text option values still require Unicode; `run --file` and `run --script` retain native paths. No ranked gap or readiness estimate changes. -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** trivial (#19: ODT default language kept when styles are written from the model); previously trivial (#10 narrowed: a turned inline picture whose file keeps no room for the turn keeps its line to its frame, as in Word); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously 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 (gap 4: a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (Drawing Canvas members picked and moved on their own, #2637); previously trivial (gap 4: a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (#29: typed `\int`, `\sum`… + Space wait for their limits, observed in Word for Windows on #4938, #4917); previously trivial (only the PDF sent to the printer leaves out link annotations; Save these pages as PDF keeps them, #4734; no ranked gap changed); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (gap 6: a print job waiting on its driver can be cancelled, #5710; no ranked gap changed); previously trivial (gap 6: the printer list no longer waits on printer drivers, #5710; no ranked gap changed); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` defaults true and is written in schema order); previously trivial (ink page lookups reuse scanned paragraph prefixes, #3614); previously trivial (#19: ODT settings for what the standard leaves open removed); previously trivial (#19: ODT element audit; files from other applications checked); previously trivial (#11: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (#4: fonts that aren't installed are flagged in the font box and status bar); previously trivial (#19: ODT sections inside text boxes kept as read); previously trivial (#19: an ODT saved without edits keeps what WordCraft doesn't model); previously trivial (#19: ODT interpretation profile, WordCraft / LibreOffice / custom); previously trivial (#19: ODT form controls placed and multi-line; custom shapes keep their geometry); previously trivial (#19: ODT in-line frames placed against the text; template instantiation listed as left); previously trivial (#19: ODT charts kept as read; frame outlines; default header height); previously trivial (#19: ODT tables no longer gain repeated header rows); previously trivial (#19: ODT padding without a border, unequal columns, column breaks, picture-only lines); previously trivial (#19: ODT tables' margins and spacing, header spacing, pictures alone in a paragraph); previously trivial (#19: no LibreOffice template changes page count through a save); previously trivial (#19: ODT variables, emphasis marks, page backgrounds, fixed tables, default size); previously trivial (#19: ODT checked against LibreOffice's own templates: placeholders, first-page styles, unsized pages, metafile logos, `.ott`); previously trivial (#19: ODT at ~90%: custom shapes, cell formulas, macros kept, turned text, control sizes and buttons); previously trivial (#19 narrowed: ODT read and written nearly whole; estimate 18–27 h → 10–16 h); previously trivial (#10 narrowed: text in a turned text box is drawn turned with it); previously trivial (gap 19 narrowed: ODT heading numbering read and written); previously trivial (gap 19 narrowed: ODT table borders and padding read and written); previously trivial (gap 19 narrowed: ODT heading style looks read and written); previously trivial (gap 19 narrowed: ODT tab stops read and written); previously trivial (gap 19 narrowed: ODT character formatting read and written); previously trivial (gap 19 narrowed: ODT list formats read and written); previously trivial (gap 19 narrowed: ODT comments read and written); previously trivial (gap 19 narrowed: ODT footnotes and endnotes read and written); previously trivial (gap 19 narrowed: ODT headers and footers written, text fields and paragraph spacing read and written); previously trivial (#8: Options › Language lists Your languages and Add a language… replaces the Language packs table); previously trivial (#8: the missing-pack bar works on a fresh install and counts the caret's language); previously trivial (#8: Language pack languages are in Set Proofing Language, Review › Language and the status bar; built-in proofing is named as such); previously trivial (#20: layout resource caps and linear-time passes (#3867, #3866)); previously trivial (#3 narrowed: a pasted text box story is charged for the formatting it copies); previously trivial (#3 narrowed: a .doc table row keeps one override per cell); previously trivial (#3 narrowed: a .doc file's sections find their paragraphs by index); previously minor (#11: Arabic interface with mirrored shell landed, #1195; hi/id/pt-PT and Hebrew UI remain); previously trivial (#8: language-packs-2 is published and pinned: 75 packs, adding Danish, German (Germany, Austria, Switzerland), Esperanto, Estonian, Persian, Croatian, Hungarian, Norwegian (Bokmål, Nynorsk), Dutch and Swedish (Sweden, Finland); no ranked gap changed); previously trivial (#8: language-packs-1 is published and pinned, 61 packs: Lithuanian, Romanian, Catalan, French, Greek, Slovak, Serbian and Latvian install as Language packs; Dutch, German and the other compounding languages wait on craft-proof; no ranked gap changed); previously minor (#8: Language packs: every other language's spelling and hyphenation installs from File › Options › Language or the missing-pack bar, through the font store; Lithuanian and Romanian are available as a Language pack once language-packs-1 is published; Dutch, Catalan, French, Greek, Slovak, Serbian and Latvian packs wait on craft-proof engine support); previously trivial (gap 8: English spelling reads SCOWL 2026, one dictionary per English, #40, #520, #5205; no ranked gap changed);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (#26 narrowed: MHT opens and `w:altChunk` content is brought in on open; saving MHT remains) previously trivial (gap 8 points at craft-proof in craft-libs, its data in craft-i18n, #5202; no ranked gap changed); previously trivial (arrowheads keep their kind, width and length and are drawn at Word's sizes; no ranked gap changed); previously trivial (.doc default font from the stylesheet's standard font, #5066; no ranked gap changed); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page; no ranked gap changed); previously trivial (tab leader dots spaced and placed as in Word; no ranked gap changed); previously trivial (a list level above counts its first number at the first deeper item; no ranked gap changed); previously trivial (only the PDF sent to the printer leaves out link annotations; Save these pages as PDF keeps them, #4734; no ranked gap changed); previously trivial (documents with links print: the print job leaves out link annotations, #4734; no ranked gap changed; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion reference-run membership uses one ordered walk, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (gap 19: RTF reads and writes WMF and EMF pictures, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously 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-11-10 · **Change:** trivial (gap #1: the opt-in `cargo xtask docx-corpus` harness is complete; no real-world corpus or Word comparison is checked in, so the gap stays open); previously trivial (#19: ODT default language kept when styles are written from the model); previously trivial (#10 narrowed: a turned inline picture whose file keeps no room for the turn keeps its line to its frame, as in Word); previously trivial (Protected typing boundary lookup counts preceding objects once and indexes editable permission IDs (#3614); caret movement and enforcement policy are unchanged; previously 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 (gap 4: a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (Drawing Canvas members picked and moved on their own, #2637); previously trivial (gap 4: a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (#29: typed `\int`, `\sum`… + Space wait for their limits, observed in Word for Windows on #4938, #4917); previously trivial (only the PDF sent to the printer leaves out link annotations; Save these pages as PDF keeps them, #4734; no ranked gap changed); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (gap 6: a print job waiting on its driver can be cancelled, #5710; no ranked gap changed); previously trivial (gap 6: the printer list no longer waits on printer drivers, #5710; no ranked gap changed); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (built-in citation source lookups, #4888; current-main progress records retained); previously trivial (MATH construction reuse, #3630); previously trivial (DOCX `w:adjustRightInd` defaults true and is written in schema order); previously trivial (ink page lookups reuse scanned paragraph prefixes, #3614); previously trivial (#19: ODT settings for what the standard leaves open removed); previously trivial (#19: ODT element audit; files from other applications checked); previously trivial (#11: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously trivial (#4: fonts that aren't installed are flagged in the font box and status bar); previously trivial (#19: ODT sections inside text boxes kept as read); previously trivial (#19: an ODT saved without edits keeps what WordCraft doesn't model); previously trivial (#19: ODT interpretation profile, WordCraft / LibreOffice / custom); previously trivial (#19: ODT form controls placed and multi-line; custom shapes keep their geometry); previously trivial (#19: ODT in-line frames placed against the text; template instantiation listed as left); previously trivial (#19: ODT charts kept as read; frame outlines; default header height); previously trivial (#19: ODT tables no longer gain repeated header rows); previously trivial (#19: ODT padding without a border, unequal columns, column breaks, picture-only lines); previously trivial (#19: ODT tables' margins and spacing, header spacing, pictures alone in a paragraph); previously trivial (#19: no LibreOffice template changes page count through a save); previously trivial (#19: ODT variables, emphasis marks, page backgrounds, fixed tables, default size); previously trivial (#19: ODT checked against LibreOffice's own templates: placeholders, first-page styles, unsized pages, metafile logos, `.ott`); previously trivial (#19: ODT at ~90%: custom shapes, cell formulas, macros kept, turned text, control sizes and buttons); previously trivial (#19 narrowed: ODT read and written nearly whole; estimate 18–27 h → 10–16 h); previously trivial (#10 narrowed: text in a turned text box is drawn turned with it); previously trivial (gap 19 narrowed: ODT heading numbering read and written); previously trivial (gap 19 narrowed: ODT table borders and padding read and written); previously trivial (gap 19 narrowed: ODT heading style looks read and written); previously trivial (gap 19 narrowed: ODT tab stops read and written); previously trivial (gap 19 narrowed: ODT character formatting read and written); previously trivial (gap 19 narrowed: ODT list formats read and written); previously trivial (gap 19 narrowed: ODT comments read and written); previously trivial (gap 19 narrowed: ODT footnotes and endnotes read and written); previously trivial (gap 19 narrowed: ODT headers and footers written, text fields and paragraph spacing read and written); previously trivial (#8: Options › Language lists Your languages and Add a language… replaces the Language packs table); previously trivial (#8: the missing-pack bar works on a fresh install and counts the caret's language); previously trivial (#8: Language pack languages are in Set Proofing Language, Review › Language and the status bar; built-in proofing is named as such); previously trivial (#20: layout resource caps and linear-time passes (#3867, #3866)); previously trivial (#3 narrowed: a pasted text box story is charged for the formatting it copies); previously trivial (#3 narrowed: a .doc table row keeps one override per cell); previously trivial (#3 narrowed: a .doc file's sections find their paragraphs by index); previously minor (#11: Arabic interface with mirrored shell landed, #1195; hi/id/pt-PT and Hebrew UI remain); previously trivial (#8: language-packs-2 is published and pinned: 75 packs, adding Danish, German (Germany, Austria, Switzerland), Esperanto, Estonian, Persian, Croatian, Hungarian, Norwegian (Bokmål, Nynorsk), Dutch and Swedish (Sweden, Finland); no ranked gap changed); previously trivial (#8: language-packs-1 is published and pinned, 61 packs: Lithuanian, Romanian, Catalan, French, Greek, Slovak, Serbian and Latvian install as Language packs; Dutch, German and the other compounding languages wait on craft-proof; no ranked gap changed); previously minor (#8: Language packs: every other language's spelling and hyphenation installs from File › Options › Language or the missing-pack bar, through the font store; Lithuanian and Romanian are available as a Language pack once language-packs-1 is published; Dutch, Catalan, French, Greek, Slovak, Serbian and Latvian packs wait on craft-proof engine support); previously trivial (gap 8: English spelling reads SCOWL 2026, one dictionary per English, #40, #520, #5205; no ranked gap changed);; previously trivial (DOCX table rows and cells inside selected alternate-content branches survive open and repeated saves (#5219); broader corpus qualification and readiness estimates unchanged); previously trivial (#26 narrowed: MHT opens and `w:altChunk` content is brought in on open; saving MHT remains) previously trivial (gap 8 points at craft-proof in craft-libs, its data in craft-i18n, #5202; no ranked gap changed); previously trivial (arrowheads keep their kind, width and length and are drawn at Word's sizes; no ranked gap changed); previously trivial (.doc default font from the stylesheet's standard font, #5066; no ranked gap changed); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page; no ranked gap changed); previously trivial (tab leader dots spaced and placed as in Word; no ranked gap changed); previously trivial (a list level above counts its first number at the first deeper item; no ranked gap changed); previously trivial (only the PDF sent to the printer leaves out link annotations; Save these pages as PDF keeps them, #4734; no ranked gap changed); previously trivial (documents with links print: the print job leaves out link annotations, #4734; no ranked gap changed; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion reference-run membership uses one ordered walk, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (gap 19: RTF reads and writes WMF and EMF pictures, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously 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 > **Page Setup update:** 2026-11-07 · Page Setup number boxes keep long input inside the field, including accepted margin values after focus leaves (#5650); accepted ranges and readiness estimates are unchanged. > **Floating anchor row segments:** 2026-11-07 · A floating anchor after a manual page/column break counts visible content on the far side of the same wrapped row. Marker-only cover anchors retain their previous-page rule. Synthetic picture spacing, placement and history controls; no new native Word measurement. Readiness estimates unchanged. @@ -81,7 +81,7 @@ Page drawing indexes text-box warp lookups by paragraph and story for the curren | # | Gap | B | Evidence | Impact | Hours | Doc | |---|---|---|---|---|---|---| -| 1 | **DOCX never tested on real-world files.** No corpus of files from Word, Google Docs, LibreOffice and Pages has been opened, rendered and round-tripped and compared with Word page by page | B | No corpus in the repo; `crates/docx/tests` are synthetic fixtures (including omitted/empty paragraph defaults and imported TOC range preservation); "DOCX fidelity corpus: not started" since 2026-10-06. Field reports fixed one by one: a cover page's theme-coloured shapes (#611), freeforms inside groups and text-box margins and Resize to fit (#743), shape gradients and transparency (#1500), cover-page positions relative to the page and freeforms drawn back to their start (#743), Word's text watermark in headers, read and written (#1290), VML freeform rule lines in headers, and `flowChartOr` drawn with its spokes (#1644); explicit DrawingML outline dashes and flat/square/round caps preserved; paragraph-relative header/footer/cell/text-box float origins corrected (cu20we, synthetic regressions) | Everyone: the files people receive are the files that break | 30–50 | [file-format-parity.md](file-format-parity.md) | +| 1 | **DOCX never tested on real-world files.** No corpus of files from Word, Google Docs, LibreOffice and Pages has been opened, rendered and round-tripped and compared with Word page by page | B | No corpus in the repo; `crates/docx/tests` are synthetic fixtures (including omitted/empty paragraph defaults and imported TOC range preservation); "DOCX fidelity corpus: not started" since 2026-10-06; the `cargo xtask docx-corpus` runner (open, render, save and reopen every `.docx` under a local directory, reporting text and page-count differences) is complete, but no real-world corpus is checked in and no Word comparison exists yet. Field reports fixed one by one: a cover page's theme-coloured shapes (#611), freeforms inside groups and text-box margins and Resize to fit (#743), shape gradients and transparency (#1500), cover-page positions relative to the page and freeforms drawn back to their start (#743), Word's text watermark in headers, read and written (#1290), VML freeform rule lines in headers, and `flowChartOr` drawn with its spokes (#1644); explicit DrawingML outline dashes and flat/square/round caps preserved; paragraph-relative header/footer/cell/text-box float origins corrected (cu20we, synthetic regressions) | Everyone: the files people receive are the files that break | 30–50 | [file-format-parity.md](file-format-parity.md) | | 3 | **Crashes and freezes in the field**: startup crash on Intel UHD Graphics (#170, open), a crash on macOS 12.7.6 Intel (#979, open) (lag on GPUs without a DirectX 12 driver fixed, #316; 32-bit Windows exited at launch because DirectX 12 graphics pipeline creation failed, now OpenGL), freezes (#59 Thai fonts and #31 font selector, both open; #77 closed), broken shape tool (#142, open); the Windows 11 no-write-without-admin (#218) and unmovable images (#82) reports are closed (pictures and shapes in Behind Text drag through the text over them, #1313); memory growth on every font change fixed (#848: the font list no longer loads each family it previews) | B | 197 open issues (2026-10-12), among them the crash and freeze reports #170, #979, #59 and #31 | Anyone hit loses work or trust; the never-crash standard covers panics, not hangs or GPU driver faults | 20–30 | [target-app-parity.md](target-app-parity.md) (Stability) | | 4 | **Pagination differs from Word**: Aptos has no metric-matched substitute; legacy compatibility options only partially covered; no page-by-page comparison harness | B | In-line pictures raised or lowered (`w:position`) set their line's height as in Word, past their own height too (#3984, #5796). SECTIONPAGES now counts shared continuous-section pages in body and header/footer fields; legacy same-style cell spacing preserved for measured modes 11/12/14, with mode 15 and non-cell controls; Contextual spacing corrected in body/header probes and repeated table-cell runs; [layout-parity.md](layout-parity.md); [typing-parity.md](typing-parity.md) Known gaps; non-overlapping body floating tables clear header tables; stray labels on page-break-only list paragraphs fixed multi-paragraph field-code blank lines fixed; centred numbered heading labels after leading page breaks fixed (#2964); Arial Unicode MS no longer selects monospace substitutes; a slash opening a word travels whole to the next line (#2963) 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, so a TOC entry's page number keeps its leader (#1840). A floating object anchored on a later page of a long paragraph is drawn on that page, also when footnotes or widow control move its line on (#4250). Fonts the document uses that aren't installed are flagged in the font box and status bar, except those drawn in a metric-compatible substitute (Carlito for Calibri, Liberation Sans for Arial) and symbol-font text (Symbol, Wingdings, Webdings), so the user knows when line breaks can differ from where the document was made; `font.missing` lists the substituted fonts in the text the current view lays out (capped, for hostile documents), marking the metric-compatible ones `metricCompatible`. | Page counts and line breaks differ, which matters for forms, legal and academic work | 30–50 + owner (font) | [layout-parity.md](layout-parity.md) | | 4 | **Pagination differs from Word**: Aptos has no metric-matched substitute; legacy compatibility options only partially covered; no page-by-page comparison harness | B | SECTIONPAGES now counts shared continuous-section pages in body and header/footer fields; legacy same-style cell spacing preserved for measured modes 11/12/14, with mode 15 and non-cell controls; Contextual spacing corrected in body/header probes and repeated table-cell runs; [layout-parity.md](layout-parity.md); [typing-parity.md](typing-parity.md) Known gaps; non-overlapping body floating tables clear header tables; stray labels on page-break-only list paragraphs fixed multi-paragraph field-code blank lines fixed; centred numbered heading labels after leading page breaks fixed (#2964); Arial Unicode MS no longer selects monospace substitutes; a slash opening a word travels whole to the next line (#2963) 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, so a TOC entry's page number keeps its leader (#1840). A floating object anchored on a later page of a long paragraph is drawn on that page, also when footnotes or widow control move its line on (#4250); one anchored right after a page break, before text, is drawn on the new page (#4262). Fonts the document uses that aren't installed are flagged in the font box and status bar, except those drawn in a metric-compatible substitute (Carlito for Calibri, Liberation Sans for Arial) and symbol-font text (Symbol, Wingdings, Webdings), so the user knows when line breaks can differ from where the document was made; `font.missing` lists the substituted fonts in the text the current view lays out (capped, for hostile documents), marking the metric-compatible ones `metricCompatible`. | Page counts and line breaks differ, which matters for forms, legal and academic work | 30–50 + owner (font) | [layout-parity.md](layout-parity.md) | @@ -181,6 +181,8 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text ## Revision history +> 2026-11-10 · Gap 1: the opt-in `cargo xtask docx-corpus` runner opens, renders, saves and reopens a local `.docx` directory and reports text and page-count differences; no corpus is checked in and no Word comparison exists, so the gap stays open and readiness is unchanged. + > 2026-11-03 · Section `w:chapStyle` values now preserve the complete unsigned-byte range, including 10; values above 255 are rejected. > 2026-11-05 · Gap 16: Arabic letters join across a change of formatting and past hidden or deleted text (#4093); readiness unchanged. diff --git a/xtask/src/main.rs b/xtask/src/main.rs index a134fc7a09..be62554ce4 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -33,8 +33,10 @@ commands: (stops at first failure) corpus [--download] show where test corpora live; --download fetches PngSuite into corpus/pngsuite - docx-corpus --dir [--out ] + docx-corpus --dir [--out ] [--all-pages] [--timeout ] [--cli ] open, render and round-trip every .docx under a local corpus; writes JSON + Markdown + (--all-pages renders every page; --cli uses an existing wordcraft-cli; + `docx-corpus --help` lists all options) stats [--exact] count tests and lines per crate (--exact: ask the test harness via `-- --list`) parity recompute the Word feature-parity summary in docs/parity-checklist.md visual-diff [--private] [--dpi N] From 3c159e233172fca70cfa12039dc0069accd6b8cb Mon Sep 17 00:00:00 2001 From: fluorine Date: Tue, 10 Nov 2026 16:04:10 -0400 Subject: [PATCH 053/609] Canvas: keep the arrow off the paper, show the text pointer only over a page The grey around and between pages and the rulers showed the I-beam although no text can be typed there. They keep the arrow now; a drag begun on the page keeps its I-beam. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/canvas.rs | 6 +++++- crates/ui-egui/src/canvas/tests.rs | 29 +++++++++++++++++++++++++++++ crates/ui-egui/src/ibeam.rs | 14 +++++--------- 3 files changed, 39 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index af20588859..8da9e1320a 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1417,7 +1417,11 @@ fn finish_canvas_frame(finish: CanvasFinish<'_>, out: egui::scroll_area::ScrollA || latest.and_then(|p| page_at(&rects, layout, geo.scale, p)).is_some_and(|(pg, x, y)| layout.selection_bar_at(pg, x, y).is_some())); // An armed Format Painter shows over the text, as Word's brush does; egui has no brush, // so the copy pointer stands in (#3453). The selection bar keeps its arrow. - let fallback = if in_bar { + // Off the paper (the rulers, the grey around and between pages) no text can be typed: + // the arrow stays. A drag that started on the page keeps its I-beam. + let on_paper = + latest.is_some_and(|p| area.contains(p) && on_visible_page(&rects, &geo.bands, p)) || app.canvas.unit_drag.is_some() || resp.dragged(); + let fallback = if in_bar || !on_paper { egui::CursorIcon::Default } else if app.session.painter.is_some() { egui::CursorIcon::Copy diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 62772c4b8d..16f2c2bc09 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1163,6 +1163,35 @@ fn an_armed_format_painter_changes_the_pointer() { assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "the selection bar keeps its arrow"); } +/// The text pointer shows over the paper only: the grey beside a page keeps the arrow. +#[test] +fn the_text_pointer_stays_off_the_grey_around_the_page() { + let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default()); + a.run("text.insert", json!({"text": "Some text"})).unwrap(); + a.run("view.commentsPane", json!({"value": false})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut WordApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + a, + ); + for _ in 0..6 { + h.step(); + } + let c = h.state_mut().session.layout().caret(&Pos::body(0, 4)).expect("caret"); + let y = c.top + c.height / 2.0; + let on_page = page_to_screen(h.state_mut(), c.page, c.x, y).expect("on screen"); + let beside = page_to_screen(h.state_mut(), c.page, -40.0, y).expect("on screen"); + h.event(egui::Event::PointerMoved(on_page)); + h.step(); + assert_ne!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "text pointer on the paper"); + h.event(egui::Event::PointerMoved(beside)); + h.step(); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "arrow on the grey beside the page"); +} + /// #4410: with the Format Painter armed, a double-click on a word paints that word, and the /// painter goes off again (it was only dragging across the text that painted it). #[test] diff --git a/crates/ui-egui/src/ibeam.rs b/crates/ui-egui/src/ibeam.rs index ccb811c807..ff64395b4d 100644 --- a/crates/ui-egui/src/ibeam.rs +++ b/crates/ui-egui/src/ibeam.rs @@ -163,18 +163,14 @@ mod tests { } } - /// #1746 review: off the shown page (the gap between pages, the seam where Hide White Space - /// cuts the margins) the I-beam contrasts with the canvas, not the paper. With the dark page - /// the two differ: white over the page, black over the light canvas. + /// Off the shown page (the gap between pages, the seam where Hide White Space cuts the + /// margins) no I-beam is drawn: the arrow shows, and over the page it is white on the dark page. #[test] - fn the_drawn_i_beam_takes_the_canvas_colour_off_the_page() { + fn the_drawn_i_beam_stays_on_the_page() { let text = vec!["A line of text to fill the pages."; 120].join("\n"); let mut h = window_at(true, true, 1.0, 800.0, &text); h.state_mut().session.view.zoom = 0.5; h.run_steps(3); - let canvas = crate::theme::Tokens::get(&h.ctx).canvas; - let off = crate::canvas::caret_contrast(wordcraft_doc::props::Rgb(canvas.r(), canvas.g(), canvas.b())); - assert_eq!(off, Color32::BLACK, "the light canvas"); // The fill is drawn last. let fill = |h: &mut H, at: egui::Pos2| stem_strokes(h, at).last().map(|s| s.color); let rects = h.state_mut().canvas.page_rects.clone(); @@ -183,7 +179,7 @@ mod tests { let gap = egui::pos2(x, (rects[0].max.y + rects[1].min.y) / 2.0); assert!(rects[0].max.y < gap.y && gap.y < rects[1].min.y, "a gap between the pages: {rects:?}"); assert_eq!(fill(&mut h, egui::pos2(x, rects[0].center().y)), Some(Color32::WHITE), "on the dark page"); - assert_eq!(fill(&mut h, gap), Some(off), "between the pages"); + assert_eq!(fill(&mut h, gap), None, "between the pages"); // On the seam where Hide White Space cuts page 1's bottom margin and page 2's top. assert!(h.state_mut().run("view.hideWhiteSpace", serde_json::json!({"value": true})).is_ok()); h.run_steps(3); @@ -191,7 +187,7 @@ mod tests { let body_bottom = h.state_mut().session.layout().pages[0].body.bottom(); let band_end = crate::canvas::page_to_screen(h.state_mut(), 0, 300.0, body_bottom).unwrap().y + crate::canvas::WHITE_SPACE_PAD * scale; assert_eq!(fill(&mut h, egui::pos2(x, band_end - 20.0)), Some(Color32::WHITE), "on page 1's text area"); - assert_eq!(fill(&mut h, egui::pos2(x, band_end + crate::canvas::SEAM / 2.0)), Some(off), "on the seam over the cut margins"); + assert_eq!(fill(&mut h, egui::pos2(x, band_end + crate::canvas::SEAM / 2.0)), None, "on the seam over the cut margins"); } /// Elsewhere the system's own I-beam stays. From eac757af34d61067f98d474e30ac8785104e062d Mon Sep 17 00:00:00 2001 From: Fluorine Date: Tue, 10 Nov 2026 19:07:59 -0400 Subject: [PATCH 054/609] Keep off-paper drag cursor as arrow --- crates/ui-egui/src/canvas.rs | 5 +++-- crates/ui-egui/src/canvas/tests.rs | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8da9e1320a..b325717548 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1419,8 +1419,9 @@ fn finish_canvas_frame(finish: CanvasFinish<'_>, out: egui::scroll_area::ScrollA // so the copy pointer stands in (#3453). The selection bar keeps its arrow. // Off the paper (the rulers, the grey around and between pages) no text can be typed: // the arrow stays. A drag that started on the page keeps its I-beam. - let on_paper = - latest.is_some_and(|p| area.contains(p) && on_visible_page(&rects, &geo.bands, p)) || app.canvas.unit_drag.is_some() || resp.dragged(); + let on_paper = latest.is_some_and(|p| area.contains(p) && on_visible_page(&rects, &geo.bands, p)) + || app.canvas.unit_drag.is_some() + || (resp.dragged() && ui.input(|i| i.pointer.press_origin().is_some_and(|p| area.contains(p) && on_visible_page(&rects, &geo.bands, p)))); let fallback = if in_bar || !on_paper { egui::CursorIcon::Default } else if app.session.painter.is_some() { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 16f2c2bc09..57595cb3aa 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1190,6 +1190,28 @@ fn the_text_pointer_stays_off_the_grey_around_the_page() { h.event(egui::Event::PointerMoved(beside)); h.step(); assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "arrow on the grey beside the page"); + + // A drag that starts on the page retains its text pointer after moving off it. + h.event(egui::Event::PointerMoved(on_page)); + h.step(); + h.event(egui::Event::PointerButton { pos: on_page, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.step(); + h.event(egui::Event::PointerMoved(beside)); + h.step(); + assert_ne!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "a drag that began on the page keeps its text pointer"); + h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.step(); + + // A drag that begins in the grey area must not inherit the text cursor merely because the + // canvas response is dragged. Keep the pointer off the page for the whole drag. + h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.step(); + let further_beside = beside + egui::vec2(20.0, 0.0); + h.event(egui::Event::PointerMoved(further_beside)); + h.step(); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "arrow during a drag that began in the grey area"); + h.event(egui::Event::PointerButton { pos: further_beside, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.step(); } /// #4410: with the Format Painter armed, a double-click on a word paints that word, and the From 519ddb612ba71e623aae61bb0956baaa904fd31a Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Fri, 23 Oct 2026 12:29:32 +0000 Subject: [PATCH 055/609] Reconcile inline objects with U+FFFC markers on .json open Fixes #3678 Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/doc/src/document.rs | 5 ++++- crates/doc/src/para.rs | 14 ++++++++++++++ crates/doc/src/tests.rs | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 87b922b0c0..e2e951730d 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -795,7 +795,10 @@ impl Document { stories.extend(self.parts.values_mut().map(|p| &mut p.blocks)); for blocks in stories { for b in blocks.iter_mut() { - edit::each_para_mut(Arc::make_mut(b), 0, &mut Paragraph::normalize); + edit::each_para_mut(Arc::make_mut(b), 0, &mut |p: &mut Paragraph| { + p.normalize(); + p.reconcile_objects(); + }); } } } diff --git a/crates/doc/src/para.rs b/crates/doc/src/para.rs index 0ed90870b1..bad6c7dbee 100644 --- a/crates/doc/src/para.rs +++ b/crates/doc/src/para.rs @@ -340,6 +340,20 @@ impl Paragraph { self.runs = out; } + /// Make the objects match the U+FFFC markers one to one (files lie): drop surplus objects, + /// and remove markers past the last object. Runs must already cover the text. + pub fn reconcile_objects(&mut self) { + let markers: Vec = self.text.match_indices(OBJ).map(|(i, _)| i).collect(); + if self.objects.len() > markers.len() { + self.objects.truncate(markers.len()); + self.touch(); + } + // Last first so earlier offsets stay valid; past `objects.len()` nothing is drained. + for &off in markers.iter().skip(self.objects.len()).rev() { + let _ = self.delete(off, off + OBJ.len_utf8()); + } + } + /// Delete `a..b` (bytes). Objects inside are removed. pub fn delete(&mut self, a: usize, b: usize) -> Result<()> { let (a, b) = (a.min(b), a.max(b)); diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 088bd3bd2c..7abd063554 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -814,3 +814,35 @@ fn missing_pictures_are_capped_deduplicated_and_not_content() { assert!(!serde_json::to_string(&d).unwrap().contains("p0")); assert_eq!(MissingPictureReason::ExternalTarget.label(), "external target"); } + +#[test] +fn normalize_runs_reconciles_objects_with_markers() { + let c = CharProps::default(); + let markers = |p: &Paragraph| p.text.chars().filter(|ch| *ch == '\u{FFFC}').count(); + let build = || { + let mut d = Document::from_text("abc"); + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + p.insert_object(1, fs("A"), &c).unwrap(); + p.insert_object(5, fs("B"), &c).unwrap(); + d + }; + // More objects than markers (as a hand-edited .json can say): the surplus goes. + let mut d = build(); + d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().objects.push(fs("C")); + d.normalize_runs(); + let p = d.para(StoryRef::Body, &Path::top(0)).unwrap(); + assert_eq!((markers(p), p.objects.len()), (2, 2)); + assert_eq!(p.objects, vec![fs("A"), fs("B")]); + // More markers than objects: the unmatched marker goes, runs still cover the text. + let mut d = build(); + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + p.text.push('\u{FFFC}'); + p.runs[0].len += 3; + d.normalize_runs(); + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + assert_eq!((markers(p), p.objects.len()), (2, 2)); + assert_eq!(p.runs.iter().map(|r| r.len).sum::(), p.text.len()); + // Deleting the first marker keeps B on the second. + p.delete(1, 4).unwrap(); + assert_eq!(p.objects, vec![fs("B")]); +} From 1b8934c8233f493752eba0fb73ee99173f46bac8 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:17:57 +0000 Subject: [PATCH 056/609] fix: reconcile unmatched U+FFFC markers in one linear pass (no cap) Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/doc/src/para.rs | 61 +++++++++++++++++++++++++--- crates/doc/src/tests.rs | 88 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 143 insertions(+), 6 deletions(-) diff --git a/crates/doc/src/para.rs b/crates/doc/src/para.rs index bad6c7dbee..ffeac509cf 100644 --- a/crates/doc/src/para.rs +++ b/crates/doc/src/para.rs @@ -342,16 +342,65 @@ impl Paragraph { /// Make the objects match the U+FFFC markers one to one (files lie): drop surplus objects, /// and remove markers past the last object. Runs must already cover the text. + /// + /// One scan finds the unmatched markers, one pass removes them and the runs and objects are + /// fixed up once, so the cost is linear in the paragraph however many markers are unmatched. + /// There is no cap on the markers: stopping early would leave markers without objects. pub fn reconcile_objects(&mut self) { - let markers: Vec = self.text.match_indices(OBJ).map(|(i, _)| i).collect(); - if self.objects.len() > markers.len() { - self.objects.truncate(markers.len()); + let keep = self.objects.len(); + // Byte offsets of the unmatched markers (every marker after the first `keep`), ascending. + let mut seen = 0usize; + let mut drop: Vec = Vec::new(); + for (i, _) in self.text.match_indices(OBJ) { + if seen >= keep { + drop.push(i); + } + seen += 1; + } + if self.objects.len() > seen { + self.objects.truncate(seen); self.touch(); } - // Last first so earlier offsets stay valid; past `objects.len()` nothing is drained. - for &off in markers.iter().skip(self.objects.len()).rev() { - let _ = self.delete(off, off + OBJ.len_utf8()); + if drop.is_empty() { + return; } + let w = OBJ.len_utf8(); + if self.text.len() == drop.len() * w { + // Emptying: the mark keeps the formatting of what was deleted (as `delete` does). + let revisions = (self.mark.ins, self.mark.del, self.mark.fmt_change.clone()); + let mut mark = self.props_of_char(0).clone(); + (mark.ins, mark.del, mark.fmt_change) = revisions; + self.mark = mark; + } + // Shrink the runs: each removed marker takes `w` bytes off the run that holds it. + let mut d = 0usize; + let mut start = 0usize; + for r in &mut self.runs { + let re = start + r.len; + let mut cut = 0usize; + while let Some(&off) = drop.get(d) { + if off >= re { + break; + } + if off >= start { + cut += w; + } + d += 1; + } + start = re; + r.len -= cut.min(r.len); + } + let mut out = String::with_capacity(self.text.len() - drop.len() * w); + // The pieces between markers; marker `k` sits before piece `k + 1` and stays if matched. + for (k, piece) in self.text.split(OBJ).enumerate() { + if k > 0 && k <= keep { + out.push(OBJ); + } + out.push_str(piece); + } + self.text = out; + self.normalize(); + self.touch(); } /// Delete `a..b` (bytes). Objects inside are removed. diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 7abd063554..32ba3ce987 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -846,3 +846,91 @@ fn normalize_runs_reconciles_objects_with_markers() { p.delete(1, 4).unwrap(); assert_eq!(p.objects, vec![fs("B")]); } + +#[test] +fn reconcile_objects_drops_many_unmatched_markers_in_one_pass() { + let c = CharProps::default(); + let mut d = Document::from_text(""); + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + p.insert_object(0, fs("A"), &c).unwrap(); + p.insert_object(p.text.len(), fs("B"), &c).unwrap(); + let extra = 50_000; + // "x" followed by many unmatched markers around more text, in one run. + p.text = format!("\u{FFFC}x\u{FFFC}{}y{}z", "\u{FFFC}".repeat(extra), "\u{FFFC}".repeat(extra)); + p.runs = vec![Run { len: p.text.len(), props: c.clone() }]; + p.reconcile_objects(); + assert_eq!(p.text, "\u{FFFC}x\u{FFFC}yz"); + assert_eq!(p.objects, vec![fs("A"), fs("B")]); + assert_eq!(p.runs.iter().map(|r| r.len).sum::(), p.text.len()); +} + +#[test] +fn reconcile_objects_keeps_every_matched_object() { + let c = CharProps::default(); + let n = 100_050; + let mut d = Document::from_text(""); + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + p.text = "\u{FFFC}".repeat(n); + p.objects = (0..n).map(|_| fs("A")).collect(); + p.runs = vec![Run { len: p.text.len(), props: c }]; + p.reconcile_objects(); + assert_eq!(p.objects.len(), n); + assert_eq!(p.text.matches('\u{FFFC}').count(), n); + assert_eq!(p.runs.iter().map(|r| r.len).sum::(), p.text.len()); +} + +#[test] +fn reconcile_objects_keeps_run_props_across_several_runs() { + let (plain, bold) = (CharProps::default(), CharProps { bold: Some(true), ..CharProps::default() }); + let italic = CharProps { italic: Some(true), ..CharProps::default() }; + let mut d = Document::from_text(""); + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + p.objects = vec![fs("A")]; + // Runs: plain "ab" | bold "" (only unmatched, becomes empty) | italic "c" | plain "d". + let x = "\u{FFFC}"; + let parts = [ + (format!("a\u{FFFC}b{x}"), plain.clone()), + (format!("{x}{x}"), bold), + (format!("{x}c{x}"), italic.clone()), + ("d".to_string(), plain.clone()), + ]; + p.text = parts.iter().map(|(t, _)| t.as_str()).collect(); + p.runs = parts.iter().map(|(t, c)| Run { len: t.len(), props: c.clone() }).collect(); + p.reconcile_objects(); + assert_eq!(p.text, "a\u{FFFC}bcd"); + assert_eq!(p.objects, vec![fs("A")]); + let got: Vec<(usize, CharProps)> = p.runs.iter().map(|r| (r.len, r.props.clone())).collect(); + // "ab" plain (5 bytes: 1 + 3 + 1), "c" italic, "d" plain. + assert_eq!(got, vec![(5, plain.clone()), (1, italic), (1, plain)]); +} + +#[test] +fn reconcile_objects_marker_on_run_boundary_shrinks_the_right_run() { + let (plain, bold) = (CharProps::default(), CharProps { bold: Some(true), ..CharProps::default() }); + let mut d = Document::from_text(""); + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + let x = "\u{FFFC}"; + // plain "ab" | bold "cd" : the marker is the first byte of the second run. + p.text = format!("ab{x}cd"); + p.runs = vec![Run { len: 2, props: plain.clone() }, Run { len: 2 + x.len(), props: bold.clone() }]; + p.reconcile_objects(); + assert_eq!(p.text, "abcd"); + let got: Vec<(usize, CharProps)> = p.runs.iter().map(|r| (r.len, r.props.clone())).collect(); + assert_eq!(got, vec![(2, plain), (2, bold)]); +} + +#[test] +fn reconcile_objects_all_unmatched_markers_empties_the_paragraph() { + let bold = CharProps { bold: Some(true), ..CharProps::default() }; + let mut d = Document::from_text(""); + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + p.text = "\u{FFFC}".repeat(3); + p.runs = vec![Run { len: p.text.len(), props: bold.clone() }]; + p.mark = CharProps { ins: Some(7), ..CharProps::default() }; + p.reconcile_objects(); + assert_eq!(p.text, ""); + assert!(p.objects.is_empty()); + assert!(p.runs.is_empty()); + // The mark takes the deleted formatting but keeps its own revision. + assert_eq!(p.mark, CharProps { bold: Some(true), ins: Some(7), ..CharProps::default() }); +} From 68c5dfe8c769d6ab8766dfc67dea69b51370dabd Mon Sep 17 00:00:00 2001 From: fluorine Date: Wed, 11 Nov 2026 10:34:47 -0400 Subject: [PATCH 057/609] Canvas: remember where a press began so scrolling cannot change the pointer Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/canvas.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index b325717548..fb552c5873 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -156,6 +156,9 @@ pub struct CanvasState { /// A drag after a double-click, triple-click or Ctrl/⌘+click: the unit it extends by, the /// unit first selected, and the last position the pointer hit. unit_drag: Option, + /// Whether the press now held went down on a page: kept until release, so scrolling under the + /// pointer does not change it. + press_on_paper: Option, pub last_highlight: String, pub last_font_color: String, pub last_shading: String, @@ -401,6 +404,7 @@ impl Default for CanvasState { last_press: None, hf_press_switched: false, unit_drag: None, + press_on_paper: None, last_highlight: "yellow".into(), last_font_color: "C00000".into(), last_shading: "FFF2CC".into(), @@ -1419,9 +1423,13 @@ fn finish_canvas_frame(finish: CanvasFinish<'_>, out: egui::scroll_area::ScrollA // so the copy pointer stands in (#3453). The selection bar keeps its arrow. // Off the paper (the rulers, the grey around and between pages) no text can be typed: // the arrow stays. A drag that started on the page keeps its I-beam. - let on_paper = latest.is_some_and(|p| area.contains(p) && on_visible_page(&rects, &geo.bands, p)) - || app.canvas.unit_drag.is_some() - || (resp.dragged() && ui.input(|i| i.pointer.press_origin().is_some_and(|p| area.contains(p) && on_visible_page(&rects, &geo.bands, p)))); + let on_here = latest.is_some_and(|p| area.contains(p) && on_visible_page(&rects, &geo.bands, p)); + if ui.input(|i| i.pointer.primary_pressed()) { + app.canvas.press_on_paper = Some(on_here); + } else if !ui.input(|i| i.pointer.primary_down()) { + app.canvas.press_on_paper = None; + } + let on_paper = on_here || app.canvas.unit_drag.is_some() || (resp.dragged() && app.canvas.press_on_paper == Some(true)); let fallback = if in_bar || !on_paper { egui::CursorIcon::Default } else if app.session.painter.is_some() { From b395c45437b9297dc96d41b56653141debcf7c42 Mon Sep 17 00:00:00 2001 From: fluorine Date: Wed, 11 Nov 2026 10:57:15 -0400 Subject: [PATCH 058/609] Canvas: classify a press by its own position and gate unit drags on it A press and a move in one frame no longer let the move decide whether the press began on the paper. A unit selection that began in the grey keeps the arrow. --- crates/ui-egui/src/canvas.rs | 10 ++++++++-- crates/ui-egui/src/canvas/tests.rs | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index fb552c5873..104b934e48 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1425,11 +1425,17 @@ fn finish_canvas_frame(finish: CanvasFinish<'_>, out: egui::scroll_area::ScrollA // the arrow stays. A drag that started on the page keeps its I-beam. let on_here = latest.is_some_and(|p| area.contains(p) && on_visible_page(&rects, &geo.bands, p)); if ui.input(|i| i.pointer.primary_pressed()) { - app.canvas.press_on_paper = Some(on_here); + let pressed_at = ui.input(|i| { + i.events.iter().rev().find_map(|e| match e { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => Some(*pos), + _ => None, + }) + }); + app.canvas.press_on_paper = Some(pressed_at.map_or(on_here, |p| area.contains(p) && on_visible_page(&rects, &geo.bands, p))); } else if !ui.input(|i| i.pointer.primary_down()) { app.canvas.press_on_paper = None; } - let on_paper = on_here || app.canvas.unit_drag.is_some() || (resp.dragged() && app.canvas.press_on_paper == Some(true)); + let on_paper = on_here || ((app.canvas.unit_drag.is_some() || resp.dragged()) && app.canvas.press_on_paper == Some(true)); let fallback = if in_bar || !on_paper { egui::CursorIcon::Default } else if app.session.painter.is_some() { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 57595cb3aa..9e5e395339 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1212,6 +1212,26 @@ fn the_text_pointer_stays_off_the_grey_around_the_page() { assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "arrow during a drag that began in the grey area"); h.event(egui::Event::PointerButton { pos: further_beside, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); h.step(); + + // A press on the page and a move onto the grey that arrive in one frame: the press decides. + h.event(egui::Event::PointerMoved(on_page)); + h.step(); + h.event(egui::Event::PointerButton { pos: on_page, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerMoved(beside)); + h.step(); + assert_ne!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "press and move in one frame keep the text pointer"); + h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.step(); + + // A Ctrl/Cmd press in the grey area starts a unit selection, but the pointer stays an arrow. + let ctrl = egui::Modifiers::COMMAND; + h.event(egui::Event::PointerMoved(beside)); + h.step(); + h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: true, modifiers: ctrl }); + h.step(); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "arrow during a unit selection that began in the grey area"); + h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: false, modifiers: ctrl }); + h.step(); } /// #4410: with the Format Painter armed, a double-click on a word paints that word, and the From 021269b675c20d9e9383c1f6f233f6ff9f16389e Mon Sep 17 00:00:00 2001 From: fluorine Date: Wed, 11 Nov 2026 11:10:11 -0400 Subject: [PATCH 059/609] Cursor test: set the Ctrl modifier and check the unit selection starts --- crates/ui-egui/src/canvas/tests.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 9e5e395339..2a51e3beff 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1227,10 +1227,13 @@ fn the_text_pointer_stays_off_the_grey_around_the_page() { let ctrl = egui::Modifiers::COMMAND; h.event(egui::Event::PointerMoved(beside)); h.step(); + h.event(egui::Event::ModifiersChanged(ctrl)); h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: true, modifiers: ctrl }); h.step(); + assert!(h.state().canvas.unit_drag.is_some(), "the Ctrl press starts a unit selection"); assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "arrow during a unit selection that began in the grey area"); h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: false, modifiers: ctrl }); + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); h.step(); } From 892235af064e7a8fbe09f1f927f975c0e946110f Mon Sep 17 00:00:00 2001 From: Mauro Mazzieri Date: Wed, 11 Nov 2026 16:53:42 +0000 Subject: [PATCH 060/609] Different first page: a continuous section whose first paragraph runs over still began on the page before Addresses the CodeRabbit review: the run-over case (with a regression test) and the even-page header in docs/layout-parity.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JesQG7ckr7g2qSfBwGkTqM --- crates/layout/src/headers.rs | 12 ++++++++++-- crates/layout/src/tests.rs | 33 +++++++++++++++++++++++++++++++++ docs/layout-parity.md | 4 ++-- 3 files changed, 45 insertions(+), 4 deletions(-) diff --git a/crates/layout/src/headers.rs b/crates/layout/src/headers.rs index c6825fca1c..df0928737b 100644 --- a/crates/layout/src/headers.rs +++ b/crates/layout/src/headers.rs @@ -40,13 +40,21 @@ pub(crate) fn section_side(start: SectionStart, restart: Option, last: u32, /// header and footer go on: the page where the section begins. A page's section is the one at its /// top, so a section that starts continuously part-way down `prev` has no first page of its own: /// Word shows the earlier section's header there and the section's default one from the next page -/// on. `sections` as [`Document::sections`] gives them (each with its last block). +/// on, also when its first paragraph begins on `prev` and runs over. `sections` as +/// [`Document::sections`] gives them (each with its last block). pub(crate) fn begins_section(sections: &[(usize, &SectionProps)], prev: Option<&Page>, page: &Page) -> bool { if prev.is_some_and(|p| p.section == page.section) { return false; } let start = page.section.checked_sub(1).and_then(|k| sections.get(k)).map_or(0, |(end, _)| end.saturating_add(1)); - start >= page.first_block + // A first paragraph (or table) that begins part-way down `prev` and runs over still began + // the section there. + let began_before = prev.is_some_and(|p| { + p.items + .iter() + .any(|it| matches!(it, Placed::Lines { story: StoryRef::Body, path, .. } if path.0.first().is_some_and(|&b| b as usize >= start))) + }); + start >= page.first_block && !began_before } /// The document's sections with their headers and footers (Word's "link to previous"), each diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 6f4e787592..176e1771d9 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -14812,6 +14812,39 @@ fn continuous_section_first_page_header_is_not_shown_on_its_second_page() { } } +/// The same when the continuous section's first paragraph begins part-way down a page and runs +/// over onto the next: the section began on the page before, so the next shows its default +/// header, not its first-page one. +#[test] +fn continuous_section_first_paragraph_running_over_keeps_first_page_header_hidden() { + use wordcraft_doc::section::SectionStart; + let mut paras: Vec = (0..44).map(|i| format!("Paragraph {i}")).collect(); + // Section 2's first paragraph: long enough to start low on page 1 and run onto page 2. + paras.push("word ".repeat(1200)); + paras.extend((0..60).map(|i| format!("After {i}"))); + let mut d = Document::from_text(¶s.join("\n")); + let part = |d: &mut Document, t: &str| { + d.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(Paragraph::with_text(t, Default::default()))]) + }; + let (one, first, two) = (part(&mut d, "ONE"), part(&mut d, "FIRST"), part(&mut d, "TWO")); + let mut s1 = d.last_section.clone(); + s1.headers.default = Some(one); + d.para_mut(StoryRef::Body, &Path::top(43)).unwrap().section = Some(Box::new(s1)); + d.last_section.start = SectionStart::Continuous; + d.last_section.title_page = true; + d.last_section.headers.first = Some(first); + d.last_section.headers.default = Some(two); + let l = lay(&d); + let begins = l.caret(&Pos::body(44, 0)).unwrap().page; + assert_eq!(l.caret(&Pos::body(43, 0)).unwrap().page, begins, "the second section starts part-way down a page"); + let next = begins + 1; + assert!(l.pages.get(next).is_some_and(|p| p.first_block == 44), "its first paragraph runs over onto the next page"); + let shown: Vec<_> = l.pages.iter().map(|p| p.header_story).collect(); + assert_eq!(shown[begins], Some(one)); + assert!(shown[next..].iter().all(|h| *h == Some(two)), "{shown:?}"); + assert!(l.pages[next..].iter().all(|p| p.hf_slot == crate::HfSlot::Default)); +} + /// Sections starting continuously one after another still go onto new pages: a paragraph that /// doesn't fit below the text above it moves on rather than running off the page (#3907). A /// hundred one-line sections lay out like a hundred plain paragraphs. diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 37b33b9e4b..ecf0ccdd03 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -1,6 +1,6 @@ # Layout and pagination parity with Microsoft Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** trivial (a section with a different first page that starts continuously part-way down a page shows its first-page header nowhere: the page it starts on keeps the earlier section's header and the next shows its default one, as in Word for Windows); previously trivial (from the second section on, headers, footers and note separators are measured with their own section's document grid and SECTION/SECTIONPAGES values, #4683); previously trivial (a turned inline picture whose file keeps no room for the turn keeps its line to its frame, the frame turned a quarter in Word 2013+ layout); previously trivial (a picture lowered further than its own height lowers its line as far, its top on the baseline); previously trivial (a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a line of only pictures is as tall as they reach, never less than its font's height; a legacy check box sizes its line as text of its size, #3984); previously trivial (spaces before a line's first character keep their width in justified and distributed lines, as in Word); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (Times and Courier take their Windows counterparts' line spacing; 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 (a click just outside a floating table, by a cell whose text is turned, goes to the text beside or after it, #4181; 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 (PR #4545: eligible cell floats keep in-bounds offsets; overflow confinement retains the front-of-text, turned-cell and native-acceptance limits); previously trivial (MATH construction reuse, #3630; previously 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 (ODT documents: a line of only pictures keeps its font's height; no setting for it any more); previously trivial (ODT documents: padding is the standard's box model always; picture-only line height is an ODF interpretation setting); previously trivial (行頭禁則 also covers the small kana and the prolonged sound mark at ordinary break opportunities, as JIS X 4051 §4 specifies, inferred from the standard and synthetic tests rather than checked in Word); previously trivial (a missing font is drawn in an installed metric twin before any other substitute: Arial for Helvetica on Windows, Tinos before macOS Times for Times New Roman); previously trivial (ODT documents: padding without a border takes room); previously trivial (ODT documents: a line of only pictures is as tall as they are); previously trivial (ODT documents: a table's own space above and below; header and footer spacing kept past a tall header); previously trivial (a page break before a table's first row moves the table; emphasis marks drawn with room in the line); previously trivial (text in a turned text box turns with it; previously trivial: an in-line picture, shape or chart moves with its run's raise or lowering, Word's `w:position`; previously trivial (layout work bounds: header-row repeats budgeted per layout, cached picture outlines charged to the decode budget, linked-box chain widths exact up to a work cap, #3867); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a table row that would leave a cell empty on a page that already holds something, its picture or first line not fitting there, moves on whole instead of leaving the other cells' text beside the empty cell, #4272); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (tab leader dots spaced and placed as in Word); previously trivial (a level above that hasn't counted yet takes its first number at the first deeper item); previously trivial (paragraph side borders lie beyond their distance from the text, #5036); previously trivial (with a header taller than the top margin, Margin-anchored drawings, header-cell pins and header-table obstacles use the rendered body top; TopMargin and InsideMargin keep their declared band, #2485; previously trivial: connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (field results take the `\* DollarText`, `\* Hex` and `\* ArabicDash` switches, #4226; previously trivial: a cell spanning columns shares its extra minimum width by the columns' preferred widths, equally in automatic tables, #1883; previously 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 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** trivial (a section with a different first page that starts continuously part-way down a page shows its first-page header nowhere: the page it starts on keeps the earlier section's header and the next shows its default one (its even one on an even page, with different odd and even pages), as in Word for Windows, also when its first paragraph runs over from the page it starts on); previously trivial (from the second section on, headers, footers and note separators are measured with their own section's document grid and SECTION/SECTIONPAGES values, #4683); previously trivial (a turned inline picture whose file keeps no room for the turn keeps its line to its frame, the frame turned a quarter in Word 2013+ layout); previously trivial (a picture lowered further than its own height lowers its line as far, its top on the baseline); previously trivial (a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a line of only pictures is as tall as they reach, never less than its font's height; a legacy check box sizes its line as text of its size, #3984); previously trivial (spaces before a line's first character keep their width in justified and distributed lines, as in Word); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (Times and Courier take their Windows counterparts' line spacing; 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 (a click just outside a floating table, by a cell whose text is turned, goes to the text beside or after it, #4181; 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 (PR #4545: eligible cell floats keep in-bounds offsets; overflow confinement retains the front-of-text, turned-cell and native-acceptance limits); previously trivial (MATH construction reuse, #3630; previously 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 (ODT documents: a line of only pictures keeps its font's height; no setting for it any more); previously trivial (ODT documents: padding is the standard's box model always; picture-only line height is an ODF interpretation setting); previously trivial (行頭禁則 also covers the small kana and the prolonged sound mark at ordinary break opportunities, as JIS X 4051 §4 specifies, inferred from the standard and synthetic tests rather than checked in Word); previously trivial (a missing font is drawn in an installed metric twin before any other substitute: Arial for Helvetica on Windows, Tinos before macOS Times for Times New Roman); previously trivial (ODT documents: padding without a border takes room); previously trivial (ODT documents: a line of only pictures is as tall as they are); previously trivial (ODT documents: a table's own space above and below; header and footer spacing kept past a tall header); previously trivial (a page break before a table's first row moves the table; emphasis marks drawn with room in the line); previously trivial (text in a turned text box turns with it; previously trivial: an in-line picture, shape or chart moves with its run's raise or lowering, Word's `w:position`; previously trivial (layout work bounds: header-row repeats budgeted per layout, cached picture outlines charged to the decode budget, linked-box chain widths exact up to a work cap, #3867); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a table row that would leave a cell empty on a page that already holds something, its picture or first line not fitting there, moves on whole instead of leaving the other cells' text beside the empty cell, #4272); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (tab leader dots spaced and placed as in Word); previously trivial (a level above that hasn't counted yet takes its first number at the first deeper item); previously trivial (paragraph side borders lie beyond their distance from the text, #5036); previously trivial (with a header taller than the top margin, Margin-anchored drawings, header-cell pins and header-table obstacles use the rendered body top; TopMargin and InsideMargin keep their declared band, #2485; previously trivial: connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (field results take the `\* DollarText`, `\* Hex` and `\* ArabicDash` switches, #4226; previously trivial: a cell spanning columns shares its extra minimum width by the columns' preferred widths, equally in automatic tables, #1883; previously 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 > **Floating anchor row segments:** 2026-11-07 · A floating anchor after a manual page/column break counts visible content on the far side of the same wrapped row. Marker-only cover anchors retain their previous-page rule. Synthetic picture spacing, placement and history controls; no new native Word measurement. Readiness estimates unchanged. @@ -307,7 +307,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | Date | Change | Summary | |---|---|---| -| 2026-11-09 | trivial | Different first page: a page is its section's first only if the section begins on it; a continuous section starting part-way down a page no longer shows its first-page header (and footer) on its second page, compared with Word for Windows 365 on a synthetic file. `layout::tests::continuous_section_first_page_header_is_not_shown_on_its_second_page` | +| 2026-11-09 | trivial | Different first page: a page is its section's first only if the section begins on it; a continuous section starting part-way down a page no longer shows its first-page header (and footer) on its second page (its default header, or its even one on an even page with different odd and even pages), compared with Word for Windows 365 on a synthetic file; the same when its first paragraph begins part-way down the page and runs over onto the next (not measured separately). `layout::tests::continuous_section_first_page_header_is_not_shown_on_its_second_page`, `continuous_section_first_paragraph_running_over_keeps_first_page_header_hidden` | | 2026-11-04 | trivial | Headers, footers and note separators of the second and later sections are measured with their own section's document grid and SECTION/SECTIONPAGES values, not the previous section's; a regression from the #4501 refactor (#4683). `layout::tests::pages::a_sections_header_is_measured_without_the_previous_sections_grid` | | 2026-11-08 | trivial | Turned inline pictures with no recorded effect extent keep their line to the frame (exchanged near a quarter turn in Word 2013+ layout) and overhang it, cut at the line's top and bottom, as in Word | | 2026-11-08 | trivial | Contextual spacing drops the space after a table cell's last paragraph in the Normal style, the end-of-cell mark counting as a Normal paragraph; another style keeps it, and a middle or bottom cell of a split row lines up without the dropped space (#5450) (`layout::tests::contextual_spacing_drops_the_space_after_a_cells_last_normal_paragraph`, `a_bottom_cell_of_a_split_row_ignores_a_dropped_space_after_beside_it`). | From a525210f48de41f5a9b8127ec29fbd0124544695 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Wed, 11 Nov 2026 19:03:44 +0100 Subject: [PATCH 061/609] #6331: Updating fields keeps CREATEDATE on the document's creation date CREATEDATE is formatted from the document's creation date (dcterms:created) in local time, not from the clock. A creation date that can't be read keeps the field's result; a document never saved (no creation date yet) still shows today. --- crates/engine/src/cmd/insert.rs | 3 ++- crates/engine/src/cmd/references/fields.rs | 19 +++++++++++++++- crates/engine/src/cmd/references/tests.rs | 25 ++++++++++++++++++++++ docs/layout-parity.md | 1 + 4 files changed, 46 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index c80082c82d..2d44a4562e 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -16,7 +16,8 @@ mod objects; pub(crate) use header_footer::saved_copy; use header_footer::{create_hf, edit_hf, header_footer, new_empty_headers, strip_headers}; pub use items::{ - DropCapState, default_date_picture, drop_cap_state, format_date, format_date_at, format_date_in, format_date_parts, format_date_parts_in, + DropCapState, default_date_picture, drop_cap_state, format_date, format_date_at, format_date_at_in, format_date_in, format_date_parts, + format_date_parts_in, }; use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol}; use links::{bookmark, delete_bookmark, link, link_targets}; diff --git a/crates/engine/src/cmd/references/fields.rs b/crates/engine/src/cmd/references/fields.rs index f56752f9e5..547fd34a54 100644 --- a/crates/engine/src/cmd/references/fields.rs +++ b/crates/engine/src/cmd/references/fields.rs @@ -380,7 +380,18 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> { "DATE" | "TIME" | "CREATEDATE" | "SAVEDATE" | "PRINTDATE" => { let lang = field_lang(&s.doc, p, k); let pic = date_picture(instr).unwrap_or_else(|| default_picture(&name, lang.as_deref())); - updates.push((k, text_result(instr, crate::cmd::insert::format_date_in(&pic, lang.as_deref())))); + let created = s.doc.core.created.trim(); + // CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11). One + // never saved has no creation date yet and saving stamps now; an unreadable + // date keeps the result it has. + let text = if name != "CREATEDATE" || created.is_empty() { + crate::cmd::insert::format_date_in(&pic, lang.as_deref()) + } else if let Some(unix) = unix_from_w3cdtf(created) { + crate::cmd::insert::format_date_at_in(&pic, lang.as_deref(), unix, crate::cmd::local_offset_secs(unix)) + } else { + continue; + }; + updates.push((k, text_result(instr, text))); } "REF" | "PAGEREF" => { let f = FieldCode::parse(instr); @@ -530,6 +541,12 @@ fn field_lang(doc: &wordcraft_doc::Document, p: &wordcraft_doc::Paragraph, k: us doc.styles.resolve_char(p.props.style.as_deref(), p.props_of_char(off)).lang } +/// Seconds since the epoch of a core-properties timestamp (`2019-05-05T12:00:00Z`, any offset or +/// fraction); `None` for another form or an instant before 1970. +fn unix_from_w3cdtf(stamp: &str) -> Option { + u64::try_from(chrono::DateTime::parse_from_rfc3339(stamp).ok()?.timestamp()).ok() +} + /// Word's default date or time picture when a field instruction carries no `\@` picture switch. fn default_picture(name: &str, lang: Option<&str>) -> String { if name == "TIME" { "h:mm am/pm".into() } else { crate::cmd::insert::default_date_picture(lang).into() } diff --git a/crates/engine/src/cmd/references/tests.rs b/crates/engine/src/cmd/references/tests.rs index b2838cd9f9..33ab174400 100644 --- a/crates/engine/src/cmd/references/tests.rs +++ b/crates/engine/src/cmd/references/tests.rs @@ -495,6 +495,31 @@ fn update_fields_all_covers_every_story() { s.run("references.updateFields", &json!({"all": "yes"})).unwrap(); } +/// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11), not today's date. +#[test] +fn createdate_keeps_the_creation_date_on_update() { + let mut s = Session::new(wordcraft_doc::Document::new()); + s.doc.core.created = "2019-05-05T12:00:00Z".into(); + s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap(); + s.run("insert.field", &json!({"instr": "CREATEDATE"})).unwrap(); + s.run("references.updateFields", &json!({})).unwrap(); + let results: Vec = fields(&s).into_iter().map(|f| f.1).collect(); + assert_eq!(results, ["2019-05", "5/5/2019"]); +} + +/// A creation date that can't be read leaves the field's result as it was; a document that has +/// never been saved is created now (saving stamps that time as its creation date). +#[test] +fn createdate_without_a_readable_creation_date() { + let mut s = Session::new(wordcraft_doc::Document::new()); + s.doc.core.created = "sometime in May".into(); + s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap(); + assert_eq!(fields(&s)[0].1, "2019-05"); + s.doc.core.created.clear(); + s.run("references.updateFields", &json!({})).unwrap(); + assert_eq!(fields(&s)[0].1, crate::cmd::insert::format_date("yyyy-MM")); +} + #[test] fn toc_tabs_ignore_nonentries() { let mut s = Session::new(wordcraft_doc::Document::from_text("Before\nContents\nOld\t9\nAfter")); diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 0a39f59cca..97e88e18b9 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -328,6 +328,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | 2026-11-04 | trivial | Output counts a locked SEQ and not one in a tracked deletion, as Word does; readiness estimates unchanged | | 2026-11-01 | trivial | SEQ fields in text boxes are numbered where their boxes are anchored, in output and after F9, and a REF finds a bookmark in a text box | | 2026-11-01 | trivial | SEQ, STYLEREF and REF fields show fresh results in output; readiness estimates unchanged | +| 2026-11-11 | trivial | Update Field shows CREATEDATE as the document's creation date (`dcterms:created`, in local time), not today's; a creation date it can't read leaves the result as it was (#6331); readiness estimates unchanged | | 2026-10-29 | trivial | Print Markup balloon anchor discovery walks paragraph objects once (#3614); readiness estimates unchanged | | 2026-11-03 | trivial | A decimal tab scans the text after it once, not once per cluster. Separate from the #3412 word-measurement fix | | 2026-10-30 | trivial | Layout work bounds for hostile documents (#3867): header-row repeats budgeted per layout and counting canvas members; picture-outline decode budget charged for cached outlines too, so cold and warm layouts wrap alike; linked-box chains keep exact widths up to a work cap, not 16 widths; `gridAfter` bounded | From 1336bc27cb80b394c21d10b841d8865e86507a86 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:16:39 +0100 Subject: [PATCH 062/609] #6331 review: CREATEDATE in documents from templates, opened files without a date, date-only values A document made from a template no longer inherits the template's creation date: it has none until it is saved, so CREATEDATE shows today. A file opened without a creation date keeps the field's cached result, as one with an unreadable date already did; only a new, never-saved document uses today. A date-only creation date (2019-05-05, which W3CDTF allows) shows as that calendar day in every time zone. The test's expected date for 12:00 UTC now follows the local offset, so it passes east of UTC+12 too. --- crates/engine/src/cmd/file.rs | 2 ++ crates/engine/src/cmd/references/fields.rs | 28 ++++++++++++++-------- crates/engine/src/cmd/references/tests.rs | 16 ++++++++++++- crates/engine/src/cmd/user_templates.rs | 23 ++++++++++++++++++ 4 files changed, 58 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index c676e2c802..540fdf31c4 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -316,6 +316,8 @@ pub(crate) fn new_from_template(s: &mut Session, v: &Value) -> CmdResult { let path = p::req_str(v, "path")?; let (mut doc, _) = read_document(s, path, v)?; doc.settings.attached_template = Some(path.to_string()); + // A new document: not created when the template was. Saving stamps its creation date. + doc.core.created.clear(); if p::bool(v, "replaceBlank") == Some(true) && s.used_because().is_none() { s.set_document(doc); } else { diff --git a/crates/engine/src/cmd/references/fields.rs b/crates/engine/src/cmd/references/fields.rs index 547fd34a54..7802ec8565 100644 --- a/crates/engine/src/cmd/references/fields.rs +++ b/crates/engine/src/cmd/references/fields.rs @@ -381,13 +381,14 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> { let lang = field_lang(&s.doc, p, k); let pic = date_picture(instr).unwrap_or_else(|| default_picture(&name, lang.as_deref())); let created = s.doc.core.created.trim(); - // CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11). One - // never saved has no creation date yet and saving stamps now; an unreadable - // date keeps the result it has. - let text = if name != "CREATEDATE" || created.is_empty() { + // CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11). A new + // document, never saved, has no creation date yet and saving stamps now. A + // file opened without one, or with one that can't be read, keeps the result + // it has. + let text = if name != "CREATEDATE" || (created.is_empty() && s.path.is_none()) { crate::cmd::insert::format_date_in(&pic, lang.as_deref()) - } else if let Some(unix) = unix_from_w3cdtf(created) { - crate::cmd::insert::format_date_at_in(&pic, lang.as_deref(), unix, crate::cmd::local_offset_secs(unix)) + } else if let Some((unix, offset)) = created_at(created) { + crate::cmd::insert::format_date_at_in(&pic, lang.as_deref(), unix, offset) } else { continue; }; @@ -541,10 +542,17 @@ fn field_lang(doc: &wordcraft_doc::Document, p: &wordcraft_doc::Paragraph, k: us doc.styles.resolve_char(p.props.style.as_deref(), p.props_of_char(off)).lang } -/// Seconds since the epoch of a core-properties timestamp (`2019-05-05T12:00:00Z`, any offset or -/// fraction); `None` for another form or an instant before 1970. -fn unix_from_w3cdtf(stamp: &str) -> Option { - u64::try_from(chrono::DateTime::parse_from_rfc3339(stamp).ok()?.timestamp()).ok() +/// A core-properties creation date as seconds since the epoch and the UTC offset to show it at: +/// an instant (`2019-05-05T12:00:00Z`, any offset or fraction) at the local offset, or a calendar +/// date (`2019-05-05`, which W3CDTF allows) at its own midnight, whatever the time zone. `None` +/// for another form or a date before 1970. +fn created_at(stamp: &str) -> Option<(u64, i64)> { + if let Ok(t) = chrono::DateTime::parse_from_rfc3339(stamp) { + let unix = u64::try_from(t.timestamp()).ok()?; + return Some((unix, crate::cmd::local_offset_secs(unix))); + } + let day = chrono::NaiveDate::parse_from_str(stamp, "%Y-%m-%d").ok()?; + Some((u64::try_from(day.and_hms_opt(0, 0, 0)?.and_utc().timestamp()).ok()?, 0)) } /// Word's default date or time picture when a field instruction carries no `\@` picture switch. diff --git a/crates/engine/src/cmd/references/tests.rs b/crates/engine/src/cmd/references/tests.rs index 33ab174400..4ba7d4f7d2 100644 --- a/crates/engine/src/cmd/references/tests.rs +++ b/crates/engine/src/cmd/references/tests.rs @@ -504,7 +504,16 @@ fn createdate_keeps_the_creation_date_on_update() { s.run("insert.field", &json!({"instr": "CREATEDATE"})).unwrap(); s.run("references.updateFields", &json!({})).unwrap(); let results: Vec = fields(&s).into_iter().map(|f| f.1).collect(); - assert_eq!(results, ["2019-05", "5/5/2019"]); + // 12:00 UTC is 5 May from UTC-12 to UTC+11:59, the next day east of that. + let unix = 1_557_057_600; + let (_, _, day, _, _) = crate::cmd::local_civil(unix, crate::cmd::local_offset_secs(unix)); + assert_eq!(results, ["2019-05".to_string(), format!("5/{day}/2019")]); + assert!(day == 5 || day == 6, "{day}"); + // A date without a time is that calendar day in every time zone. + s.doc.core.created = "2019-06-07".into(); + s.run("references.updateFields", &json!({})).unwrap(); + let results: Vec = fields(&s).into_iter().map(|f| f.1).collect(); + assert_eq!(results, ["2019-06", "6/7/2019"]); } /// A creation date that can't be read leaves the field's result as it was; a document that has @@ -515,7 +524,12 @@ fn createdate_without_a_readable_creation_date() { s.doc.core.created = "sometime in May".into(); s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap(); assert_eq!(fields(&s)[0].1, "2019-05"); + // A file opened without a creation date keeps the result too. s.doc.core.created.clear(); + s.path = Some(std::env::temp_dir().join("opened.docx")); + s.run("references.updateFields", &json!({})).unwrap(); + assert_eq!(fields(&s)[0].1, "2019-05"); + s.path = None; s.run("references.updateFields", &json!({})).unwrap(); assert_eq!(fields(&s)[0].1, crate::cmd::insert::format_date("yyyy-MM")); } diff --git a/crates/engine/src/cmd/user_templates.rs b/crates/engine/src/cmd/user_templates.rs index ff7b5bca87..17e0aed66f 100644 --- a/crates/engine/src/cmd/user_templates.rs +++ b/crates/engine/src/cmd/user_templates.rs @@ -337,6 +337,29 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// A document made from a template is created now, not when the template was: it has no + /// creation date until it is saved, so CREATEDATE in it shows today. + #[test] + fn new_from_template_has_no_creation_date_of_its_own_yet() { + let d = scratch("created"); + let path = d.join("Dated.dotx"); + let mut t = Session::new(wordcraft_doc::Document::new()); + t.run("document.setText", &json!({"text": "Dated"})).unwrap(); + t.doc.core.created = "2019-05-05T12:00:00Z".into(); + crate::io::save_path(&path, &t.doc).unwrap(); + let mut s = Session::new(wordcraft_doc::Document::new()); + s.run("file.newFromTemplate", &json!({"path": path.to_string_lossy()})).unwrap(); + assert_eq!(s.doc.core.created, ""); + s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy""#, "result": "2019"})).unwrap(); + s.run("references.updateFields", &json!({})).unwrap(); + assert!(s.doc.plain_text(wordcraft_doc::StoryRef::Body).contains(&crate::cmd::insert::format_date("yyyy"))); + // The template itself keeps its date. + let mut again = Session::new(wordcraft_doc::Document::new()); + again.run("file.open", &json!({"path": path.to_string_lossy()})).unwrap(); + assert_eq!(again.doc.core.created, "2019-05-05T12:00:00Z"); + let _ = std::fs::remove_dir_all(&d); + } + /// #3433: a template the platform hands the app takes an untouched blank document's place /// (`replaceBlank`), as a file `file.open` opens does; otherwise, and without the flag, the /// new document opens beside the others, as File › New's does. Either way the template on From 61ef4aab3caafffffa9a401e6de5ed7eb355b4f6 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Thu, 12 Nov 2026 15:25:09 +0000 Subject: [PATCH 063/609] #6131: File > Export to DOCX, ODT or RTF writes a copy and keeps the document's file Export ran a plain Save As, which made the exported file the document's file and cleared its unsaved changes, so the next Save went to the copy. file.save and file.saveAs take "copy": true, which writes the file and leaves the document's path, unsaved state and save stamps alone. Export uses it on the desktop and in the browser. --- crates/engine/src/cmd/file.rs | 22 +++++++--- crates/engine/src/tests.rs | 32 +++++++++++++++ crates/ui-egui/src/app/commands.rs | 19 ++++++++- crates/ui-egui/src/file_dialogs.rs | 5 ++- crates/ui-egui/src/file_dialogs/tests.rs | 51 ++++++++++++++++++++++++ 5 files changed, 119 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index c676e2c802..2498f72146 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -94,9 +94,9 @@ pub fn specs() -> Vec { .pure(), CommandSpec::new("file.save", "Save", "File", save) .key("Mod+S / Shift+F12 / Alt+Shift+F2") - .params(r#"{"path"?: string, "password"?: string (encrypt this and later saves with it, as file.encrypt does), "markup"?: bool (Print Markup for a PDF, PNG, HTML, Markdown or text copy: comments shown; default file.printMarkup), "format"?: "wordml2003" (an .xml file as a Word 2003 XML Document) | "flatopc" (as a Word XML Document, the default; saving over a Word 2003 XML file keeps that format), "strict"?: bool (a .pdf or .png only: refuse, writing nothing, if a character can't be drawn or a picture is missing; see file.strictReport)}"#) + .params(r#"{"path"?: string, "password"?: string (encrypt this and later saves with it, as file.encrypt does), "markup"?: bool (Print Markup for a PDF, PNG, HTML, Markdown or text copy: comments shown; default file.printMarkup), "format"?: "wordml2003" (an .xml file as a Word 2003 XML Document) | "flatopc" (as a Word XML Document, the default; saving over a Word 2003 XML file keeps that format), "strict"?: bool (a .pdf or .png only: refuse, writing nothing, if a character can't be drawn or a picture is missing; see file.strictReport), "copy"?: bool (write a copy, as File › Export does: the document keeps its own file, unsaved changes and save stamps; not with `password`)}"#) .pure(), - CommandSpec::new("file.saveAs", "Save As", "File", save_as).key(super::mac_or("F12 / Mod+Shift+S", "F12 / Alt+F2")).params(r#"{"path": string, "password"?: string, "markup"?: bool, "format"?: string (as file.save), "strict"?: bool (as file.save)}"#).pure(), + CommandSpec::new("file.saveAs", "Save As", "File", save_as).key(super::mac_or("F12 / Mod+Shift+S", "F12 / Alt+F2")).params(r#"{"path": string, "password"?: string, "markup"?: bool, "format"?: string (as file.save), "strict"?: bool (as file.save), "copy"?: bool (as file.save)}"#).pure(), // Pure: the password must not land in Repeat or a recorded macro, and it isn't an edit // to undo; it marks the document as changed itself. CommandSpec::new("file.encrypt", "Encrypt with Password", "File › Info › Protect Document", encrypt) @@ -373,6 +373,12 @@ fn save(s: &mut Session, v: &Value) -> CmdResult { } }; check_strict_output(p::bool(v, "strict").unwrap_or(false), &path.to_string_lossy())?; + // A copy (File › Export, #6131) is written and nothing else: the document keeps its own file, + // its unsaved changes and its save stamps, so the next Save still goes to the original. + let as_copy = p::bool(v, "copy") == Some(true); + if as_copy && v.get("password").is_some_and(|pw| !pw.is_null()) { + return Err(CmdError::Params("`password` changes the document's own saves, so it can't come with `copy` (use file.encrypt)".into())); + } if let Some(pw) = v.get("password").filter(|pw| !pw.is_null()) { let Some(pw) = pw.as_str().filter(|pw| !pw.is_empty()) else { return Err(CmdError::Params("`password` must be a non-empty string (file.encrypt removes a password)".into())); @@ -407,11 +413,15 @@ fn save(s: &mut Session, v: &Value) -> CmdResult { let password = s.password.as_ref().map(crate::io::Password::as_str); // A header/footer just made and left empty isn't saved (#960). let copy = super::insert::saved_copy(s); - if let Err(e) = crate::io::save_path_with(&path, copy.as_ref().unwrap_or(&s.doc), password, &opts) { - (s.doc.settings.zoom, s.doc.core.last_modified_by, s.doc.core.created, s.doc.core.modified, s.doc.core.revision) = before_stamp; - return Err(CmdError::Failed(e)); - } + let written = crate::io::save_path_with(&path, copy.as_ref().unwrap_or(&s.doc), password, &opts); let encrypted = password.is_some() && crate::io::can_encrypt(&path.to_string_lossy()); + if written.is_err() || as_copy { + (s.doc.settings.zoom, s.doc.core.last_modified_by, s.doc.core.created, s.doc.core.modified, s.doc.core.revision) = before_stamp; + } + written.map_err(CmdError::Failed)?; + if as_copy { + return Ok(json!({"saved": true, "path": path.to_string_lossy(), "encrypted": encrypted, "copy": true})); + } // A save in a format that doesn't keep everything (plain text, Markdown, a page image) is a // copy, except over the document's own file: a note.txt opened and saved is saved (#2376). let own_file = s.path.as_deref() == Some(path.as_path()); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6439b3de9e..004bdf0155 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5633,6 +5633,38 @@ fn saving_a_text_file_over_itself_saves_the_document() { let _ = std::fs::remove_dir_all(&dir); } +/// #6131: File › Export to DOCX, ODT or RTF writes a copy (`copy: true`). It made the copy the +/// document's file and cleared its unsaved changes, so the next Save went to the copy and the +/// original kept its old text. The copy has the edits; the document keeps its file, its changes +/// and its save stamps. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn exporting_a_copy_keeps_the_documents_file() { + let dir = std::env::temp_dir().join(format!("wordcraft-engine-export-copy-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let body = |p: &std::path::Path| crate::io::open_path(p).unwrap().plain_text(wordcraft_doc::StoryRef::Body); + for ext in ["docx", "odt", "rtf"] { + let original = dir.join(format!("a-{ext}.docx")); + let mut s = Session::new(wordcraft_doc::Document::new()); + run(&mut s, "text.insert", json!({"text": "first"})); + run(&mut s, "file.save", json!({"path": original.to_string_lossy()})); + run(&mut s, "text.insert", json!({"text": " edited"})); + let stamps = (s.doc.core.revision, s.doc.core.modified.clone()); + let copy = dir.join(format!("copy.{ext}")); + let r = run(&mut s, "file.saveAs", json!({"path": copy.to_string_lossy(), "copy": true})); + assert_eq!(r["saved"], true, "{ext}"); + assert_eq!(body(©), "first edited", "{ext}: the copy has the edits"); + assert_eq!(s.path.as_deref(), Some(original.as_path()), "{ext}: the document keeps its file"); + assert!(s.dirty, "{ext}: the document keeps its unsaved changes"); + assert_eq!((s.doc.core.revision, s.doc.core.modified.clone()), stamps, "{ext}: the document's save stamps are untouched"); + run(&mut s, "file.save", json!({})); + assert_eq!(body(&original), "first edited", "{ext}: Save still writes the original"); + assert!(!s.dirty); + } + let _ = std::fs::remove_dir_all(&dir); +} + /// A save that fails to write (no permission, disk full, a bad path) leaves the document's own /// save stamps untouched: `stamp_save` runs before the fallible write, so a prior version of this /// left `modified`/`created`/`last_modified_by`/`revision`/`zoom` changed for a save that never diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 568c7ef839..ff9541479a 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -142,16 +142,26 @@ impl WordApp { if self.services.download.is_some() && matches!(id, "file.save" | "file.saveAs" | "file.exportPdf" | "file.exportPng") { let name = params.get("path").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| self.web_save_name(id)); let name = if id == "file.exportPdf" && !name.ends_with(".pdf") { format!("{name}.pdf") } else { name }; + // `copy` (File › Export, #6131) writes a copy: the document keeps its unsaved changes, + // its name and its save stamps, as for a PDF. + let as_copy = params.get("copy").and_then(Value::as_bool) == Some(true); // A save with a password encrypts this and later saves (`file.save`'s `password`). if matches!(id, "file.save" | "file.saveAs") && let Some(pw) = params.get("password").filter(|v| !v.is_null()) { + if as_copy { + return Err("`password` changes the document's own saves, so it can't come with `copy` (use file.encrypt)".into()); + } if !wordcraft_engine::io::can_encrypt(&name) || pw.as_str().is_none_or(str::is_empty) { return Err("only Word documents (.docx, .docm, .dotx, .dotm) and OpenDocument text files (.odt, .ott) can be saved with a password, and it can't be empty".into()); } self.session.run("file.encrypt", &json!({"password": pw})).map_err(|e| e.to_string())?; } // A save is a save, download or not: advance the revision and modified stamp (#262). + // A copy carries fresh stamps too, but the document's own are put back after. + let doc = &self.session.doc; + let before_stamp = + (doc.settings.zoom, doc.core.last_modified_by.clone(), doc.core.created.clone(), doc.core.modified.clone(), doc.core.revision); if matches!(id, "file.save" | "file.saveAs") { self.session.stamp_save(); } @@ -159,7 +169,12 @@ impl WordApp { let password = if matches!(id, "file.save" | "file.saveAs") { self.session.password.as_ref().map(wordcraft_engine::Password::as_str) } else { None }; let opts = wordcraft_engine::cmd::file::export_options(&self.session, ¶ms); - let bytes = wordcraft_engine::io::save_bytes_with(&name, &self.session.doc, password, &opts)?; + let bytes = wordcraft_engine::io::save_bytes_with(&name, &self.session.doc, password, &opts); + if as_copy { + let core = &mut self.session.doc.core; + (self.session.doc.settings.zoom, core.last_modified_by, core.created, core.modified, core.revision) = before_stamp; + } + let bytes = bytes?; // A ticket left over from an earlier call isn't this save's. let saves = self.services.async_saves.clone(); if let Some(saves) = &saves { @@ -167,7 +182,7 @@ impl WordApp { } // An export is a copy, and so is a save in a format that doesn't keep everything (a // page image, plain text): the document itself still has unsaved changes. - let marked_saved = matches!(id, "file.save" | "file.saveAs") && keeps_everything(&name); + let marked_saved = matches!(id, "file.save" | "file.saveAs") && !as_copy && keeps_everything(&name); // Save As tells the host page the document is now this file, which it only is when the // save marks it saved. A Save under a name the page never sent (an untitled document, // an imported .doc saved as .docx) is a new file too, never an overwrite. diff --git a/crates/ui-egui/src/file_dialogs.rs b/crates/ui-egui/src/file_dialogs.rs index a4399b6f00..23a1aa7285 100644 --- a/crates/ui-egui/src/file_dialogs.rs +++ b/crates/ui-egui/src/file_dialogs.rs @@ -296,9 +296,10 @@ impl WordApp { let r = if ext == "png" { self.run("file.exportPng", json!({"path": path})) } else if ext == crate::print_page::EXPORT_WORD_2003 { - self.run("file.saveAs", json!({"path": path, "format": ext})) + self.run("file.saveAs", json!({"path": path, "format": ext, "copy": true})) } else { - self.run("file.saveAs", json!({"path": path})) + // An export is a copy: the document keeps its own file and changes (#6131). + self.run("file.saveAs", json!({"path": path, "copy": true})) }; if r.is_ok() { self.status(crate::i18n::fmt(tl!("Exported {path}"), &[("path", &crate::i18n::isolate_path(&path))])); diff --git a/crates/ui-egui/src/file_dialogs/tests.rs b/crates/ui-egui/src/file_dialogs/tests.rs index 837cb96a87..7bd0ea297b 100644 --- a/crates/ui-egui/src/file_dialogs/tests.rs +++ b/crates/ui-egui/src/file_dialogs/tests.rs @@ -711,3 +711,54 @@ fn many_failed_fonts_end_with_a_count() { let msg = a.status_msg.as_ref().map(|(m, _)| m.clone()).unwrap_or_default(); assert_eq!(msg, "Added 0 fonts; 5 couldn't be read: f0.ttf, f1.ttf, f2.ttf and 2 more"); } + +/// #6131: File › Export to DOCX, ODT or RTF writes a copy. It ran a plain Save As, which made +/// the copy the document's file and cleared its unsaved changes, so the next Save updated the +/// copy and the original kept its old text. +#[test] +fn export_writes_a_copy_and_keeps_the_documents_file() { + let dir = scratch("export-copy"); + for ext in ["docx", "odt", "rtf"] { + let original = dir.join(format!("a-{ext}.docx")); + let (mut a, _) = async_app(); + a.run("text.insert", json!({"text": "first"})).unwrap(); + a.run("file.save", json!({"path": original.to_string_lossy()})).unwrap(); + a.run("text.insert", json!({"text": " edited"})).unwrap(); + let copy = dir.join(format!("copy.{ext}")); + a.finish_pick(AfterPick::Export { ext: ext.into() }, Some(copy.to_string_lossy().into_owned())).unwrap(); + assert_eq!(saved_text(©), "first edited", "{ext}: the copy has the edits"); + assert_eq!(a.session.path.as_deref(), Some(original.as_path()), "{ext}: the document keeps its file"); + assert!(a.session.dirty, "{ext}: the document keeps its unsaved changes"); + a.run("file.save", json!({})).unwrap(); + assert_eq!(saved_text(&original), "first edited", "{ext}: Save still writes the original"); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// #6131, browser: exporting a DOCX, ODT or RTF copy downloads it and leaves the document's +/// unsaved changes and save stamps alone. +#[test] +fn web_export_downloads_a_copy_and_keeps_unsaved_changes() { + let got: Rc)>>> = Rc::default(); + let sink = got.clone(); + let services = Services { + download: Some(Box::new(move |n: &str, b: &[u8]| { + sink.borrow_mut().push((n.to_string(), b.to_vec())); + Ok(()) + })), + ..Default::default() + }; + let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), services); + typed(&mut a); + for ext in ["docx", "odt", "rtf"] { + let revision = a.session.doc.core.revision; + let name = format!("copy.{ext}"); + a.finish_pick(AfterPick::Export { ext: ext.into() }, Some(name.clone())).unwrap(); + let (downloaded, bytes) = got.borrow_mut().pop().unwrap(); + assert_eq!(downloaded, name); + let back = wordcraft_engine::io::open_bytes(&name, &bytes).unwrap(); + assert_eq!(back.plain_text(wordcraft_doc::StoryRef::Body), UNSAVED, "{ext}: the copy has the text"); + assert!(a.session.dirty, "{ext}: the document keeps its unsaved changes"); + assert_eq!(a.session.doc.core.revision, revision, "{ext}: the document's save stamps are untouched"); + } +} From f438ec29439e3489b671853480bc5c02b10105e3 Mon Sep 17 00:00:00 2001 From: Fin Warman Date: Thu, 12 Nov 2026 12:00:09 +0000 Subject: [PATCH 064/609] Page-anchored frames in a table cell stay in the cell --- crates/layout/src/boxes.rs | 4 +++- crates/layout/src/tests.rs | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/layout/src/boxes.rs b/crates/layout/src/boxes.rs index 45387a9de2..265ccc3209 100644 --- a/crates/layout/src/boxes.rs +++ b/crates/layout/src/boxes.rs @@ -228,6 +228,8 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout { // Word has no frames in a text box: a framed paragraph there (its style's frame, usually) // runs with the box's text (#2357). let frames = !matches!(story, StoryRef::Part(id) if ctx.doc.parts.get(&id).is_some_and(|p| p.kind == wordcraft_doc::PartKind::TextBox)); + // Nor in a table cell for a frame placed on the page: Word keeps its text in the cell. + let cell_frame = |fr: &wordcraft_doc::props::TextFrame| !in_cell || fr.v_anchor == "text"; // The bottom of the last paragraph's lines. let mut prev_end = 0.0f32; for (i, b) in blocks.iter().enumerate() { @@ -242,7 +244,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout { // A text frame (a footer's page number in a frame, say) is placed apart, like a // floating object, and the text after it wraps around it; it takes no room in // the flow. - if let Some(fr) = pl.rp.frame.clone().filter(|_| frames) { + if let Some(fr) = pl.rp.frame.clone().filter(|fr| frames && cell_frame(fr)) { let fw = fr.w.unwrap_or_else(|| natural_width(&pl)).clamp(1.0, 1584.0); let pf = if (fw - width).abs() > 0.01 { ctx.para_labelled(p, fw, table, &[], label) } else { pl }; let h = match fr.h { diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index b83e5bf3fb..80e720908e 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -10399,6 +10399,26 @@ fn a_text_frame_in_a_cell_floats_beside_the_text() { assert!(frame.x > text.x + 200.0, "right-aligned in the cell: {} vs {}", frame.x, text.x); } +/// A cell paragraph framed against the page (a divider page's floating table, its paragraphs +/// carrying the table's page position as a frame) stays in its cell in Word. WordCraft placed it +/// apart at the page offset, past the page's foot, and added a blank page per divider. +#[test] +fn a_page_anchored_frame_in_a_cell_stays_in_the_cell() { + use wordcraft_doc::props::TextFrame; + let mut d = Document::from_text("Above"); + let mut t = Table::new(1, 1, 300.0); + let mut framed = wordcraft_doc::Paragraph::with_text("Divider", Default::default()); + framed.props.frame = Some(TextFrame { y: 777.5, h_anchor: "page".into(), v_anchor: "page".into(), wrap: "around".into(), ..Default::default() }); + let text = wordcraft_doc::Paragraph::with_text("Cell text", Default::default()); + t.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(framed), wordcraft_doc::para_block(text)]; + d.insert_block(StoryRef::Body, &Path::top(1), wordcraft_doc::Block::Table(t)).unwrap(); + let l = lay(&d); + let at = |i: u32| l.caret(&Pos { story: StoryRef::Body, path: Path(vec![1, 0, 0, i]), off: 0 }).unwrap(); + let (frame, text) = (at(0), at(1)); + assert!(text.top > frame.top + 5.0, "the framed paragraph takes its line: {} vs {}", frame.top, text.top); + assert_eq!(l.pages.len(), 1, "no page for the frame's offset"); +} + /// Word has no frames inside a text box: a paragraph there whose style carries a frame (a /// letterhead's "Weld" and "Governor" styles, framed at the page's left) runs in the box's text /// like any other. WordCraft placed each one apart at the frame's offset, so two of them in a row From 07e4b515fcdd97702462c3d05e3c1c0634ffb7bf Mon Sep 17 00:00:00 2001 From: Fin Warman Date: Thu, 12 Nov 2026 16:17:27 +0000 Subject: [PATCH 065/609] Turned text in an at-least row wraps to its minimum height --- crates/layout/src/table.rs | 16 ++++++++++++---- crates/layout/src/tests.rs | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/crates/layout/src/table.rs b/crates/layout/src/table.rs index 9ea319127b..55c186b06f 100644 --- a/crates/layout/src/table.rs +++ b/crates/layout/src/table.rs @@ -606,11 +606,19 @@ pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], ava } else if turn.is_turned() { collapsed = false; // Turned text: its lines run along the cell's height. An exact row height sets - // their length; otherwise they get the length the text needs unwrapped and the row - // grows to fit (the second pass lays them out again if the row ends up taller). + // their length, and a minimum height does when the lines fit across the column; + // otherwise they get the length the text needs unwrapped and the row grows to fit + // (the second pass lays them out again if the row ends up taller). let snap = (ctx.counters.clone(), ctx.eq_count); - let len = match (row.props.height, row.props.height_rule) { - (Some(h), HeightRule::Exact) if h > 0.0 => (h + row_bottom - insets).clamp(4.0, TURNED_LIMIT), + let preferred = row.props.height.filter(|h| h.is_finite() && *h > 0.0).map(|h| h.clamp(4.0, TURNED_LIMIT)); + let wrapped = preferred.filter(|_| !ctx.boxes.inside() && row.props.height_rule == HeightRule::AtLeast).filter(|h| { + let probe = layout_box(ctx, BoxInput::cell(story, &cell.blocks, &cpath, *h, text, depth)); + (ctx.counters, ctx.eq_count) = (snap.0.clone(), snap.1); + probe.height.max(probe.floats_bottom) <= cw + 0.01 + }); + let len = match (row.props.height, row.props.height_rule, wrapped) { + (Some(h), HeightRule::Exact, _) if h > 0.0 => (h + row_bottom - insets).clamp(4.0, TURNED_LIMIT), + (_, _, Some(h)) => h, _ => { let probe = layout_box(ctx, BoxInput::cell(story, &cell.blocks, &cpath, TURNED_MAX, text, depth)).items; (ctx.counters, ctx.eq_count) = (snap.0.clone(), snap.1); diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index b83e5bf3fb..23691f6471 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -2594,6 +2594,40 @@ fn turned_text_wraps_in_an_exact_row() { assert!(after.top < b.y + 72.0 + 30.0, "the row keeps its exact height: {after:?}"); } +#[test] +fn turned_text_uses_min_height() { + crate::test_fonts(); + for turn in [TextDirection::Up, TextDirection::Down] { + let mut d = Document::from_text("After"); + let mut t = Table::new(1, 2, 160.0); + t.props.style = None; + t.rows[0].props.height = Some(80.0); + t.rows[0].props.height_rule = wordcraft_doc::props::HeightRule::AtLeast; + t.rows[0].cells[1].props.text_direction = turn; + t.rows[0].cells[1].blocks = vec![wordcraft_doc::para_block(Paragraph::with_text("Compensation pad type", Default::default()))]; + d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap(); + let l = lay(&d); + let rect = l.pages[0] + .items + .iter() + .find_map(|it| match it { + Placed::Cell { rect, cell: 1, .. } => Some(*rect), + _ => None, + }) + .unwrap(); + assert!((rect.h - 80.0).abs() < 0.01, "{rect:?}"); + let lines = l.pages[0] + .items + .iter() + .find_map(|it| match it { + Placed::Lines { path, l0, l1, .. } if path.0 == [0, 0, 1, 0] => Some(l1 - l0), + _ => None, + }) + .unwrap(); + assert!(lines > 1); + } +} + #[test] fn hostile_turned_cells_never_panic() { crate::test_fonts(); From c37ee263ce551bf5ac9aafad0becbebc055c7d4d Mon Sep 17 00:00:00 2001 From: Fin Warman Date: Thu, 12 Nov 2026 16:07:08 +0000 Subject: [PATCH 066/609] Turned text in a merged cell wraps to its rows' minimum height --- crates/layout/src/table.rs | 26 ++++++++++++++++++++++++-- crates/layout/src/tests.rs | 22 ++++++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/crates/layout/src/table.rs b/crates/layout/src/table.rs index 55c186b06f..a3eb4da450 100644 --- a/crates/layout/src/table.rs +++ b/crates/layout/src/table.rs @@ -87,6 +87,26 @@ struct Turned { top: f32, } +/// The minimum height of the rows a vertically merged cell starting at row `ri`, grid column +/// `g`, spans, when it spans more than one and each has a minimum (`w:hRule="atLeast"`): Word +/// wraps the cell's turned text to it when the lines fit across the column. +fn merged_min_height(t: &Table, ri: usize, g: usize) -> Option { + let starts = t.cell_at_grid(ri, g).and_then(|ci| t.rows.get(ri)?.cells.get(ci)).is_some_and(|c| c.props.vmerge == VMerge::Restart); + if !starts { + return None; + } + let min = |r: &Row| r.props.height.filter(|h| h.is_finite() && *h > 0.0 && r.props.height_rule == HeightRule::AtLeast); + let mut total = min(t.rows.get(ri)?)?; + let mut k = ri + 1; + while let Some(r) = t.rows.get(k) + && t.cell_at_grid(k, g).is_some_and(|ci| t.grid_col(k, ci) == g && r.cells.get(ci).is_some_and(|c| c.props.vmerge == VMerge::Continue)) + { + total += min(r)?; + k += 1; + } + (k > ri + 1).then_some(total) +} + /// The number of grid columns of `t` ([`Table::cols`]), which walks every row (each row counted /// as a step of [`crate::work`]). fn grid_cols(t: &Table) -> usize { @@ -610,8 +630,10 @@ pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], ava // otherwise they get the length the text needs unwrapped and the row grows to fit // (the second pass lays them out again if the row ends up taller). let snap = (ctx.counters.clone(), ctx.eq_count); - let preferred = row.props.height.filter(|h| h.is_finite() && *h > 0.0).map(|h| h.clamp(4.0, TURNED_LIMIT)); - let wrapped = preferred.filter(|_| !ctx.boxes.inside() && row.props.height_rule == HeightRule::AtLeast).filter(|h| { + let merged = merged_min_height(t, ri, g); + let preferred = merged.or(row.props.height.filter(|h| h.is_finite() && *h > 0.0)).map(|h| h.clamp(4.0, TURNED_LIMIT)); + let at_least = merged.is_some() || row.props.height_rule == HeightRule::AtLeast; + let wrapped = preferred.filter(|_| !ctx.boxes.inside() && at_least).filter(|h| { let probe = layout_box(ctx, BoxInput::cell(story, &cell.blocks, &cpath, *h, text, depth)); (ctx.counters, ctx.eq_count) = (snap.0.clone(), snap.1); probe.height.max(probe.floats_bottom) <= cw + 0.01 diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 23691f6471..2d1bb194bf 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -2628,6 +2628,28 @@ fn turned_text_uses_min_height() { } } +#[test] +fn turned_text_wraps_to_merged_rows_height() { + use wordcraft_doc::props::{HeightRule, VMerge}; + crate::test_fonts(); + let mut d = turned_table(TextDirection::Down, &"word ".repeat(15), None); + if let Some(Block::Table(t)) = d.body.get_mut(1).map(Arc::make_mut) { + t.rows.push(t.rows[0].clone()); + t.rows[1].cells[1].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("", Default::default()))]; + t.rows[0].cells[1].props.vmerge = VMerge::Restart; + t.rows[1].cells[1].props.vmerge = VMerge::Continue; + for row in &mut t.rows { + row.props.height = Some(40.0); + row.props.height_rule = HeightRule::AtLeast; + } + } + let l = lay(&d); + let it = turned_lines(&l); + let lines = if let Placed::Lines { l0, l1, .. } = it { l1 - l0 } else { 0 }; + let b = it.turned_bounds().unwrap(); + assert!(lines > 1 && b.h > 40.0 && b.h < 85.0, "wraps to both rows' 80pt, not one row's 40pt: {lines} lines, {b:?}"); +} + #[test] fn hostile_turned_cells_never_panic() { crate::test_fonts(); From c120c09423187c1c690bff7c822420512c399fb9 Mon Sep 17 00:00:00 2001 From: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Date: Tue, 27 Oct 2026 22:30:32 +0300 Subject: [PATCH 067/609] Layout: a right tab past the right indent takes its text up to the stop, as in Word A TOC entry in Word's TOC styles has a right indent and a right tab with a dot leader at the margin, past that indent. Word keeps the page number on the entry's line whenever it fits between the text and the stop, so the number ends past the indent. WordCraft checked the first character after the tab against the right indent (the tab has no room yet), and moved the tab and its number to the next line when the text ended less than a digit short of the indent. Measured in Word for Mac 16.93 (Times New Roman 12pt, right indent 1cm, stop at the margin): entries whose text ends 0.4, 1, 2, 3, 4, 5 and 5.8pt short of the indent all keep their dot leader and number on the line, the number ending at the stop. With a 0.2cm indent the number stays on the line when 18.7pt are left before the stop and goes to the next line when 16.7pt are left. Text after a right or decimal tab now fits while it ends before the stop. The running shift of the tab also no longer counts the tab's own room as text: it dropped back to nothing after every second character, so those characters were checked against the indent as well. A tab whose text is pending starts with no room on the line it goes to. --- crates/layout/src/para/lines.rs | 21 +++++++++++---- crates/layout/src/tests.rs | 48 +++++++++++++++++++++++++++++++++ docs/layout-parity.md | 1 + 3 files changed, 65 insertions(+), 5 deletions(-) diff --git a/crates/layout/src/para/lines.rs b/crates/layout/src/para/lines.rs index 821132f6aa..d04dba2619 100644 --- a/crates/layout/src/para/lines.rs +++ b/crates/layout/src/para/lines.rs @@ -856,19 +856,29 @@ impl Scan { } self.x += w; } - _ => self.pending_tab = Some((j, stop, self.x)), + _ => { + // Its room grows from nothing with its text (a tab moved on from the line before + // may still hold the width it had there). + if let Some(c) = pl.clusters.get_mut(j) { + c.adv = 0.0; + } + self.pending_tab = Some((j, stop, self.x)); + } } if stop.leader != TabLeader::None { self.leaders.push((j, stop.leader)); } } - /// Whether text after a right/centre tab grows leftwards into the tab's space first. + /// Whether text after a right/centre tab grows leftwards into the tab's space first. Up to a + /// right or decimal stop it fits even past the right indent (Word: a TOC entry whose text ends + /// less than a digit short of the indent keeps its page number on its line when the stop is + /// at the margin); unshifted, the text after the tab ends at `x - room`. fn absorbs(&self, pl: &ParaLayout, advance: f32) -> bool { self.pending_tab.is_some_and(|(tj, stop, _)| { let room = pl.clusters.get(tj).map(|t| t.adv).unwrap_or(0.0); match stop.align { - TabAlign::Right | TabAlign::Decimal => room >= advance, + TabAlign::Right | TabAlign::Decimal => room >= advance || self.x - room + advance <= stop.pos + 0.01, TabAlign::Center => room >= advance / 2.0 && self.x + advance / 2.0 <= self.right_edge + 0.01, _ => false, } @@ -944,7 +954,9 @@ impl Scan { /// Text after a decimal/centre/right tab shifts as it grows. fn shift_pending_tab(&mut self, pl: &mut ParaLayout) { let Some((tj, stop, tx)) = self.pending_tab else { return }; - let seg_w = self.x - tx; + // `x` includes the room the tab has so far. + let old = pl.clusters.get(tj).map(|c| c.adv).unwrap_or(0.0); + let seg_w = self.x - tx - old; let shift = match stop.align { TabAlign::Right => stop.pos - tx - seg_w, TabAlign::Center => stop.pos - tx - seg_w / 2.0, @@ -953,7 +965,6 @@ impl Scan { _ => 0.0, }; let shift = shift.max(0.0); - let old = pl.clusters.get(tj).map(|c| c.adv).unwrap_or(0.0); if (shift - old).abs() > 0.001 { let delta = shift - old; if let Some(c) = pl.clusters.get_mut(tj) { diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index a15f2f672b..0280e4fe62 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -1847,6 +1847,54 @@ fn leader_dots_are_spaced_and_placed_as_in_word() { } } +/// A TOC entry with a right indent and its right tab at the margin, past the indent (Word's TOC +/// styles): the page number may end past the indent, up to the stop. Like Word, the number stays +/// on the text's line whenever it fits between the text and the stop, also when the text ends +/// less than a digit short of the indent; when it doesn't fit there, the tab and the number go +/// to the next line as before. +#[test] +fn right_tab_past_the_right_indent_takes_its_number_up_to_the_stop() { + use wordcraft_doc::props::{TabAlign, TabLeader, TabStop}; + let stop = 72.0 + 468.0; + let mut close = 0; + for indent in [28.35f32, 6.0] { + let edge = stop - indent; + for m in 20..40 { + for r in 2..7 { + let text = format!("{}{}\t104", "abc ".repeat(m), "y".repeat(r)); + let n = text.chars().count(); + let tab = n - 4; + let mut d = Document::from_text(&text); + d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| { + p.indent_right = Some(indent); + p.tabs = Some(vec![TabStop { pos: 468.0, align: TabAlign::Right, leader: TabLeader::Dot }]); + }) + .unwrap(); + let l = lay(&d); + let Some(para) = l.pages[0].items.iter().find_map(|i| if let Placed::Lines { para, .. } = i { Some(para.clone()) } else { None }) + else { + panic!("no lines") + }; + let line_of = |k: usize| para.lines.iter().position(|l| l.c0 <= k && k < l.c1).unwrap(); + // Where the text ends and how wide the number is (the text's last letter and the number + // are each on one line; the last two letters are both a "y"). + let last = l.caret(&Pos::body(0, tab - 1)).unwrap().x; + let text_end = last + (last - l.caret(&Pos::body(0, tab - 2)).unwrap().x); + let end = l.caret(&Pos::body(0, n)).unwrap().x; + let number = end - l.caret(&Pos::body(0, n - 3)).unwrap().x; + assert!((end - stop).abs() < 0.5, "indent {indent}, {m} words + {r}: number ends at {end}"); + assert_eq!(line_of(tab), line_of(n - 1), "indent {indent}, {m} words + {r}: the tab and its number are on different lines"); + let same = line_of(tab) == line_of(tab - 1); + assert_eq!(same, text_end + number <= stop + 0.01, "indent {indent}, {m} words + {r}: text ends at {text_end}, number {number} wide"); + if same && text_end > edge - number / 3.0 { + close += 1; + } + } + } + } + assert!(close > 0, "no entry whose text ends within a digit of the indent"); +} + /// A left tab whose only stop is past the right indent wraps; on the next line it still can't /// reach that stop, so it takes no room there and its text starts at the indent instead of /// going to a line of its own. diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 0a39f59cca..2b02835e69 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -383,6 +383,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | 2026-10-27 | trivial | A kept-together paragraph in a continuous section is measured against the next page's body, so a tall different first-page header no longer splits one that fits on page 2 (#3907 CodeRabbit) | | 2026-10-27 | trivial | 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 | trivial | 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-27 | trivial | A right or decimal tab past the right indent (a TOC entry's page number at the margin) keeps its text on the line while it ends before the stop, also when the text before the tab ends less than a digit short of the indent; measured in Word for Mac 16.93. `layout::tests::right_tab_past_the_right_indent_takes_its_number_up_to_the_stop` | | 2026-10-20 | trivial | A click below a floating table, outside its cells, goes to the paragraph beside or after it instead of a cell of its last row, as checked in Word (#2038) | | 2026-10-19 | trivial | A right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, starts the next line with its text instead of ending the line (a TOC entry's page number keeps its leader); a left tab still past the right indent there takes no room (#1840) | | 2026-10-19 | trivial | Justified lines (compatibility mode 15) shrink their spaces to fit one more word by at most a quarter of the spaces' width (was a fifth) and by at most 0.355 of that word's own width with the space before it. Measured in Word for Mac with synthetic justified paragraphs: words of 2.7 to 80 pt, spaces of 3.3 and 6.7 pt, only justified text, last lines included, never in modes 12 and 14. A real paper's justified abstract now breaks like Word on all 23 lines (3 before); on 180 real-world papers, page counts matching Word went from 139 to 142, none further | From fe1cecbb90924948a55669f72f1214995035d655 Mon Sep 17 00:00:00 2001 From: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Date: Tue, 27 Oct 2026 22:52:22 +0300 Subject: [PATCH 068/609] Layout: a paragraph kept with a table needs its header rows and the start of its first row Keep with next asked a table that follows for a flat 24 pt. Word keeps the paragraph (a table caption, typically) with the table's repeated header rows and the start of its first row: when they don't fit under it, the paragraph goes over with the table instead of staying alone at the foot of the page. The first row need not fit whole; the least room it can start in is enough (two lines of a cell's text with widow/orphan control, compatibility mode 15). table_start_need lays the table out and finds that room with row_can_start. The look-ahead restores the list and equation counters, so numbered items in the table's cells are counted once. --- crates/layout/src/flow.rs | 2 ++ crates/layout/src/table_flow.rs | 24 +++++++++++++ crates/layout/src/tests.rs | 61 +++++++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+) diff --git a/crates/layout/src/flow.rs b/crates/layout/src/flow.rs index f47cb16151..63f338849d 100644 --- a/crates/layout/src/flow.rs +++ b/crates/layout/src/flow.rs @@ -8,6 +8,7 @@ use super::floats::{ use super::notes::{DECOR_STORY, NoteBox, para_notes}; use super::page::{PageBuilder, PageFrame, item_bottom}; use super::placed::Placed; +use super::table_flow::table_start_need; use super::{ Arc, Block, Counters, Document, HashMap, InlineObject, Level, LineEnd, Page, ParaLayout, Paragraph, Path, Rect, StoryRef, TextDirection, ViewMode, outline, para, @@ -1057,6 +1058,7 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, counte } } } + Some(Block::Table(t)) if t.props.float.is_none() => table_start_need(ctx, t, block + 1, width), Some(Block::Table(_)) => 24.0, None => 0.0, } diff --git a/crates/layout/src/table_flow.rs b/crates/layout/src/table_flow.rs index 538e9eb746..4528a06799 100644 --- a/crates/layout/src/table_flow.rs +++ b/crates/layout/src/table_flow.rs @@ -70,6 +70,30 @@ pub(crate) fn footer_table_wraps(ctx: &mut Ctx, pb: &PageBuilder) -> Vec f32 { + // A look ahead: list and equation numbers in the cells don't count yet. + let (counters, eq_count) = (ctx.counters.clone(), ctx.eq_count); + let tl = table::layout_table(ctx, StoryRef::Body, t, &[block as u32], width, 1); + (ctx.counters, ctx.eq_count) = (counters, eq_count); + let headers = t.rows.iter().take_while(|r| r.props.header).count(); + let head: f32 = tl.rows.iter().take(headers).map(|r| r.height).sum(); + let (Some(row), Some(laid)) = (t.rows.get(headers), tl.rows.get(headers)) else { return head }; + // ponytail: bisection assumes starting a row gets no harder with more room. + let (mut lo, mut hi) = (0.0f32, laid.height); + for _ in 0..12 { + let mid = (lo + hi) / 2.0; + if row_can_start(ctx.doc, row, laid, mid, f32::MAX) { + hi = mid; + } else { + lo = mid; + } + } + head + hi +} + fn row_keeps_next(row: &table::RowLayout) -> bool { let Some(items) = row.cells.first().and_then(|cell| row.items.get(cell.items.clone())) else { return false }; let Some((depth, story)) = items diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index a15f2f672b..6c6b440da2 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -15322,3 +15322,64 @@ fn turned_cell_float_keeps_its_along_text_offset() { assert!((confined.y - reference.y).abs() < 0.01, "{direction:?}: {confined:?} vs {reference:?}"); } } + +/// A caption kept with the next paragraph (`keepNext`) before a table goes over with the table +/// when the table's repeated header row and the start of its first row don't fit under it, as in +/// Word, instead of staying alone at the foot of the page: keep with next asked a table for a +/// flat 24 pt. The first row need not fit whole: Word keeps the caption where the row splits +/// under it with two lines (widow/orphan control in the cell). Swept over the filler lines above, +/// so the caption lands at every offset from the foot of the page. +#[test] +fn a_caption_kept_with_a_table_goes_over_with_the_start_of_its_first_row() { + let mut split_under_it = false; + for fill in 20..40 { + let mut d = Document::from_text(&format!("{}Caption", "filler\n".repeat(fill))); + // No space after: what a kept paragraph's space after adds is not this test's. + d.format_paragraphs(&Pos::body(fill, 0), &Pos::body(fill, 0), &|p| { + p.keep_next = Some(true); + p.space_after = Some(0.0); + }) + .unwrap(); + let mut t = Table::new(2, 1, 468.0); + t.rows[0].props.header = true; + t.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Header", Default::default()))]; + t.rows[1].cells[0].blocks = + vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(&"first row words go on and on ".repeat(60), Default::default()))]; + d.insert_block(StoryRef::Body, &Path::top(fill + 1), wordcraft_doc::Block::Table(t)).unwrap(); + let l = lay(&d); + let page = l + .pages + .iter() + .position(|p| p.items.iter().any(|it| matches!(it, Placed::Lines { story: StoryRef::Body, path, .. } if *path == Path::top(fill)))) + .unwrap(); + // Lines of the first row's text on a page. + let first_row_lines = |pi: usize| -> usize { + l.pages.get(pi).map_or(0, |p| { + p.items + .iter() + .filter_map(|it| match it { + Placed::Lines { path, l0, l1, .. } if path.0.len() > 1 && path.0.get(1) == Some(&1) => Some(l1 - l0), + _ => None, + }) + .sum() + }) + }; + let here = first_row_lines(page); + assert!(here >= 2, "{fill} filler lines: the caption's page {} holds {here} lines of the first row", page + 1); + split_under_it |= first_row_lines(page + 1) > 0; + } + assert!(split_under_it, "the caption never stays above a first row that splits"); +} + +/// Looking ahead at a table for keep with next lays it out once more: the list items in its cells +/// are still counted once, where the table is placed. +#[test] +fn list_items_in_a_table_after_a_kept_caption_are_counted_once() { + let mut d = Document::from_text("Caption"); + d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.keep_next = Some(true)).unwrap(); + let items = numbered(&mut d, &["first item", "second item"], ParaProps::default()); + let mut t = Table::new(1, 1, 468.0); + t.rows[0].cells[0].blocks = items.into_iter().map(wordcraft_doc::para_block).collect(); + d.insert_block(StoryRef::Body, &Path::top(1), wordcraft_doc::Block::Table(t)).unwrap(); + assert_eq!(labels(&lay(&d)), ["1.", "2."]); +} From ee424da341f7adeefd0aa5a6453f1bb5d9922188 Mon Sep 17 00:00:00 2001 From: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Date: Tue, 27 Oct 2026 23:00:44 +0300 Subject: [PATCH 069/609] Layout: a row starts whole only where the border below it fits too, as placing it needs row_can_start took a row as fitting where its height did, while place_table also wants the border below it (the row's edge). A first row that can't split then looked as if it started under a kept caption that it actually left alone at the foot of the page. The whole-row check and the start estimate include the edge. --- crates/layout/src/table_flow.rs | 5 +++-- crates/layout/src/tests.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/layout/src/table_flow.rs b/crates/layout/src/table_flow.rs index 4528a06799..0b2d89d041 100644 --- a/crates/layout/src/table_flow.rs +++ b/crates/layout/src/table_flow.rs @@ -82,7 +82,7 @@ pub(crate) fn table_start_need(ctx: &mut Ctx, t: &wordcraft_doc::Table, block: u let head: f32 = tl.rows.iter().take(headers).map(|r| r.height).sum(); let (Some(row), Some(laid)) = (t.rows.get(headers), tl.rows.get(headers)) else { return head }; // ponytail: bisection assumes starting a row gets no harder with more room. - let (mut lo, mut hi) = (0.0f32, laid.height); + let (mut lo, mut hi) = (0.0f32, laid.height + laid.edge); for _ in 0..12 { let mid = (lo + hi) / 2.0; if row_can_start(ctx.doc, row, laid, mid, f32::MAX) { @@ -174,7 +174,8 @@ fn split_keeping_nested(doc: &wordcraft_doc::Document, row: &table::RowLayout, r } fn row_can_start(doc: &wordcraft_doc::Document, row: &wordcraft_doc::Row, laid: &table::RowLayout, room: f32, page_height: f32) -> bool { - if laid.height <= room + 0.01 { + // Whole, the row needs the border below it too, as `place_table` places it. + if laid.height + laid.edge <= room + 0.01 { return true; } if row.props.header || row.props.cant_split || (row.props.height_rule == HeightRule::Exact && row.props.height.is_some_and(|h| h > 0.0)) { diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 6c6b440da2..edd7762538 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -15383,3 +15383,29 @@ fn list_items_in_a_table_after_a_kept_caption_are_counted_once() { d.insert_block(StoryRef::Body, &Path::top(1), wordcraft_doc::Block::Table(t)).unwrap(); assert_eq!(labels(&lay(&d)), ["1.", "2."]); } + +/// A first row that can't split starts under a kept caption only where it fits with the border +/// below it, as placing it needs: otherwise the caption goes over with it instead of staying +/// alone at the foot of the page. Swept over the caption's space before in 1 pt steps, so the +/// room left lands between the row's height and its height with the border. +#[test] +fn a_caption_kept_with_an_unsplittable_row_counts_the_border_below_it() { + for fill in 20..34 { + for push in 0..24 { + let mut d = ruled_table(fill, 3, 6.0); + let Some(wordcraft_doc::Block::Table(t)) = d.body.get_mut(fill).map(std::sync::Arc::make_mut) else { panic!("no table") }; + t.rows[0].props.cant_split = true; + let mut caption = wordcraft_doc::Paragraph::with_text("Caption", Default::default()); + caption.props.keep_next = Some(true); + caption.props.space_before = Some(push as f32); + // No space after: what a kept paragraph's space after adds is not this test's. + caption.props.space_after = Some(0.0); + d.insert_block(StoryRef::Body, &Path::top(fill), wordcraft_doc::Block::Para(caption)).unwrap(); + let l = lay(&d); + let page_of = |hit: &dyn Fn(&Placed) -> bool| l.pages.iter().position(|p| p.items.iter().any(hit)).unwrap(); + let caption = page_of(&|it| matches!(it, Placed::Lines { story: StoryRef::Body, path, .. } if *path == Path::top(fill))); + let row = page_of(&|it| matches!(it, Placed::Cell { row: 0, .. })); + assert_eq!(caption, row, "{fill} filler lines, {push} pt before the caption: the caption stays on page {} alone", caption + 1); + } + } +} From 69578bbc6f3037e4947f6da8689f3b1414bec4da Mon Sep 17 00:00:00 2001 From: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Date: Tue, 27 Oct 2026 23:03:17 +0300 Subject: [PATCH 070/609] Layout: a kept paragraph fits by itself where its last line's text does Keep with next moves a paragraph only when it fits on the page by itself, and that check took its whole height, while placing the lines lets the last line's extra leading (multiple spacing above single) run into the bottom margin. A double-spaced caption whose text ends above the margin then stayed alone at the foot of the page, its table on the next. Word moves it with the table (measured in Word for Mac: Times New Roman 12 pt, double spacing, the caption 0, 4 and 8 pt below 52 exactly 12 pt lines; not kept, it stays on page 1). The check now uses the fit the lines are placed with (`fit_height`). --- crates/layout/src/flow.rs | 5 ++++- crates/layout/src/tests.rs | 39 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/crates/layout/src/flow.rs b/crates/layout/src/flow.rs index 63f338849d..c881b79d9e 100644 --- a/crates/layout/src/flow.rs +++ b/crates/layout/src/flow.rs @@ -343,7 +343,10 @@ impl<'a> Flow<'a> { line.end == LineEnd::PageBreak && self.pl.lines.last().is_some_and(|mark| only_markers(self.p, mark.start..mark.stop)) }); let height = self.pl.height + rooms.top + if break_mark { 0.0 } else { rooms.bottom }; - if !(rp.keep_lines || (rp.keep_next && pb.y + height <= pb.bottom + 0.01)) { + // It fits by itself where its last line does, that line's leading past its text in the bottom + // margin (Word moves a kept double-spaced caption whose text ends above the margin). + let own = self.pl.lines.last().map_or(height, |l| height - l.height + fit_height(pb, l, rp, pb.notes.is_empty())); + if !(rp.keep_lines || (rp.keep_next && pb.y + own <= pb.bottom + 0.01)) { return before; } let need = height + if rp.keep_next { next_first_line(ctx, self.block, self.width, 0, &mut ctx.counters.clone()) } else { 0.0 }; diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index edd7762538..4b175fca0e 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -15409,3 +15409,42 @@ fn a_caption_kept_with_an_unsplittable_row_counts_the_border_below_it() { } } } + +/// A double-spaced caption kept with a table fits by itself where its text does, its last line's +/// leading running into the bottom margin, and so it goes over with the table that doesn't fit +/// under it. Measured in Word for Mac (Times New Roman 12 pt, double spacing, the caption's top +/// 0, 4 and 8 pt below the foot of 52 exactly 12 pt lines): not kept, the caption stays at the +/// foot of page 1; kept, it starts page 2 with the table. +#[test] +fn a_kept_caption_whose_leading_runs_into_the_bottom_margin_goes_with_the_table() { + use wordcraft_doc::props::LineSpacing; + let fill = 52; + for push in [0.0f32, 4.0, 8.0] { + for keep in [false, true] { + let mut d = Document::from_text(&format!("{}Caption", "filler\n".repeat(fill))); + let styles = Arc::make_mut(&mut d.styles); + styles.default_chr.font = Some(WRAP_TEST_FONT.into()); + styles.default_chr.size = Some(12.0); + for i in 0..=fill { + let p = d.para_mut(StoryRef::Body, &Path::top(i)).unwrap(); + p.props.line_spacing = Some(if i < fill { LineSpacing::Exactly(12.0) } else { LineSpacing::Multiple(2.0) }); + p.props.space_before = Some(if i < fill { 0.0 } else { push }); + p.props.space_after = Some(0.0); + p.props.keep_next = Some(i == fill && keep); + } + let mut t = Table::new(3, 1, 468.0); + t.rows[0].props.cant_split = true; + for row in &mut t.rows { + row.cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("row", Default::default()))]; + } + d.insert_block(StoryRef::Body, &Path::top(fill + 1), wordcraft_doc::Block::Table(t)).unwrap(); + let l = lay(&d); + let caption = l + .pages + .iter() + .position(|p| p.items.iter().any(|it| matches!(it, Placed::Lines { story: StoryRef::Body, path, .. } if *path == Path::top(fill)))) + .unwrap(); + assert_eq!(caption, usize::from(keep), "{push} pt before the caption, kept with the table: {keep}"); + } + } +} From 9f34d3790e90746812f474632118f96dce5c9962 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Thu, 12 Nov 2026 20:19:30 +0000 Subject: [PATCH 071/609] ODT: a header as tall as the page leaves the text room (#5806) A header's fo:min-height raised to the page height made the text's top margin the bottom of the page, so each page drew one line off the paper and the rest of the body was lost from the render and PDF. Header and footer bands now grow the margins only while the text keeps half an inch, as Page Setup's margins must; the smaller band is kept whole. --- crates/formats/src/odt/import.rs | 29 ++++++++++++----- crates/formats/src/odt/tests_more/headers.rs | 33 ++++++++++++++++++++ docs/odf-interpretation.md | 4 ++- 3 files changed, 58 insertions(+), 8 deletions(-) diff --git a/crates/formats/src/odt/import.rs b/crates/formats/src/odt/import.rs index 8660fd122f..5c97bf11b8 100644 --- a/crates/formats/src/odt/import.rs +++ b/crates/formats/src/odt/import.rs @@ -1213,6 +1213,9 @@ fn line_numbering(a: &Attrs) -> Option { Some(LineNumbering { count_by, start: 1, distance, restart }) } +/// Text room, points, that header and footer bands leave on a page (as Page Setup's margins must). +const MIN_TEXT_ROOM: f32 = 36.0; + /// A page layout's header or footer area (`style:header-style`/`style:footer-style`, ODF 1.3 /// §16.6–16.7): its minimum height and its spacing from the text, in points. #[derive(Clone, Copy, Default)] @@ -1390,19 +1393,31 @@ fn read_pages(xml: &[u8], paper: (f32, f32)) -> Pages { // measures the header's distance and the text's margin from the edge. How the band's // height and spacing add up, and what an unstated height or spacing rule is, the // standard leaves open (see `Band::room`). - let limit = sec.page_w.max(sec.page_h); + // The bands grow the margins only while the text keeps half an inch (Page Setup's rule for + // margins), or what the page's margins leave: a band as tall as the page (to fit a + // full-page picture, #5806) would put the text below the paper. The smaller band is kept + // whole and the other takes the rest. + let fit = (sec.page_h - sec.margin_top - sec.margin_bottom - MIN_TEXT_ROOM).max(0.0); + let (h_room, h_gap) = if header { hb.room() } else { (0.0, 0.0) }; + let (f_room, f_gap) = if footer { fb.room() } else { (0.0, 0.0) }; + let (h_room, f_room) = (h_room.max(0.0), f_room.max(0.0)); + let (h_room, f_room) = if h_room <= f_room { + let h = h_room.min(fit); + (h, f_room.min(fit - h)) + } else { + let f = f_room.min(fit); + (h_room.min(fit - f), f) + }; if header { - let (room, gap) = hb.room(); sec.header = sec.margin_top; - sec.margin_top = (sec.margin_top + room).min(limit); + sec.margin_top += h_room; // Content taller than the band pushes the text down, the spacing below it kept or not. - sec.header_gap = gap; + sec.header_gap = h_gap; } if footer { - let (room, gap) = fb.room(); sec.footer = sec.margin_bottom; - sec.margin_bottom = (sec.margin_bottom + room).min(limit); - sec.footer_gap = gap; + sec.margin_bottom += f_room; + sec.footer_gap = f_gap; } // A one-column layout keeps the default columns (and their gap). if let Some(c) = cols.as_ref().filter(|c| c.count > 1) { diff --git a/crates/formats/src/odt/tests_more/headers.rs b/crates/formats/src/odt/tests_more/headers.rs index 80478447d4..57c779bc10 100644 --- a/crates/formats/src/odt/tests_more/headers.rs +++ b/crates/formats/src/odt/tests_more/headers.rs @@ -186,6 +186,39 @@ fn a_header_without_a_stated_height_has_no_band() { } } +#[test] +fn a_header_band_as_tall_as_the_page_leaves_the_text_room() { + // #5806: a header's min-height raised to the page height (to fit a full-page picture) made + // the text's top margin the page's bottom edge, so each page drew one line off the paper and + // the rest of the text was lost. The bands grow the margins only while the text keeps half an + // inch, as Page Setup's margins must. + let content = format!( + r#"ab"#, + crate::odt::tests::NS_T + ); + let hf = "HF"; + let room = |styles: &str| { + let s = import(&crate::odt::tests::package(&content, Some(styles))).unwrap().last_section; + (s.page_h - s.margin_top - s.margin_bottom, s) + }; + let tall_header = styles_with_header(hf).replace(r#"fo:min-height="0.5cm""#, r#"fo:min-height="29.7cm""#); + let (left, s) = room(&tall_header); + assert!(left >= 36.0 - 0.05, "text room {left}: {s:?}"); + // The header still starts at the page margin; the text right after as much band as fits. + let near = |a: f32, b: f32| (a - b).abs() < 0.05; + assert!(near(s.header, cm(2.0)) && near(s.margin_top, s.page_h - cm(3.0) - 36.0), "{s:?}"); + // A footer as tall as the page leaves it too, and so do both at once. + let tall_footer = styles_with_header(hf).replace(r#"fo:min-height="1cm""#, r#"fo:min-height="29.7cm""#); + let (left, s) = room(&tall_footer); + assert!(left >= 36.0 - 0.05 && near(s.margin_top, cm(2.75)), "text room {left}: {s:?}"); + let both = tall_header.replace(r#"fo:min-height="1cm""#, r#"fo:min-height="29.7cm""#); + let (left, s) = room(&both); + assert!(left >= 36.0 - 0.05, "text room {left}: {s:?}"); + // Bands that fit are as stated. + let (_, s) = room(&styles_with_header(hf)); + assert!(near(s.margin_top, cm(2.75)) && near(s.margin_bottom, cm(3.0)), "{s:?}"); +} + #[test] fn header_and_footer_distances_round_trip() { let mut d = Document::new(); diff --git a/docs/odf-interpretation.md b/docs/odf-interpretation.md index 9f3217a4e1..2b925b0e43 100644 --- a/docs/odf-interpretation.md +++ b/docs/odf-interpretation.md @@ -1,6 +1,6 @@ # How WordCraft interprets OpenDocument files -> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-05 · **Change:** trivial (a document's language: kept on any save, and stated when written from the model); previously major (no more settings: one choice for each case the standard leaves open); previously trivial (what is written as read: unchanged paragraphs with drawings, comments, changes or marks too); previously minor (the two presets are Microsoft Word style and LibreOffice style; CLI values listed one by one); previously minor (deviations from the standard listed; ODF 1.2 → 1.3 checked); previously major (new: the ODF interpretation profile and the list of every case) +> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-12 · **Change:** trivial (header and footer bands leave the text room on the page, #5806); previously trivial (a document's language: kept on any save, and stated when written from the model); previously major (no more settings: one choice for each case the standard leaves open); previously trivial (what is written as read: unchanged paragraphs with drawings, comments, changes or marks too); previously minor (the two presets are Microsoft Word style and LibreOffice style; CLI values listed one by one); previously minor (deviations from the standard listed; ODF 1.2 → 1.3 checked); previously major (new: the ODF interpretation profile and the list of every case) OpenDocument (ODF 1.3, OASIS) leaves some of a document's look to the application. Part 3 §16.2 says that when no style sets a property and the standard gives no default, "an @@ -37,6 +37,7 @@ knows of, so none gets lost. | Page margins a page layout doesn't state | §20.206–20.209 refer to XSL §7.10 (initial value 0); whether that default comes with the reference is not said | 0 (XSL's initial value) | 2 cm (its own files always state theirs; some of its templates don't) | | Height of a header or footer whose style states none | §20.212.2 `fo:min-height`: no default | 0 (as tall as its text) | 0.5 cm | | *(meaning)* Whether a header's stated minimum height includes its stated spacing from the body | §20.212.2, §20.207: not said | no: spacing comes after the height | yes | +| *(meaning)* Header and footer heights that, with the page margins, leave no room for text (a header as tall as the page, to fit a full-page picture) | §20.212.2: not said | the bands take what leaves the text half an inch (Page Setup's rule for margins), the smaller band kept whole; the header is still drawn as tall as its content | not measured | | A header taller than its height with `style:dynamic-spacing` unstated | §20.264: no default | off: the spacing is kept (on, with no height stated, would always drop the spacing the file states) | off | | Where paragraph tab stops, default ones too, are measured from when `settings.xml` doesn't say | §19.512.3 `style:position` doesn't say; §19.861 covers only indexes | the margin (as Word; ONLYOFFICE's files mean this too) | the paragraph's left indent (its `TabsRelativeToIndent` default): explicit stops, the default stops every interval and the hanging indent's stop all move with the indent (measured) | | Gap between columns when `style:columns` states none | §19.233 `fo:column-gap`: no default (and explicitly not XSL's) | 0.5 in (Word's) | 0 | @@ -164,6 +165,7 @@ from public bug reports and ONLYOFFICE's converter test snapshots): | Date | Change | |---|---| +| 2026-11-12 | Header and footer heights too tall for the page (#5806): the bands leave the text half an inch, the smaller band kept whole. A header as tall as the page put the text below the paper, and the body was lost from the render and PDF. | | 2026-11-05 | A document's language is read from its default style or Standard and written back from the model. It was lost when a style or list definition changed (numbering, a new style), and readers then showed the document in their own default language. Styles written from the model no longer say English for a document that isn't. A language's script (`fo:script`) is kept with it, and a style with no parent takes the default style's language when Standard's differs. | | 2026-11-04 | The settings removed: File › Options › Advanced › OpenDocument files, `file.options` `odf`, `WORDCRAFT_ODF`, the LibreOffice style and custom values. WordCraft makes one choice for each case the standard leaves open, the one the default made, so nothing changes for a document opened with the default. What a file states is still followed, its `TabsRelativeToIndent` and `AddParaTableSpacing` among it. LibreOffice's choices stay listed beside WordCraft's. | | 2026-11-04 | How WordCraft writes ODF: unchanged paragraphs and tables with drawings, comments, tracked changes, notes or marks are written as read too (the text said from the model); what is edited, and the cases left in the element audit, from the model. | From 3d04c471a469bec24f9c15ff5843575c4358bf3f Mon Sep 17 00:00:00 2001 From: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Date: Tue, 27 Oct 2026 23:03:43 +0300 Subject: [PATCH 072/609] Layout: a paragraph kept with a table counts its space after The table starts below the space after the paragraph before it, so a paragraph kept with a table needs that space too, as Word has it: with 12 pt after a caption, Word moves the caption with the table once the header row and the start of the first row don't fit under the caption and its space after (measured in Word for Mac, compatibility modes 12 and 15). --- crates/layout/src/flow.rs | 4 +++- crates/layout/src/tests.rs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/crates/layout/src/flow.rs b/crates/layout/src/flow.rs index c881b79d9e..63e86fd781 100644 --- a/crates/layout/src/flow.rs +++ b/crates/layout/src/flow.rs @@ -349,7 +349,9 @@ impl<'a> Flow<'a> { if !(rp.keep_lines || (rp.keep_next && pb.y + own <= pb.bottom + 0.01)) { return before; } - let need = height + if rp.keep_next { next_first_line(ctx, self.block, self.width, 0, &mut ctx.counters.clone()) } else { 0.0 }; + // A table starts below the paragraph's space after. + let gap = if matches!(ctx.doc.body.get(self.block + 1).map(|b| &**b), Some(Block::Table(_))) { rp.space_after } else { 0.0 }; + let need = height + if rp.keep_next { gap + next_first_line(ctx, self.block, self.width, 0, &mut ctx.counters.clone()) } else { 0.0 }; // (Against the whole column: balanced columns grow to hold it.) // With the 0.01 pt of slack the other fit checks take. if pb.y + need > pb.bottom + 0.01 && !pb.fresh() && need <= pb.next_room(self.body_top) { diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 4b175fca0e..16f689ecff 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -15448,3 +15448,35 @@ fn a_kept_caption_whose_leading_runs_into_the_bottom_margin_goes_with_the_table( } } } + +/// A paragraph kept with a table counts its space after: the table starts below it, so the +/// caption goes over with the table when the header row and the start of the first row fit under +/// the caption but not under its space after (measured in Word for Mac, 12 pt after the caption, +/// compatibility modes 12 and 15). The bottom margin shrinks a point at a time. +#[test] +fn a_caption_kept_with_a_table_counts_its_space_after() { + for extra in 0..40 { + let fill = 22; + let mut d = Document::from_text(&format!("{}Caption", "filler\n".repeat(fill))); + d.last_section.margin_bottom -= extra as f32; + d.format_paragraphs(&Pos::body(fill, 0), &Pos::body(fill, 0), &|p| { + p.keep_next = Some(true); + p.space_after = Some(12.0); + }) + .unwrap(); + let mut t = Table::new(2, 1, 468.0); + t.rows[0].props.header = true; + t.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Header", Default::default()))]; + t.rows[1].cells[0].blocks = + vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(&"first row words go on and on ".repeat(60), Default::default()))]; + d.insert_block(StoryRef::Body, &Path::top(fill + 1), wordcraft_doc::Block::Table(t)).unwrap(); + let l = lay(&d); + let page = l + .pages + .iter() + .find(|p| p.items.iter().any(|it| matches!(it, Placed::Lines { story: StoryRef::Body, path, .. } if *path == Path::top(fill)))) + .unwrap(); + let rows: Vec = page.items.iter().filter_map(|it| if let Placed::Cell { row, .. } = it { Some(*row) } else { None }).collect(); + assert!(rows.contains(&1), "bottom margin -{extra}: the caption's page holds rows {rows:?}"); + } +} From 979077101fe2379f9630f24f56c5070928fe4528 Mon Sep 17 00:00:00 2001 From: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Date: Tue, 27 Oct 2026 23:03:42 +0300 Subject: [PATCH 073/609] Layout: tables at the foot of a page before Word 2013 layout Measured in Word for Mac with synthetic documents in compatibility modes 12 and 14 (and a document that doesn't state one): a row split across pages divides its cells' text at any line, with no widow/orphan control in the cells; the repeated header rows stay alone at the foot of a page when no line of the first row fits under them; and a paragraph kept with the table keeps with the header rows only (and the border below them, as placing them needs). Mode 15 (Word 2013 layout) is as before. --- crates/layout/src/para/paragraph.rs | 5 +++ crates/layout/src/table_flow.rs | 10 +++++- crates/layout/src/tests.rs | 54 +++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 1 deletion(-) diff --git a/crates/layout/src/para/paragraph.rs b/crates/layout/src/para/paragraph.rs index 6b2605e37c..a7c4129bc5 100644 --- a/crates/layout/src/para/paragraph.rs +++ b/crates/layout/src/para/paragraph.rs @@ -101,6 +101,11 @@ fn is_special(c: char) -> bool { fn paragraph_props(p: &Paragraph, env: &ParaEnv) -> ResolvedPara { let doc = env.doc; let mut rp = doc.styles.resolve_para_in(&p.props, env.table.map(|t| &t.para)); + // Before Word 2013 layout (compatibility mode 15) a row split across pages divides its cells' + // text at any line: widow/orphan control doesn't apply in a table (measured in modes 12, 14). + if env.table.is_some() && doc.settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT { + rp.widow_control = false; + } if let Some(spacing) = env.read_line_spacing.filter(|s| s.is_finite() && (1.0..=2.0).contains(s)) { rp.line_spacing = wordcraft_doc::props::LineSpacing::Multiple(spacing); } diff --git a/crates/layout/src/table_flow.rs b/crates/layout/src/table_flow.rs index 0b2d89d041..9f93c6c32a 100644 --- a/crates/layout/src/table_flow.rs +++ b/crates/layout/src/table_flow.rs @@ -73,6 +73,8 @@ pub(crate) fn footer_table_wraps(ctx: &mut Ctx, pb: &PageBuilder) -> Vec f32 { // A look ahead: list and equation numbers in the cells don't count yet. let (counters, eq_count) = (ctx.counters.clone(), ctx.eq_count); @@ -80,6 +82,10 @@ pub(crate) fn table_start_need(ctx: &mut Ctx, t: &wordcraft_doc::Table, block: u (ctx.counters, ctx.eq_count) = (counters, eq_count); let headers = t.rows.iter().take_while(|r| r.props.header).count(); let head: f32 = tl.rows.iter().take(headers).map(|r| r.height).sum(); + if headers > 0 && ctx.doc.settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT { + // With the border below the last of them, as `place_table` places them. + return head + tl.rows.get(headers - 1).map_or(0.0, |r| r.edge); + } let (Some(row), Some(laid)) = (t.rows.get(headers), tl.rows.get(headers)) else { return head }; // ponytail: bisection assumes starting a row gets no harder with more room. let (mut lo, mut hi) = (0.0f32, laid.height + laid.edge); @@ -259,9 +265,11 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc t.rows.get(ri).is_some_and(|r| r.props.height_rule == HeightRule::AtLeast && r.props.height.is_some_and(|h| h > room + 0.01)) }; // Like Word, repeated header rows don't stay alone at the bottom of a page: when the first row - // after them can't start under them there, the table starts on the next page. + // after them can't start under them there, the table starts on the next page. Before Word + // 2013 layout (compatibility mode 15) they do (measured in modes 12 and 14). let first = header_rows.len(); if !header_rows.is_empty() + && ctx.doc.settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT && !pb.at_top() && let Some(row) = tl.rows.get(first) { diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 4b175fca0e..558c69f6df 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -15448,3 +15448,57 @@ fn a_kept_caption_whose_leading_runs_into_the_bottom_margin_goes_with_the_table( } } } + +/// Before Word 2013 layout (compatibility mode 15, measured in Word for Mac in modes 12 and 14) a +/// row split across pages divides its cells' text at any line, the repeated header row may stay +/// alone at the foot of a page, and a caption kept with the table keeps with the header row only. +/// The caption's space before grows a point at a time under lines exactly 12 pt high, so it lands +/// at every offset from the foot of the page, whatever the font's metrics. +#[test] +fn before_word_2013_layout_a_kept_caption_goes_with_the_header_row_only() { + let (mut one_line, mut header_alone) = (false, false); + // 44 lines end 120 pt above the bottom margin. + let fill = 44; + for push in 0..120 { + let mut d = Document::from_text(&format!("{}Caption", "filler\n".repeat(fill))); + d.settings.compat_mode = wordcraft_doc::LEGACY_COMPAT_MODE; + d.format_paragraphs(&Pos::body(0, 0), &Pos::body(fill - 1, 0), &|p| { + p.line_spacing = Some(wordcraft_doc::props::LineSpacing::Exactly(12.0)); + p.space_before = Some(0.0); + p.space_after = Some(0.0); + }) + .unwrap(); + // (No space after the caption: the table starts right under it.) + d.format_paragraphs(&Pos::body(fill, 0), &Pos::body(fill, 0), &|p| { + p.keep_next = Some(true); + p.space_before = Some(push as f32); + p.space_after = Some(0.0); + }) + .unwrap(); + let mut t = Table::new(2, 1, 468.0); + t.rows[0].props.header = true; + t.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Header", Default::default()))]; + t.rows[1].cells[0].blocks = + vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(&"first row words go on and on ".repeat(60), Default::default()))]; + d.insert_block(StoryRef::Body, &Path::top(fill + 1), wordcraft_doc::Block::Table(t)).unwrap(); + let l = lay(&d); + let page = l + .pages + .iter() + .find(|p| p.items.iter().any(|it| matches!(it, Placed::Lines { story: StoryRef::Body, path, .. } if *path == Path::top(fill)))) + .unwrap(); + let rows: Vec = page.items.iter().filter_map(|it| if let Placed::Cell { row, .. } = it { Some(*row) } else { None }).collect(); + let lines: usize = page + .items + .iter() + .filter_map(|it| match it { + Placed::Lines { path, l0, l1, .. } if path.0.len() > 1 && path.0.get(1) == Some(&1) => Some(l1 - l0), + _ => None, + }) + .sum(); + assert!(rows.contains(&0), "{push} pt before the caption: the caption is alone on its page"); + one_line |= lines == 1; + header_alone |= !rows.contains(&1); + } + assert!(one_line && header_alone, "one line of the first row: {one_line}, the header row alone: {header_alone}"); +} From 40810c50de03c8ec7c52a445ddc0bd7851ae0224 Mon Sep 17 00:00:00 2001 From: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:14:49 +0300 Subject: [PATCH 074/609] Layout: an inline picture is as high as its whole twips, as in Word Word keeps a picture's height in whole twips and drops the rest of the EMUs: 2661310 EMU (209.552pt) is drawn 209.55pt high, and at the foot of a page only that has to fit above the bottom margin. Word for Mac: a picture of 14170.998 twips stays where one of 14171 twips moves on, at single and 1.5 spacing. Test: a_picture_is_as_high_as_its_whole_twips_and_fits_by_them_at_the_page_bottom (fails before this change). --- crates/layout/src/para/paragraph.rs | 5 +++++ crates/layout/src/tests.rs | 34 +++++++++++++++++++++++++++++ docs/layout-parity.md | 1 + 3 files changed, 40 insertions(+) diff --git a/crates/layout/src/para/paragraph.rs b/crates/layout/src/para/paragraph.rs index 6b2605e37c..09027afa03 100644 --- a/crates/layout/src/para/paragraph.rs +++ b/crates/layout/src/para/paragraph.rs @@ -392,6 +392,11 @@ impl<'a> Shaped<'a> { }, _ => w, }; + // Word keeps the height in whole twips and drops the rest of the EMUs: 2007874 EMU + // (3161.99tw) is drawn 158.05pt high, and only that has to fit above the bottom margin + // (Word for Mac and Windows). Back to whole EMUs first: f32 points keep them to the EMU + // for pictures up to a page high. + let h = (((h as f64 * 12_700.0).round() / 635.0).floor() / 20.0) as f32; let (w, h) = (w.clamp(1.0, 4000.0), h.clamp(1.0, 4000.0)); let s = if env.fit_objects && w > maxw { maxw / w } else { 1.0 }; // The line makes room for effects (shadows) around the picture too, and diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index a15f2f672b..241d6d324f 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -5758,6 +5758,40 @@ fn line_spacing_does_not_scale_pictures() { assert!((line.baseline - line.top - 144.0).abs() < 0.01, "the picture stands on the baseline"); } +#[test] +fn a_picture_is_as_high_as_its_whole_twips_and_fits_by_them_at_the_page_bottom() { + // Word drops the EMUs past a whole twip: a picture 1 EMU short of a twip taller than the room + // left is 400pt high and stays, one 1.2tw taller is 400.05pt and moves on (Word for Mac and + // Windows: a 209.552pt picture is drawn 209.55pt high). + use wordcraft_doc::props::LineSpacing; + let room = 400.0; + let doc = |pic: f32| { + let mut d = Document::from_text("Text"); + let s = d.last_section.clone(); + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + p.props.line_spacing = Some(LineSpacing::Exactly(20.0)); + p.props.space_before = Some(0.0); + p.props.space_after = Some(s.page_h - s.margin_bottom - s.margin_top - 20.0 - room); + let mut q = wordcraft_doc::Paragraph::with_text("", Default::default()); + q.props.line_spacing = Some(LineSpacing::Multiple(1.0)); + q.props.space_before = Some(0.0); + q.insert_object(0, picture(100.0, pic, Default::default()), &Default::default()).unwrap(); + d.body.push(wordcraft_doc::para_block(q)); + d + }; + let first_line = |l: &DocLayout| { + l.pages[0].items.iter().find_map(|i| match i { + Placed::Lines { para, l0, .. } if para.lines[*l0].text_asc >= room - 1.0 => Some(para.lines[*l0].text_asc), + _ => None, + }) + }; + // 1 EMU short of a whole twip still drops the twip. + let l = lay(&doc(room + 0.05 - 1.0 / 12_700.0)); + let Some(asc) = first_line(&l) else { panic!("a picture 1 EMU under 400.05pt should stay on page 1 ({} pages)", l.pages.len()) }; + assert!((asc - room).abs() < 0.001, "the picture is {asc}pt high, want {room}"); + assert!(first_line(&lay(&doc(room + 0.06))).is_none(), "a picture of 400.05pt should move on"); +} + #[test] fn multiple_line_spacing_adds_its_leading_below_the_text() { crate::test_fonts(); diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 0a39f59cca..c4422c9fb4 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -527,6 +527,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | 2026-11-02 | trivial | For ODT documents, LibreOffice's layout: a line holding only in-line pictures is as tall as they are, without its font's ascent and descent (`Settings::odf_layout`, set when an ODT opens; Word keeps the font's, so other documents are unchanged). Measured in LibreOffice: a 3.6 pt rule's line is 3.6 pt; WordCraft's had been 15.5 pt (`tests::a_line_of_only_pictures_fits_them_in_odt_documents`) | | 2026-11-02 | trivial | Beyond Word, for ODT documents: a table's own space above and below (`TableProps::space_before`/`space_after`) moves the text around it, and a header (footer) taller than its margin keeps its spacing between it and the body (`SectionProps::header_gap`/`footer_gap`; Word keeps none, so DOCX documents are unchanged) (`tests::a_tables_own_space_above_and_below_moves_the_text`, `tests::body_starts_right_below_a_tall_header`) | | 2026-11-02 | trivial | A page break before the paragraph in a table's first row moves the whole table to the next page, as in Word (it was ignored); emphasis marks (Font › Emphasis mark) are drawn over or under each character and make the line taller | +| 2026-11-12 | trivial | An in-line picture is as high as its whole twips: Word keeps the height in twips and drops the rest of the EMUs (2661310 EMU, 209.552 pt, is drawn 209.55 pt high), and at the foot of a page only that has to fit above the bottom margin. In Word for Mac a picture of 14170.998 twips stays on the page and one of 14171 twips moves on (`tests::a_picture_is_as_high_as_its_whole_twips_and_fits_by_them_at_the_page_bottom`) | Maintenance on 2026-10-12 retains current tracked-deletion, endnote, footer-total, text-box and balloon layout while supplying explicit cell identity at every box call. The native Word From cf0f6876b998c380b422809d83ea059ecee90fde Mon Sep 17 00:00:00 2001 From: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:39:51 +0300 Subject: [PATCH 075/609] layout: a letter ending a line is measured without its kerning pair with the next Word lays each line out on its own: a long word broken by letters fits only as far as its letters fit without the pair they kern with the letter that goes on to the next line. A cell's width swept a twip at a time in Word for Windows (Times New Roman 10 pt, kerning on): the first 12 letters of a 15-letter word fit from their width alone, 0.34 pt more than they take with the pair after them, so narrow cells broke a letter later than Word. Each cluster keeps what kerning added to its advance; the fit check drops it when a letter follows. Test: a_word_broken_by_letters_ends_without_its_kerning_pair (fails before this change). --- crates/layout/src/para/builder.rs | 9 ++++++-- crates/layout/src/para/lines.rs | 13 ++++++++++- crates/layout/src/para/model.rs | 3 +++ crates/layout/src/para/paragraph.rs | 1 + crates/layout/src/tests.rs | 13 ++++++++++- crates/layout/src/tests/line_end_kern.rs | 29 ++++++++++++++++++++++++ 6 files changed, 64 insertions(+), 4 deletions(-) create mode 100644 crates/layout/src/tests/line_end_kern.rs diff --git a/crates/layout/src/para/builder.rs b/crates/layout/src/para/builder.rs index 99ae60f6f3..7a44aa3713 100644 --- a/crates/layout/src/para/builder.rs +++ b/crates/layout/src/para/builder.rs @@ -415,12 +415,15 @@ impl<'a> Builder<'a> { let ge = bounds.get(bi + 1).copied().unwrap_or(shape_text.len()); let g0 = self.glyphs.len() as u32; let mut adv = 0.0f32; + // What kerning added to the last glyph's advance: its pair with the next glyph. + let mut kern = 0.0f32; while let Some(g) = shaped.get(gi) { if g.cluster >= ge { break; } self.glyphs.push(Glyph { gid: g.gid, dx: adv + g.x_offset as f32 * k * hscale, dy: g.y_offset as f32 * k }); adv += g.x_advance as f32 * k * hscale; + kern = if rc.kerned() && !key.rtl { (g.x_advance as f32 - st.face.advance(g.gid) as f32) * k * hscale } else { 0.0 }; gi += 1; } let g1 = self.glyphs.len() as u32; @@ -448,6 +451,7 @@ impl<'a> Builder<'a> { obj_h: 0.0, obj_d: 0.0, dot: s == "." || s == ",", + kern: if kind == ClKind::Text && g1 == g0 + 1 { kern } else { 0.0 }, }); } if matches!(dir, Dir::Para) { @@ -520,6 +524,7 @@ impl<'a> Builder<'a> { obj_h: 0.0, obj_d: 0.0, dot: false, + kern: 0.0, }); return; }; @@ -553,7 +558,7 @@ impl<'a> Builder<'a> { let style = first.style; let g1 = added.last().map(|c| c.g1).unwrap_or(g0); self.shown.push((self.clusters.len(), text.to_string(), ranges)); - self.clusters.push(Cluster { start, end, adv: x, kind: ClKind::Text, style, g0, g1, break_after: false, obj_h: 0.0, obj_d: 0.0, dot: false }); + self.clusters.push(Cluster { start, end, adv: x, kind: ClKind::Text, style, g0, g1, break_after: false, obj_h: 0.0, obj_d: 0.0, dot: false, kern: 0.0 }); } /// Shape `texts` on top of one another as one cluster for `start..end`: each aligned within @@ -603,7 +608,7 @@ impl<'a> Builder<'a> { if !text.is_empty() { self.shown.push((k, text, ranges)); } - self.clusters.push(Cluster { start, end, adv, kind: ClKind::Text, style, g0, g1, break_after: false, obj_h: 0.0, obj_d: 0.0, dot: false }); + self.clusters.push(Cluster { start, end, adv, kind: ClKind::Text, style, g0, g1, break_after: false, obj_h: 0.0, obj_d: 0.0, dot: false, kern: 0.0 }); Some(k) } } diff --git a/crates/layout/src/para/lines.rs b/crates/layout/src/para/lines.rs index 821132f6aa..9812752a04 100644 --- a/crates/layout/src/para/lines.rs +++ b/crates/layout/src/para/lines.rs @@ -894,7 +894,7 @@ impl Scan { 0.0 }; let fits = absorbs - || self.x + advance - pl.auto_space_after(j) <= self.right_edge + shrink + 0.01 + || self.x + advance - pl.auto_space_after(j) - line_end_kern(pl, j) <= self.right_edge + shrink + 0.01 || c.kind == ClKind::Space || c.kind == ClKind::Marker; if !fits && pl.is_edit_boundary(c.start) && (c0..j).any(|k| pl.clusters.get(k).is_some_and(takes_room)) { @@ -1060,6 +1060,17 @@ impl Scan { } } +/// The kerning cluster `j` loses when the line ends after it inside a word: Word measures a line's +/// last letter without its pair with the letter that goes on to the next line (a cell's width +/// swept a twip at a time in Word: the letters before a broken kerning pair fit only where they +/// fit on their own, without the pair). +fn line_end_kern(pl: &ParaLayout, j: usize) -> f32 { + match (pl.clusters.get(j), pl.clusters.get(j + 1)) { + (Some(c), Some(next)) if next.kind == ClKind::Text => c.kern, + _ => 0.0, + } +} + /// Narrowest span text flows into beside a floating object, points. Word puts an empty /// paragraph beside a floating table in a 21.3pt gap but not in an 18.6pt one. const MIN_SPAN: f32 = 20.0; diff --git a/crates/layout/src/para/model.rs b/crates/layout/src/para/model.rs index 7c5aa4b3ed..756aeb07bb 100644 --- a/crates/layout/src/para/model.rs +++ b/crates/layout/src/para/model.rs @@ -144,6 +144,9 @@ pub struct Cluster { pub obj_d: f32, /// The cluster is a decimal separator (decimal tabs align on it). pub dot: bool, + /// The kerning between this cluster and the next (part of `adv`, usually negative): a line + /// that ends between them lays the cluster out without it. + pub kern: f32, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/crates/layout/src/para/paragraph.rs b/crates/layout/src/para/paragraph.rs index 6b2605e37c..979a0cea24 100644 --- a/crates/layout/src/para/paragraph.rs +++ b/crates/layout/src/para/paragraph.rs @@ -62,6 +62,7 @@ impl Slot { obj_h, obj_d, dot: false, + kern: 0.0, } } } diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index a15f2f672b..d6fb3643c4 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -12,6 +12,7 @@ mod complex; mod float_top; mod grid; mod ligature; +mod line_end_kern; pub(crate) mod linear; mod missing_glyphs; mod nbsp; @@ -931,7 +932,7 @@ fn a_megabyte_long_word_lays_out_quickly() { /// A cluster with the given advance and kind, for the tests that measure a word by hand. fn word_cluster(kind: para::ClKind, adv: f32, break_after: bool) -> para::Cluster { - para::Cluster { start: 0, end: 1, adv, kind, style: 0, g0: 0, g1: 1, break_after, obj_h: 0.0, obj_d: 0.0, dot: false } + para::Cluster { start: 0, end: 1, adv, kind, style: 0, g0: 0, g1: 1, break_after, obj_h: 0.0, obj_d: 0.0, dot: false, kern: 0.0 } } /// A word that a negative advance makes narrower still fits beside a float: the width of a word @@ -7592,6 +7593,16 @@ fn no_line_break_right_after_a_slash() { assert!(lines > 10, "{lines} lines"); } +/// The lines of the body's first paragraph, as text. +fn body_lines(l: &DocLayout, text: &str) -> Vec { + l.pages + .iter() + .flat_map(|p| &p.items) + .filter_map(|it| if let Placed::Lines { para, l0, l1, .. } = it { Some(para.lines[*l0..*l1].iter().map(|line| text[line.start..line.stop].to_string())) } else { None }) + .flatten() + .collect() +} + /// #2963: a word after a slash ("caption /заполняется") wraps whole, as in Word. UAX #14 forbids a /// break between the space and the slash, and the break after the slash is dropped (Word keeps /// "and/or" whole), so the slash word had no break before it and split between two letters. diff --git a/crates/layout/src/tests/line_end_kern.rs b/crates/layout/src/tests/line_end_kern.rs new file mode 100644 index 0000000000..b7d246c33c --- /dev/null +++ b/crates/layout/src/tests/line_end_kern.rs @@ -0,0 +1,29 @@ +//! A long word broken by letters: the letter ending the line is measured without its kerning +//! pair with the letter that goes on to the next line (Word, a line's width swept a twip at a +//! time: the letters before a broken kerning pair fit only where they fit on their own). + +use super::*; + +#[test] +fn a_word_broken_by_letters_ends_without_its_kerning_pair() { + let text = "AVAVAVAVAVAVAVAVAVAV"; + let doc = |indent_right: f32| { + let mut d = Document::from_text(text); + Arc::make_mut(&mut d.styles).default_chr.kern = Some(1.0); + d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap(); + d + }; + // The word on one line: the first five letters' width with the "AV" pair after the fifth + // and without it. + let l = lay(&doc(0.0)); + let para = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap(); + let paired: f32 = para.clusters[..5].iter().map(|c| c.adv).sum(); + let alone = paired - para.clusters[4].kern; + assert!(alone - paired > 0.1, "the test font kerns \"AV\": {paired} vs {alone}"); + // A line between the two takes four letters, as in Word; with the pair it took five. + let got = body_lines(&lay(&doc(468.0 - (paired + alone) / 2.0)), text); + assert_eq!(got.first().map(String::as_str), Some("AVAV"), "{got:?}"); + // A line as wide as the five letters alone takes them. + let got = body_lines(&lay(&doc(468.0 - alone - 0.004)), text); + assert_eq!(got.first().map(String::as_str), Some("AVAVA"), "{got:?}"); +} From 6a35fc23a77967a05a2513c10bdf5b01bca8def9 Mon Sep 17 00:00:00 2001 From: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:48:32 +0300 Subject: [PATCH 076/609] Layout: a multiple-spaced line's leading may run past a footer above the margin Word lets the leading of a page's last line with multiple spacing above single run into the bottom margin (fit_height). It lets it run past the top of a footer that reaches above the margin just the same: only the text has to end above the footer, whatever the footer holds (a page number, several lines of text, an empty exact-height paragraph). WordCraft kept the whole line clear of such a footer and moved it to the next page. Measured in Word for Mac and Windows: a 1.5-spaced 12pt line pushed down by half a point at a time stays on the page while its text ends above the footer, with a one-line page-number footer 6.6pt and 28pt above the margin, a four-line footer and an empty 120pt exact-height paragraph; with a title-page footer, the first page's own footer counts there. The page builder keeps the leading's floor as the page starts: the bottom margin, or the top of that page's footer when it is higher. Test: pages::a_multiple_spaced_lines_leading_may_run_past_a_footer_above_the_margin (fails before this change). --- crates/layout/src/flow.rs | 6 +-- crates/layout/src/page.rs | 11 ++++++ crates/layout/src/pass.rs | 1 + crates/layout/src/tests/pages.rs | 64 ++++++++++++++++++++++++++++++++ docs/layout-parity.md | 1 + 5 files changed, 80 insertions(+), 3 deletions(-) diff --git a/crates/layout/src/flow.rs b/crates/layout/src/flow.rs index f47cb16151..5f1e929b73 100644 --- a/crates/layout/src/flow.rs +++ b/crates/layout/src/flow.rs @@ -741,10 +741,10 @@ fn notes_limit(pb: &PageBuilder, new_notes: &[NoteBox], line_notes: &[NoteBox]) /// the text (see `baseline_offset`), and Word lets that leading of a page's last line run into the /// bottom margin: only the text has to fit (observed: a double-spaced 12pt line stays on the page /// while its text ends above the margin, about half a line lower than when the whole line must -/// fit). Only the bottom margin takes that leading: a footer taller than the margin, or -/// footnotes (`free` is false), keep the whole line clear of them. +/// fit). Only the bottom margin takes that leading, or the top of a footer that reaches above it +/// (see [`PageBuilder::at_margin`]): footnotes (`free` is false) keep the whole line clear of them. fn fit_height(pb: &PageBuilder, l: ¶::Line, rp: &wordcraft_doc::resolve::ResolvedPara, free: bool) -> f32 { - let at_margin = pb.bottom >= pb.sect.page_h - pb.sect.margin_bottom - 0.01; + let at_margin = pb.at_margin(); match rp.line_spacing { // `baseline` is from the paragraph's top; the text ends a descent below it. wordcraft_doc::props::LineSpacing::Multiple(m) if m > 1.0 && at_margin && free => (l.baseline - l.top + l.text_desc).clamp(0.0, l.height), diff --git a/crates/layout/src/page.rs b/crates/layout/src/page.rs index 14c611f2da..0747cfebad 100644 --- a/crates/layout/src/page.rs +++ b/crates/layout/src/page.rs @@ -80,6 +80,9 @@ pub(crate) struct PageBuilder<'a> { /// Top of the footer of the pages being started: a footer reaching above the bottom margin /// pushes the body up (`f32::MAX`: no footer). pub(crate) foot_top: f32, + /// How low the last line's leading may reach on the current page: the bottom margin, or the + /// top of a footer reaching above it (set as the page starts, from that page's footer). + pub(crate) leading_floor: f32, /// The wrap areas pages start with ([`EarlyFloats`]) ... pub(crate) early: &'a EarlyFloats, /// ... and how many of the current page's `excl` they are (its first ones). @@ -324,6 +327,7 @@ impl PageBuilder<'_> { self.number = self.restart_at.take().unwrap_or_else(|| self.number.saturating_add(1)); let (w, h) = if self.web { (s.page_w, f32::MAX / 4.0) } else { (s.page_w, s.page_h) }; let bottom = self.body_bottom(body_top); + self.leading_floor = (s.page_h - s.margin_bottom).min(self.foot_top); let body = Rect::new(s.margin_left + s.gutter, body_top, s.text_width(), (bottom - body_top).max(36.0)); let mut decor = Vec::new(); if !self.web { @@ -401,6 +405,13 @@ impl PageBuilder<'_> { self.bottom = self.bottom.min(self.top + h); } } + /// Whether the body ends at the bottom margin, or at the top of a footer that reaches above + /// it: the page's last multiple-spaced line may leave its leading there (see `fit_height`). + /// Word lets it run past the footer's top as into the margin, whatever the footer holds (a + /// page number, several lines of text, an empty paragraph): only the text has to end above it. + pub(crate) fn at_margin(&self) -> bool { + self.bottom >= self.leading_floor - 0.01 + } /// The bottom of the body on a page started with its body at `body_top`: a footer taller than /// the bottom margin pushes it up (Word: no gap), leaving it at least a little room. fn body_bottom(&self, body_top: f32) -> f32 { diff --git a/crates/layout/src/pass.rs b/crates/layout/src/pass.rs index a29b2a700c..654393d8a2 100644 --- a/crates/layout/src/pass.rs +++ b/crates/layout/src/pass.rs @@ -220,6 +220,7 @@ fn new_page_builder<'p>( sect_beneath: false, beneath: false, foot_top: f32::MAX, + leading_floor: 0.0, early, seeded: 0, settle, diff --git a/crates/layout/src/tests/pages.rs b/crates/layout/src/tests/pages.rs index 46252bac6e..d46c7ccd83 100644 --- a/crates/layout/src/tests/pages.rs +++ b/crates/layout/src/tests/pages.rs @@ -584,6 +584,70 @@ fn a_roman_page_number_in_the_footer_stays_roman_with_the_page_count_in_the_body } } +#[test] +fn a_multiple_spaced_lines_leading_may_run_past_a_footer_above_the_margin() { + // A footer reaching above the bottom margin: Word lets the leading of the page's last + // 1.5-spaced line run past its top as into the margin, only the text has to fit, whatever the + // footer holds. Word for Mac and Windows, a 1.5-spaced 12pt line pushed down by half a point: + // it stays while its text ends above the footer (up to 0.4pt above), with a one-line + // page-number footer above the margin by 6.6pt and by 28pt, with a four-line footer, and with + // an empty exact-height 120pt paragraph. Also when the footer is the first page's own (a title + // page footer, the other pages' footer short): the first page's footer counts there. + use wordcraft_doc::props::LineSpacing; + // (footer lines, their text, the title page's own footer, footer distance from the page bottom) + let cases: [(usize, &str, bool, Option); 4] = + [(1, "", false, None), (1, "", true, None), (1, "7", false, Some(72.0)), (4, "Footer line", false, None)]; + for (lines, text, first, from_bottom) in cases { + let mut past_footer = 0; + for shift in (0..28).step_by(2) { + let mut d = Document::from_text(&"Several words wrap onto many lines of a long paragraph. ".repeat(60)); + if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(0).map(Arc::make_mut) { + p.props.line_spacing = Some(LineSpacing::Multiple(1.5)); + p.props.space_before = Some(shift as f32); + p.props.widow_control = Some(false); + } + let foot_paras = (0..lines) + .map(|_| { + let mut f = Paragraph::with_text(text, Default::default()); + if text.is_empty() { + f.props.line_spacing = Some(LineSpacing::Exactly(120.0)); + } + para_block(f) + }) + .collect(); + let id = d.add_part(PartKind::Footer, foot_paras); + if let Some(f) = from_bottom { + d.last_section.footer = f; + } + if first { + d.last_section.title_page = true; + d.last_section.footers.first = Some(id); + } else { + d.last_section.footers.default = Some(id); + } + let l = lay(&d); + let foot = l.pages[0].body.bottom(); + let what = format!("footer of {lines} x {text:?}, shift {shift}"); + assert!(foot < d.last_section.page_h - d.last_section.margin_bottom - 1.0, "{what}: the footer reaches above the margin: {foot}"); + let Some(Placed::Lines { y, para, l0, l1, .. }) = + l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { story: StoryRef::Body, .. })) + else { + panic!("{what}: no body lines on page 1") + }; + let (first, last, next) = (¶.lines[*l0], ¶.lines[*l1 - 1], ¶.lines[*l1]); + let top = y + last.top - first.top; + let text_end = top + (last.baseline - last.top) + last.text_desc; + assert!(text_end <= foot + 0.01, "{what}: the last line's text ends at {text_end}, below the footer at {foot}"); + let next_text_end = top + last.height + (next.baseline - next.top) + next.text_desc; + assert!(next_text_end > foot + 0.01, "{what}: the next line's text would end at {next_text_end}, above the footer at {foot}"); + if top + last.height > foot + 0.01 { + past_footer += 1; + } + } + assert!(past_footer > 0, "footer of {lines} x {text:?}: some shift should leave the last line's leading past the footer"); + } +} + #[test] fn a_page_ends_when_a_multiple_spaced_lines_text_no_longer_fits() { // Multiple spacing puts its extra leading below the text, and Word lets that leading of a diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 0a39f59cca..6cd336d450 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -527,6 +527,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | 2026-11-02 | trivial | For ODT documents, LibreOffice's layout: a line holding only in-line pictures is as tall as they are, without its font's ascent and descent (`Settings::odf_layout`, set when an ODT opens; Word keeps the font's, so other documents are unchanged). Measured in LibreOffice: a 3.6 pt rule's line is 3.6 pt; WordCraft's had been 15.5 pt (`tests::a_line_of_only_pictures_fits_them_in_odt_documents`) | | 2026-11-02 | trivial | Beyond Word, for ODT documents: a table's own space above and below (`TableProps::space_before`/`space_after`) moves the text around it, and a header (footer) taller than its margin keeps its spacing between it and the body (`SectionProps::header_gap`/`footer_gap`; Word keeps none, so DOCX documents are unchanged) (`tests::a_tables_own_space_above_and_below_moves_the_text`, `tests::body_starts_right_below_a_tall_header`) | | 2026-11-02 | trivial | A page break before the paragraph in a table's first row moves the whole table to the next page, as in Word (it was ignored); emphasis marks (Font › Emphasis mark) are drawn over or under each character and make the line taller | +| 2026-11-12 | trivial | A page's last multiple-spaced line may leave its leading past the top of a footer that reaches above the bottom margin, as it may in the margin: only its text has to end above the footer, whatever the footer holds (a page number, several lines of text, an empty exact-height paragraph), the first page's own footer counting on the first page. Word for Mac and Windows, a 1.5-spaced 12 pt line moved down in 0.5 pt steps: it stays while its text ends above the footer. Footnotes still keep the whole line clear of them (`tests::pages::a_multiple_spaced_lines_leading_may_run_past_a_footer_above_the_margin`) | Maintenance on 2026-10-12 retains current tracked-deletion, endnote, footer-total, text-box and balloon layout while supplying explicit cell identity at every box call. The native Word From f420ef4d6a5de39a455fde832d5dbe08dca83002 Mon Sep 17 00:00:00 2001 From: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:33:35 +0300 Subject: [PATCH 077/609] Fonts: a character Times New Roman's twin lacks keeps the twin's line height MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Liberation Serif 2.1 lacks "₽", and 1.07 also "‒", which Times New Roman has: Word sets them in Times New Roman and the line is as tall as its, while WordCraft drew them from the UI sans fallback (1.326 em against 1.150), 2.5-3.3pt taller at 14pt. The glyph still comes from the fallback (Source Sans 3 "₽" and "‒" are 0.497 em wide against Times New Roman's 0.5); the line takes the run's font metrics. East Asian fallback faces keep their own height. Test: times_twin_fallback::a_twin_fallback_keeps_the_twins_line_height (fails before this change). --- crates/layout/src/para/builder.rs | 14 +++++ crates/layout/src/tests.rs | 1 + .../layout/src/tests/times_twin_fallback.rs | 52 +++++++++++++++++++ docs/layout-parity.md | 1 + 4 files changed, 68 insertions(+) create mode 100644 crates/layout/src/tests/times_twin_fallback.rs diff --git a/crates/layout/src/para/builder.rs b/crates/layout/src/para/builder.rs index 99ae60f6f3..7edf00c130 100644 --- a/crates/layout/src/para/builder.rs +++ b/crates/layout/src/para/builder.rs @@ -139,6 +139,15 @@ impl<'a> Builder<'a> { // the height Word gives it. let (a, d) = match wordcraft_fonts::word::symbol_line(&rc.font, &r) { Some((a, d)) => (a * face.upem, d * face.upem), + // A character Times New Roman or its metric twin lacks: the twin lacks more than + // Times New Roman ("‒", "₽" in Liberation Serif), so the line is as tall as the run's + // font, as with Times New Roman in Word, not as the taller fallback. East Asian text + // keeps its face's height. + None if face_override.is_some() && is_times_twin(&r.face.family) && !face.is_east_asian() => { + let (a, d) = wordcraft_fonts::word::line_metrics(&r.face); + let k = face.upem / r.face.upem.max(1.0); + (a * k, d * k) + } None => wordcraft_fonts::word::line_metrics(&face), }; let k = size as f64 / face.upem.max(1.0); @@ -608,6 +617,11 @@ impl<'a> Builder<'a> { } } +/// Times New Roman or one of its metric twins. +fn is_times_twin(family: &str) -> bool { + ["Times New Roman", "Liberation Serif", "Tinos"].iter().any(|f| family.eq_ignore_ascii_case(f)) +} + /// Lay out an `EQ \o` field (ECMA-376 Part 1 §17.16.5.20): its arguments drawn on top of one /// another, as one cluster. An enclosure symbol among them (○ □ △ ◇, see /// [`wordcraft_doc::eq::EncloseShape`]) is drawn as a shape around the text rather than as a diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index a15f2f672b..fd14ccf1f3 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -21,6 +21,7 @@ mod pages; mod styleref; mod table_contact; mod textbox; +mod times_twin_fallback; mod vertical; const WRAP_TEST_FONT: &str = "Source Sans 3"; diff --git a/crates/layout/src/tests/times_twin_fallback.rs b/crates/layout/src/tests/times_twin_fallback.rs new file mode 100644 index 0000000000..c287bb0055 --- /dev/null +++ b/crates/layout/src/tests/times_twin_fallback.rs @@ -0,0 +1,52 @@ +//! A character Times New Roman's metric twin lacks ("‒", "₽" in Liberation Serif) is drawn from +//! a fallback face, but the line is as tall as the twin's: Times New Roman has those characters, +//! so Word's line is as tall as Times New Roman's, not the taller UI sans. + +use crate::{Document, LayoutCache, LayoutOptions, Placed, layout}; + +/// Inter under the family name "Tinos" (a metric twin of Times New Roman), from the bundled font +/// so the test needs no installed font. Inter lacks "☐"; Source Sans 3 (the fallback) has it and +/// its line is taller (1.326 em against 1.21). +fn fake_tinos() -> &'static str { + const FAMILY: &str = "Tinos"; + let inter = wordcraft_fonts::word::resolve("Inter", false, false).face; + assert!(!inter.covers('☐')); + let mut data = inter.data().to_vec(); + let u16_at = |d: &[u8], o: usize| u16::from_be_bytes([d[o], d[o + 1]]) as usize; + let u32_at = |d: &[u8], o: usize| u32::from_be_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]]) as usize; + let (name, len) = (0..u16_at(&data, 4)) + .map(|i| 12 + 16 * i) + .find(|&r| &data[r..r + 4] == b"name") + .map(|r| (u32_at(&data, r + 8), u32_at(&data, r + 12))) + .unwrap(); + let wide = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::>(); + for (from, to) in [(wide("Inter"), wide(FAMILY)), (b"Inter".to_vec(), FAMILY.as_bytes().to_vec())] { + for i in name..name + len - from.len() { + if data[i..i + from.len()] == from[..] { + data[i..i + from.len()].copy_from_slice(&to); + } + } + } + wordcraft_fonts::FontDb::global().add_font(data); + FAMILY +} + +fn line_height(text: &str, font: &str) -> f32 { + let chr = wordcraft_doc::CharProps { font: Some(font.into()), size: Some(14.0), ..Default::default() }; + let mut d = Document::new(); + d.body = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(text, chr))]; + let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default()); + l.pages.iter().flat_map(|p| &p.items).find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.lines[0].height) } else { None }).unwrap() +} + +#[test] +fn a_twin_fallback_keeps_the_twins_line_height() { + crate::test_fonts(); + let tinos = fake_tinos(); + assert_eq!(wordcraft_fonts::word::resolve(tinos, false, false).face.family, tinos, "the test font is installed under its own name"); + let plain = line_height("Aa", tinos); + let boxed = line_height("A☐a", tinos); + assert!((boxed - plain).abs() < 0.01, "a line with a fallback character is {boxed} pt, without it {plain} pt"); + // Other fonts keep the fallback's taller line. + assert!(line_height("A☐a", "Inter") > line_height("Aa", "Inter") + 1.0); +} diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 0a39f59cca..85ec0fde69 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -527,6 +527,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | 2026-11-02 | trivial | For ODT documents, LibreOffice's layout: a line holding only in-line pictures is as tall as they are, without its font's ascent and descent (`Settings::odf_layout`, set when an ODT opens; Word keeps the font's, so other documents are unchanged). Measured in LibreOffice: a 3.6 pt rule's line is 3.6 pt; WordCraft's had been 15.5 pt (`tests::a_line_of_only_pictures_fits_them_in_odt_documents`) | | 2026-11-02 | trivial | Beyond Word, for ODT documents: a table's own space above and below (`TableProps::space_before`/`space_after`) moves the text around it, and a header (footer) taller than its margin keeps its spacing between it and the body (`SectionProps::header_gap`/`footer_gap`; Word keeps none, so DOCX documents are unchanged) (`tests::a_tables_own_space_above_and_below_moves_the_text`, `tests::body_starts_right_below_a_tall_header`) | | 2026-11-02 | trivial | A page break before the paragraph in a table's first row moves the whole table to the next page, as in Word (it was ignored); emphasis marks (Font › Emphasis mark) are drawn over or under each character and make the line taller | +| 2026-11-12 | trivial | A character Times New Roman's metric twin lacks (Liberation Serif 2.1 has no "₽", 1.07 no "‒" either) is still drawn from a fallback face, but the line keeps the twin's height, as Word's line keeps Times New Roman's: Times New Roman has those characters. The UI sans fallback made such a line 2.5–3.3 pt taller at 14 pt. East Asian fallback faces keep their own height (`tests::times_twin_fallback::a_twin_fallback_keeps_the_twins_line_height`) | Maintenance on 2026-10-12 retains current tracked-deletion, endnote, footer-total, text-box and balloon layout while supplying explicit cell identity at every box call. The native Word From 7fd2dc9127c937ed0808f08aab2d37d9461be656 Mon Sep 17 00:00:00 2001 From: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Date: Tue, 3 Nov 2026 20:42:27 +0300 Subject: [PATCH 078/609] layout: a letter ending a line keeps the half of its kerning pair with the letter before A shaper splits a pair from an old-style kern table between its two letters, half in the first one's advance and half in the second one's advance and offset. The kerning kept for the line-end measure (a letter ending a line inside a word is measured without its pair with the next) took the second letter's half for its pair with the next letter, so a letter after a kerned pair was measured wider than it is at the end of a line. Word for Windows, a font with only a kern table: Word set "...3Vy" of a base64 token on one line, WordCraft moved the "y" on. Test: a_letter_ending_a_line_keeps_its_pair_with_the_letter_before (fails before this change). --- crates/layout/src/para/builder.rs | 41 +++++++++++- crates/layout/src/tests.rs | 8 ++- crates/layout/src/tests/line_end_kern.rs | 85 ++++++++++++++++++++++++ docs/layout-parity.md | 1 + 4 files changed, 131 insertions(+), 4 deletions(-) diff --git a/crates/layout/src/para/builder.rs b/crates/layout/src/para/builder.rs index 7a44aa3713..29f4dfeef2 100644 --- a/crates/layout/src/para/builder.rs +++ b/crates/layout/src/para/builder.rs @@ -423,7 +423,7 @@ impl<'a> Builder<'a> { } self.glyphs.push(Glyph { gid: g.gid, dx: adv + g.x_offset as f32 * k * hscale, dy: g.y_offset as f32 * k }); adv += g.x_advance as f32 * k * hscale; - kern = if rc.kerned() && !key.rtl { (g.x_advance as f32 - st.face.advance(g.gid) as f32) * k * hscale } else { 0.0 }; + kern = if rc.kerned() && !key.rtl { pair_with_next(g, st.face.advance(g.gid)) * k * hscale } else { 0.0 }; gi += 1; } let g1 = self.glyphs.len() as u32; @@ -558,7 +558,20 @@ impl<'a> Builder<'a> { let style = first.style; let g1 = added.last().map(|c| c.g1).unwrap_or(g0); self.shown.push((self.clusters.len(), text.to_string(), ranges)); - self.clusters.push(Cluster { start, end, adv: x, kind: ClKind::Text, style, g0, g1, break_after: false, obj_h: 0.0, obj_d: 0.0, dot: false, kern: 0.0 }); + self.clusters.push(Cluster { + start, + end, + adv: x, + kind: ClKind::Text, + style, + g0, + g1, + break_after: false, + obj_h: 0.0, + obj_d: 0.0, + dot: false, + kern: 0.0, + }); } /// Shape `texts` on top of one another as one cluster for `start..end`: each aligned within @@ -608,11 +621,33 @@ impl<'a> Builder<'a> { if !text.is_empty() { self.shown.push((k, text, ranges)); } - self.clusters.push(Cluster { start, end, adv, kind: ClKind::Text, style, g0, g1, break_after: false, obj_h: 0.0, obj_d: 0.0, dot: false, kern: 0.0 }); + self.clusters.push(Cluster { + start, + end, + adv, + kind: ClKind::Text, + style, + g0, + g1, + break_after: false, + obj_h: 0.0, + obj_d: 0.0, + dot: false, + kern: 0.0, + }); Some(k) } } +/// What kerning added to a glyph's advance (in font units) for its pair with the next glyph. An +/// old-style `kern` table's pair is split between its two glyphs, the second's half in its advance +/// and its offset alike: that half is the pair with the glyph before, which stays on the line. +fn pair_with_next(g: &wordcraft_fonts::ShapedGlyph, plain_advance: f64) -> f32 { + let added = g.x_advance as f32 - plain_advance as f32; + let before = if added != 0.0 { g.x_offset as f32 } else { 0.0 }; + added - before +} + /// Lay out an `EQ \o` field (ECMA-376 Part 1 §17.16.5.20): its arguments drawn on top of one /// another, as one cluster. An enclosure symbol among them (○ □ △ ◇, see /// [`wordcraft_doc::eq::EncloseShape`]) is drawn as a shape around the text rather than as a diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index d6fb3643c4..19a3c684e7 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -7598,7 +7598,13 @@ fn body_lines(l: &DocLayout, text: &str) -> Vec { l.pages .iter() .flat_map(|p| &p.items) - .filter_map(|it| if let Placed::Lines { para, l0, l1, .. } = it { Some(para.lines[*l0..*l1].iter().map(|line| text[line.start..line.stop].to_string())) } else { None }) + .filter_map(|it| { + if let Placed::Lines { para, l0, l1, .. } = it { + Some(para.lines[*l0..*l1].iter().map(|line| text[line.start..line.stop].to_string())) + } else { + None + } + }) .flatten() .collect() } diff --git a/crates/layout/src/tests/line_end_kern.rs b/crates/layout/src/tests/line_end_kern.rs index b7d246c33c..85ea9cec04 100644 --- a/crates/layout/src/tests/line_end_kern.rs +++ b/crates/layout/src/tests/line_end_kern.rs @@ -27,3 +27,88 @@ fn a_word_broken_by_letters_ends_without_its_kerning_pair() { let got = body_lines(&lay(&doc(468.0 - alone - 0.004)), text); assert_eq!(got.first().map(String::as_str), Some("AVAVA"), "{got:?}"); } + +/// Inter under the family name "Kernx" with its `GPOS` hidden and an old-style `kern` table that +/// kerns "AV" by `units` (and nothing else): a shaper splits such a pair between the two letters, +/// half in the first one's advance and half in the second one's advance and offset. +fn legacy_kern_family(units: i16) -> &'static str { + const FAMILY: &str = "Kernx"; + let inter = wordcraft_fonts::word::resolve("Inter", false, false).face; + let (a, v) = (inter.glyph_for('A') as u16, inter.glyph_for('V') as u16); + let src = inter.data().to_vec(); + let u16_at = |d: &[u8], o: usize| u16::from_be_bytes([d[o], d[o + 1]]) as usize; + let u32_at = |d: &[u8], o: usize| u32::from_be_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]]) as usize; + // The tables, `GPOS` renamed so no shaper reads it, and the new `kern` table. + let mut tables: Vec<([u8; 4], Vec)> = (0..u16_at(&src, 4)) + .map(|i| { + let r = 12 + 16 * i; + let tag: [u8; 4] = src[r..r + 4].try_into().unwrap(); + let tag = if &tag == b"GPOS" { *b"XPOS" } else { tag }; + (tag, src[u32_at(&src, r + 8)..u32_at(&src, r + 8) + u32_at(&src, r + 12)].to_vec()) + }) + .collect(); + let mut kern = Vec::new(); + for x in [0u16, 1, 0, 20, 0x0001, 1, 6, 0, 0, a, v] { + kern.extend(x.to_be_bytes()); + } + kern.extend(units.to_be_bytes()); + tables.push((*b"kern", kern)); + tables.sort_by_key(|t| t.0); + // The font file again: its header, the table records, then the tables (4-byte aligned). + let n = tables.len(); + let mut data = src[..12].to_vec(); + data[4..6].copy_from_slice(&(n as u16).to_be_bytes()); + let mut at = 12 + 16 * n; + let mut body = Vec::new(); + for (tag, t) in &tables { + data.extend(tag); + data.extend(0u32.to_be_bytes()); + data.extend((at as u32).to_be_bytes()); + data.extend((t.len() as u32).to_be_bytes()); + body.extend(t); + while body.len() % 4 != 0 { + body.push(0); + } + at = 12 + 16 * n + body.len(); + } + data.extend(body); + // The family name, in the name table's UTF-16 and single-byte records alike. + let name = tables.iter().take_while(|t| &t.0 != b"name").map(|t| t.1.len().div_ceil(4) * 4).sum::() + 12 + 16 * n; + let len = tables.iter().find(|t| &t.0 == b"name").map_or(0, |t| t.1.len()); + let wide = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::>(); + for (from, to) in [(wide("Inter"), wide(FAMILY)), (b"Inter".to_vec(), FAMILY.as_bytes().to_vec())] { + for i in name..name + len - from.len() { + if data[i..i + from.len()] == from[..] { + data[i..i + from.len()].copy_from_slice(&to); + } + } + } + wordcraft_fonts::FontDb::global().add_font(data); + FAMILY +} + +/// A letter ending a line whose kerning pair with the letter before it the shaper split between +/// them keeps that pair: only its pair with the letter going on to the next line is dropped +/// (Word for Windows, a font with only an old-style `kern` table: "...3Vy" of a base64 token on +/// one line, where the "y" carrying half the "Vy" pair measured it wider and moved it on). +#[test] +fn a_letter_ending_a_line_keeps_its_pair_with_the_letter_before() { + crate::test_fonts(); + let text = "AVAVAVAVAVAVAVAVAVAV"; + let family = legacy_kern_family(-300); + let doc = |indent_right: f32| { + let mut d = Document::from_text(text); + let st = Arc::make_mut(&mut d.styles); + st.default_chr.kern = Some(1.0); + st.default_chr.font = Some(family.into()); + d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap(); + d + }; + let l = lay(&doc(0.0)); + let para = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap(); + // "AVAVAV" on a line: the "AV" pairs in it kerned, the "VA" after it not kerned at all. + let six: f32 = para.clusters[..6].iter().map(|c| c.adv).sum(); + assert!(para.clusters[0].kern < -0.5, "the test font kerns \"AV\": {}", para.clusters[0].kern); + let got = body_lines(&lay(&doc(468.0 - six - 0.004)), text); + assert_eq!(got.first().map(String::as_str), Some("AVAVAV"), "{got:?}"); +} diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 0a39f59cca..41d5c59644 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -527,6 +527,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | 2026-11-02 | trivial | For ODT documents, LibreOffice's layout: a line holding only in-line pictures is as tall as they are, without its font's ascent and descent (`Settings::odf_layout`, set when an ODT opens; Word keeps the font's, so other documents are unchanged). Measured in LibreOffice: a 3.6 pt rule's line is 3.6 pt; WordCraft's had been 15.5 pt (`tests::a_line_of_only_pictures_fits_them_in_odt_documents`) | | 2026-11-02 | trivial | Beyond Word, for ODT documents: a table's own space above and below (`TableProps::space_before`/`space_after`) moves the text around it, and a header (footer) taller than its margin keeps its spacing between it and the body (`SectionProps::header_gap`/`footer_gap`; Word keeps none, so DOCX documents are unchanged) (`tests::a_tables_own_space_above_and_below_moves_the_text`, `tests::body_starts_right_below_a_tall_header`) | | 2026-11-02 | trivial | A page break before the paragraph in a table's first row moves the whole table to the next page, as in Word (it was ignored); emphasis marks (Font › Emphasis mark) are drawn over or under each character and make the line taller | +| 2026-11-12 | trivial | A letter ending a line inside a word is measured without its kerning pair with the letter that goes on to the next line, as Word lays each line out on its own: a long word broken by letters fits only as far as its letters fit without that pair. A pair from an old-style `kern` table, which the shaper splits between its two letters, stays with the letter before (`tests::line_end_kern`) | Maintenance on 2026-10-12 retains current tracked-deletion, endnote, footer-total, text-box and balloon layout while supplying explicit cell identity at every box call. The native Word From f4862c6b0ee53258f7c4383858a95487389eee1b Mon Sep 17 00:00:00 2001 From: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:40:33 +0300 Subject: [PATCH 079/609] Line spacing: a multiple adds a multiple of the tallest run, not of a mixed line A line mixing fonts is as tall as the tallest ascent over the deepest descent of its runs, more than any one run's own height. At multiple spacing Word adds (m - 1) x the tallest run's own height to it, not (m - 1) x the mixed line's: 10pt Times New Roman with a 10pt Courier New run steps 18.09pt at 1.5 spacing and 23.84pt at double in Word for Windows, where multiplying the 12.34pt line gives 18.51 and 24.68; in Word for Mac the 12.24pt line steps 17.97 and 23.69pt (12.24 + 0.5 x 11.49 and + 11.49, Times New Roman being the taller run). The paragraph mark's font doesn't matter. Test: multiple_spacing_adds_a_multiple_of_the_tallest_run_not_of_the_mixed_line (fails before this change). --- crates/layout/src/para/lines.rs | 15 ++++++++++++--- crates/layout/src/tests.rs | 28 ++++++++++++++++++++++++++++ docs/layout-parity.md | 1 + 3 files changed, 41 insertions(+), 3 deletions(-) diff --git a/crates/layout/src/para/lines.rs b/crates/layout/src/para/lines.rs index 821132f6aa..5b9bb4c81e 100644 --- a/crates/layout/src/para/lines.rs +++ b/crates/layout/src/para/lines.rs @@ -411,7 +411,7 @@ impl<'e> Breaker<'e> { /// tallest picture on it (which sits on the baseline). fn extents(&self, pl: &ParaLayout, (c0, c1): (usize, usize)) -> Extents { let rp = &self.rp; - let mut ex = Extents { asc: 0.0, desc: 0.0, obj_asc: 0.0, obj_desc: 0.0, text: false }; + let mut ex = Extents { asc: 0.0, desc: 0.0, obj_asc: 0.0, obj_desc: 0.0, text: false, single: 0.0 }; let mut any = false; let dropped = pl.drop_cap.map_or(0, |d| d.0); for (k, c) in pl.clusters.get(c0..c1).into_iter().flatten().enumerate() { @@ -455,6 +455,7 @@ impl<'e> Breaker<'e> { }; ex.asc = ex.asc.max(a); ex.desc = ex.desc.max(d); + ex.single = ex.single.max(a + d); any = true; // Text needs its descent below the line; so do inline math (an object with its own // descent) and a check box. A line break ending the line is no text. @@ -472,7 +473,7 @@ impl<'e> Breaker<'e> { /// The line's height, baseline and text extent. fn measure(&self, pl: &ParaLayout, range: (usize, usize)) -> Measure { let rp = &self.rp; - let Extents { mut asc, mut desc, obj_asc, obj_desc, text } = self.extents(pl, range); + let Extents { mut asc, mut desc, obj_asc, obj_desc, text, single } = self.extents(pl, range); let mut text_natural = asc + desc; let font_desc = desc; desc = desc.max(obj_desc); @@ -518,6 +519,10 @@ impl<'e> Breaker<'e> { } } } + // Multiple spacing adds (m - 1) x the tallest of the line's runs, not of the line: a line + // mixing fonts is as much taller as its runs' extents make it, once (Word for Mac and + // Windows: 10 pt Times New Roman with 10 pt Courier New at 1.5 and double spacing). + let leading = if single > 0.0 && !pictures_alone { single.min(text_natural) } else { text_natural }; // Keep the picture floor independent of list-label metrics. let natural = asc + desc; let pictures = if obj_asc > asc { obj_asc + desc } else { 0.0 }; @@ -526,7 +531,9 @@ impl<'e> Breaker<'e> { let (height, centred) = match (rp.line_spacing, grid) { (LineSpacing::Multiple(m), Some(g)) => ((g.snap_height(natural) * m).max(g.snap_height(pictures)), true), (LineSpacing::AtLeast(v), Some(g)) => (g.snap_height(natural.max(pictures)).max(v), true), - (LineSpacing::Multiple(m), None) => ((text_natural * m + label_extra).max(text_pictures + (m - 1.0).max(0.0) * text_natural), false), + (LineSpacing::Multiple(m), None) => { + ((text_natural + (m - 1.0) * leading + label_extra).max(text_pictures + (m - 1.0).max(0.0) * text_natural), false) + } (LineSpacing::AtLeast(v), None) => (natural.max(text_pictures).max(v), false), (LineSpacing::Exactly(v), _) => (v, false), }; @@ -699,6 +706,8 @@ struct Extents { obj_desc: f32, /// Whether the line holds text besides its pictures (spaces and tabs don't count). text: bool, + /// The tallest of its runs' own heights (ascent plus descent): the multiple's leading. + single: f32, } /// A line's height and baseline, and the extent of its text. diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index a15f2f672b..4452b66cab 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -7592,6 +7592,34 @@ fn no_line_break_right_after_a_slash() { assert!(lines > 10, "{lines} lines"); } +#[test] +fn multiple_spacing_adds_a_multiple_of_the_tallest_run_not_of_the_mixed_line() { + // A line mixing fonts is taller than either font's own line; Word adds (m - 1) x the tallest + // run's own height to it, not (m - 1) x the line's (Word for Mac and Windows: 10pt Times New + // Roman with 10pt Courier New, 18.09pt at 1.5 spacing where 1.5 x the 12.34pt line gives 18.51). + let font = |(f, size): (&str, f32)| wordcraft_doc::CharProps { font: Some(f.into()), size: Some(size), ..Default::default() }; + let height = |fonts: &[(&str, f32)], m: f32| { + let mut p = wordcraft_doc::Paragraph::with_text("run ", font(fonts[0])); + for &f in &fonts[1..] { + p.append(wordcraft_doc::Paragraph::with_text("run ", font(f))); + } + p.props = ParaProps { line_spacing: Some(wordcraft_doc::props::LineSpacing::Multiple(m)), ..Default::default() }; + let mut d = Document::new(); + d.body = vec![wordcraft_doc::para_block(p)]; + let l = lay(&d); + l.pages[0].items.iter().find_map(|i| if let Placed::Lines { para, .. } = i { Some(para.lines[0].height) } else { None }).unwrap() + }; + // The larger sans has the taller ascent, the serif the deeper descent. + let (sans, serif) = (("Inter", 12.0), ("Source Serif 4", 10.5)); + let tallest = height(&[sans], 1.0).max(height(&[serif], 1.0)); + let mixed = height(&[sans, serif], 1.0); + assert!(mixed > tallest + 0.1, "the fonts don't make a taller line together: {mixed} vs {tallest}"); + for m in [1.5, 2.0] { + let got = height(&[sans, serif], m); + assert!((got - (mixed + (m - 1.0) * tallest)).abs() < 0.01, "{m}: {got}, line {mixed}, tallest run {tallest}"); + } +} + /// #2963: a word after a slash ("caption /заполняется") wraps whole, as in Word. UAX #14 forbids a /// break between the space and the slash, and the break after the slash is dropped (Word keeps /// "and/or" whole), so the slash word had no break before it and split between two letters. diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 0a39f59cca..a4d63f7c07 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -527,6 +527,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | 2026-11-02 | trivial | For ODT documents, LibreOffice's layout: a line holding only in-line pictures is as tall as they are, without its font's ascent and descent (`Settings::odf_layout`, set when an ODT opens; Word keeps the font's, so other documents are unchanged). Measured in LibreOffice: a 3.6 pt rule's line is 3.6 pt; WordCraft's had been 15.5 pt (`tests::a_line_of_only_pictures_fits_them_in_odt_documents`) | | 2026-11-02 | trivial | Beyond Word, for ODT documents: a table's own space above and below (`TableProps::space_before`/`space_after`) moves the text around it, and a header (footer) taller than its margin keeps its spacing between it and the body (`SectionProps::header_gap`/`footer_gap`; Word keeps none, so DOCX documents are unchanged) (`tests::a_tables_own_space_above_and_below_moves_the_text`, `tests::body_starts_right_below_a_tall_header`) | | 2026-11-02 | trivial | A page break before the paragraph in a table's first row moves the whole table to the next page, as in Word (it was ignored); emphasis marks (Font › Emphasis mark) are drawn over or under each character and make the line taller | +| 2026-11-12 | trivial | Multiple line spacing adds (m − 1) × the tallest run's own height (ascent plus descent), not (m − 1) × the height of a line mixing fonts, which is taller than any of its runs: 10 pt Times New Roman with a 10 pt Courier New run steps 18.09 pt at 1.5 lines and 23.84 pt at double in Word for Windows, where multiplying the 12.34 pt line gave 18.51 and 24.68 (Word for Mac: a 12.24 pt line steps 17.97 and 23.69 pt). Lines of only pictures are unchanged (`tests::multiple_spacing_adds_a_multiple_of_the_tallest_run_not_of_the_mixed_line`) | Maintenance on 2026-10-12 retains current tracked-deletion, endnote, footer-total, text-box and balloon layout while supplying explicit cell identity at every box call. The native Word From 20b8ce57a8e468e7dff5350c6b69676c290b7623 Mon Sep 17 00:00:00 2001 From: Reuben Grinberg Date: Tue, 3 Nov 2026 15:48:53 -0600 Subject: [PATCH 080/609] Compare: mark a whole inserted/deleted paragraph's mark (#3750) --- crates/engine/src/cmd/tools/compare.rs | 8 ++- crates/engine/src/cmd/tools/tests.rs | 71 ++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/tools/compare.rs b/crates/engine/src/cmd/tools/compare.rs index a62397d830..4c8fad4d22 100644 --- a/crates/engine/src/cmd/tools/compare.rs +++ b/crates/engine/src/cmd/tools/compare.rs @@ -202,7 +202,13 @@ fn block_text(b: &Block, depth: usize) -> String { } } -/// Returns a copy of `b` with all text runs and paragraph marks (or nested table cells) updated by `f`. +/// A copy of the block with every run (in tables, every cell's) changed by `f`, and a paragraph's +/// mark along with them, so a whole inserted or deleted paragraph carries the revision even when +/// the paragraph is empty (`format` returns early for a length-0 range). +/// +/// Known limitation: resolving a revision needs a following paragraph, so a paragraph inserted at +/// the very end (rejected) or deleted from the very end (accepted) still leaves one empty +/// paragraph. That is a separate follow-up, not handled here. fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps), depth: usize) -> Block { match b { Block::Para(p) => { diff --git a/crates/engine/src/cmd/tools/tests.rs b/crates/engine/src/cmd/tools/tests.rs index 0dcc04e0fc..ced4455b7c 100644 --- a/crates/engine/src/cmd/tools/tests.rs +++ b/crates/engine/src/cmd/tools/tests.rs @@ -9,6 +9,77 @@ fn compare_marks_changes() { assert_eq!(s.doc.plain_text(StoryRef::Body), "The dog sat.\nKeep this.\nNew line here."); } +/// Top-level body blocks that are empty paragraphs. +fn empty_paras(s: &Session) -> usize { + s.doc.body.iter().filter(|b| matches!(b.as_para(), Some(p) if p.is_empty())).count() +} + +#[test] +fn compare_marks_a_whole_paragraph_and_its_mark() { + // A whole inserted paragraph carries the insertion on its mark, not just on its runs. + let mut s = Session::new(Document::from_text("A\nB")); + s.run("review.compare", &json!({"text": "A\nNEW\nB"})).unwrap(); + assert_eq!(s.doc.body.len(), 3); + let mid = s.doc.body[1].as_para().unwrap(); + assert_eq!(mid.plain_text(), "NEW"); + assert!(mid.mark.ins.is_some(), "the inserted paragraph's mark is not marked inserted"); + s.run("review.rejectAll", &json!({})).unwrap(); + assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB"); + assert_eq!(s.doc.body.len(), 2); + assert_eq!(empty_paras(&s), 0, "rejecting an inserted paragraph left an empty paragraph behind"); + let mut s = Session::new(Document::from_text("A\nB")); + s.run("review.compare", &json!({"text": "A\nNEW\nB"})).unwrap(); + s.run("review.acceptAll", &json!({})).unwrap(); + assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nNEW\nB"); + assert_eq!(s.doc.body.len(), 3); + assert_eq!(empty_paras(&s), 0, "accepting an inserted paragraph left an empty paragraph behind"); + + // A whole deleted paragraph carries the deletion on its mark. + let mut s = Session::new(Document::from_text("A\nOLD\nB")); + s.run("review.compare", &json!({"text": "A\nB"})).unwrap(); + assert_eq!(s.doc.body.len(), 3); + let mid = s.doc.body[1].as_para().unwrap(); + assert_eq!(mid.plain_text(), "OLD"); + assert!(mid.mark.del.is_some(), "the deleted paragraph's mark is not marked deleted"); + s.run("review.acceptAll", &json!({})).unwrap(); + assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB"); + assert_eq!(s.doc.body.len(), 2); + assert_eq!(empty_paras(&s), 0, "accepting a deleted paragraph left an empty paragraph behind"); + let mut s = Session::new(Document::from_text("A\nOLD\nB")); + s.run("review.compare", &json!({"text": "A\nB"})).unwrap(); + s.run("review.rejectAll", &json!({})).unwrap(); + assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nOLD\nB"); + assert_eq!(s.doc.body.len(), 3); + assert_eq!(empty_paras(&s), 0, "rejecting a deleted paragraph left an empty paragraph behind"); +} + +#[test] +fn compare_marks_an_empty_paragraphs_mark() { + // An empty inserted paragraph is stamped on its mark, though `format` skips its empty range. + let mut s = Session::new(Document::from_text("A\nB")); + s.run("review.compare", &json!({"text": "A\n\nB"})).unwrap(); + assert_eq!(s.doc.body.len(), 3); + let empty = s.doc.body[1].as_para().unwrap(); + assert!(empty.is_empty()); + assert!(empty.mark.ins.is_some(), "the empty inserted paragraph's mark is not marked inserted"); + s.run("review.rejectAll", &json!({})).unwrap(); + assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB"); + assert_eq!(s.doc.body.len(), 2); + assert_eq!(empty_paras(&s), 0, "rejecting an empty inserted paragraph left it behind"); + + // An empty deleted paragraph is stamped on its mark too. + let mut s = Session::new(Document::from_text("A\n\nB")); + s.run("review.compare", &json!({"text": "A\nB"})).unwrap(); + assert_eq!(s.doc.body.len(), 3); + let empty = s.doc.body[1].as_para().unwrap(); + assert!(empty.is_empty()); + assert!(empty.mark.del.is_some(), "the empty deleted paragraph's mark is not marked deleted"); + s.run("review.acceptAll", &json!({})).unwrap(); + assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB"); + assert_eq!(s.doc.body.len(), 2); + assert_eq!(empty_paras(&s), 0, "accepting an empty deleted paragraph left it behind"); +} + #[test] fn compare_options_ignore_case_and_white_space() { let original = "The Cat sat.\nTwo spaces here."; From 6ce224d4b38f48455ee17e8f3619e68b60bd2419 Mon Sep 17 00:00:00 2001 From: Reuben Grinberg Date: Thu, 5 Nov 2026 08:29:36 -0600 Subject: [PATCH 081/609] Compare: keep another author's deletion stamp on whole-marked paragraphs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address benandez's review: the del closure in mark_block now uses get_or_insert so a paragraph already carrying another author's tracked deletion keeps that author's revision on its runs and its mark; the ins closure deliberately keeps overwriting (the revised side is a raw clone whose revision indices are never relinked — see the comment; that sourcing is the #5571 root cause). p.touch() after mutating an empty paragraph's mark. Characterization tests pin the terminal-paragraph limitation and the section-break resolve limitation (the resolve fix is filed separately). --- crates/engine/src/cmd/tools/compare.rs | 20 +++++- crates/engine/src/cmd/tools/tests.rs | 86 ++++++++++++++++++++++++++ 2 files changed, 104 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/tools/compare.rs b/crates/engine/src/cmd/tools/compare.rs index 4c8fad4d22..b298ee4ae5 100644 --- a/crates/engine/src/cmd/tools/compare.rs +++ b/crates/engine/src/cmd/tools/compare.rs @@ -146,9 +146,22 @@ pub(super) fn compare(s: &mut Session, v: &Value) -> CmdResult { (Some(Block::Para(pa)), Some(Block::Para(pb))) => out.push(para_block(word_diff(&s.doc, pa, pb, &mut ctx))), _ => { if let Some(x) = a { - out.push(Arc::new(mark_block(x, &|c| c.del = Some(del), 0))); + // An existing deletion is another author's: keep their revision + // stamp instead of re-attributing the paragraph to this compare. + out.push(Arc::new(mark_block( + x, + &|c| { + c.del.get_or_insert(del); + }, + 0, + ))); } if let Some(x) = b { + // The revised side is a raw clone of the revised document (its + // blocks are never relinked into this session's revisions), so any + // stamp it carries names a revision of *that* document: overwrite + // it, since a foreign index kept here would be worse than a valid + // one. out.push(Arc::new(mark_block(x, &|c| c.ins = Some(ins), 0))); } } @@ -208,7 +221,9 @@ fn block_text(b: &Block, depth: usize) -> String { /// /// Known limitation: resolving a revision needs a following paragraph, so a paragraph inserted at /// the very end (rejected) or deleted from the very end (accepted) still leaves one empty -/// paragraph. That is a separate follow-up, not handled here. +/// paragraph. That is a separate follow-up, not handled here. A section-carrying inserted paragraph +/// is a second such limitation: `remove_empty_para` refuses it, so when it is rejected its +/// paragraph is joined into the next one, which takes its properties. fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps), depth: usize) -> Block { match b { Block::Para(p) => { @@ -216,6 +231,7 @@ fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps), depth: usize) -> Block { let len = p.len(); let _ = p.format(0, len, f); f(&mut p.mark); + p.touch(); Block::Para(p) } Block::Table(t) => { diff --git a/crates/engine/src/cmd/tools/tests.rs b/crates/engine/src/cmd/tools/tests.rs index ced4455b7c..c5e45521ea 100644 --- a/crates/engine/src/cmd/tools/tests.rs +++ b/crates/engine/src/cmd/tools/tests.rs @@ -80,6 +80,92 @@ fn compare_marks_an_empty_paragraphs_mark() { assert_eq!(empty_paras(&s), 0, "accepting an empty deleted paragraph left it behind"); } +#[test] +fn compare_keeps_another_authors_deletion_stamp() { + // A paragraph the original already carries as a tracked deletion by another author: Compare + // must keep that author's revision on its runs and on its paragraph mark, not re-attribute + // the block to its own deletion revision. + let mut doc = Document::from_text("A\nOLD\nB"); + doc.revisions.push(wordcraft_doc::Revision::new(RevisionKind::Delete, "Alice", "")); + let p = doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap(); + for r in &mut p.runs { + r.props.del = Some(0); + } + p.mark.del = Some(0); + let mut s = Session::new(doc); + s.run("review.compare", &json!({"text": "A\nB", "author": "Bob"})).unwrap(); + assert_eq!(s.doc.body.len(), 3); + let mid = s.doc.body[1].as_para().unwrap(); + assert_eq!(mid.plain_text(), "OLD"); + assert!(mid.runs.iter().all(|r| r.props.del == Some(0)), "the runs' deletion was re-stamped: {:?}", mid.runs); + assert_eq!(mid.mark.del, Some(0), "the paragraph mark's deletion was re-stamped"); + assert_eq!(s.doc.revisions.first().map(|r| (r.kind, r.author.as_str())), Some((RevisionKind::Delete, "Alice"))); +} + +#[test] +fn compare_pins_the_terminal_inserted_paragraph_limitation() { + // Characterizes the limitation documented on `mark_block` (compare.rs): resolving a revision + // needs a following paragraph, so a paragraph inserted at the very end is rejected but leaves + // one empty paragraph behind. Flip this test when the follow-up fix lands. + let mut s = Session::new(Document::from_text("A\nB")); + s.run("review.compare", &json!({"text": "A\nB\nC"})).unwrap(); + assert_eq!(s.doc.body.len(), 3); + s.run("review.rejectAll", &json!({})).unwrap(); + assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\n", "the rejected terminal paragraph still leaves a line"); + assert_eq!(s.doc.body.len(), 3); + assert_eq!(empty_paras(&s), 1, "the rejected terminal paragraph is left as one empty paragraph"); +} + +#[test] +fn compare_pins_the_terminal_deleted_paragraph_limitation() { + // The mirror of `compare_pins_the_terminal_inserted_paragraph_limitation`: a paragraph deleted + // from the very end is accepted but still leaves one empty paragraph. Characterizes the + // limitation documented on `mark_block` (compare.rs); flip when the follow-up fix lands. + let mut s = Session::new(Document::from_text("A\nB\nC")); + s.run("review.compare", &json!({"text": "A\nB"})).unwrap(); + assert_eq!(s.doc.body.len(), 3); + s.run("review.acceptAll", &json!({})).unwrap(); + assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\n", "the accepted terminal deletion still leaves a line"); + assert_eq!(s.doc.body.len(), 3); + assert_eq!(empty_paras(&s), 1, "the accepted terminal deletion is left as one empty paragraph"); +} + +#[test] +fn compare_pins_rejecting_an_inserted_section_restyles_the_next_paragraph() { + // Characterizes a known limitation recorded on `mark_block` (compare.rs): rejecting an + // inserted paragraph that carries a section break. `resolve`'s `remove_empty_para` refuses + // paragraphs carrying a section, so once the inserted paragraph's text is rejected the empty + // paragraph is joined into the next one, which takes its properties. Here the original "Body" + // is Heading 1; after Reject All it carries the inserted paragraph's Normal properties. The + // real fix belongs to `resolve` (`remove_empty_para`/`join_next_para`): flip this test when it + // lands. + let mut original = Document::from_text("Intro\nBody"); + original.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap().props.style = Some("Heading1".into()); + let mut s = Session::new(original); + + let mut rev = Document::from_text("Intro\nAppendix\nBody"); + { + let p = rev.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap(); + p.props.style = Some("Normal".into()); + p.section = Some(Box::new(wordcraft_doc::section::SectionProps::default())); + } + rev.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(2)).unwrap().props.style = Some("Heading1".into()); + let path = std::env::temp_dir().join(format!("wc-compare-section-{}.docx", std::process::id())); + crate::io::save_path(&path, &rev).unwrap(); + s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap(); + let _ = std::fs::remove_file(&path); + s.run("review.rejectAll", &json!({})).unwrap(); + assert_eq!(s.doc.plain_text(StoryRef::Body), "Intro\nBody"); + assert_eq!(s.doc.body.len(), 2); + let body = s.doc.body[1].as_para().unwrap(); + assert_eq!(body.plain_text(), "Body"); + assert_eq!( + body.props.style.as_deref(), + Some("Normal"), + "the current (wrong) outcome: the following paragraph took the inserted sectioned paragraph's properties" + ); +} + #[test] fn compare_options_ignore_case_and_white_space() { let original = "The Cat sat.\nTwo spaces here."; From 791e144fd75ced93dcb97e5ddada8ff6fdbfe4f8 Mon Sep 17 00:00:00 2001 From: Reuben Grinberg Date: Wed, 11 Nov 2026 10:37:12 +0000 Subject: [PATCH 082/609] Compare: flip the inserted-section pin to the fixed behaviour (#5667, fixed on main by #5734) --- crates/engine/src/cmd/tools/tests.rs | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/tools/tests.rs b/crates/engine/src/cmd/tools/tests.rs index c5e45521ea..96c43cb519 100644 --- a/crates/engine/src/cmd/tools/tests.rs +++ b/crates/engine/src/cmd/tools/tests.rs @@ -132,13 +132,14 @@ fn compare_pins_the_terminal_deleted_paragraph_limitation() { #[test] fn compare_pins_rejecting_an_inserted_section_restyles_the_next_paragraph() { - // Characterizes a known limitation recorded on `mark_block` (compare.rs): rejecting an - // inserted paragraph that carries a section break. `resolve`'s `remove_empty_para` refuses - // paragraphs carrying a section, so once the inserted paragraph's text is rejected the empty - // paragraph is joined into the next one, which takes its properties. Here the original "Body" - // is Heading 1; after Reject All it carries the inserted paragraph's Normal properties. The - // real fix belongs to `resolve` (`remove_empty_para`/`join_next_para`): flip this test when it - // lands. + // Pins the fixed behaviour for rejecting an inserted paragraph that carries a section + // break. This was a known limitation recorded on `mark_block` (compare.rs): `resolve`'s + // `remove_empty_para` refused paragraphs carrying a section, so once the inserted + // paragraph's text was rejected the empty paragraph was joined into the next one, which + // took its properties ("Body" came back Normal instead of its original Heading 1). Fixed + // on main by #5734 (issue #5667): `resolve_para` now removes the section break first, so + // the empty paragraph goes whole and the following paragraph keeps its own properties. + // After Reject All the original is restored exactly. let mut original = Document::from_text("Intro\nBody"); original.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap().props.style = Some("Heading1".into()); let mut s = Session::new(original); @@ -161,8 +162,8 @@ fn compare_pins_rejecting_an_inserted_section_restyles_the_next_paragraph() { assert_eq!(body.plain_text(), "Body"); assert_eq!( body.props.style.as_deref(), - Some("Normal"), - "the current (wrong) outcome: the following paragraph took the inserted sectioned paragraph's properties" + Some("Heading1"), + "the following paragraph keeps its own properties (fixed on main by #5734)" ); } From 959bc5450587c1e91db3094841b1ca4bc82308dd Mon Sep 17 00:00:00 2001 From: Reuben Grinberg Date: Wed, 11 Nov 2026 11:01:19 +0000 Subject: [PATCH 083/609] rustfmt: collapse the flipped pin assertion onto one line --- crates/engine/src/cmd/tools/tests.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/tools/tests.rs b/crates/engine/src/cmd/tools/tests.rs index 96c43cb519..b3f13d6b86 100644 --- a/crates/engine/src/cmd/tools/tests.rs +++ b/crates/engine/src/cmd/tools/tests.rs @@ -160,11 +160,7 @@ fn compare_pins_rejecting_an_inserted_section_restyles_the_next_paragraph() { assert_eq!(s.doc.body.len(), 2); let body = s.doc.body[1].as_para().unwrap(); assert_eq!(body.plain_text(), "Body"); - assert_eq!( - body.props.style.as_deref(), - Some("Heading1"), - "the following paragraph keeps its own properties (fixed on main by #5734)" - ); + assert_eq!(body.props.style.as_deref(), Some("Heading1"), "the following paragraph keeps its own properties (fixed on main by #5734)"); } #[test] From 0345dd28f359ac0dcf9ec51706fbffd5b3c8632e Mon Sep 17 00:00:00 2001 From: Reuben Grinberg Date: Fri, 13 Nov 2026 08:54:06 -0600 Subject: [PATCH 084/609] =?UTF-8?q?Compare:=20mark=5Fblock=20doc=20?= =?UTF-8?q?=E2=80=94=20the=20section-carrying=20case=20is=20fixed=20on=20m?= =?UTF-8?q?ain=20(#5734),=20not=20a=20limitation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/engine/src/cmd/tools/compare.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/tools/compare.rs b/crates/engine/src/cmd/tools/compare.rs index b298ee4ae5..1dbda83d8e 100644 --- a/crates/engine/src/cmd/tools/compare.rs +++ b/crates/engine/src/cmd/tools/compare.rs @@ -221,9 +221,10 @@ fn block_text(b: &Block, depth: usize) -> String { /// /// Known limitation: resolving a revision needs a following paragraph, so a paragraph inserted at /// the very end (rejected) or deleted from the very end (accepted) still leaves one empty -/// paragraph. That is a separate follow-up, not handled here. A section-carrying inserted paragraph -/// is a second such limitation: `remove_empty_para` refuses it, so when it is rejected its -/// paragraph is joined into the next one, which takes its properties. +/// paragraph. That is a separate follow-up, not handled here. A section-carrying inserted +/// paragraph is not such a case: `resolve_para` removes the section break first (#5734, issue +/// #5667), so rejecting it takes the paragraph out whole and the following paragraph keeps its +/// own properties. fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps), depth: usize) -> Block { match b { Block::Para(p) => { From 7612fe17db54f49b176a09fadc9c961af441f4e7 Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:48:08 -0500 Subject: [PATCH 085/609] #6516: toggles on a partly formatted selection follow its first character Word decides Bold, Italic, Underline and the other character toggles on a selection from its first character in document order: if it has the format, the whole selection loses it; otherwise the whole selection gets it. WordCraft turned the format on unless every selected character had it. A caret keeps its existing rule, explicit values still set, and the ribbon state is unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/format.rs | 14 +++++++++-- crates/engine/src/tests.rs | 44 +++++++++++++++++++++++++++++++++ docs/typing-parity.md | 13 +++++++++- 3 files changed, 68 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index ce35c9b348..6574b7778e 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -310,10 +310,20 @@ fn resolved(s: &Session) -> Vec { out } +/// Whether a toggle without a `value` turns its format on. A selection follows its first character +/// in document order, as Word does: one that starts formatted loses the format, all of it (#6516). +fn turns_on(s: &Session, has: impl Fn(&ResolvedChar) -> bool) -> bool { + let chars = resolved(s); + if !s.sel.is_collapsed() || selected_text_box(s).is_some() || column_rows(s).is_some() { + return !chars.first().is_some_and(has); + } + !chars.iter().all(has) +} + fn toggle(s: &mut Session, v: &Value, get: fn(&ResolvedChar) -> bool, set: fn(&mut CharProps, bool)) -> CmdResult { let on = match p::bool(v, "value") { Some(b) => b, - None => !resolved(s).iter().all(get), + None => turns_on(s, get), }; apply(s, &|c| set(c, on)) } @@ -323,7 +333,7 @@ fn underline(s: &mut Session, v: &Value) -> CmdResult { let on = match (p::bool(v, "value"), style) { (Some(b), _) => b, (None, Some(_)) => true, - (None, None) => !resolved(s).iter().all(|r| r.underline != Underline::None), + (None, None) => turns_on(s, |r| r.underline != Underline::None), }; let u = if on { style.unwrap_or(Underline::Single) } else { Underline::None }; apply(s, &|c| c.underline = Some(u)) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a05053b78b..e5c630c8ef 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -839,6 +839,50 @@ fn bold_toggles_selection_and_caret_word() { assert_eq!(p.props_of_char(9).italic, None); } +/// A partly formatted selection toggles by its first character, as Word does (#6516). +#[test] +fn toggles_on_mixed_selection_follow_first_character() { + // `Abc abc` with `fmt` set by `cmd`, then `cmd` with `v` on the selection `from` → `to`. + let toggled = |cmd: &str, fmt: (usize, usize), from: usize, to: usize, v: serde_json::Value| -> String { + let mut s = s(); + run(&mut s, "text.insert", json!({"text": "Abc abc"})); + let sel = |s: &mut Session, a: usize, b: usize| { + run(s, "select.range", json!({"anchor": {"block": 0, "off": a}, "focus": {"block": 0, "off": b}})); + }; + sel(&mut s, fmt.0, fmt.1); + run(&mut s, cmd, json!({"value": true})); + sel(&mut s, from, to); + run(&mut s, cmd, v); + let p = s.doc.para_at(&Pos::body(0, 0)).unwrap(); + (0..7) + .map(|i| { + let c = p.props_of_char(i); + match cmd { + "format.italic" => c.italic == Some(true), + "format.underline" => c.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None), + _ => c.bold == Some(true), + } + }) + .map(|on| if on { 'F' } else { '.' }) + .collect() + }; + let t = || json!({}); + for cmd in ["format.bold", "format.italic", "format.underline"] { + // `FFF....`: a selection starting on formatted text removes the format from all of it. + assert_eq!(toggled(cmd, (0, 3), 2, 5, t()), "FF.....", "{cmd}"); + assert_eq!(toggled(cmd, (0, 3), 0, 7, t()), ".......", "{cmd}"); + assert_eq!(toggled(cmd, (0, 3), 1, 7, t()), "F......", "{cmd}"); + // Made right to left: still the first character in document order. + assert_eq!(toggled(cmd, (0, 3), 5, 2, t()), "FF.....", "{cmd}"); + assert_eq!(toggled(cmd, (0, 3), 7, 0, t()), ".......", "{cmd}"); + // `....FFF`: a selection starting on plain text applies it to all of it. + assert_eq!(toggled(cmd, (4, 7), 0, 7, t()), "FFFFFFF", "{cmd}"); + // An explicit value still sets. + assert_eq!(toggled(cmd, (0, 3), 0, 7, json!({"value": true})), "FFFFFFF", "{cmd}"); + assert_eq!(toggled(cmd, (4, 7), 0, 7, json!({"value": false})), ".......", "{cmd}"); + } +} + #[test] fn border_toggles_and_saves() { use wordcraft_doc::props::Border; diff --git a/docs/typing-parity.md b/docs/typing-parity.md index 6ad5a1a3e6..2e0d180d6a 100644 --- a/docs/typing-parity.md +++ b/docs/typing-parity.md @@ -1,6 +1,6 @@ # Typing parity with Word -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-04 · **Change:** minor (#3693: additional Delete Previous Sentence command and shortcut; Word-parity estimates unchanged); previously trivial (Ctrl+K on a selection retypes it with a changed Text to display); previously trivial (equation `\int` + Space waits for its limits, `_x^y` then Space builds them and typing goes into the operand, and any character that can't continue `\name` corrects it, observed in Word for Windows on #4938, #4917); previously minor (English spelling by dialect from SCOWL 2026, CP2; previously trivial: a tracked heading or border-line AutoFormat replaces another author's formatting change; previously trivial: Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (highlight at a caret leaves the word alone, #4086); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial: tests and notes for the border-line, table, tab-indent and wide-space rules; previously trivial: `*Bold* and _italic_ as real formatting` in AutoFormat As You Type; previously trivial: highlight target includes selected paragraph marks, #4085; previously trivial: full-target highlight check beyond 10,000 runs, #4085; previously trivial: queued IME replacements are rejected before mutation after their marked composition loses its body/equation target; previously trivial: the transactional equation delete proves its commit with the engine revision; previously trivial: a refused byte-counted equation deletion drops only the immediately adjacent stale replacement, so a later direct commit still applies; previously trivial: a tracked own-insertion shifts the rest of a two-sided IME deletion; previously trivial: AutoCorrect/AutoFormat classification compares the actual paragraph; previously trivial: a replaced body starts a new input-method context and interrupts the composition; a quote the engine leaves as typed is the input method's own change; equation `DeleteSurrounding` erases counted characters; previously trivial: AutoCorrect finds the word after a no-break space or an ideographic space; 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 trivial: while an input method composes, the caret and its candidate window sit at the input method's cursor inside the composition; previously trivial: Ctrl+Tab types a tab in a table cell, #3137; previously trivial: List AutoFormat triggers in front of an already-written paragraph, not only a fresh empty one, checked in Word for Windows, #3352; previously trivial: AltGr types its characters without opening KeyTips on Linux, #2388; previously trivial: Delete on whole selected cells leaves one empty paragraph in each, with the cell's last paragraph's formatting; nested tables go too, #2802; 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: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: a slash opening a word travels whole to the next line, #2963; previously trivial: typing over a selection takes the first selected character's formatting, also when the selection was made right to left, #2879; previously trivial: Turkish and Azerbaijani case mapping in AutoCorrect, #1923; previously trivial: smart quotes in Hebrew pinned: logical order, ” in acronyms as in Word, #1670; previously trivial: Backspace on a selected table, rows or columns deletes them, Delete clears them, #1844; previously trivial: typed text takes its direction from its own letters, #1543; previously trivial: an input method's request to erase text around the caret is honoured, so web typing in Cyrillic and other non-Latin text no longer repeats, #1480; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: a heading-list preset keeps Heading styles and makes other paragraphs Heading 1, as in Word, #1793; previously trivial: numbered headings: a heading-linked Multilevel List numbers new headings by their style; numbering keeps a heading a heading, #1793; previously trivial: reversing an automatic capital adds an exception, #1857; previously trivial: smart quotes open after guillemets and low quotes and nest; previously trivial: Enter on an empty list item numbered by its paragraph style moves it up a level, #2143; previously trivial: Backspace after a section break and Delete before it remove the break, also on the last paragraph, #2127; previously trivial: a table inserted in right-to-left text is right to left, so Tab moves left, #2634; previously trivial: Shift+Delete cuts the selection on every platform, #1669; previously trivial: Select All then Delete removes a table the document starts with, #1198; previously trivial: Alt+numpad character codes, #961; previously trivial: Down and Up from a line start beside a table go into it, #1007; previously trivial: sample-text formulas on Enter, #1067; previously trivial: Track Changes: Accept All after a tracked delete from a paragraph end keeps the next paragraph; Reject All after typing into an empty paragraph keeps it (#864); previously minor: Correct TWo INitial CApitals, cAPS LOCK and table-cell capitals, #544; previously trivial: complex-script caret and Backspace, #604; Move Paragraph Up/Down, Promote/Demote, Go Back and Alt+X keys, #343; the body IME deletion maps signed placeholder growth/shrink, keeps control markers outside the range and scopes its undo join to the matching replacement) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-13 · **Change:** trivial (#6516: Bold and the other toggles on a partly formatted selection follow its first character, observed in Word for Windows); previously minor (#3693: additional Delete Previous Sentence command and shortcut; Word-parity estimates unchanged); previously trivial (Ctrl+K on a selection retypes it with a changed Text to display); previously trivial (equation `\int` + Space waits for its limits, `_x^y` then Space builds them and typing goes into the operand, and any character that can't continue `\name` corrects it, observed in Word for Windows on #4938, #4917); previously minor (English spelling by dialect from SCOWL 2026, CP2; previously trivial: a tracked heading or border-line AutoFormat replaces another author's formatting change; previously trivial: Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (highlight at a caret leaves the word alone, #4086); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial: tests and notes for the border-line, table, tab-indent and wide-space rules; previously trivial: `*Bold* and _italic_ as real formatting` in AutoFormat As You Type; previously trivial: highlight target includes selected paragraph marks, #4085; previously trivial: full-target highlight check beyond 10,000 runs, #4085; previously trivial: queued IME replacements are rejected before mutation after their marked composition loses its body/equation target; previously trivial: the transactional equation delete proves its commit with the engine revision; previously trivial: a refused byte-counted equation deletion drops only the immediately adjacent stale replacement, so a later direct commit still applies; previously trivial: a tracked own-insertion shifts the rest of a two-sided IME deletion; previously trivial: AutoCorrect/AutoFormat classification compares the actual paragraph; previously trivial: a replaced body starts a new input-method context and interrupts the composition; a quote the engine leaves as typed is the input method's own change; equation `DeleteSurrounding` erases counted characters; previously trivial: AutoCorrect finds the word after a no-break space or an ideographic space; 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 trivial: while an input method composes, the caret and its candidate window sit at the input method's cursor inside the composition; previously trivial: Ctrl+Tab types a tab in a table cell, #3137; previously trivial: List AutoFormat triggers in front of an already-written paragraph, not only a fresh empty one, checked in Word for Windows, #3352; previously trivial: AltGr types its characters without opening KeyTips on Linux, #2388; previously trivial: Delete on whole selected cells leaves one empty paragraph in each, with the cell's last paragraph's formatting; nested tables go too, #2802; 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: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: a slash opening a word travels whole to the next line, #2963; previously trivial: typing over a selection takes the first selected character's formatting, also when the selection was made right to left, #2879; previously trivial: Turkish and Azerbaijani case mapping in AutoCorrect, #1923; previously trivial: smart quotes in Hebrew pinned: logical order, ” in acronyms as in Word, #1670; previously trivial: Backspace on a selected table, rows or columns deletes them, Delete clears them, #1844; previously trivial: typed text takes its direction from its own letters, #1543; previously trivial: an input method's request to erase text around the caret is honoured, so web typing in Cyrillic and other non-Latin text no longer repeats, #1480; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: a heading-list preset keeps Heading styles and makes other paragraphs Heading 1, as in Word, #1793; previously trivial: numbered headings: a heading-linked Multilevel List numbers new headings by their style; numbering keeps a heading a heading, #1793; previously trivial: reversing an automatic capital adds an exception, #1857; previously trivial: smart quotes open after guillemets and low quotes and nest; previously trivial: Enter on an empty list item numbered by its paragraph style moves it up a level, #2143; previously trivial: Backspace after a section break and Delete before it remove the break, also on the last paragraph, #2127; previously trivial: a table inserted in right-to-left text is right to left, so Tab moves left, #2634; previously trivial: Shift+Delete cuts the selection on every platform, #1669; previously trivial: Select All then Delete removes a table the document starts with, #1198; previously trivial: Alt+numpad character codes, #961; previously trivial: Down and Up from a line start beside a table go into it, #1007; previously trivial: sample-text formulas on Enter, #1067; previously trivial: Track Changes: Accept All after a tracked delete from a paragraph end keeps the next paragraph; Reject All after typing into an empty paragraph keeps it (#864); previously minor: Correct TWo INitial CApitals, cAPS LOCK and table-cell capitals, #544; previously trivial: complex-script caret and Backspace, #604; Move Paragraph Up/Down, Promote/Demote, Go Back and Alt+X keys, #343; the body IME deletion maps signed placeholder growth/shrink, keeps control markers outside the range and scopes its undo join to the matching replacement) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 What Word does when you type, observed black-box (same keystrokes typed into Word and WordCraft, results read back paragraph by paragraph) and pinned by tests in @@ -601,6 +601,16 @@ command is one Undo step and still obeys editing protection and the 1–1638 pt limits. Original-fixture engine and Linux CLI/headless UI save/reopen checks cover this correction; native Windows interaction and Microsoft Word remain untested. +## Toggling a partly formatted selection + +Bold, Italic, Underline, Strikethrough, Subscript and the other character toggles decide from +the selection's first character in document order, whichever way it was made (#6516). If that +character has the format, the whole selection loses it; otherwise the whole selection gets it. +With `Abc abc` and `Abc` bold, Bold on `c a` leaves only `Ab` bold; Bold on `abc abc` with only +the last `abc` bold makes it all bold. Observed in Word for Windows. A caret keeps its own rule, +and an explicit `value` still sets. The ribbon still shows a mixed selection as off. +Regression: `toggles_on_mixed_selection_follow_first_character`. + ## Empty paragraph removal Deleting a paragraph mark whose preceding paragraph was already empty preserves the @@ -614,6 +624,7 @@ DOCX and Undo/Redo (Leaf #152). No new Word or native UI comparison was run. | Date | Change | Summary | |---|---|---| +| 2026-11-13 | trivial | Toggles on a partly formatted selection follow its first character, as observed in Word for Windows (#6516) | | 2026-11-04 | trivial | Ctrl+K on a selection: a changed Text to display replaces the selected text before it is linked | | 2026-11-07 | trivial | Removing an already-empty paragraph preserves the following paragraph properties, mark and inline formatting. Delete, Backspace, selected marks, outline/TOC, DOCX and Undo/Redo have synthetic coverage (Leaf #152); no new Word or native acceptance run. | | 2026-10-30 | trivial | Equations: `\int` + Space waits for its limits; `_x^y` then Space builds them, Space alone builds the operator without, typing goes into its operand, and Enter or an arrow key builds it without going into the operand (#4917). Review: any character that can't continue `\name` corrects it (`\int_0^1`, `\alpha+`), and `∫∫` takes the operand into the inner operator; the Word rows are now observed in Word for Windows on #4938, Enter, arrows and `∫∫` are not | From a620ad3587f8750b04c3d63aa18a87e04a1af71e Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:51:20 -0500 Subject: [PATCH 086/609] #6517: a typographic apostrophe is part of the word at the caret Bold and the other character formats at a caret, and double-click's word unit (Paragraph::word_at), now treat U+2019 like a straight apostrophe, as Word does. is_word_char is unchanged, so Ctrl+Arrow and Ctrl+Backspace/Delete keep their behaviour. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/para.rs | 18 +++++++++++++++++- crates/engine/src/cmd/format.rs | 3 ++- crates/engine/src/tests.rs | 26 ++++++++++++++++++++++++++ docs/typing-parity.md | 9 ++++++++- 4 files changed, 53 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/para.rs b/crates/doc/src/para.rs index 0ed90870b1..5d8fcc7270 100644 --- a/crates/doc/src/para.rs +++ b/crates/doc/src/para.rs @@ -553,7 +553,8 @@ impl Paragraph { /// The word around `off` (double-click): (start, end) without trailing space. pub fn word_at(&self, off: usize) -> (usize, usize) { let off = self.clamp(off); - let is_w = |c: char| crate::bidi::is_word_char(c); + // Word's word unit takes a typographic apostrophe (’) like `'`, at either end too (#6517). + let is_w = |c: char| crate::bidi::is_word_char(c) || c == '’'; let mut a = off; for (i, c) in self.text.get(..off).unwrap_or("").char_indices().rev() { if !is_w(c) { @@ -786,6 +787,21 @@ mod tests { assert_eq!(p.prev_boundary(0), 0); } + #[test] + fn word_at_takes_a_typographic_apostrophe_like_a_straight_one() { + // Byte offsets: `’` is three bytes. Word: `don’t ` (#6517). + let p = Paragraph::with_text("don’t stop", CharProps::default()); + assert_eq!(p.word_at(1), (0, 8)); + assert_eq!(p.word_at(2), (0, 8)); + let p = Paragraph::with_text("the dogs’ bone", CharProps::default()); + assert_eq!(p.word_at(5), (4, 12)); + let p = Paragraph::with_text("’tis here", CharProps::default()); + assert_eq!(p.word_at(3), (0, 7)); + assert_eq!(p.word_at(4), (0, 7)); + let p = Paragraph::with_text("well-known", CharProps::default()); + assert_eq!(p.word_at(1), (0, 4)); + } + proptest::proptest! { #[test] fn edits_keep_runs_consistent(ops in proptest::collection::vec((0u8..4, 0usize..40, 0usize..40, "[a-zé ]{0,5}"), 0..40)) { diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index ce35c9b348..dd430358b2 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -171,7 +171,8 @@ fn target(s: &Session) -> Option<(Pos, Pos)> { return Some((a, b)); } let p = s.doc.para_at(&a)?; - let is_w = |c: char| c.is_alphanumeric() || c == '\'' || c == '_'; + // Word takes a typographic apostrophe (’) like `'` here (#6517). + let is_w = |c: char| c.is_alphanumeric() || matches!(c, '\'' | '’' | '_'); let before = p.text.get(..a.off)?.chars().next_back(); let after = p.text.get(a.off..)?.chars().next(); if before.is_some_and(is_w) && after.is_some_and(is_w) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a05053b78b..408091fde2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -839,6 +839,32 @@ fn bold_toggles_selection_and_caret_word() { assert_eq!(p.props_of_char(9).italic, None); } +#[test] +fn bold_at_a_caret_takes_a_word_with_a_typographic_apostrophe() { + // Word bolds `don’t` and `dogs’` whole: `’` is part of the word like `'` (#6517). + let bold_word = |text: &str, caret: usize| { + let mut s = s(); + run(&mut s, "text.insert", json!({"text": text})); + run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": caret}})); + run(&mut s, "format.bold", json!({})); + let p = s.doc.para_at(&Pos::body(0, 0)).unwrap().clone(); + p.text.char_indices().filter(|&(i, _)| p.props_of_char(i).bold == Some(true)).map(|(_, c)| c).collect::() + }; + assert_eq!(bold_word("don’t stop", 1), "don’t"); + assert_eq!(bold_word("the dogs’ bone", 5), "dogs’"); + assert_eq!(bold_word("’tis here", 3), "’tis"); +} + +#[test] +fn select_word_takes_a_typographic_apostrophe() { + let mut s = s(); + run(&mut s, "text.insert", json!({"text": "don’t stop"})); + run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 1}})); + run(&mut s, "select.word", json!({})); + let (a, b) = s.sel.ordered(); + assert_eq!((a.off, b.off), (0, 8), "`don’t ` with its trailing space, as Word selects it (#6517)"); +} + #[test] fn border_toggles_and_saves() { use wordcraft_doc::props::Border; diff --git a/docs/typing-parity.md b/docs/typing-parity.md index 6ad5a1a3e6..2ef51a0b1f 100644 --- a/docs/typing-parity.md +++ b/docs/typing-parity.md @@ -1,6 +1,6 @@ # Typing parity with Word -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-04 · **Change:** minor (#3693: additional Delete Previous Sentence command and shortcut; Word-parity estimates unchanged); previously trivial (Ctrl+K on a selection retypes it with a changed Text to display); previously trivial (equation `\int` + Space waits for its limits, `_x^y` then Space builds them and typing goes into the operand, and any character that can't continue `\name` corrects it, observed in Word for Windows on #4938, #4917); previously minor (English spelling by dialect from SCOWL 2026, CP2; previously trivial: a tracked heading or border-line AutoFormat replaces another author's formatting change; previously trivial: Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (highlight at a caret leaves the word alone, #4086); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial: tests and notes for the border-line, table, tab-indent and wide-space rules; previously trivial: `*Bold* and _italic_ as real formatting` in AutoFormat As You Type; previously trivial: highlight target includes selected paragraph marks, #4085; previously trivial: full-target highlight check beyond 10,000 runs, #4085; previously trivial: queued IME replacements are rejected before mutation after their marked composition loses its body/equation target; previously trivial: the transactional equation delete proves its commit with the engine revision; previously trivial: a refused byte-counted equation deletion drops only the immediately adjacent stale replacement, so a later direct commit still applies; previously trivial: a tracked own-insertion shifts the rest of a two-sided IME deletion; previously trivial: AutoCorrect/AutoFormat classification compares the actual paragraph; previously trivial: a replaced body starts a new input-method context and interrupts the composition; a quote the engine leaves as typed is the input method's own change; equation `DeleteSurrounding` erases counted characters; previously trivial: AutoCorrect finds the word after a no-break space or an ideographic space; 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 trivial: while an input method composes, the caret and its candidate window sit at the input method's cursor inside the composition; previously trivial: Ctrl+Tab types a tab in a table cell, #3137; previously trivial: List AutoFormat triggers in front of an already-written paragraph, not only a fresh empty one, checked in Word for Windows, #3352; previously trivial: AltGr types its characters without opening KeyTips on Linux, #2388; previously trivial: Delete on whole selected cells leaves one empty paragraph in each, with the cell's last paragraph's formatting; nested tables go too, #2802; 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: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: a slash opening a word travels whole to the next line, #2963; previously trivial: typing over a selection takes the first selected character's formatting, also when the selection was made right to left, #2879; previously trivial: Turkish and Azerbaijani case mapping in AutoCorrect, #1923; previously trivial: smart quotes in Hebrew pinned: logical order, ” in acronyms as in Word, #1670; previously trivial: Backspace on a selected table, rows or columns deletes them, Delete clears them, #1844; previously trivial: typed text takes its direction from its own letters, #1543; previously trivial: an input method's request to erase text around the caret is honoured, so web typing in Cyrillic and other non-Latin text no longer repeats, #1480; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: a heading-list preset keeps Heading styles and makes other paragraphs Heading 1, as in Word, #1793; previously trivial: numbered headings: a heading-linked Multilevel List numbers new headings by their style; numbering keeps a heading a heading, #1793; previously trivial: reversing an automatic capital adds an exception, #1857; previously trivial: smart quotes open after guillemets and low quotes and nest; previously trivial: Enter on an empty list item numbered by its paragraph style moves it up a level, #2143; previously trivial: Backspace after a section break and Delete before it remove the break, also on the last paragraph, #2127; previously trivial: a table inserted in right-to-left text is right to left, so Tab moves left, #2634; previously trivial: Shift+Delete cuts the selection on every platform, #1669; previously trivial: Select All then Delete removes a table the document starts with, #1198; previously trivial: Alt+numpad character codes, #961; previously trivial: Down and Up from a line start beside a table go into it, #1007; previously trivial: sample-text formulas on Enter, #1067; previously trivial: Track Changes: Accept All after a tracked delete from a paragraph end keeps the next paragraph; Reject All after typing into an empty paragraph keeps it (#864); previously minor: Correct TWo INitial CApitals, cAPS LOCK and table-cell capitals, #544; previously trivial: complex-script caret and Backspace, #604; Move Paragraph Up/Down, Promote/Demote, Go Back and Alt+X keys, #343; the body IME deletion maps signed placeholder growth/shrink, keeps control markers outside the range and scopes its undo join to the matching replacement) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-13 · **Change:** trivial (a typographic apostrophe is part of the word at the caret for character formats and double-click, #6517); previously minor (#3693: additional Delete Previous Sentence command and shortcut; Word-parity estimates unchanged); previously trivial (Ctrl+K on a selection retypes it with a changed Text to display); previously trivial (equation `\int` + Space waits for its limits, `_x^y` then Space builds them and typing goes into the operand, and any character that can't continue `\name` corrects it, observed in Word for Windows on #4938, #4917); previously minor (English spelling by dialect from SCOWL 2026, CP2; previously trivial: a tracked heading or border-line AutoFormat replaces another author's formatting change; previously trivial: Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (highlight at a caret leaves the word alone, #4086); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial: tests and notes for the border-line, table, tab-indent and wide-space rules; previously trivial: `*Bold* and _italic_ as real formatting` in AutoFormat As You Type; previously trivial: highlight target includes selected paragraph marks, #4085; previously trivial: full-target highlight check beyond 10,000 runs, #4085; previously trivial: queued IME replacements are rejected before mutation after their marked composition loses its body/equation target; previously trivial: the transactional equation delete proves its commit with the engine revision; previously trivial: a refused byte-counted equation deletion drops only the immediately adjacent stale replacement, so a later direct commit still applies; previously trivial: a tracked own-insertion shifts the rest of a two-sided IME deletion; previously trivial: AutoCorrect/AutoFormat classification compares the actual paragraph; previously trivial: a replaced body starts a new input-method context and interrupts the composition; a quote the engine leaves as typed is the input method's own change; equation `DeleteSurrounding` erases counted characters; previously trivial: AutoCorrect finds the word after a no-break space or an ideographic space; 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 trivial: while an input method composes, the caret and its candidate window sit at the input method's cursor inside the composition; previously trivial: Ctrl+Tab types a tab in a table cell, #3137; previously trivial: List AutoFormat triggers in front of an already-written paragraph, not only a fresh empty one, checked in Word for Windows, #3352; previously trivial: AltGr types its characters without opening KeyTips on Linux, #2388; previously trivial: Delete on whole selected cells leaves one empty paragraph in each, with the cell's last paragraph's formatting; nested tables go too, #2802; 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: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: a slash opening a word travels whole to the next line, #2963; previously trivial: typing over a selection takes the first selected character's formatting, also when the selection was made right to left, #2879; previously trivial: Turkish and Azerbaijani case mapping in AutoCorrect, #1923; previously trivial: smart quotes in Hebrew pinned: logical order, ” in acronyms as in Word, #1670; previously trivial: Backspace on a selected table, rows or columns deletes them, Delete clears them, #1844; previously trivial: typed text takes its direction from its own letters, #1543; previously trivial: an input method's request to erase text around the caret is honoured, so web typing in Cyrillic and other non-Latin text no longer repeats, #1480; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: a heading-list preset keeps Heading styles and makes other paragraphs Heading 1, as in Word, #1793; previously trivial: numbered headings: a heading-linked Multilevel List numbers new headings by their style; numbering keeps a heading a heading, #1793; previously trivial: reversing an automatic capital adds an exception, #1857; previously trivial: smart quotes open after guillemets and low quotes and nest; previously trivial: Enter on an empty list item numbered by its paragraph style moves it up a level, #2143; previously trivial: Backspace after a section break and Delete before it remove the break, also on the last paragraph, #2127; previously trivial: a table inserted in right-to-left text is right to left, so Tab moves left, #2634; previously trivial: Shift+Delete cuts the selection on every platform, #1669; previously trivial: Select All then Delete removes a table the document starts with, #1198; previously trivial: Alt+numpad character codes, #961; previously trivial: Down and Up from a line start beside a table go into it, #1007; previously trivial: sample-text formulas on Enter, #1067; previously trivial: Track Changes: Accept All after a tracked delete from a paragraph end keeps the next paragraph; Reject All after typing into an empty paragraph keeps it (#864); previously minor: Correct TWo INitial CApitals, cAPS LOCK and table-cell capitals, #544; previously trivial: complex-script caret and Backspace, #604; Move Paragraph Up/Down, Promote/Demote, Go Back and Alt+X keys, #343; the body IME deletion maps signed placeholder growth/shrink, keeps control markers outside the range and scopes its undo join to the matching replacement) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 What Word does when you type, observed black-box (same keystrokes typed into Word and WordCraft, results read back paragraph by paragraph) and pinned by tests in @@ -46,6 +46,12 @@ columns ignore marks outside the selected range. Palette state is outside docume Highlighting formats the selection only: with a caret, even inside a word, it sets the colour for what is typed next and leaves the word alone, as in Word (#4086; Bold and other character formats still take the word at the caret). +The word at the caret, for Bold and the other character formats and for double-click, +takes a typographic apostrophe (`’`, as AutoCorrect types it) like a straight one, also at +either end: `don’t`, `dogs’` and `’tis` are whole words, while a hyphen still ends one +(`well-known`). Observed in Word for Windows on #6517; pinned by +`bold_at_a_caret_takes_a_word_with_a_typographic_apostrophe` and +`select_word_takes_a_typographic_apostrophe`. Ctrl+arrow word moves are unchanged. Regressions: `highlight_shortcut_toggles_the_last_colour` and `highlight_toggle_handles_mixed_inherited_and_pending_formatting`. Synthetic command/key @@ -614,6 +620,7 @@ DOCX and Undo/Redo (Leaf #152). No new Word or native UI comparison was run. | Date | Change | Summary | |---|---|---| +| 2026-11-13 | trivial | Bold and other character formats at a caret, and double-click, take a word with a typographic apostrophe whole (`don’t`, `dogs’`), as Word for Windows does (#6517) | | 2026-11-04 | trivial | Ctrl+K on a selection: a changed Text to display replaces the selected text before it is linked | | 2026-11-07 | trivial | Removing an already-empty paragraph preserves the following paragraph properties, mark and inline formatting. Delete, Backspace, selected marks, outline/TOC, DOCX and Undo/Redo have synthetic coverage (Leaf #152); no new Word or native acceptance run. | | 2026-10-30 | trivial | Equations: `\int` + Space waits for its limits; `_x^y` then Space builds them, Space alone builds the operator without, typing goes into its operand, and Enter or an arrow key builds it without going into the operand (#4917). Review: any character that can't continue `\name` corrects it (`\int_0^1`, `\alpha+`), and `∫∫` takes the operand into the inner operator; the Word rows are now observed in Word for Windows on #4938, Enter, arrows and `∫∫` are not | From 824a5e2c1d82a27a48bf4520d30909fafe543e30 Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:01:00 -0500 Subject: [PATCH 087/609] #6516: pin that a selection from an empty paragraph follows its first text Word ignores an empty paragraph's mark at the start of the selection and decides from the first text character (review on #6519). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/tests.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e5c630c8ef..b253e0beb4 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -883,6 +883,28 @@ fn toggles_on_mixed_selection_follow_first_character() { } } +/// A selection that starts in an empty paragraph: Word decides from the first text character, not +/// from the empty paragraph's mark (observed in Word for Windows, #6516 review). +#[test] +fn toggle_on_a_selection_from_an_empty_paragraph_follows_the_first_text() { + let toggled = |mark_bold: bool, text_bold: bool| -> Option { + let mut s = s(); + run(&mut s, "text.newParagraph", json!({})); + run(&mut s, "text.insert", json!({"text": "abc"})); + let first = Pos::body(0, 0); + s.doc.para_mut(first.story, &first.path).unwrap().mark.bold = Some(mark_bold); + run(&mut s, "select.range", json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 1, "off": 3}})); + run(&mut s, "format.bold", json!({"value": text_bold})); + run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 0}, "focus": {"block": 1, "off": 3}})); + run(&mut s, "format.bold", json!({})); + s.doc.para_at(&Pos::body(1, 0)).unwrap().props_of_char(0).bold + }; + // A bold empty paragraph before plain text: Bold goes on. + assert_eq!(toggled(true, false), Some(true)); + // A plain empty paragraph before bold text: Bold comes off. + assert_eq!(toggled(false, true), Some(false)); +} + #[test] fn border_toggles_and_saves() { use wordcraft_doc::props::Border; From 022be202c19efdfb3447f4b454e3b519083d5e17 Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:08:43 -0500 Subject: [PATCH 088/609] #6517: the thesaurus looks up a quoted word without its quotes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The word unit now keeps a typographic quote at its ends, so the caret word in ‘good’ is good’. The thesaurus lookup trims enclosing quotes and keeps an apostrophe inside the word (review on #6520). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/review/proofing.rs | 4 +++- crates/engine/src/tests.rs | 11 +++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/review/proofing.rs b/crates/engine/src/cmd/review/proofing.rs index 39d19c1ecb..e8c40679f5 100644 --- a/crates/engine/src/cmd/review/proofing.rs +++ b/crates/engine/src/cmd/review/proofing.rs @@ -167,7 +167,9 @@ pub(super) fn thesaurus(s: &mut Session, v: &Value) -> CmdResult { let f = s.sel.focus.clone(); let p = s.doc.para_at(&f).ok_or_else(|| CmdError::Failed("no word".into()))?; let (a, b) = p.word_at(f.off); - p.text.get(a..b).unwrap_or("").trim().to_lowercase() + // The word unit keeps quotes at its ends (`‘good’` → `good’`); look the word up without + // them, keeping an apostrophe inside it (`don’t`) (#6517). + p.text.get(a..b).unwrap_or("").trim().trim_matches(|c| matches!(c, '’' | '‘' | '\'')).to_lowercase() } }; let syn = T.iter().find(|(w, _)| *w == word).map(|(_, l)| l.to_vec()).unwrap_or_default(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 408091fde2..2b0f429bf9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -865,6 +865,17 @@ fn select_word_takes_a_typographic_apostrophe() { assert_eq!((a.off, b.off), (0, 8), "`don’t ` with its trailing space, as Word selects it (#6517)"); } +#[test] +fn thesaurus_at_a_caret_looks_up_a_quoted_word_without_its_quotes() { + // The word unit now takes `’`, so `‘good’` gives `good’`; the lookup drops enclosing quotes. + let mut s = s(); + run(&mut s, "text.insert", json!({"text": "a ‘good’ day"})); + run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 6}})); + let r = run(&mut s, "review.thesaurus", json!({})); + assert_eq!(r["word"], json!("good")); + assert!(r["synonyms"].as_array().is_some_and(|a| !a.is_empty()), "{r}"); +} + #[test] fn border_toggles_and_saves() { use wordcraft_doc::props::Border; From da295eb0c511c1448848c1e890fadff53eef3e50 Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:22:03 -0500 Subject: [PATCH 089/609] #6517: a chosen synonym keeps the quotes around the word MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The thesaurus lookup and the context menu's synonym replacement now share one range, review::thesaurus_word: the word unit without the spaces after it or the quotes around it. Replacing good in ‘good’ gives ‘fine’, not ‘fine (review on #6520). --- crates/engine/src/cmd/review.rs | 1 + crates/engine/src/cmd/review/proofing.rs | 22 ++++++++++++++++------ crates/engine/src/tests.rs | 19 +++++++++++++++++++ crates/ui-egui/src/canvas/context_menu.rs | 11 +++++------ 4 files changed, 41 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/review.rs b/crates/engine/src/cmd/review.rs index f0539f0a1c..7a7652b48f 100644 --- a/crates/engine/src/cmd/review.rs +++ b/crates/engine/src/cmd/review.rs @@ -12,6 +12,7 @@ use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p}; mod changes; mod comments; mod proofing; +pub use proofing::thesaurus_word; pub(crate) use changes::StyleTarget; pub use changes::{ diff --git a/crates/engine/src/cmd/review/proofing.rs b/crates/engine/src/cmd/review/proofing.rs index e8c40679f5..99023775b4 100644 --- a/crates/engine/src/cmd/review/proofing.rs +++ b/crates/engine/src/cmd/review/proofing.rs @@ -128,6 +128,20 @@ pub(super) fn suggestions(s: &mut Session, v: &Value) -> CmdResult { } } +/// The word at the caret that the thesaurus looks up and a chosen synonym replaces: the word unit +/// without the spaces after it or the quotes around it, so `‘good’` is `good` and its quotes stay +/// when it is replaced; an apostrophe inside a word (`don’t`) is kept (#6517). +pub fn thesaurus_word(s: &Session) -> Option<(Pos, Pos)> { + let f = &s.sel.focus; + let p = s.doc.para_at(f)?; + let (a, b) = p.word_at(f.off); + let w = p.text.get(a..b)?; + let edge = |c: char| c.is_whitespace() || matches!(c, '’' | '‘' | '\''); + let start = a + (w.len() - w.trim_start_matches(edge).len()); + let end = (a + w.trim_end_matches(edge).len()).max(start); + Some((Pos { off: start, ..f.clone() }, Pos { off: end, ..f.clone() })) +} + /// A tiny built-in thesaurus of common words (our own list). pub(super) fn thesaurus(s: &mut Session, v: &Value) -> CmdResult { const T: &[(&str, &[&str])] = &[ @@ -164,12 +178,8 @@ pub(super) fn thesaurus(s: &mut Session, v: &Value) -> CmdResult { let word = match p::str(v, "word") { Some(w) => w.to_lowercase(), None => { - let f = s.sel.focus.clone(); - let p = s.doc.para_at(&f).ok_or_else(|| CmdError::Failed("no word".into()))?; - let (a, b) = p.word_at(f.off); - // The word unit keeps quotes at its ends (`‘good’` → `good’`); look the word up without - // them, keeping an apostrophe inside it (`don’t`) (#6517). - p.text.get(a..b).unwrap_or("").trim().trim_matches(|c| matches!(c, '’' | '‘' | '\'')).to_lowercase() + let (a, b) = thesaurus_word(s).ok_or_else(|| CmdError::Failed("no word".into()))?; + s.doc.para_at(&a).and_then(|p| p.text.get(a.off..b.off)).unwrap_or("").to_lowercase() } }; let syn = T.iter().find(|(w, _)| *w == word).map(|(_, l)| l.to_vec()).unwrap_or_default(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2b0f429bf9..699187f1bf 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -876,6 +876,25 @@ fn thesaurus_at_a_caret_looks_up_a_quoted_word_without_its_quotes() { assert!(r["synonyms"].as_array().is_some_and(|a| !a.is_empty()), "{r}"); } +#[test] +fn a_synonym_replaces_the_word_and_keeps_its_quotes() { + // The range a chosen synonym replaces (the context menu's): the word without its quotes or the + // space after it, while an apostrophe inside a word stays part of it (#6517). + let word = |text: &str, caret: usize| { + let mut s = s(); + run(&mut s, "text.insert", json!({"text": text, "raw": true})); + run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": caret}})); + let (a, b) = crate::cmd::review::thesaurus_word(&s).unwrap(); + s.sel = crate::Selection { anchor: a, focus: b }; + run(&mut s, "text.insert", json!({"text": "fine", "raw": true})); + s.doc.plain_text(StoryRef::Body) + }; + assert_eq!(word("a ‘good’ day", 6), "a ‘fine’ day"); + assert_eq!(word("a 'good' day", 4), "a 'fine' day"); + assert_eq!(word("a good day", 3), "a fine day"); + assert_eq!(word("don’t go", 1), "fine go"); +} + #[test] fn border_toggles_and_saves() { use wordcraft_doc::props::Border; diff --git a/crates/ui-egui/src/canvas/context_menu.rs b/crates/ui-egui/src/canvas/context_menu.rs index 514a31204e..0ce7bb8119 100644 --- a/crates/ui-egui/src/canvas/context_menu.rs +++ b/crates/ui-egui/src/canvas/context_menu.rs @@ -108,12 +108,11 @@ pub(super) fn context_menu(app: &mut WordApp, ui: &mut Ui) { crate::rtl::root(ui, |ui| { for w in syn.iter().filter_map(|x| x.as_str()) { if ui.button(w).clicked() { - let _ = app.run("select.word", json!({})); - let (a, b) = app.session.sel.ordered(); - let trimmed = app.session.doc.para_at(&a).and_then(|p| p.text.get(a.off..b.off)).map(|t| t.trim_end().len()).unwrap_or(0); - let end = wordcraft_doc::Pos { off: a.off + trimmed, ..b }; - app.session.sel = wordcraft_engine::Selection { anchor: a, focus: end }; - let _ = app.run("text.insert", json!({"text": w, "raw": true})); + // The word the synonyms were looked up for: quotes around it stay (#6517). + if let Some((a, b)) = wordcraft_engine::cmd::review::thesaurus_word(&app.session) { + app.session.sel = wordcraft_engine::Selection { anchor: a, focus: b }; + let _ = app.run("text.insert", json!({"text": w, "raw": true})); + } ui.close(); } } From 8f8bec4ad7838aecea79f029138a77bc4d05b6b3 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Fri, 13 Nov 2026 23:04:30 +0000 Subject: [PATCH 090/609] Tag PDF link annotations with Link and OBJR (#6464) --- crates/pdf/src/export.rs | 12 +++++-- crates/pdf/src/exporter.rs | 54 +++++++++++++++++++++++++++-- crates/pdf/src/exporter/draw.rs | 4 ++- crates/pdf/src/exporter/nav.rs | 30 ++++++++-------- crates/pdf/src/exporter/text.rs | 19 ++++++---- crates/pdf/src/tests.rs | 61 +++++++++++++++++++++++++++++++++ 6 files changed, 152 insertions(+), 28 deletions(-) diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index 81b7b94d20..3c1817980d 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -104,6 +104,7 @@ fn write_attempt(doc: &Document, lay: &DocLayout, opts: &PdfOptions, pages: &[us tags: Vec::new(), tag_index: HashMap::new(), links: Vec::new(), + last_link: None, bookmarks: std::cell::OnceCell::new(), }; if let Some(o) = ex.outline(pages) { @@ -133,8 +134,15 @@ fn write_attempt(doc: &Document, lay: &DocLayout, opts: &PdfOptions, pages: &[us } } surface.finish(); - for annotation in annotations { - kp.add_annotation(annotation); + for (annotation, tag_slot) in annotations { + if opts.tagged + && let Some((para_idx, child_idx)) = tag_slot + { + let annot_id = kp.add_tagged_annotation(annotation); + ex.attach_link_annotation(para_idx, child_idx, annot_id); + } else { + kp.add_annotation(annotation); + } } kp.finish(); } diff --git a/crates/pdf/src/exporter.rs b/crates/pdf/src/exporter.rs index 77fe80c348..8006214427 100644 --- a/crates/pdf/src/exporter.rs +++ b/crates/pdf/src/exporter.rs @@ -16,6 +16,16 @@ mod draw; mod nav; mod text; +pub(crate) struct LinkRect { + pub(crate) x0: f32, + pub(crate) y0: f32, + pub(crate) x1: f32, + pub(crate) y1: f32, + pub(crate) target: String, + /// `(para_idx, child_idx)` in `Exporter::tags` for this link's `Tag::Link` group. + pub(crate) tag: Option<(usize, usize)>, +} + pub(crate) struct Exporter<'a> { pub(crate) doc: &'a Document, pub(crate) lay: &'a DocLayout, @@ -35,8 +45,10 @@ pub(crate) struct Exporter<'a> { pub(crate) vectors: HashMap>>, pub(crate) tags: Vec, pub(crate) tag_index: HashMap<(StoryRef, DocPath), usize>, - /// Link rectangles on the current page: (x0, y0, x1, y1, target). - pub(crate) links: Vec<(f32, f32, f32, f32, String)>, + /// Link rectangles on the current page. + pub(crate) links: Vec, + /// Index in `links` touched by the most recent `Draw::Glyphs` item, if any. + pub(crate) last_link: Option, /// Bookmark positions by name (the first of a name wins), gathered once: looking each internal /// link up by walking the whole document made a long document with a linked table of contents /// take seconds to export. @@ -186,10 +198,48 @@ impl Exporter<'_> { } } + /// Attach a paragraph's marked-content `id` to its `Tag::Link` group when `draw` recorded a + /// link rectangle, or directly to the paragraph entry otherwise. + fn attach_para_link(&mut self, idx: usize, id: Identifier) { + if let Some(li) = self.last_link.take() + && let Some(link) = self.links.get_mut(li) + { + if let Some((p_idx, c_idx)) = link.tag + && let Some(Node::Group(g)) = self.tags.get_mut(p_idx).and_then(|e| e.children.get_mut(c_idx)) + { + g.push(Node::Leaf(id)); + return; + } + if let Some(e) = self.tags.get_mut(idx) { + let c_idx = e.children.len(); + e.children.push(Node::Group(TagGroup::with_children(Tag::Link, vec![Node::Leaf(id)]))); + link.tag = Some((idx, c_idx)); + return; + } + } + if let Some(e) = self.tags.get_mut(idx) { + e.children.push(Node::Leaf(id)); + } + } + + /// Insert a link annotation's `OBJR` identifier as the first child of its `Tag::Link` group. + pub(crate) fn attach_link_annotation(&mut self, para_idx: usize, child_idx: usize, annot_id: Identifier) { + if let Some(Node::Group(g)) = self.tags.get_mut(para_idx).and_then(|e| e.children.get_mut(child_idx)) { + g.children.insert(0, Node::Leaf(annot_id)); + } + } + /// One draw of a paragraph's line, tagged for what it is: text as the paragraph's content /// (structure entry `idx`), pictures and figures on their own, anything else an artifact. fn line_item(&mut self, s: &mut Surface, d: &Draw, idx: usize) { match d { + Draw::Glyphs { link: Some(_), .. } if self.opts.tagged && self.opts.links => { + self.last_link = None; + let id = s.start_tagged(ContentTag::Span(SpanTag::empty())); + self.draw(s, d); + s.end_tagged(); + self.attach_para_link(idx, id); + } Draw::Glyphs { .. } | Draw::Turned { .. } => self.tagged(s, Role::Para(idx), None, |me, s| me.draw(s, d)), // A picture marked decorative: an artifact screen readers skip. Draw::Image { decorative: true, .. } => self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| me.draw(s, d)), diff --git a/crates/pdf/src/exporter/draw.rs b/crates/pdf/src/exporter/draw.rs index 5ad2f16a36..3a63211798 100644 --- a/crates/pdf/src/exporter/draw.rs +++ b/crates/pdf/src/exporter/draw.rs @@ -31,7 +31,9 @@ impl Exporter<'_> { } None => self.glyphs(s, face, *size, glyphs, paint, (text, ranges)), } - if let Some(l) = link { + if self.opts.links + && let Some(l) = link + { self.link_rect(face, *size, glyphs, l); } } diff --git a/crates/pdf/src/exporter/nav.rs b/crates/pdf/src/exporter/nav.rs index fa03f8dd60..ff180bfe5a 100644 --- a/crates/pdf/src/exporter/nav.rs +++ b/crates/pdf/src/exporter/nav.rs @@ -53,24 +53,22 @@ impl Exporter<'_> { None } - pub(crate) fn annotations(&self, fit: Fit) -> Vec { + pub(super) fn link_target(&self, target: &str) -> Option { + if let Some(name) = target.strip_prefix('#') { + self.bookmark(name).map(|(page, x, y)| Target::Destination(XyzDestination::new(page, Point::from_xy(x, y)).into())) + } else { + // Unsafe targets (javascript:, file:, shares, other schemes) get no link; the text stays. + write::uri_target(target) + } + } + + pub(crate) fn annotations(&self, fit: Fit) -> Vec<(Annotation, Option<(usize, usize)>)> { let mut v = Vec::new(); - for (x0, y0, x1, y1, target) in &self.links { - let ((x0, y0), (x1, y1)) = (fit.point(*x0, *y0), fit.point(*x1, *y1)); + for link in &self.links { + let ((x0, y0), (x1, y1)) = (fit.point(link.x0, link.y0), fit.point(link.x1, link.y1)); let Some(rect) = krilla::geom::Rect::from_ltrb(x0, y0, x1, y1) else { continue }; - let t = if let Some(name) = target.strip_prefix('#') { - match self.bookmark(name) { - Some((page, x, y)) => Target::Destination(XyzDestination::new(page, Point::from_xy(x, y)).into()), - None => continue, - } - } else { - // Unsafe targets (javascript:, file:, shares, other schemes) get no link; the text stays. - match write::uri_target(target) { - Some(t) => t, - None => continue, - } - }; - v.push(Annotation::new_link(LinkAnnotation::new(rect, t), Some(target.clone()))); + let Some(t) = self.link_target(&link.target) else { continue }; + v.push((Annotation::new_link(LinkAnnotation::new(rect, t), Some(link.target.clone())), link.tag)); } v } diff --git a/crates/pdf/src/exporter/text.rs b/crates/pdf/src/exporter/text.rs index d1eeeb74b3..a574243987 100644 --- a/crates/pdf/src/exporter/text.rs +++ b/crates/pdf/src/exporter/text.rs @@ -163,20 +163,25 @@ impl Exporter<'_> { let adv = face.advance(last.0) as f32 * size / face.upem.max(1.0) as f32; let (x0, x1) = (first.1.min(last.1), first.1.max(last.1) + adv); let (y0, y1) = (first.2 - size * 0.85, first.2 + size * 0.25); - if ![x0, x1, y0, y1].iter().all(|v| ok(*v)) { + if ![x0, x1, y0, y1].iter().all(|v| ok(*v)) || x0 >= x1 || y0 >= y1 { + return; + } + if self.link_target(link).is_none() { return; } if let Some(prev) = self.links.last_mut() - && prev.4 == link - && (prev.1 - y0).abs() < 0.5 - && x0 - prev.2 < size + && prev.target == link + && (prev.y0 - y0).abs() < 0.5 + && x0 - prev.x1 < size { - prev.0 = prev.0.min(x0); - prev.2 = prev.2.max(x1); + prev.x0 = prev.x0.min(x0); + prev.x1 = prev.x1.max(x1); + self.last_link = Some(self.links.len() - 1); return; } if self.links.len() < 10_000 { - self.links.push((x0, y0, x1, y1, link.to_string())); + self.links.push(super::LinkRect { x0, y0, x1, y1, target: link.to_string(), tag: None }); + self.last_link = Some(self.links.len() - 1); } } diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index d767b7b644..1ce5e350be 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -1486,6 +1486,7 @@ fn bookmark_destination_is_the_page_of_its_start() { tags: Vec::new(), tag_index: HashMap::new(), links: Vec::new(), + last_link: None, bookmarks: std::cell::OnceCell::new(), }; let (page, x, y) = ex.bookmark("target").unwrap(); @@ -3000,3 +3001,63 @@ fn chart_and_equation_text_keep_their_pdf_bytes() { ["B", "o", "d", "y", " ", "t", "e", "x", "R", "v", "n", "u", "2", "0", "4", "+", "1", "\u{1D465}"].into_iter().map(String::from).collect(); assert_eq!(shown, expected); } + +#[test] +fn link_annotations_are_tagged_with_link_and_objr() { + use hayro_syntax::object::{Array, Dict, Name, Object}; + + let mut p = Paragraph::with_text("Visit ", CharProps::default()); + let link_props = CharProps { link: Some("https://example.com".into()), ..Default::default() }; + p.insert_text(p.len(), "Example", &link_props).unwrap(); + p.insert_text(p.len(), " now", &CharProps::default()).unwrap(); + let mut d = Document::new(); + d.core.title = "Link test".into(); + d.body = vec![para_block(p)]; + + let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap(); + let pdf = hayro_syntax::Pdf::new(bytes).unwrap(); + let page = &pdf.pages()[0]; + let annots = page.raw().get::(b"Annots").expect("page Annots"); + let annot = annots.iter::().next().expect("link annotation"); + assert!(annot.get::(b"StructParent").is_some(), "link annotation missing /StructParent"); + let annot_id = format!("{:?}", annot.obj_id().expect("indirect annotation")); + + let root = pdf.xref().get::(pdf.xref().root_id()).unwrap(); + let struct_tree = root.get::(b"StructTreeRoot").expect("StructTreeRoot"); + + fn find_links(dict: &Dict, out: &mut Vec<(bool, Option)>) { + if dict.get::(b"S").is_some_and(|s| s.as_ref() == b"Link") { + let mut has_mcid = false; + let mut objr = None; + if let Some(k) = dict.get::(b"K") { + for item in k.iter::() { + match item { + Object::Number(_) => has_mcid = true, + Object::Dict(d) if d.get::(b"Type").is_some_and(|t| t.as_ref() == b"OBJR") => { + objr = d.get::(b"Obj").and_then(|o| o.obj_id()).map(|id| format!("{id:?}")); + } + _ => {} + } + } + } + out.push((has_mcid, objr)); + } + if let Some(k) = dict.get::(b"K") { + for item in k.iter::() { + if let Object::Dict(child) = item { + find_links(&child, out); + } + } + } else if let Some(child) = dict.get::(b"K") { + find_links(&child, out); + } + } + + let mut links = Vec::new(); + find_links(&struct_tree, &mut links); + assert!(!links.is_empty(), "StructTreeRoot has no /Link structure element (annot {annot_id})"); + assert!( + links.iter().any(|(mcid, objr)| *mcid && objr.as_deref() == Some(&annot_id)), + "Link element missing MCID or OBJR for {annot_id}: {links:?}" + ); +} From 778ccf6db3c2eaa297fa65e9e2fccd874dc79cc8 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Fri, 13 Nov 2026 23:28:06 +0000 Subject: [PATCH 091/609] pdf: tag tables with Table, TR, TH and TD structure elements (#6463) --- crates/pdf/src/exporter.rs | 46 +++++------ crates/pdf/src/lib.rs | 4 +- crates/pdf/src/tags.rs | 163 +++++++++++++++++++++++++++++++++++-- crates/pdf/src/tests.rs | 20 +++++ 4 files changed, 200 insertions(+), 33 deletions(-) diff --git a/crates/pdf/src/exporter.rs b/crates/pdf/src/exporter.rs index 77fe80c348..99cc505dcf 100644 --- a/crates/pdf/src/exporter.rs +++ b/crates/pdf/src/exporter.rs @@ -3,7 +3,7 @@ use super::glyphs::{baseline, cluster_ends, glyph_id, glyph_outlines, left_to_ri use super::options::{PdfError, PdfOptions}; use super::paint::{append_path, fill, grown, norm, ok, paint_fill, pdf_line_cap, rect_path, shape_effects, shape_path}; use super::picture::{Vector, build_vector, load_image, paint_of, vector_picture}; -use super::tags::{Role, TagEntry, figure_alt, graphic_alt, holds_picture, holds_text}; +use super::tags::{Role, TagEntry, build_tag_tree, figure_alt, graphic_alt, holds_picture, holds_text}; use super::{ Annotation, Arc, Artifact, ArtifactType, ClKind, ContentTag, DocLayout, DocPath, Document, Draw, FaceRef, Fill, FillRule, Font, HashMap, HashSet, Identifier, Image, InlineObject, ItemDisplay, KrillaGlyph, LineCap, LineEnd, LineJoin, LineStyle, LinkAnnotation, Node, NonZeroU16, Outline, @@ -139,13 +139,14 @@ impl Exporter<'_> { e.children.push(Node::Leaf(id)); } } - Role::Figure => { + Role::Figure(source) => { let id: Identifier = s.start_tagged(ContentTag::Other); f(self, s); s.end_tagged(); let alt = alt.map(str::to_string).filter(|a| !a.is_empty()).or_else(|| Some("picture".to_string())); let g = TagGroup::with_children(Tag::Figure(alt), vec![Node::Leaf(id)]); - self.tags.push(TagEntry { kind: Tag::Div.into(), children: vec![Node::Group(g)] }); + let source = source.filter(|(_, p)| p.0.len() >= 4).map(|(st, p)| (st, p.clone())); + self.tags.push(TagEntry { kind: Tag::Div.into(), children: vec![Node::Group(g)], source }); } } } @@ -153,7 +154,7 @@ impl Exporter<'_> { /// A rotated inline picture or group: turned as a whole, with each picture in it tagged on its /// own, so a decorative picture is an artifact while the others stay figures with their alt /// text. A described shape's figure keeps its description; anything else is an artifact. - fn rotated_pictures(&mut self, s: &mut Surface, d: &Draw) { + fn rotated_pictures(&mut self, s: &mut Surface, d: &Draw, source: Option<(StoryRef, &DocPath)>) { match d { Draw::Rotated { cx, cy, spin, items } => { if !ok(*cx) || !ok(*cy) { @@ -162,7 +163,7 @@ impl Exporter<'_> { let [a, b, c, d, e, f] = spin.matrix(*cx, *cy); s.push_transform(&Transform::from_row(a, b, c, d, e, f)); for it in items { - self.rotated_pictures(s, it); + self.rotated_pictures(s, it, source); } s.pop(); } @@ -171,13 +172,13 @@ impl Exporter<'_> { let Some(clip) = rect_path(rect) else { return }; s.push_clip_path(&clip, &FillRule::NonZero); for it in items { - self.rotated_pictures(s, it); + self.rotated_pictures(s, it, source); } s.pop(); } Draw::Image { decorative: true, .. } => self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| me.draw(s, d)), - Draw::Image { alt, .. } => self.tagged(s, Role::Figure, Some(alt), |me, s| me.draw(s, d)), - Draw::Figure { alt, draws, .. } => self.tagged(s, Role::Figure, Some(alt), |me, s| { + Draw::Image { alt, .. } => self.tagged(s, Role::Figure(source), Some(alt), |me, s| me.draw(s, d)), + Draw::Figure { alt, draws, .. } => self.tagged(s, Role::Figure(source), Some(alt), |me, s| { for d in draws { me.draw(s, d); } @@ -188,22 +189,22 @@ impl Exporter<'_> { /// One draw of a paragraph's line, tagged for what it is: text as the paragraph's content /// (structure entry `idx`), pictures and figures on their own, anything else an artifact. - fn line_item(&mut self, s: &mut Surface, d: &Draw, idx: usize) { + fn line_item(&mut self, s: &mut Surface, d: &Draw, idx: usize, story: StoryRef, path: &DocPath) { match d { Draw::Glyphs { .. } | Draw::Turned { .. } => self.tagged(s, Role::Para(idx), None, |me, s| me.draw(s, d)), // A picture marked decorative: an artifact screen readers skip. Draw::Image { decorative: true, .. } => self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| me.draw(s, d)), - Draw::Image { alt, .. } => self.tagged(s, Role::Figure, Some(alt), |me, s| me.draw(s, d)), + Draw::Image { alt, .. } => self.tagged(s, Role::Figure(Some((story, path))), Some(alt), |me, s| me.draw(s, d)), // A rotated inline picture, or a rotated group holding pictures: turned as a // whole, each picture tagged on its own (see `rotated_pictures`). - Draw::Rotated { items, .. } if items.iter().any(holds_picture) => self.rotated_pictures(s, d), + Draw::Rotated { items, .. } if items.iter().any(holds_picture) => self.rotated_pictures(s, d, Some((story, path))), // A clip (a turned picture cut at its line, an exact-height cell's lines, a canvas's // members): each draw in it tagged as it would be outside it. Draw::Clip { rect, items } => { let Some(clip) = rect_path(rect) else { return }; s.push_clip_path(&clip, &FillRule::NonZero); for it in items { - self.line_item(s, it, idx); + self.line_item(s, it, idx, story, path); } s.pop(); } @@ -211,7 +212,7 @@ impl Exporter<'_> { // without text falls to the artifacts below. Draw::Rotated { items, .. } if items.iter().any(holds_text) => self.tagged(s, Role::Para(idx), None, |me, s| me.draw(s, d)), // An inline chart, diagram or described shape: its text is part of the figure, not the paragraph. - Draw::Figure { alt, kind, draws: inner } => self.tagged(s, Role::Figure, Some(figure_alt(alt, *kind)), |me, s| { + Draw::Figure { alt, kind, draws: inner } => self.tagged(s, Role::Figure(Some((story, path))), Some(figure_alt(alt, *kind)), |me, s| { for d in inner { me.draw(s, d); } @@ -257,7 +258,7 @@ impl Exporter<'_> { Placed::Lines { story, path, para, .. } => { let idx = self.entry(*story, path, para); for d in &draws { - self.line_item(s, d, idx); + self.line_item(s, d, idx, *story, path); } } Placed::Image { story, path, off, .. } => { @@ -266,7 +267,7 @@ impl Exporter<'_> { let role = if obj.is_some_and(InlineObject::is_decorative) || *off == usize::MAX { Role::Artifact(ArtifactType::Other) } else { - Role::Figure + Role::Figure(Some((*story, path))) }; let alt = match obj { Some(InlineObject::Image { alt, .. }) => alt.clone(), @@ -279,7 +280,7 @@ impl Exporter<'_> { }); } // A floating shape with a description: a figure (see `shape_figure_alt`). - Placed::Shape { alt, .. } if !alt.is_empty() => self.tagged(s, Role::Figure, Some(alt), |me, s| { + Placed::Shape { alt, .. } if !alt.is_empty() => self.tagged(s, Role::Figure(None), Some(alt), |me, s| { for d in &draws { me.draw(s, d); } @@ -289,7 +290,7 @@ impl Exporter<'_> { Some(InlineObject::Graphic { alt, .. }) => graphic_alt(alt, graphic.kind).to_string(), _ => graphic.kind.noun().to_string(), }; - self.tagged(s, Role::Figure, Some(&alt), |me, s| { + self.tagged(s, Role::Figure(Some((*story, path))), Some(&alt), |me, s| { for d in &draws { me.draw(s, d); } @@ -327,21 +328,14 @@ impl Exporter<'_> { } _ => Tag::P.into(), }; - self.tags.push(TagEntry { kind, children: Vec::new() }); + self.tags.push(TagEntry { kind, children: Vec::new(), source: Some((story, path.clone())) }); let i = self.tags.len() - 1; self.tag_index.insert((story, path.clone()), i); i } pub(crate) fn tag_tree(&mut self) -> TagTree { - let mut tree = TagTree::new().with_lang(self.doc.styles.default_chr.lang.clone()); - for e in std::mem::take(&mut self.tags) { - if e.children.is_empty() { - continue; - } - tree.push(TagGroup::with_children(e.kind, e.children)); - } - tree + build_tag_tree(self.doc, std::mem::take(&mut self.tags)) } /// The watermark text stretched over its box (Word's `v:textpath fitshape`): its advance across diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index de43694a7f..a5feb4e144 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -25,7 +25,7 @@ pub mod imposition; use std::collections::{HashMap, HashSet}; -use std::num::NonZeroU16; +use std::num::{NonZeroU16, NonZeroU32}; use std::sync::Arc; use craft_pdf::write::{self, Metadata, WriteError, Writer, backend as krilla}; @@ -41,7 +41,7 @@ use krilla::outline::{Outline, OutlineNode}; use krilla::page::PageSettings; use krilla::paint::{Fill, FillRule, LineCap, LineJoin, Stroke, StrokeDash}; use krilla::surface::Surface; -use krilla::tagging::{Artifact, ArtifactType, ContentTag, Identifier, Node, SpanTag, Tag, TagGroup, TagKind, TagTree}; +use krilla::tagging::{Artifact, ArtifactType, ContentTag, Identifier, Node, SpanTag, TableHeaderScope, Tag, TagGroup, TagKind, TagTree}; use krilla::text::{Font, GlyphId, KrillaGlyph}; use wordcraft_doc::graphic::GraphicKind; use wordcraft_doc::para::{InlineObject, ShapeKind}; diff --git a/crates/pdf/src/tags.rs b/crates/pdf/src/tags.rs index b9ca50cd6c..e2cd6f516c 100644 --- a/crates/pdf/src/tags.rs +++ b/crates/pdf/src/tags.rs @@ -1,4 +1,4 @@ -use super::{ArtifactType, Draw, GraphicKind, Node, TagKind}; +use super::{ArtifactType, DocPath, Document, Draw, GraphicKind, Node, NonZeroU32, StoryRef, TableHeaderScope, Tag, TagGroup, TagKind, TagTree}; /// A chart's or diagram's alt text: its own, else what it is ("chart", "diagram"). pub(crate) fn graphic_alt(alt: &str, kind: GraphicKind) -> &str { @@ -32,21 +32,174 @@ pub(crate) fn figure_alt(alt: &str, kind: Option) -> &str { } } -/// A structure element being collected (one per paragraph, in reading order). +/// A structure element being collected (one per paragraph or figure, in reading order). pub(crate) struct TagEntry { pub(crate) kind: TagKind, pub(crate) children: Vec, + /// Paragraph `(story, path)` this entry belongs to, used to nest table cell entries under `Table`/`TR`/`TH` or `TD`. + pub(crate) source: Option<(StoryRef, DocPath)>, } /// What the content being drawn is, for tagging. #[derive(Clone, Copy, PartialEq)] -pub(crate) enum Role { +pub(crate) enum Role<'a> { /// Paragraph content of the structure entry at this index. Para(usize), /// Header/footer, decorations: not part of the structure. Artifact(ArtifactType), - /// A floating picture (its own Figure). - Figure, + /// A figure (its own `Figure`), optionally anchored to `(story, path)`. + Figure(Option<(StoryRef, &'a DocPath)>), +} + +enum StructNode { + Leaf(TagGroup), + Table(TableNode), +} + +struct TableNode { + story: StoryRef, + path: DocPath, + rows: Vec, +} + +struct RowNode { + index: usize, + cells: Vec, +} + +struct CellNode { + index: usize, + children: Vec, +} + +/// Build the PDF structure tree, nesting table cell entries under `Table` -> `TR` -> `TH` / `TD`. +pub(crate) fn build_tag_tree(doc: &Document, tags: Vec) -> TagTree { + let mut roots = Vec::new(); + for e in tags { + if e.children.is_empty() { + continue; + } + let group = TagGroup::with_children(e.kind, e.children); + match e.source { + Some((story, path)) if path.0.len() >= 4 => insert_into_nodes(&mut roots, story, &path, group), + _ => roots.push(StructNode::Leaf(group)), + } + } + let mut tree = TagTree::new().with_lang(doc.styles.default_chr.lang.clone()); + for node in roots { + tree.push(into_tag_group(doc, node)); + } + tree +} + +fn insert_into_nodes(mut nodes: &mut Vec, story: StoryRef, path: &DocPath, group: TagGroup) { + let mut k = 0usize; + while k.saturating_add(3) < path.0.len() { + let Some(prefix) = path.0.get(..=k) else { break }; + let Some(&row_raw) = path.0.get(k + 1) else { break }; + let Some(&cell_raw) = path.0.get(k + 2) else { break }; + let table_path = DocPath(prefix.to_vec()); + let row_idx = row_raw as usize; + let cell_idx = cell_raw as usize; + + let table_pos = nodes.iter().rposition(|n| matches!(n, StructNode::Table(t) if t.story == story && t.path == table_path)); + let table_pos = match table_pos { + Some(pos) => pos, + None => { + nodes.push(StructNode::Table(TableNode { story, path: table_path, rows: Vec::new() })); + nodes.len() - 1 + } + }; + let Some(StructNode::Table(table)) = nodes.get_mut(table_pos) else { return }; + + let row_pos = match table.rows.binary_search_by_key(&row_idx, |r| r.index) { + Ok(pos) => pos, + Err(pos) => { + table.rows.insert(pos, RowNode { index: row_idx, cells: Vec::new() }); + pos + } + }; + let Some(row) = table.rows.get_mut(row_pos) else { return }; + + let cell_pos = match row.cells.binary_search_by_key(&cell_idx, |c| c.index) { + Ok(pos) => pos, + Err(pos) => { + row.cells.insert(pos, CellNode { index: cell_idx, children: Vec::new() }); + pos + } + }; + let Some(cell) = row.cells.get_mut(cell_pos) else { return }; + + nodes = &mut cell.children; + k = k.saturating_add(3); + } + nodes.push(StructNode::Leaf(group)); +} + +fn into_tag_group(doc: &Document, node: StructNode) -> TagGroup { + match node { + StructNode::Leaf(g) => g, + StructNode::Table(t) => { + let doc_table = doc.table(t.story, &t.path); + let row_nodes = t + .rows + .into_iter() + .map(|r| { + let doc_row = doc_table.and_then(|dt| dt.rows.get(r.index)); + let is_header = doc_row.is_some_and(|dr| dr.props.header); + let cell_nodes = r + .cells + .into_iter() + .map(|c| { + let doc_cell = doc_row.and_then(|dr| dr.cells.get(c.index)); + let col_span = doc_cell.and_then(|dc| NonZeroU32::new(dc.span() as u32)).filter(|n| n.get() > 1); + let row_span = + doc_table.and_then(|dt| cell_row_span(dt, r.index, c.index)).and_then(NonZeroU32::new).filter(|n| n.get() > 1); + let tag: TagKind = if is_header { + Tag::TH(TableHeaderScope::Column).with_col_span(col_span).with_row_span(row_span).into() + } else { + Tag::TD.with_col_span(col_span).with_row_span(row_span).into() + }; + let children = c.children.into_iter().map(|ch| Node::Group(into_tag_group(doc, ch))).collect(); + Node::Group(TagGroup::with_children(tag, children)) + }) + .collect(); + Node::Group(TagGroup::with_children(Tag::TR, cell_nodes)) + }) + .collect(); + TagGroup::with_children(Tag::Table, row_nodes) + } + } +} + +fn cell_row_span(table: &wordcraft_doc::Table, row_idx: usize, cell_idx: usize) -> Option { + let row = table.rows.get(row_idx)?; + let cell = row.cells.get(cell_idx)?; + if cell.props.vmerge != wordcraft_doc::props::VMerge::Restart { + return None; + } + let grid_col = row.first_grid().saturating_add(row.cells.get(..cell_idx)?.iter().map(wordcraft_doc::Cell::span).sum::()); + let mut span = 1u32; + for next_row in table.rows.get(row_idx.saturating_add(1)..)? { + let mut g = next_row.first_grid(); + let mut matched = false; + for nc in &next_row.cells { + if g == grid_col && nc.props.vmerge == wordcraft_doc::props::VMerge::Continue { + matched = true; + break; + } + g = g.saturating_add(nc.span()); + if g > grid_col { + break; + } + } + if matched { + span = span.saturating_add(1); + } else { + break; + } + } + (span > 1).then_some(span) } #[cfg(test)] diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index d767b7b644..b551c544ee 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -3000,3 +3000,23 @@ fn chart_and_equation_text_keep_their_pdf_bytes() { ["B", "o", "d", "y", " ", "t", "e", "x", "R", "v", "n", "u", "2", "0", "4", "+", "1", "\u{1D465}"].into_iter().map(String::from).collect(); assert_eq!(shown, expected); } + +#[test] +fn tables_are_tagged_with_table_tr_th_and_td() { + use wordcraft_doc::{Cell, Row, Table, props::RowProps}; + let mut d = Document::from_text("A table."); + let header = Row { + props: RowProps { header: true, ..Default::default() }, + cells: vec![Cell::with_text("Head"), Cell::with_text("Col2")], + ..Default::default() + }; + let body = Row { cells: vec![Cell::with_text("Cell10"), Cell::with_text("Cell11")], ..Default::default() }; + let t = Table { grid: vec![120.0, 120.0], rows: vec![header, body], ..Default::default() }; + d.body.push(Arc::new(wordcraft_doc::Block::Table(t))); + let raw = String::from_utf8_lossy(&export(&d, &PdfOptions { tagged: true, compress: false, ..Default::default() }).unwrap()).into_owned(); + assert!(raw.contains("/S/Table") || raw.contains("/S /Table"), "missing /S /Table in:\n{raw}"); + assert!(raw.contains("/S/TR") || raw.contains("/S /TR"), "missing /S /TR in:\n{raw}"); + assert!(raw.contains("/S/TH") || raw.contains("/S /TH"), "missing /S /TH in:\n{raw}"); + assert!(raw.contains("/S/TD") || raw.contains("/S /TD"), "missing /S /TD in:\n{raw}"); + assert!(raw.contains("/Scope/Column") || raw.contains("/Scope /Column"), "missing /Scope /Column on TH"); +} From c0c42caf9574e2ac0efb81d8cd40c7d28b586a8c Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Sat, 14 Nov 2026 00:13:46 +0000 Subject: [PATCH 092/609] Layout: measure sibling paragraph floats from a wrapped first line (#6567) --- crates/layout/src/floats.rs | 44 ++++++++++++++++++++++++++++++++----- crates/layout/src/tests.rs | 40 +++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 5 deletions(-) diff --git a/crates/layout/src/floats.rs b/crates/layout/src/floats.rs index 933c09c321..5f58c8927a 100644 --- a/crates/layout/src/floats.rs +++ b/crates/layout/src/floats.rs @@ -477,6 +477,7 @@ fn anchor_floats_but( ctx.fields.page_format = pb.page_format; let (col_x, width) = (pb.col_x(), pb.col_w()); let mut rects = HashMap::new(); + let mut areas = HashMap::new(); if !pb.web && place { // (A mark from a page before may be short of the areas this page started with.) pb.excl.truncate(excl_mark.max(pb.seeded)); @@ -513,20 +514,53 @@ fn anchor_floats_but( // with it known from the start (#2048). let above = area.as_ref().filter(|a| text_before && a.0.y < top - 0.5).map(|a| (page, a.clone())); ctx.floats_above.insert((block, oi), above); - if let Some(area) = area { - match early.and_then(|v| v.iter().position(|(b, k, _)| (*b, *k) == (block, oi))).filter(|k| *k < pb.seeded) { + let slot = if let Some(area) = area { + let b = area.0.bottom(); + let k = match early.and_then(|v| v.iter().position(|(b, k, _)| (*b, *k) == (block, oi))).filter(|k| *k < pb.seeded) { Some(k) => { if let Some(slot) = pb.excl.get_mut(k) { *slot = area; } + k } - None => pb.excl.push(area), - } - } + None => { + let k = pb.excl.len(); + pb.excl.push(area); + k + } + }; + Some((k, b)) + } else { + None + }; + areas.insert(oi, slot); } } let rel = rel_exclusions(&body_wraps(ctx, pb), col_x, y0); let pl = ctx.para_labelled(p, width, None, &rel, label.clone()); + let lead = pl.lines.first().map_or(0.0, |l| l.top.max(0.0)); + if !pb.web && place && lead > 0.0 { + let page = pb.pages.len().saturating_sub(1); + let top = y0 - before; + let text_before = top > pb.top + 0.5 || pb.col > 0; + let frame = PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror }; + for (oi, o) in p.objects.iter().enumerate() { + let Some((_, _, float)) = floating(o) else { continue }; + let Some(&area) = areas.get(&oi) else { continue }; + let Some(&r) = rects.get(&oi) else { continue }; + if area.is_none_or(|(_, b)| float.y < 0.0 && b < y0 + lead - 0.5) { + let moved = float_rect(Some(frame), (col_x, width), top + lead, r.w, r.h, float); + rects.insert(oi, moved); + if let Some((k, _)) = area + && let Some(slot) = pb.excl.get_mut(k) + { + slot.0.y += moved.y - r.y; + let above = (text_before && slot.0.y < top - 0.5).then(|| (page, slot.clone())); + ctx.floats_above.insert((block, oi), above); + } + } + } + } (rects, pl, rel) } diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index e9be02b217..ddaa6d728e 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -15444,3 +15444,43 @@ fn turned_cell_float_keeps_its_along_text_offset() { assert!((confined.y - reference.y).abs() < 0.01, "{direction:?}: {confined:?} vs {reference:?}"); } } + +/// #6567: when a wrapping float (such as a page-tall `wrapTopAndBottom` frame) pushes its anchor +/// paragraph's first line to the bottom of the page, sibling paragraph-relative floats with +/// negative vertical offsets are measured from the displaced paragraph line rather than placed +/// above the page from the pre-wrap origin. +#[test] +fn negative_offset_floats_in_a_paragraph_pushed_down_by_a_wrapping_float_stay_on_the_page() { + use wordcraft_doc::para::{Anchor, Float, FloatAlign, Wrap}; + let mut doc = Document::from_text(""); + doc.last_section.page_w = 595.3; + doc.last_section.page_h = 841.9; + let mut para = Paragraph::new(); + let title = Float { + wrap: Wrap::InFrontOfText, + h_rel: Anchor::Margin, + h_align: Some(FloatAlign::Center), + v_rel: Anchor::Paragraph, + y: -652.55, + ..Default::default() + }; + let row = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 36.0, y: -460.75, ..Default::default() }; + let frame = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: -43.11, ..Default::default() }; + para.insert_object(para.len(), rect_shape(378.5, 105.75, title), &Default::default()).unwrap(); + para.insert_object(para.len(), rect_shape(194.55, 38.45, row), &Default::default()).unwrap(); + para.insert_object(para.len(), rect_shape(556.46, 802.52, frame), &Default::default()).unwrap(); + doc.body = vec![wordcraft_doc::para_block(para)]; + + let l = lay(&doc); + assert_eq!(l.pages.len(), 1); + let placed = shapes(&l.pages[0].items); + assert_eq!(placed.len(), 3, "{placed:?}"); + let frame_rect = placed.iter().find(|r| (r.h - 802.52).abs() < 0.1).unwrap(); + let title_rect = placed.iter().find(|r| (r.h - 105.75).abs() < 0.1).unwrap(); + let row_rect = placed.iter().find(|r| (r.h - 38.45).abs() < 0.1).unwrap(); + let line_top = first_line_top(&l.pages[0].items); + assert!((frame_rect.y - (72.0 - 43.11)).abs() < 0.5, "frame stays at the top of the page: {frame_rect:?}"); + assert!((title_rect.y - (line_top - 652.55)).abs() < 0.5, "title measured from displaced line {line_top}: {title_rect:?}"); + assert!((row_rect.y - (line_top - 460.75)).abs() < 0.5, "row measured from displaced line {line_top}: {row_rect:?}"); + assert!(title_rect.y > frame_rect.y && row_rect.bottom() < frame_rect.bottom(), "{placed:?}"); +} From 50041c808cac27d947203c98e0a7648988345479 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Sat, 14 Nov 2026 01:02:27 +0000 Subject: [PATCH 093/609] Address review: keep a re-placed float's x, and don't move a wrap area onto the first line (#6567) A float placed again from a pushed-down first line takes only its new vertical position, so its drawn rect and wrap area stay together across. A wrapping float whose moved area would reach the first line stays where it was: that line was laid out without it in the way. --- crates/layout/src/floats.rs | 7 ++++++- crates/layout/src/tests.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/layout/src/floats.rs b/crates/layout/src/floats.rs index 5f58c8927a..df9b67289b 100644 --- a/crates/layout/src/floats.rs +++ b/crates/layout/src/floats.rs @@ -549,7 +549,12 @@ fn anchor_floats_but( let Some(&area) = areas.get(&oi) else { continue }; let Some(&r) = rects.get(&oi) else { continue }; if area.is_none_or(|(_, b)| float.y < 0.0 && b < y0 + lead - 0.5) { - let moved = float_rect(Some(frame), (col_x, width), top + lead, r.w, r.h, float); + // Only down: across it stays where it was placed (`settle_early` may have moved it). + let moved = Rect { y: float_rect(Some(frame), (col_x, width), top + lead, r.w, r.h, float).y, ..r }; + // A wrap area moved onto the first line would cover text laid out without it. + if area.is_some_and(|(_, b)| b + (moved.y - r.y) > y0 + lead - 0.5) { + continue; + } rects.insert(oi, moved); if let Some((k, _)) = area && let Some(slot) = pb.excl.get_mut(k) diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index ddaa6d728e..3ea7e0593f 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -15484,3 +15484,29 @@ fn negative_offset_floats_in_a_paragraph_pushed_down_by_a_wrapping_float_stay_on assert!((row_rect.y - (line_top - 460.75)).abs() < 0.5, "row measured from displaced line {line_top}: {row_rect:?}"); assert!(title_rect.y > frame_rect.y && row_rect.bottom() < frame_rect.bottom(), "{placed:?}"); } + +/// #6567 review: a wrapping float above its paragraph that would land on the first line when +/// placed from it again isn't moved there: that line was laid out without it in the way. +#[test] +fn a_wrapping_float_isnt_moved_onto_a_first_line_laid_out_without_it() { + crate::test_fonts(); + use wordcraft_doc::para::{Anchor, Float, Wrap}; + let mut doc = Document::from_text("Words in the first line of the paragraph."); + let frame = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, ..Default::default() }; + let square = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: -10.0, ..Default::default() }; + doc.insert_object(&Pos::body(0, 0), rect_shape(150.0, 50.0, square), &Default::default()).unwrap(); + doc.insert_object(&Pos::body(0, 0), rect_shape(200.0, 100.0, frame), &Default::default()).unwrap(); + let l = lay(&doc); + let items = &l.pages[0].items; + let square = shapes(items).into_iter().find(|r| (r.h - 50.0).abs() < 0.1).unwrap(); + let (x, y, height) = items + .iter() + .find_map(|i| match i { + Placed::Lines { x, y, para, story: StoryRef::Body, .. } => para.lines.first().map(|l| (*x + l.left, *y, l.height)), + _ => None, + }) + .unwrap(); + assert!(y > 72.0 + 99.0, "the frame pushes the first line down: {y}"); + let overlaps = square.y < y + height && square.bottom() > y && square.x < x + 1.0 && square.right() > x; + assert!(!overlaps, "the float {square:?} covers the first line's text at ({x}, {y})"); +} From c7b4310dc127eb151f87724e6f31e536fdcda456 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Sat, 14 Nov 2026 01:07:13 +0000 Subject: [PATCH 094/609] Address review: keep a TD/TH for blank table cells (#6463) --- crates/pdf/src/tags.rs | 19 ++++++++++--------- crates/pdf/src/tests.rs | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/crates/pdf/src/tags.rs b/crates/pdf/src/tags.rs index e2cd6f516c..2553f60f72 100644 --- a/crates/pdf/src/tags.rs +++ b/crates/pdf/src/tags.rs @@ -76,13 +76,12 @@ struct CellNode { pub(crate) fn build_tag_tree(doc: &Document, tags: Vec) -> TagTree { let mut roots = Vec::new(); for e in tags { - if e.children.is_empty() { - continue; - } - let group = TagGroup::with_children(e.kind, e.children); - match e.source { - Some((story, path)) if path.0.len() >= 4 => insert_into_nodes(&mut roots, story, &path, group), - _ => roots.push(StructNode::Leaf(group)), + let group = (!e.children.is_empty()).then(|| TagGroup::with_children(e.kind, e.children)); + match (e.source, group) { + // A blank cell still gets its TD/TH, so the row keeps every column's position. + (Some((story, path)), group) if path.0.len() >= 4 => insert_into_nodes(&mut roots, story, &path, group), + (_, Some(group)) => roots.push(StructNode::Leaf(group)), + _ => {} } } let mut tree = TagTree::new().with_lang(doc.styles.default_chr.lang.clone()); @@ -92,7 +91,7 @@ pub(crate) fn build_tag_tree(doc: &Document, tags: Vec) -> TagTree { tree } -fn insert_into_nodes(mut nodes: &mut Vec, story: StoryRef, path: &DocPath, group: TagGroup) { +fn insert_into_nodes(mut nodes: &mut Vec, story: StoryRef, path: &DocPath, group: Option) { let mut k = 0usize; while k.saturating_add(3) < path.0.len() { let Some(prefix) = path.0.get(..=k) else { break }; @@ -133,7 +132,9 @@ fn insert_into_nodes(mut nodes: &mut Vec, story: StoryRef, path: &Do nodes = &mut cell.children; k = k.saturating_add(3); } - nodes.push(StructNode::Leaf(group)); + if let Some(group) = group { + nodes.push(StructNode::Leaf(group)); + } } fn into_tag_group(doc: &Document, node: StructNode) -> TagGroup { diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index b551c544ee..a9f2e37085 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -3020,3 +3020,22 @@ fn tables_are_tagged_with_table_tr_th_and_td() { assert!(raw.contains("/S/TD") || raw.contains("/S /TD"), "missing /S /TD in:\n{raw}"); assert!(raw.contains("/Scope/Column") || raw.contains("/Scope /Column"), "missing /Scope /Column on TH"); } + +/// A blank cell still gets its TD or TH, so a filled cell after it keeps its column. +#[test] +fn blank_table_cells_keep_their_td_and_th() { + use wordcraft_doc::{Cell, Row, Table, props::RowProps}; + let mut d = Document::from_text("A table."); + let header = Row { + props: RowProps { header: true, ..Default::default() }, + cells: vec![Cell::with_text(""), Cell::with_text("Col2")], + ..Default::default() + }; + let body = Row { cells: vec![Cell::with_text(""), Cell::with_text("Cell11")], ..Default::default() }; + let t = Table { grid: vec![120.0, 120.0], rows: vec![header, body], ..Default::default() }; + d.body.push(Arc::new(wordcraft_doc::Block::Table(t))); + let raw = String::from_utf8_lossy(&export(&d, &PdfOptions { tagged: true, compress: false, ..Default::default() }).unwrap()).into_owned(); + let count = |tag: &str| raw.matches(&format!("/S/{tag}")).count() + raw.matches(&format!("/S /{tag}")).count(); + assert_eq!(count("TH"), 2, "both header cells, including the blank one"); + assert_eq!(count("TD"), 2, "both body cells, including the blank one"); +} From b687f1cd6fb2415bc6de3b672f7fe430fd30ecf7 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Sat, 14 Nov 2026 01:18:00 +0000 Subject: [PATCH 095/609] Address review: keep separated link runs in separate Link elements (#6464) --- crates/pdf/src/exporter/text.rs | 11 +++++++++++ crates/pdf/src/tests.rs | 34 +++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/crates/pdf/src/exporter/text.rs b/crates/pdf/src/exporter/text.rs index a574243987..85b4c36a08 100644 --- a/crates/pdf/src/exporter/text.rs +++ b/crates/pdf/src/exporter/text.rs @@ -158,6 +158,15 @@ impl Exporter<'_> { } } + /// Whether a link's `Link` group is still the last content of its paragraph, so more linked text + /// can join it without being read ahead of unlinked text drawn since. Untagged links always continue. + fn link_run_continues(&self, tag: Option<(usize, usize)>) -> bool { + match tag { + None => true, + Some((p, c)) => self.tags.get(p).is_some_and(|e| e.children.len() == c + 1), + } + } + pub(super) fn link_rect(&mut self, face: &FaceRef, size: f32, glyphs: &[(u32, f32, f32)], link: &str) { let (Some(first), Some(last)) = (glyphs.first(), glyphs.last()) else { return }; let adv = face.advance(last.0) as f32 * size / face.upem.max(1.0) as f32; @@ -169,10 +178,12 @@ impl Exporter<'_> { if self.link_target(link).is_none() { return; } + let continues = self.links.last().is_some_and(|prev| self.link_run_continues(prev.tag)); if let Some(prev) = self.links.last_mut() && prev.target == link && (prev.y0 - y0).abs() < 0.5 && x0 - prev.x1 < size + && continues { prev.x0 = prev.x0.min(x0); prev.x1 = prev.x1.max(x1); diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 1ce5e350be..aafc8cd482 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -3061,3 +3061,37 @@ fn link_annotations_are_tagged_with_link_and_objr() { "Link element missing MCID or OBJR for {annot_id}: {links:?}" ); } + +/// Linked text split by unlinked text keeps reading order: two Link elements, not one that +/// swallows the later run ahead of the text between. +#[test] +fn separated_link_runs_are_separate_link_elements() { + use hayro_syntax::object::{Array, Dict, Name, Object}; + + let link_props = CharProps { link: Some("https://example.com".into()), ..Default::default() }; + let mut p = Paragraph::with_text("A", link_props.clone()); + p.insert_text(p.len(), ".", &CharProps::default()).unwrap(); + p.insert_text(p.len(), "B", &link_props).unwrap(); + let mut d = Document::new(); + d.body = vec![para_block(p)]; + + let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap(); + let pdf = hayro_syntax::Pdf::new(bytes).unwrap(); + let root = pdf.xref().get::(pdf.xref().root_id()).unwrap(); + let tree = root.get::(b"StructTreeRoot").expect("StructTreeRoot"); + + fn count(dict: &Dict) -> usize { + let mut n = usize::from(dict.get::(b"S").is_some_and(|s| s.as_ref() == b"Link")); + if let Some(k) = dict.get::(b"K") { + for item in k.iter::() { + if let Object::Dict(c) = item { + n += count(&c); + } + } + } else if let Some(c) = dict.get::(b"K") { + n += count(&c); + } + n + } + assert_eq!(count(&tree), 2, "each separated link run needs its own Link element"); +} From 833082618a425e028fa341c76334d3cce2916289 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Sat, 14 Nov 2026 01:36:18 +0000 Subject: [PATCH 096/609] Address review: refuse a copy with no path, and a host copy named like the opened file (#6131) --- crates/engine/src/cmd/file.rs | 4 ++++ crates/engine/src/tests.rs | 11 +++++++++++ crates/ui-egui/src/app/commands.rs | 8 ++++++++ crates/ui-egui/src/tests.rs | 14 ++++++++++++++ 4 files changed, 37 insertions(+) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 2498f72146..b28c45896c 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -368,6 +368,10 @@ fn save(s: &mut Session, v: &Value) -> CmdResult { let path = match p::str(v, "path").map(std::path::PathBuf::from).or_else(|| s.path.clone()) { Some(p) => p, None => { + // The picker's answer would run an ordinary save, which adopts the file. + if p::bool(v, "copy") == Some(true) { + return Err(CmdError::Params("`copy` needs a `path`: the copy has to go somewhere".into())); + } s.push_ui_request(json!({"open": "saveAs"})); return Ok(json!({"saved": false})); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 004bdf0155..72208bbf6d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5665,6 +5665,17 @@ fn exporting_a_copy_keeps_the_documents_file() { let _ = std::fs::remove_dir_all(&dir); } +/// A copy with no path would open the Save As picker, whose answer is an ordinary save that adopts +/// the file: refused instead, and the picker stays closed (#6131 review). +#[test] +fn a_copy_without_a_path_is_refused() { + let mut s = Session::new(wordcraft_doc::Document::new()); + run(&mut s, "text.insert", json!({"text": "x"})); + let e = s.run("file.save", &json!({"copy": true})).unwrap_err(); + assert!(e.to_string().contains("copy"), "{e}"); + assert!(s.ui_requests.is_empty(), "no picker opens"); +} + /// A save that fails to write (no permission, disk full, a bad path) leaves the document's own /// save stamps untouched: `stamp_save` runs before the fallible write, so a prior version of this /// left `modified`/`created`/`last_modified_by`/`revision`/`zoom` changed for a save that never diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index ff9541479a..40fafb6fa5 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -145,6 +145,14 @@ impl WordApp { // `copy` (File › Export, #6131) writes a copy: the document keeps its unsaved changes, // its name and its save stamps, as for a PDF. let as_copy = params.get("copy").and_then(Value::as_bool) == Some(true); + // The host page's Save writes the opened file under its own name and its flag can't say + // "copy": a copy named like the opened file would overwrite it with unsaved text. + if as_copy && self.services.host_save.is_some() { + let opened = self.session.path.as_ref().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().to_string()); + if opened.as_deref() == Some(name.as_str()) { + return Err("a copy can't have the same name as the open document: choose another name".into()); + } + } // A save with a password encrypts this and later saves (`file.save`'s `password`). if matches!(id, "file.save" | "file.saveAs") && let Some(pw) = params.get("password").filter(|v| !v.is_null()) diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 9d9af6b0d4..c42b71ad6b 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -5012,6 +5012,20 @@ fn host_save_as_a_copy_format_is_not_save_as() { assert_eq!(a.session.path.as_deref(), Some(std::path::Path::new("report.docx"))); } +/// A copy named like the opened file can't go to the host page, whose Save would overwrite the +/// opened file with it (#6131 review). +#[test] +fn host_copy_with_the_opened_name_is_refused() { + let (mut a, got) = host_app(false); + host_open(&mut a, "report.docx"); + let e = a.execute("file.saveAs", json!({"path": "report.docx", "copy": true})).unwrap_err(); + assert!(e.contains("same name"), "{e}"); + assert!(got.borrow().is_empty(), "nothing reached the host"); + assert!(a.session.dirty); + a.execute("file.saveAs", json!({"path": "other.docx", "copy": true})).unwrap(); + assert!(a.session.dirty); +} + /// The page not getting the file is a failed save: the document keeps its changes. #[test] fn a_host_save_that_fails_leaves_the_document_unsaved() { From 7f8283a77f13457c09b4d6eabab5b3074814b33f Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Sat, 14 Nov 2026 06:48:10 +0000 Subject: [PATCH 097/609] Layout: a left tab past the right indent beside a float moves clear of it (#6577) A left tab whose stop is past the right indent wraps to start the next line. When that line was the span on a floating object's far side, the tab took no room there and its text started beside the object. Like Word, the tab now goes on to the first line clear of the object, where its text starts at the indent. Test: left_tab_past_the_right_indent_beside_a_float_moves_clear_of_it. --- crates/layout/src/para/lines.rs | 6 ++++++ crates/layout/src/tests.rs | 33 +++++++++++++++++++++++++++++++++ docs/layout-parity.md | 3 ++- 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/crates/layout/src/para/lines.rs b/crates/layout/src/para/lines.rs index 821132f6aa..865b46dd0e 100644 --- a/crates/layout/src/para/lines.rs +++ b/crates/layout/src/para/lines.rs @@ -827,6 +827,12 @@ impl Scan { bk.wrapped_tab = Some(j); return true; } + if bk.wrapped_tab == Some(j) && self.narrowed && bk.skipped < 50 { + // Wrapped into a span narrowed by a floating object (the far side of it, say): + // like Word, it goes on to the first line clear of the object (#6577). + self.skip = true; + return true; + } if bk.wrapped_tab == Some(j) { // Still past the right indent on the line it wrapped to: it takes no // room, and its text starts at the indent rather than on a line of its own. diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index e9be02b217..ab731156a8 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -1868,6 +1868,39 @@ fn left_tab_past_the_right_indent_does_not_add_a_line() { assert!((page.x - 72.0).abs() < 0.5, "the text after the tab starts at the indent: {}", page.x); } +/// Beside a floating object the wrapped tab doesn't start its text in the span on the object's +/// far side: like Word, it goes to the first line clear of the object, and its text starts at the +/// indent there (#6577). +#[test] +fn left_tab_past_the_right_indent_beside_a_float_moves_clear_of_it() { + use wordcraft_doc::props::{TabAlign, TabLeader, TabStop}; + crate::test_fonts(); + let mut d = Document::from_text("Name\tPage"); + d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| { + p.tabs = Some(vec![TabStop { pos: 500.0, align: TabAlign::Left, leader: TabLeader::None }]) + }) + .unwrap(); + // A box in the middle of the column, anchored after the text so the offsets stay those of + // "Name\tPage": the rows beside it have a span on each side. + let float = wordcraft_doc::para::Float { + wrap: wordcraft_doc::para::Wrap::Square, + h_rel: wordcraft_doc::para::Anchor::Column, + v_rel: wordcraft_doc::para::Anchor::Paragraph, + x: 184.0, + y: 0.0, + dist: 9.0, + ..Default::default() + }; + let id = text_box(&mut d, 9, "", 100.0, 43.0, float); + let l = lay(&d); + let r = box_rect(&l, id); + let name = l.caret(&Pos::body(0, 0)).unwrap(); + assert!((name.x - 72.0).abs() < 0.5 && name.top < r.bottom(), "the text before the tab starts beside the box: {name:?}, box {r:?}"); + let page = l.caret(&Pos::body(0, 5)).unwrap(); + assert!((page.x - 72.0).abs() < 0.5, "the text after the tab starts at the indent, not beside the box: {page:?}, box {r:?}"); + assert!(page.top >= r.bottom() - 0.5, "the text after the tab starts below the box: {page:?}, box {r:?}"); +} + /// A bookmark before such a tab is not text: the tab does not wrap away from it, and the /// paragraph breaks as it does without the bookmark (no line holding only the bookmark). #[test] diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 034e6cd8cb..2682aa0896 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -1,6 +1,6 @@ # Layout and pagination parity with Microsoft Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (added layout.fitOnePage to condense a multi-page document by one page while preserving typography hierarchy); previously trivial (from the second section on, headers, footers and note separators are measured with their own section's document grid and SECTION/SECTIONPAGES values, #4683); previously trivial (a turned inline picture whose file keeps no room for the turn keeps its line to its frame, the frame turned a quarter in Word 2013+ layout); previously trivial (a picture lowered further than its own height lowers its line as far, its top on the baseline); previously trivial (a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a line of only pictures is as tall as they reach, never less than its font's height; a legacy check box sizes its line as text of its size, #3984); previously trivial (spaces before a line's first character keep their width in justified and distributed lines, as in Word); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (Times and Courier take their Windows counterparts' line spacing; 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 (a click just outside a floating table, by a cell whose text is turned, goes to the text beside or after it, #4181; 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 (PR #4545: eligible cell floats keep in-bounds offsets; overflow confinement retains the front-of-text, turned-cell and native-acceptance limits); previously trivial (MATH construction reuse, #3630; previously 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 (ODT documents: a line of only pictures keeps its font's height; no setting for it any more); previously trivial (ODT documents: padding is the standard's box model always; picture-only line height is an ODF interpretation setting); previously trivial (行頭禁則 also covers the small kana and the prolonged sound mark at ordinary break opportunities, as JIS X 4051 §4 specifies, inferred from the standard and synthetic tests rather than checked in Word); previously trivial (a missing font is drawn in an installed metric twin before any other substitute: Arial for Helvetica on Windows, Tinos before macOS Times for Times New Roman); previously trivial (ODT documents: padding without a border takes room); previously trivial (ODT documents: a line of only pictures is as tall as they are); previously trivial (ODT documents: a table's own space above and below; header and footer spacing kept past a tall header); previously trivial (a page break before a table's first row moves the table; emphasis marks drawn with room in the line); previously trivial (text in a turned text box turns with it; previously trivial: an in-line picture, shape or chart moves with its run's raise or lowering, Word's `w:position`; previously trivial (layout work bounds: header-row repeats budgeted per layout, cached picture outlines charged to the decode budget, linked-box chain widths exact up to a work cap, #3867); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a table row that would leave a cell empty on a page that already holds something, its picture or first line not fitting there, moves on whole instead of leaving the other cells' text beside the empty cell, #4272); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (tab leader dots spaced and placed as in Word); previously trivial (a level above that hasn't counted yet takes its first number at the first deeper item); previously trivial (paragraph side borders lie beyond their distance from the text, #5036); previously trivial (with a header taller than the top margin, Margin-anchored drawings, header-cell pins and header-table obstacles use the rendered body top; TopMargin and InsideMargin keep their declared band, #2485; previously trivial: connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (field results take the `\* DollarText`, `\* Hex` and `\* ArabicDash` switches, #4226; previously trivial: a cell spanning columns shares its extra minimum width by the columns' preferred widths, equally in automatic tables, #1883; previously 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 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-14 · **Change:** trivial (a left tab past the right indent beside a floating object goes to the first line clear of it, #6577); previously minor (added layout.fitOnePage to condense a multi-page document by one page while preserving typography hierarchy); previously trivial (from the second section on, headers, footers and note separators are measured with their own section's document grid and SECTION/SECTIONPAGES values, #4683); previously trivial (a turned inline picture whose file keeps no room for the turn keeps its line to its frame, the frame turned a quarter in Word 2013+ layout); previously trivial (a picture lowered further than its own height lowers its line as far, its top on the baseline); previously trivial (a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a line of only pictures is as tall as they reach, never less than its font's height; a legacy check box sizes its line as text of its size, #3984); previously trivial (spaces before a line's first character keep their width in justified and distributed lines, as in Word); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (Times and Courier take their Windows counterparts' line spacing; 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 (a click just outside a floating table, by a cell whose text is turned, goes to the text beside or after it, #4181; 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 (PR #4545: eligible cell floats keep in-bounds offsets; overflow confinement retains the front-of-text, turned-cell and native-acceptance limits); previously trivial (MATH construction reuse, #3630; previously 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 (ODT documents: a line of only pictures keeps its font's height; no setting for it any more); previously trivial (ODT documents: padding is the standard's box model always; picture-only line height is an ODF interpretation setting); previously trivial (行頭禁則 also covers the small kana and the prolonged sound mark at ordinary break opportunities, as JIS X 4051 §4 specifies, inferred from the standard and synthetic tests rather than checked in Word); previously trivial (a missing font is drawn in an installed metric twin before any other substitute: Arial for Helvetica on Windows, Tinos before macOS Times for Times New Roman); previously trivial (ODT documents: padding without a border takes room); previously trivial (ODT documents: a line of only pictures is as tall as they are); previously trivial (ODT documents: a table's own space above and below; header and footer spacing kept past a tall header); previously trivial (a page break before a table's first row moves the table; emphasis marks drawn with room in the line); previously trivial (text in a turned text box turns with it; previously trivial: an in-line picture, shape or chart moves with its run's raise or lowering, Word's `w:position`; previously trivial (layout work bounds: header-row repeats budgeted per layout, cached picture outlines charged to the decode budget, linked-box chain widths exact up to a work cap, #3867); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a table row that would leave a cell empty on a page that already holds something, its picture or first line not fitting there, moves on whole instead of leaving the other cells' text beside the empty cell, #4272); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (tab leader dots spaced and placed as in Word); previously trivial (a level above that hasn't counted yet takes its first number at the first deeper item); previously trivial (paragraph side borders lie beyond their distance from the text, #5036); previously trivial (with a header taller than the top margin, Margin-anchored drawings, header-cell pins and header-table obstacles use the rendered body top; TopMargin and InsideMargin keep their declared band, #2485; previously trivial: connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (field results take the `\* DollarText`, `\* Hex` and `\* ArabicDash` switches, #4226; previously trivial: a cell spanning columns shares its extra minimum width by the columns' preferred widths, equally in automatic tables, #1883; previously 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 > **Floating anchor row segments:** 2026-11-07 · A floating anchor after a manual page/column break counts visible content on the far side of the same wrapped row. Marker-only cover anchors retain their previous-page rule. Synthetic picture spacing, placement and history controls; no new native Word measurement. Readiness estimates unchanged. @@ -307,6 +307,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | Date | Change | Summary | |---|---|---| +| 2026-11-14 | trivial | A left tab past the right indent that wraps into a span beside a floating object goes on to the first line clear of the object, its text at the indent, as in Word (#6577). `layout::tests::left_tab_past_the_right_indent_beside_a_float_moves_clear_of_it` | | 2026-11-04 | trivial | Headers, footers and note separators of the second and later sections are measured with their own section's document grid and SECTION/SECTIONPAGES values, not the previous section's; a regression from the #4501 refactor (#4683). `layout::tests::pages::a_sections_header_is_measured_without_the_previous_sections_grid` | | 2026-11-08 | trivial | Turned inline pictures with no recorded effect extent keep their line to the frame (exchanged near a quarter turn in Word 2013+ layout) and overhang it, cut at the line's top and bottom, as in Word | | 2026-11-08 | trivial | Contextual spacing drops the space after a table cell's last paragraph in the Normal style, the end-of-cell mark counting as a Normal paragraph; another style keeps it, and a middle or bottom cell of a split row lines up without the dropped space (#5450) (`layout::tests::contextual_spacing_drops_the_space_after_a_cells_last_normal_paragraph`, `a_bottom_cell_of_a_split_row_ignores_a_dropped_space_after_beside_it`). | From 104fa6133d45f0964460bfe7af266bc3ba61551d Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Sat, 14 Nov 2026 06:49:51 +0000 Subject: [PATCH 098/609] Layout: no automatic space beside an ideograph its run's installed East Asian font lacks (#6591) Word adds no autoSpaceDE/autoSpaceDN room when the run's w:eastAsia font has no ideographs, though a substituted face draws them. A declared font that isn't installed keeps the space. --- crates/layout/src/para/grid.rs | 19 +++++++++++++------ crates/layout/src/para/paragraph.rs | 27 +++++++++++++++++++++++++-- crates/layout/src/tests/autospace.rs | 26 ++++++++++++++++++++++++++ docs/layout-parity.md | 5 +++-- 4 files changed, 67 insertions(+), 10 deletions(-) diff --git a/crates/layout/src/para/grid.rs b/crates/layout/src/para/grid.rs index df370aa27b..9ddb73d573 100644 --- a/crates/layout/src/para/grid.rs +++ b/crates/layout/src/para/grid.rs @@ -78,14 +78,17 @@ pub(super) fn snap_chars(b: &mut Builder, text: &str, grid: &Grid) { /// PDF of a Chinese document at 16 pt (#2358), as JIS X 4051 asks. A field or note number is /// classed by the text it shows. The room goes after the first of the two characters; returns it /// by cluster index. -pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool) -> Vec<(usize, f32)> { +/// +/// `ea_lacks(at, c)`: the run at byte `at` names an installed East Asian font that has no glyph +/// for `c`. Word adds no room beside such a character, though a substituted face draws it (#6591). +pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool, ea_lacks: impl Fn(usize, char) -> bool) -> Vec<(usize, f32)> { let mut out = Vec::new(); if !de && !dn { return out; } let mut shown = b.shown.iter().map(|s| (s.0, s.1.as_str())).peekable(); - // The previous text cluster: index, its last character, its font size. - let mut prev: Option<(usize, char, f32)> = None; + // The previous text cluster: index, its last character, its font size, its start byte. + let mut prev: Option<(usize, char, f32, usize)> = None; for k in 0..b.clusters.len() { let Some(c) = b.clusters.get(k) else { break }; match c.kind { @@ -105,9 +108,13 @@ pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool) -> Vec prev = None; continue; }; - let size = b.styles.get(c.style as usize).map_or(0.0, |st| st.size); - if let Some((pk, pc, psize)) = prev + let (size, start) = (b.styles.get(c.style as usize).map_or(0.0, |st| st.size), c.start); + if let Some((pk, pc, psize, pstart)) = prev && let Some(side) = crate::kinsoku::auto_space(pc, first, de, dn) + && !match side { + crate::kinsoku::AsianSide::Left => ea_lacks(pstart, pc), + crate::kinsoku::AsianSide::Right => ea_lacks(start, first), + } { let asian = if side == crate::kinsoku::AsianSide::Left { psize } else { size }; let gap = if asian.is_finite() { (asian / 4.0).clamp(0.0, 400.0) } else { 0.0 }; @@ -116,7 +123,7 @@ pub(super) fn auto_space(b: &mut Builder, text: &str, de: bool, dn: bool) -> Vec out.push((pk, gap)); } } - prev = Some((k, last, size)); + prev = Some((k, last, size, start)); } out } diff --git a/crates/layout/src/para/paragraph.rs b/crates/layout/src/para/paragraph.rs index 6b2605e37c..36e885513a 100644 --- a/crates/layout/src/para/paragraph.rs +++ b/crates/layout/src/para/paragraph.rs @@ -643,6 +643,22 @@ fn shown_text(cx: &Cx) -> Option { Some(shown) } +/// Each run's end byte and the installed East Asian font (`w:eastAsia`) it names, `None` when it +/// names none or one that isn't installed. Empty when `wanted` is false or the text is ASCII, which +/// has no East Asian characters to look the fonts up for. +fn installed_east_asian_fonts(cx: &Cx, wanted: bool) -> Vec<(usize, Option)> { + if !wanted || cx.p.text.is_ascii() { + return Vec::new(); + } + cx.p.run_ranges() + .map(|(range, props)| { + let rc = cx.res.char(props); + let face = rc.font_ea.as_deref().filter(|f| !f.trim().is_empty()).map(|f| wordcraft_fonts::word::resolve(f, rc.bold, rc.italic)); + (range.end, face.filter(|r| !r.substituted).map(|r| r.face)) + }) + .collect() +} + /// Lay out one paragraph. pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout { #[cfg(test)] @@ -674,8 +690,15 @@ pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout { snap_chars(&mut sh.b, &p.text, &env.grid); } // Text on a character grid keeps to its cells. - let auto_space = - if rp.snap_to_grid && env.grid.chars.is_some() { Vec::new() } else { auto_space(&mut sh.b, &p.text, rp.auto_space_de, rp.auto_space_dn) }; + let auto_space = if rp.snap_to_grid && env.grid.chars.is_some() { + Vec::new() + } else { + let ea = installed_east_asian_fonts(&cx, rp.auto_space_de || rp.auto_space_dn); + let ea_lacks = |at: usize, c: char| { + ea.iter().find(|(end, _)| at < *end).and_then(|(_, face)| *face).is_some_and(|f: wordcraft_fonts::FaceRef| !f.covers(c)) + }; + auto_space(&mut sh.b, &p.text, rp.auto_space_de, rp.auto_space_dn, ea_lacks) + }; let mut skip = sh.left.clone(); skip.extend(sh.bare.iter().cloned()); let bt = BreakText::new(&p.text, skip); diff --git a/crates/layout/src/tests/autospace.rs b/crates/layout/src/tests/autospace.rs index a5f335fb4d..d37a3e15a8 100644 --- a/crates/layout/src/tests/autospace.rs +++ b/crates/layout/src/tests/autospace.rs @@ -85,6 +85,32 @@ fn spaces_punctuation_hangul_and_latin_alone_get_nothing() { } } +/// Word adds no automatic space, on either side, beside an ideograph whose run names an installed +/// East Asian font without ideographs, even though a substituted face draws it (#6591: 0.00 pt +/// with `w:eastAsia="Times New Roman"`). A font that isn't installed keeps the space. +#[test] +fn an_east_asian_font_without_ideographs_turns_it_off() { + crate::test_fonts(); + let with = |latin: Option<&str>, asian: &str| { + let mut d = Document::from_text("法院94年A字"); + let p = para0(&mut d); + let len = p.text.len(); + p.format(0, len, &|c: &mut CharProps| { + c.font = latin.map(str::to_string); + c.font_ea = Some(asian.to_string()); + }) + .unwrap(); + d + }; + // Source Serif 4 is installed for the tests and has no ideographs. + for d in [with(None, "Source Serif 4"), with(Some("Source Serif 4"), "Source Serif 4")] { + assert!(gaps(&d).iter().all(|g| *g == 0.0), "{:?}", gaps(&d)); + } + let d = with(None, "No Such East Asian Font 6591"); + let q = quarter(&d); + assert_eq!(gaps(&d), [0.0, q, 0.0, q, q, q, 0.0], "a font that isn't installed"); +} + #[test] fn a_field_result_is_classed_by_the_text_it_shows() { crate::test_fonts(); diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 034e6cd8cb..e84f70fcb1 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -1,6 +1,6 @@ # Layout and pagination parity with Microsoft Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (added layout.fitOnePage to condense a multi-page document by one page while preserving typography hierarchy); previously trivial (from the second section on, headers, footers and note separators are measured with their own section's document grid and SECTION/SECTIONPAGES values, #4683); previously trivial (a turned inline picture whose file keeps no room for the turn keeps its line to its frame, the frame turned a quarter in Word 2013+ layout); previously trivial (a picture lowered further than its own height lowers its line as far, its top on the baseline); previously trivial (a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a line of only pictures is as tall as they reach, never less than its font's height; a legacy check box sizes its line as text of its size, #3984); previously trivial (spaces before a line's first character keep their width in justified and distributed lines, as in Word); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (Times and Courier take their Windows counterparts' line spacing; 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 (a click just outside a floating table, by a cell whose text is turned, goes to the text beside or after it, #4181; 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 (PR #4545: eligible cell floats keep in-bounds offsets; overflow confinement retains the front-of-text, turned-cell and native-acceptance limits); previously trivial (MATH construction reuse, #3630; previously 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 (ODT documents: a line of only pictures keeps its font's height; no setting for it any more); previously trivial (ODT documents: padding is the standard's box model always; picture-only line height is an ODF interpretation setting); previously trivial (行頭禁則 also covers the small kana and the prolonged sound mark at ordinary break opportunities, as JIS X 4051 §4 specifies, inferred from the standard and synthetic tests rather than checked in Word); previously trivial (a missing font is drawn in an installed metric twin before any other substitute: Arial for Helvetica on Windows, Tinos before macOS Times for Times New Roman); previously trivial (ODT documents: padding without a border takes room); previously trivial (ODT documents: a line of only pictures is as tall as they are); previously trivial (ODT documents: a table's own space above and below; header and footer spacing kept past a tall header); previously trivial (a page break before a table's first row moves the table; emphasis marks drawn with room in the line); previously trivial (text in a turned text box turns with it; previously trivial: an in-line picture, shape or chart moves with its run's raise or lowering, Word's `w:position`; previously trivial (layout work bounds: header-row repeats budgeted per layout, cached picture outlines charged to the decode budget, linked-box chain widths exact up to a work cap, #3867); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a table row that would leave a cell empty on a page that already holds something, its picture or first line not fitting there, moves on whole instead of leaving the other cells' text beside the empty cell, #4272); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (tab leader dots spaced and placed as in Word); previously trivial (a level above that hasn't counted yet takes its first number at the first deeper item); previously trivial (paragraph side borders lie beyond their distance from the text, #5036); previously trivial (with a header taller than the top margin, Margin-anchored drawings, header-cell pins and header-table obstacles use the rendered body top; TopMargin and InsideMargin keep their declared band, #2485; previously trivial: connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (field results take the `\* DollarText`, `\* Hex` and `\* ArabicDash` switches, #4226; previously trivial: a cell spanning columns shares its extra minimum width by the columns' preferred widths, equally in automatic tables, #1883; previously 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 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-14 · **Change:** trivial (no automatic space beside an ideograph whose run names an installed East Asian font without it, #6591); previously minor (added layout.fitOnePage to condense a multi-page document by one page while preserving typography hierarchy); previously trivial (from the second section on, headers, footers and note separators are measured with their own section's document grid and SECTION/SECTIONPAGES values, #4683); previously trivial (a turned inline picture whose file keeps no room for the turn keeps its line to its frame, the frame turned a quarter in Word 2013+ layout); previously trivial (a picture lowered further than its own height lowers its line as far, its top on the baseline); previously trivial (a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a line of only pictures is as tall as they reach, never less than its font's height; a legacy check box sizes its line as text of its size, #3984); previously trivial (spaces before a line's first character keep their width in justified and distributed lines, as in Word); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (Times and Courier take their Windows counterparts' line spacing; 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 (a click just outside a floating table, by a cell whose text is turned, goes to the text beside or after it, #4181; 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 (PR #4545: eligible cell floats keep in-bounds offsets; overflow confinement retains the front-of-text, turned-cell and native-acceptance limits); previously trivial (MATH construction reuse, #3630; previously 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 (ODT documents: a line of only pictures keeps its font's height; no setting for it any more); previously trivial (ODT documents: padding is the standard's box model always; picture-only line height is an ODF interpretation setting); previously trivial (行頭禁則 also covers the small kana and the prolonged sound mark at ordinary break opportunities, as JIS X 4051 §4 specifies, inferred from the standard and synthetic tests rather than checked in Word); previously trivial (a missing font is drawn in an installed metric twin before any other substitute: Arial for Helvetica on Windows, Tinos before macOS Times for Times New Roman); previously trivial (ODT documents: padding without a border takes room); previously trivial (ODT documents: a line of only pictures is as tall as they are); previously trivial (ODT documents: a table's own space above and below; header and footer spacing kept past a tall header); previously trivial (a page break before a table's first row moves the table; emphasis marks drawn with room in the line); previously trivial (text in a turned text box turns with it; previously trivial: an in-line picture, shape or chart moves with its run's raise or lowering, Word's `w:position`; previously trivial (layout work bounds: header-row repeats budgeted per layout, cached picture outlines charged to the decode budget, linked-box chain widths exact up to a work cap, #3867); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a table row that would leave a cell empty on a page that already holds something, its picture or first line not fitting there, moves on whole instead of leaving the other cells' text beside the empty cell, #4272); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (tab leader dots spaced and placed as in Word); previously trivial (a level above that hasn't counted yet takes its first number at the first deeper item); previously trivial (paragraph side borders lie beyond their distance from the text, #5036); previously trivial (with a header taller than the top margin, Margin-anchored drawings, header-cell pins and header-table obstacles use the rendered body top; TopMargin and InsideMargin keep their declared band, #2485; previously trivial: connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (field results take the `\* DollarText`, `\* Hex` and `\* ArabicDash` switches, #4226; previously trivial: a cell spanning columns shares its extra minimum width by the columns' preferred widths, equally in automatic tables, #1883; previously 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 > **Floating anchor row segments:** 2026-11-07 · A floating anchor after a manual page/column break counts visible content on the far side of the same wrapped row. Marker-only cover anchors retain their previous-page rule. Synthetic picture spacing, placement and history controls; no new native Word measurement. Readiness estimates unchanged. @@ -92,7 +92,7 @@ Exact line spacing keeps the run font baseline around tall equations; automatic | Vertical text (`tbRl`) in sections and text boxes; cell text direction | ✅ | cell text direction (#245); text-box text direction (#369); vertical sections (`tbRl`/`btLr`, #491): the page's text area turned, lines top to bottom stacking right to left, ideographs, kana and Hangul upright, Latin on its side, caret and clicks through the turn. Missing: OpenType `vert` alternates (punctuation is moved, not substituted), arrow keys along vertical lines, upright pictures take turned room | 2–4 | | Document grid (`w:docGrid`, lines per page, characters per line) | 🟡 | #391, #401: line grid snaps line heights to whole pitches (text centred in them; `w:snapToGrid` off opts a paragraph out); character grid puts East Asian characters on the character pitch (`linesAndChars`) or all text (`snapToChars`), Latin text proportional; View › Gridlines draws it. Not yet: run-level `w:snapToGrid`, grid in headers/footers, paragraph spacing in grid lines, Word's exact glyph placement in a cell | 1–2 | | Ruby / phonetic guide, enclose characters, combined characters | 🟡 | ruby (Phonetic Guide) landed (#288): ruby text over its base by alignment, line grows to fit, in PDF; enclose and combined characters missing; ruby not yet compared with Word page by page | 2–4 | -| Automatic space between Asian text and Latin text or digits (`w:autoSpaceDE`, `w:autoSpaceDN`) | 🟡 | #2358: a quarter of the Asian character's font size after the first of two touching characters, across runs (measured on Word's PDF of a Chinese document at 16 pt, as JIS X 4051 asks); not beside East Asian punctuation, Hangul, Latin punctuation or an existing space; a field is classed by the text it shows; none at a line's end, none on a character grid the paragraph snaps to (`layout::tests::autospace`). Not yet: justification widening the space as Word does, `autoSpaceLikeWord95` | 1–2 | +| Automatic space between Asian text and Latin text or digits (`w:autoSpaceDE`, `w:autoSpaceDN`) | 🟡 | #2358: a quarter of the Asian character's font size after the first of two touching characters, across runs (measured on Word's PDF of a Chinese document at 16 pt, as JIS X 4051 asks); not beside East Asian punctuation, Hangul, Latin punctuation or an existing space; a field is classed by the text it shows; none at a line's end, none on a character grid the paragraph snaps to; none beside an ideograph whose run names an installed East Asian font that lacks it, though a substituted face draws it (#6591, measured in Word with `w:eastAsia="Times New Roman"`) (`layout::tests::autospace`). Not yet: a named East Asian font that isn't installed (kept spaced, unmeasured), `w:hint`, justification widening the space as Word does, `autoSpaceLikeWord95` | 1–2 | | Bidirectional paragraphs, mixed-direction lines; RTL tables and sections | 🟡 | #207; RTL tables (#362): grid columns from the right edge, start alignment and indent from the right margin, cell margins and left/right borders mirrored, merged and turned cells and nested tables included; RTL sections (#362): newspaper columns right to left with the line between mirrored. Right-hand page gutter (`w:rtlGutter`) missing | 1 | | Equations: display layout, numbering, wrapping long display equations | ✅ | #191; long display equations break at top-level operators (`m:brkBin`, `m:brkBinSub`), manual breaks and `m:alnAt`, continuation lines indented by `m:wrapIndent` or set right (`m:wrapRight`) (#326); an n-ary operator, delimiter, accent or group character the math font lacks is drawn from a fallback font instead of a missing-glyph box (#1273); an equation-array row without `&` is centred among aligned rows, as in Word (#2617) | — | | Hidden text excluded from breaking and hyphenation | ✅ | #173 | — | @@ -307,6 +307,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | Date | Change | Summary | |---|---|---| +| 2026-11-14 | trivial | No automatic space (`w:autoSpaceDE`, `w:autoSpaceDN`) beside an ideograph whose run names an installed East Asian font without it (#6591) | | 2026-11-04 | trivial | Headers, footers and note separators of the second and later sections are measured with their own section's document grid and SECTION/SECTIONPAGES values, not the previous section's; a regression from the #4501 refactor (#4683). `layout::tests::pages::a_sections_header_is_measured_without_the_previous_sections_grid` | | 2026-11-08 | trivial | Turned inline pictures with no recorded effect extent keep their line to the frame (exchanged near a quarter turn in Word 2013+ layout) and overhang it, cut at the line's top and bottom, as in Word | | 2026-11-08 | trivial | Contextual spacing drops the space after a table cell's last paragraph in the Normal style, the end-of-cell mark counting as a Normal paragraph; another style keeps it, and a middle or bottom cell of a split row lines up without the dropped space (#5450) (`layout::tests::contextual_spacing_drops_the_space_after_a_cells_last_normal_paragraph`, `a_bottom_cell_of_a_split_row_ignores_a_dropped_space_after_beside_it`). | From 8ac30026538f32364625ccaac1d53fdd03bff6e5 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Sat, 14 Nov 2026 06:53:45 +0000 Subject: [PATCH 099/609] Layout: a linesAndChars document grid keeps automatic spacing, as Word has it (#6584) Only snapToChars drops the automatic space between Asian text and Latin text or digits; Word lays out linesAndChars exactly as a line grid for it. --- crates/layout/src/para/paragraph.rs | 10 ++++++--- crates/layout/src/tests/autospace.rs | 31 ++++++++++++++++++++-------- crates/layout/src/tests/grid.rs | 7 +++++-- docs/layout-parity.md | 5 +++-- 4 files changed, 37 insertions(+), 16 deletions(-) diff --git a/crates/layout/src/para/paragraph.rs b/crates/layout/src/para/paragraph.rs index 6b2605e37c..a0107548bb 100644 --- a/crates/layout/src/para/paragraph.rs +++ b/crates/layout/src/para/paragraph.rs @@ -673,9 +673,13 @@ pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout { if rp.snap_to_grid { snap_chars(&mut sh.b, &p.text, &env.grid); } - // Text on a character grid keeps to its cells. - let auto_space = - if rp.snap_to_grid && env.grid.chars.is_some() { Vec::new() } else { auto_space(&mut sh.b, &p.text, rp.auto_space_de, rp.auto_space_dn) }; + // Text snapping to every cell of a character grid (`snapToChars`) keeps to its cells. On a + // `linesAndChars` grid Word keeps the automatic space, as on a line grid (#6584). + let auto_space = if rp.snap_to_grid && env.grid.snap_all && env.grid.chars.is_some() { + Vec::new() + } else { + auto_space(&mut sh.b, &p.text, rp.auto_space_de, rp.auto_space_dn) + }; let mut skip = sh.left.clone(); skip.extend(sh.bare.iter().cloned()); let bt = BreakText::new(&p.text, skip); diff --git a/crates/layout/src/tests/autospace.rs b/crates/layout/src/tests/autospace.rs index a5f335fb4d..b1b96b2200 100644 --- a/crates/layout/src/tests/autospace.rs +++ b/crates/layout/src/tests/autospace.rs @@ -102,23 +102,36 @@ fn a_field_result_is_classed_by_the_text_it_shows() { } #[test] -fn a_character_grid_the_paragraph_snaps_to_turns_it_off() { +fn a_snap_to_chars_grid_the_paragraph_snaps_to_turns_it_off() { crate::test_fonts(); - let with = |kind: DocGridType, snap: bool| { - let mut d = Document::from_text("法院94年"); - d.last_section.doc_grid = Some(DocGrid { kind, line_pitch: 18.0, char_space: 0 }); - para0(&mut d).props.snap_to_grid = Some(snap); - d - }; - let d = with(DocGridType::LinesAndChars, true); + let d = with_grid(DocGridType::SnapToChars, true); assert!(gaps(&d).iter().all(|g| *g == 0.0), "{:?}", gaps(&d)); // A line grid alone, or a paragraph that doesn't snap, keeps it. - for d in [with(DocGridType::Lines, true), with(DocGridType::LinesAndChars, false)] { + for d in [with_grid(DocGridType::Lines, true), with_grid(DocGridType::SnapToChars, false)] { let q = quarter(&d); assert_eq!(gaps(&d), [0.0, q, 0.0, q, 0.0]); } } +/// Measured in Word (#6584): on a `linesAndChars` grid every character stands where it does on a +/// line grid, the automatic space included. Only `snapToChars` drops it. +#[test] +fn a_lines_and_chars_grid_keeps_it() { + crate::test_fonts(); + for snap in [true, false] { + let d = with_grid(DocGridType::LinesAndChars, snap); + let q = quarter(&d); + assert_eq!(gaps(&d), [0.0, q, 0.0, q, 0.0], "snap_to_grid {snap}"); + } +} + +fn with_grid(kind: DocGridType, snap: bool) -> Document { + let mut d = Document::from_text("法院94年"); + d.last_section.doc_grid = Some(DocGrid { kind, line_pitch: 18.0, char_space: 0 }); + para0(&mut d).props.snap_to_grid = Some(snap); + d +} + #[test] fn the_space_takes_no_room_at_the_end_of_a_justified_line() { crate::test_fonts(); diff --git a/crates/layout/src/tests/grid.rs b/crates/layout/src/tests/grid.rs index 7e4d0a94eb..744f49a698 100644 --- a/crates/layout/src/tests/grid.rs +++ b/crates/layout/src/tests/grid.rs @@ -82,12 +82,15 @@ fn character_grid_places_east_asian_text_on_the_pitch() { let (g, p) = (first(&l), first(&plain)); let line = &g.lines[0]; let latin = text.find('a').unwrap(); + let last_asian = text[..latin].char_indices().last().unwrap().0; for (k, c) in g.clusters.iter().enumerate() { let x = line.xs[k] - line.xs[0]; if c.start < latin { - // Ideographs and kana sit on the pitch, one cell each. + // Ideographs and kana sit on the pitch, one cell each; the last one before the Latin + // text keeps the automatic space after it, as on a line grid (#6584). assert!((x - pitch * k as f32).abs() < 0.01, "cluster {k} at {x}, pitch {pitch}"); - assert!((c.adv - pitch).abs() < 0.01); + let auto_space = if c.start == last_asian { size / 4.0 } else { 0.0 }; + assert!((c.adv - pitch - auto_space).abs() < 0.01, "cluster {k} advances {}", c.adv); } else { // Latin text keeps its own advances. assert!((c.adv - p.clusters[k].adv).abs() < 0.01, "latin cluster {k}"); diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 034e6cd8cb..18e903fe96 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -1,6 +1,6 @@ # Layout and pagination parity with Microsoft Word -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (added layout.fitOnePage to condense a multi-page document by one page while preserving typography hierarchy); previously trivial (from the second section on, headers, footers and note separators are measured with their own section's document grid and SECTION/SECTIONPAGES values, #4683); previously trivial (a turned inline picture whose file keeps no room for the turn keeps its line to its frame, the frame turned a quarter in Word 2013+ layout); previously trivial (a picture lowered further than its own height lowers its line as far, its top on the baseline); previously trivial (a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a line of only pictures is as tall as they reach, never less than its font's height; a legacy check box sizes its line as text of its size, #3984); previously trivial (spaces before a line's first character keep their width in justified and distributed lines, as in Word); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (Times and Courier take their Windows counterparts' line spacing; 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 (a click just outside a floating table, by a cell whose text is turned, goes to the text beside or after it, #4181; 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 (PR #4545: eligible cell floats keep in-bounds offsets; overflow confinement retains the front-of-text, turned-cell and native-acceptance limits); previously trivial (MATH construction reuse, #3630; previously 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 (ODT documents: a line of only pictures keeps its font's height; no setting for it any more); previously trivial (ODT documents: padding is the standard's box model always; picture-only line height is an ODF interpretation setting); previously trivial (行頭禁則 also covers the small kana and the prolonged sound mark at ordinary break opportunities, as JIS X 4051 §4 specifies, inferred from the standard and synthetic tests rather than checked in Word); previously trivial (a missing font is drawn in an installed metric twin before any other substitute: Arial for Helvetica on Windows, Tinos before macOS Times for Times New Roman); previously trivial (ODT documents: padding without a border takes room); previously trivial (ODT documents: a line of only pictures is as tall as they are); previously trivial (ODT documents: a table's own space above and below; header and footer spacing kept past a tall header); previously trivial (a page break before a table's first row moves the table; emphasis marks drawn with room in the line); previously trivial (text in a turned text box turns with it; previously trivial: an in-line picture, shape or chart moves with its run's raise or lowering, Word's `w:position`; previously trivial (layout work bounds: header-row repeats budgeted per layout, cached picture outlines charged to the decode budget, linked-box chain widths exact up to a work cap, #3867); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a table row that would leave a cell empty on a page that already holds something, its picture or first line not fitting there, moves on whole instead of leaving the other cells' text beside the empty cell, #4272); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (tab leader dots spaced and placed as in Word); previously trivial (a level above that hasn't counted yet takes its first number at the first deeper item); previously trivial (paragraph side borders lie beyond their distance from the text, #5036); previously trivial (with a header taller than the top margin, Margin-anchored drawings, header-cell pins and header-table obstacles use the rendered body top; TopMargin and InsideMargin keep their declared band, #2485; previously trivial: connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (field results take the `\* DollarText`, `\* Hex` and `\* ArabicDash` switches, #4226; previously trivial: a cell spanning columns shares its extra minimum width by the columns' preferred widths, equally in automatic tables, #1883; previously 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 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-14 · **Change:** trivial (a `linesAndChars` document grid keeps the automatic space between Asian text and Latin text or digits; only `snapToChars` drops it, #6584); previously minor (added layout.fitOnePage to condense a multi-page document by one page while preserving typography hierarchy); previously trivial (from the second section on, headers, footers and note separators are measured with their own section's document grid and SECTION/SECTIONPAGES values, #4683); previously trivial (a turned inline picture whose file keeps no room for the turn keeps its line to its frame, the frame turned a quarter in Word 2013+ layout); previously trivial (a picture lowered further than its own height lowers its line as far, its top on the baseline); previously trivial (a float anchored right after a page break, before text, is drawn on the new page, #4262); previously trivial (a float anchored on a later page of a long paragraph is drawn there, #4250); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a line of only pictures is as tall as they reach, never less than its font's height; a legacy check box sizes its line as text of its size, #3984); previously trivial (spaces before a line's first character keep their width in justified and distributed lines, as in Word); previously trivial (Page drawing indexes text-box warp lookups per paragraph (#3614)); previously trivial (Times and Courier take their Windows counterparts' line spacing; 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 (a click just outside a floating table, by a cell whose text is turned, goes to the text beside or after it, #4181; 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 (PR #4545: eligible cell floats keep in-bounds offsets; overflow confinement retains the front-of-text, turned-cell and native-acceptance limits); previously trivial (MATH construction reuse, #3630; previously 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 (ODT documents: a line of only pictures keeps its font's height; no setting for it any more); previously trivial (ODT documents: padding is the standard's box model always; picture-only line height is an ODF interpretation setting); previously trivial (行頭禁則 also covers the small kana and the prolonged sound mark at ordinary break opportunities, as JIS X 4051 §4 specifies, inferred from the standard and synthetic tests rather than checked in Word); previously trivial (a missing font is drawn in an installed metric twin before any other substitute: Arial for Helvetica on Windows, Tinos before macOS Times for Times New Roman); previously trivial (ODT documents: padding without a border takes room); previously trivial (ODT documents: a line of only pictures is as tall as they are); previously trivial (ODT documents: a table's own space above and below; header and footer spacing kept past a tall header); previously trivial (a page break before a table's first row moves the table; emphasis marks drawn with room in the line); previously trivial (text in a turned text box turns with it; previously trivial: an in-line picture, shape or chart moves with its run's raise or lowering, Word's `w:position`; previously trivial (layout work bounds: header-row repeats budgeted per layout, cached picture outlines charged to the decode budget, linked-box chain widths exact up to a work cap, #3867); previously trivial (the line between columns runs as tall as the section's text, so columns for selected text have it, #5178); previously trivial (a table row that would leave a cell empty on a page that already holds something, its picture or first line not fitting there, moves on whole instead of leaving the other cells' text beside the empty cell, #4272); previously trivial (a middle or bottom cell of a row split across pages lines up on the first page); previously trivial (tab leader dots spaced and placed as in Word); previously trivial (a level above that hasn't counted yet takes its first number at the first deeper item); previously trivial (paragraph side borders lie beyond their distance from the text, #5036); previously trivial (with a header taller than the top margin, Margin-anchored drawings, header-cell pins and header-table obstacles use the rendered body top; TopMargin and InsideMargin keep their declared band, #2485; previously trivial: connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (field results take the `\* DollarText`, `\* Hex` and `\* ArabicDash` switches, #4226; previously trivial: a cell spanning columns shares its extra minimum width by the columns' preferred widths, equally in automatic tables, #1883; previously 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 > **Floating anchor row segments:** 2026-11-07 · A floating anchor after a manual page/column break counts visible content on the far side of the same wrapped row. Marker-only cover anchors retain their previous-page rule. Synthetic picture spacing, placement and history controls; no new native Word measurement. Readiness estimates unchanged. @@ -92,7 +92,7 @@ Exact line spacing keeps the run font baseline around tall equations; automatic | Vertical text (`tbRl`) in sections and text boxes; cell text direction | ✅ | cell text direction (#245); text-box text direction (#369); vertical sections (`tbRl`/`btLr`, #491): the page's text area turned, lines top to bottom stacking right to left, ideographs, kana and Hangul upright, Latin on its side, caret and clicks through the turn. Missing: OpenType `vert` alternates (punctuation is moved, not substituted), arrow keys along vertical lines, upright pictures take turned room | 2–4 | | Document grid (`w:docGrid`, lines per page, characters per line) | 🟡 | #391, #401: line grid snaps line heights to whole pitches (text centred in them; `w:snapToGrid` off opts a paragraph out); character grid puts East Asian characters on the character pitch (`linesAndChars`) or all text (`snapToChars`), Latin text proportional; View › Gridlines draws it. Not yet: run-level `w:snapToGrid`, grid in headers/footers, paragraph spacing in grid lines, Word's exact glyph placement in a cell | 1–2 | | Ruby / phonetic guide, enclose characters, combined characters | 🟡 | ruby (Phonetic Guide) landed (#288): ruby text over its base by alignment, line grows to fit, in PDF; enclose and combined characters missing; ruby not yet compared with Word page by page | 2–4 | -| Automatic space between Asian text and Latin text or digits (`w:autoSpaceDE`, `w:autoSpaceDN`) | 🟡 | #2358: a quarter of the Asian character's font size after the first of two touching characters, across runs (measured on Word's PDF of a Chinese document at 16 pt, as JIS X 4051 asks); not beside East Asian punctuation, Hangul, Latin punctuation or an existing space; a field is classed by the text it shows; none at a line's end, none on a character grid the paragraph snaps to (`layout::tests::autospace`). Not yet: justification widening the space as Word does, `autoSpaceLikeWord95` | 1–2 | +| Automatic space between Asian text and Latin text or digits (`w:autoSpaceDE`, `w:autoSpaceDN`) | 🟡 | #2358: a quarter of the Asian character's font size after the first of two touching characters, across runs (measured on Word's PDF of a Chinese document at 16 pt, as JIS X 4051 asks); not beside East Asian punctuation, Hangul, Latin punctuation or an existing space; a field is classed by the text it shows; none at a line's end, none on a `snapToChars` grid the paragraph snaps to; a `linesAndChars` grid keeps it, as a line grid does (#6584, measured in Word 16.0.17932 at 12 pt) (`layout::tests::autospace`). Not yet: justification widening the space as Word does, `autoSpaceLikeWord95` | 1–2 | | Bidirectional paragraphs, mixed-direction lines; RTL tables and sections | 🟡 | #207; RTL tables (#362): grid columns from the right edge, start alignment and indent from the right margin, cell margins and left/right borders mirrored, merged and turned cells and nested tables included; RTL sections (#362): newspaper columns right to left with the line between mirrored. Right-hand page gutter (`w:rtlGutter`) missing | 1 | | Equations: display layout, numbering, wrapping long display equations | ✅ | #191; long display equations break at top-level operators (`m:brkBin`, `m:brkBinSub`), manual breaks and `m:alnAt`, continuation lines indented by `m:wrapIndent` or set right (`m:wrapRight`) (#326); an n-ary operator, delimiter, accent or group character the math font lacks is drawn from a fallback font instead of a missing-glyph box (#1273); an equation-array row without `&` is centred among aligned rows, as in Word (#2617) | — | | Hidden text excluded from breaking and hyphenation | ✅ | #173 | — | @@ -528,6 +528,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | 2026-11-02 | trivial | Beyond Word, for ODT documents: a table's own space above and below (`TableProps::space_before`/`space_after`) moves the text around it, and a header (footer) taller than its margin keeps its spacing between it and the body (`SectionProps::header_gap`/`footer_gap`; Word keeps none, so DOCX documents are unchanged) (`tests::a_tables_own_space_above_and_below_moves_the_text`, `tests::body_starts_right_below_a_tall_header`) | | 2026-11-02 | trivial | A page break before the paragraph in a table's first row moves the whole table to the next page, as in Word (it was ignored); emphasis marks (Font › Emphasis mark) are drawn over or under each character and make the line taller | | 2026-11-12 | minor | Added layout.fitOnePage: heuristic search over discrete font half-point steps and spacing compression with anti-clutter safeguards (line-spacing floor and font-size floor) to condense multi-page documents by one page while preserving hierarchy | +| 2026-11-14 | trivial | A `linesAndChars` document grid keeps the automatic space between Asian text and Latin text or digits, as Word does; only `snapToChars` drops it (#6584) | Maintenance on 2026-10-12 retains current tracked-deletion, endnote, footer-total, text-box and balloon layout while supplying explicit cell identity at every box call. The native Word From bc0c9e4da5aa5a40516334ae7c6da02e755f9e81 Mon Sep 17 00:00:00 2001 From: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:31:32 +0300 Subject: [PATCH 100/609] Lists: a list number is never kerned, as in Word A list number took the kerning of its paragraph mark or level. Word never kerns it: "11)" in Times New Roman 12 pt with kerning on is 16 pt wide in Word, not the 15.55 pt of the kerned digits, so it passes a hanging indent the kerned one would fit in and the text moves on to the next tab stop. Test: a_list_number_is_never_kerned (fails before this change). --- crates/layout/src/para/paragraph.rs | 7 ++++++- crates/layout/src/tests.rs | 19 +++++++++++++++++++ docs/layout-parity.md | 1 + 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/layout/src/para/paragraph.rs b/crates/layout/src/para/paragraph.rs index 6b2605e37c..49f865936d 100644 --- a/crates/layout/src/para/paragraph.rs +++ b/crates/layout/src/para/paragraph.rs @@ -537,7 +537,12 @@ fn list_label(cx: &Cx, b: &mut Builder, mark_style: u32) -> Option