From 5a9e414d1ec8c8d6cd23bd15c63225a3b0498f03 Mon Sep 17 00:00:00 2001 From: OPUZZLES <109076338+OPUZZLES@users.noreply.github.com> Date: Thu, 29 Oct 2026 17:49:08 +0100 Subject: [PATCH 1/6] M9: generate all recipient label sheets (#4880) --- ROADMAP.md | 6 +- crates/engine/src/cmd/mailings.rs | 2 +- crates/engine/src/cmd/mailings/labels.rs | 85 ++++++++++++++---------- crates/engine/src/cmd/mailings/tests.rs | 68 +++++++++++++++++++ docs/gaps.md | 7 +- docs/target-app-parity.md | 5 +- docs/ui-parity.md | 5 +- 7 files changed, 135 insertions(+), 43 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 477dfb3cdc..a794c35fc4 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 (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 > **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-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. - 2026-10-22: Recovery covers every open document. Each dirty document keeps its own copy, written on the same ten-second cadence whether it is shown or not; closing a document without saving deletes its copy, as saving does, and a clean exit deletes the copies of every document saved or closed since its last copy. File › Recover lists only copies no open document keeps, and Restore opens a copy as another document (or in place of an untouched blank one), so it never replaces work. After a crash with several unsaved documents, the next start lists all of them. @@ -644,6 +645,7 @@ Footer page-table height and body wrapping are corrected. Other pagination gaps | Date | Change | Summary | |---|---|---| +| 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 | | 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..a0c6fa2a60 100644 --- a/crates/engine/src/cmd/mailings.rs +++ b/crates/engine/src/cmd/mailings.rs @@ -222,7 +222,7 @@ pub fn specs() -> Vec { r#"{"delivery": string, "return"?: string, "size"?: "Envelope #10|#9|Monarch|DL|C4|C5|C6|B5", "width"?: pt, "height"?: pt, "add"?: bool (add to this document instead of a new one)}"#, ), CommandSpec::new("mailings.labels", "Labels", "Mailings › Create", labels).params( - r#"{"text"?: string, "product"?: "letter-3x10|letter-2x10|letter-2x7|letter-2x5|letter-4x20|a4-3x7|a4-2x7|a4-3x8|a4-2x4", "rows"?: n, "cols"?: n, "fromRecipients"?: bool, "single"?: {"row": n, "col": n}}"#, + r#"{"text"?: string, "product"?: "letter-3x10|letter-2x10|letter-2x7|letter-2x5|letter-4x20|a4-3x7|a4-2x7|a4-3x8|a4-2x4", "rows"?: n, "cols"?: n, "fromRecipients"?: bool (one label per selected recipient, continuing across sheets), "single"?: {"row": n, "col": n}}"#, ), ] } diff --git a/crates/engine/src/cmd/mailings/labels.rs b/crates/engine/src/cmd/mailings/labels.rs index f0429ef516..43178ecaea 100644 --- a/crates/engine/src/cmd/mailings/labels.rs +++ b/crates/engine/src/cmd/mailings/labels.rs @@ -254,8 +254,9 @@ impl LabelProduct { } /// Labels: a new document with a table of labels laid out like the sheet (`product`; spacer -/// columns and rows stand for the gaps). A full page of the same `text` (or one recipient per -/// label), or (`single`: `{"row", "col"}`, from 1) one label at that place on the sheet. +/// columns and rows stand for the gaps). A full page of the same `text`, as many sheets as +/// needed for one label per recipient, or (`single`: `{"row", "col"}`, from 1) one label +/// at that place on the sheet. pub(super) fn labels(s: &mut Session, v: &Value) -> CmdResult { let prod = match p::str(v, "product") { Some(id) => *LabelProduct::by_id(id).ok_or_else(|| CmdError::Params(format!("unknown label product `{id}`")))?, @@ -285,46 +286,58 @@ pub(super) fn labels(s: &mut Session, v: &Value) -> CmdResult { let grid_cols: Vec> = (0..cols).flat_map(|c| [Some(c)].into_iter().chain((c + 1 < cols && h_gap > 0.5).then_some(None))).collect(); let grid_rows: Vec> = (0..rows).flat_map(|r| [Some(r)].into_iter().chain((r + 1 < rows && v_gap > 0.5).then_some(None))).collect(); let width: f32 = grid_cols.iter().map(|c| if c.is_some() { prod.width } else { h_gap }).sum(); - let mut t = Table::new(grid_rows.len(), grid_cols.len(), width); - t.props.style = None; - t.props.borders = Some(wordcraft_doc::props::Borders::default()); - t.props.fixed = true; - t.grid = grid_cols.iter().map(|c| if c.is_some() { prod.width } else { h_gap }).collect(); + let per_sheet = rows * cols; + let sheets = if from_rec { s.merge.rows.len().div_ceil(per_sheet).max(1) } else { 1 }; let mut k = 0usize; let mut made = 0usize; - for (row, r) in t.rows.iter_mut().zip(&grid_rows) { - row.props.height = Some(if r.is_some() { prod.height } else { v_gap }); - row.props.height_rule = wordcraft_doc::props::HeightRule::Exact; - for (cell, c) in row.cells.iter_mut().zip(&grid_cols) { - cell.props.width = Some(if c.is_some() { prod.width } else { h_gap }); - let (Some(r), Some(c)) = (r, c) else { continue }; - let content = match single { - Some((sr, sc)) if (sr, sc) != (r + 1, c + 1) => String::new(), - _ if from_rec => { - let rec = if k < s.merge.rows.len() { address_block(s, k) } else { String::new() }; - k += 1; - rec + d.body.clear(); + for sheet in 0..sheets { + let mut t = Table::new(grid_rows.len(), grid_cols.len(), width); + t.props.style = None; + t.props.borders = Some(wordcraft_doc::props::Borders::default()); + t.props.fixed = true; + t.grid = grid_cols.iter().map(|c| if c.is_some() { prod.width } else { h_gap }).collect(); + for (row, r) in t.rows.iter_mut().zip(&grid_rows) { + row.props.height = Some(if r.is_some() { prod.height } else { v_gap }); + row.props.height_rule = wordcraft_doc::props::HeightRule::Exact; + for (cell, c) in row.cells.iter_mut().zip(&grid_cols) { + cell.props.width = Some(if c.is_some() { prod.width } else { h_gap }); + let (Some(r), Some(c)) = (r, c) else { continue }; + let content = match single { + Some((sr, sc)) if (sr, sc) != (r + 1, c + 1) => String::new(), + _ if from_rec => { + let rec = if k < s.merge.rows.len() { address_block(s, k) } else { String::new() }; + k += 1; + rec + } + _ => text.clone(), + }; + if !content.is_empty() { + made += 1; } - _ => text.clone(), - }; - if !content.is_empty() { - made += 1; + cell.props.valign = Some(wordcraft_doc::props::VAlign::Center); + cell.blocks = content + .split('\n') + .take(20) + .map(|l| { + let mut p = Paragraph::with_text(l, CharProps::default()).styled("NoSpacing"); + p.props.align = Some(Align::Left); + p.props.indent_left = Some(9.0); + para_block(p) + }) + .collect(); } - cell.props.valign = Some(wordcraft_doc::props::VAlign::Center); - cell.blocks = content - .split('\n') - .take(20) - .map(|l| { - let mut p = Paragraph::with_text(l, CharProps::default()).styled("NoSpacing"); - p.props.align = Some(Align::Left); - p.props.indent_left = Some(9.0); - para_block(p) - }) - .collect(); } + d.body.push(std::sync::Arc::new(Block::Table(t))); + let mut end = Paragraph::new(); + if sheet + 1 < sheets { + // End each sheet with the same next-page section, so the next table + // starts at the product's top margin without a leading blank line. + end.section = Some(Box::new(d.last_section.clone())); + } + d.body.push(para_block(end)); } - d.body = vec![std::sync::Arc::new(Block::Table(t)), para_block(Paragraph::new())]; s.add_document(d); let _ = Pos::body(0, 0); - Ok(json!({"labels": if single.is_some() { 1 } else { rows * cols }, "filled": made, "product": prod.id})) + Ok(json!({"labels": if single.is_some() { 1 } else { sheets * per_sheet }, "filled": made, "product": prod.id})) } diff --git a/crates/engine/src/cmd/mailings/tests.rs b/crates/engine/src/cmd/mailings/tests.rs index c7a721594a..b16214b8b7 100644 --- a/crates/engine/src/cmd/mailings/tests.rs +++ b/crates/engine/src/cmd/mailings/tests.rs @@ -375,6 +375,74 @@ fn envelope_sizes_add_to_document_and_label_products() { assert!(s.run("mailings.labels", &json!({"product": "nope"})).is_err()); } +/// #4880: every selected recipient gets a label, including those beyond the first sheet. +#[test] +fn recipient_labels_continue_on_product_sheets() { + for product in LABEL_PRODUCTS { + let per_sheet = product.rows * product.cols; + for count in [1, per_sheet, per_sheet + 1, per_sheet * 2, per_sheet * 2 + 5] { + let mut s = Session::new(Document::from_text("Original letter")); + let rows: Vec = (0..count).map(|i| json!({"FirstName": format!("Recipient{i:03}"), "Address": "Original Street"})).collect(); + s.run("mailings.recipients", &json!({"rows": rows})).unwrap(); + let r = s.run("mailings.labels", &json!({"product": product.id, "fromRecipients": true})).unwrap(); + let sheets = count.div_ceil(per_sheet); + assert_eq!(r["filled"], count, "{}: {count} recipients", product.id); + assert_eq!(r["labels"], sheets * per_sheet); + assert_eq!(s.doc.sections().len(), sheets); + let tables: Vec<_> = s + .doc + .body + .iter() + .filter_map(|b| match &**b { + Block::Table(t) => Some(t), + _ => None, + }) + .collect(); + assert_eq!(tables.len(), sheets); + let names: Vec<_> = tables + .iter() + .flat_map(|t| t.rows.iter()) + .flat_map(|r| &r.cells) + .flat_map(|c| &c.blocks) + .filter_map(|b| match &**b { + Block::Para(p) if p.text.starts_with("Recipient") => Some(p.text.clone()), + _ => None, + }) + .collect(); + assert_eq!(names, (0..count).map(|i| format!("Recipient{i:03}")).collect::>()); + assert!(tables.windows(2).all(|t| t[0].grid == t[1].grid && t[0].props == t[1].props)); + } + } +} + +#[test] +fn recipient_label_sheets_keep_the_source_and_selected_order() { + let mut s = Session::new(Document::from_text("Original letter")); + s.run("text.insert", &json!({"text": "Draft "})).unwrap(); + let original = s.doc.clone(); + let id = s.document_id(); + let rows: Vec = (0..65).map(|i| json!({"FirstName": format!("Recipient{i:03}")})).collect(); + s.run("mailings.recipients", &json!({"rows": rows})).unwrap(); + s.run( + "mailings.filterRecipients", + &json!({"rules": [{"field": "FirstName", "op": "notEqual", "value": "Recipient003"}], + "sort": [{"field": "FirstName", "descending": true}]}), + ) + .unwrap(); + let selected = s.run("mailings.editRecipients", &json!({})).unwrap(); + let r = s.run("mailings.labels", &json!({"fromRecipients": true})).unwrap(); + assert_eq!(r["filled"], 64); + assert_eq!(r["labels"], 90); + assert_eq!(s.undo_depth(), 0, "labels are a new document"); + let text = s.doc.plain_text(StoryRef::Body); + let names: Vec<_> = text.split_whitespace().filter(|l| l.starts_with("Recipient")).collect(); + assert_eq!(names, (0..65).rev().filter(|i| *i != 3).map(|i| format!("Recipient{i:03}")).collect::>()); + s.run("view.switchWindows", &json!({"id": id})).unwrap(); + assert_eq!(s.doc, original, "the original letter stays open and unchanged"); + assert_eq!(s.run("mailings.editRecipients", &json!({})).unwrap(), selected); + assert_eq!(s.undo_depth(), 1, "the source keeps its edit history"); +} + fn b64(b: &[u8]) -> String { super::super::insert::base64_encode(b) } diff --git a/docs/gaps.md b/docs/gaps.md index dd16596f79..5b082dc6f3 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 (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-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 (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). @@ -140,6 +140,8 @@ Small follow-ups from the 2026-10-25 field, table and AutoFormat batch (#4232): - AutoFormat's `*bold*` and `_italic_` don't convert when a closing bracket or quote follows the closing mark (`(*see note*)`): the trigger checks only space and `,.;:!?` (#4098). - The ribbon's Accept and Reject buttons only open their menus; Word's main half runs Accept (Reject) and Move to Next. The ribbon needs a big split button (Paste needs one too) (#4205). +Recipient label generation (#4880) now includes all selected recipients across as many sheets as needed, retaining filtered/sorted order and the chosen product geometry. This fixes the one-sheet omission; Update Labels and Finish & Merge template behavior remain separate, and gap 21 remains open. Readiness estimates are unchanged. + ## Revision history > 2026-10-23 · cu20we review follow-up: Only paragraph-relative box floats use the pre-spacing origin. Line-relative floats and page/margin fallbacks in cells and text boxes keep the text-top origin. Synthetic controls compare zero and 24 pt space-before across all four box contexts. New cap conversion helpers and regression tests document their contracts; readiness estimates unchanged. @@ -150,6 +152,7 @@ Small follow-ups from the 2026-10-25 field, table and AutoFormat batch (#4232): | Date | Change | Summary | |---|---|---| +| 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 | | 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..b05a223221 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 (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); 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 @@ -9,6 +9,8 @@ summarizes it; [`gaps.md`](gaps.md) itemizes every shortfall; the deep checklist [`hardware-parity.md`](hardware-parity.md) and [`localization-parity.md`](localization-parity.md). The generated ribbon checklist is [`parity-checklist.md`](parity-checklist.md). +Labels → New Document with one label per recipient continues across sheets for all selected recipients (#4880). The final sheet leaves unused labels blank; address mapping, fixed-text and single-label modes stay unchanged. This is label generation, not a new Update Labels or Finish & Merge template workflow. Readiness estimates are unchanged. + ## Headline (2026-10-10, origin/main `a99dddc`, v0.4.0 + ~90 merged PRs) | Number | Value | Kind | @@ -251,6 +253,7 @@ can be used without committing Word output. | Date | Change | Summary | |---|---|---| +| 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-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) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 20a5e62475..9ab3319f11 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-25 · **Change:** trivial (Custom Document Properties dialog from File › Info › Properties › Advanced Properties…, #2982; previously trivial: View › Window › New Window opens another window on the document, each with its own caret and view; previously trivial: mail merge: First Record, Last Record and a record number box in Preview Results; Finish & Merge asks which records to merge or print, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: read only and comments-only protection grey out edits; previously trivial: the Font dialog previews "NaN" or "inf" in the Size box at 12 pt, #3663; 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 +> **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 (Custom Document Properties dialog from File › Info › Properties › Advanced Properties…, #2982; previously trivial: View › Window › New Window opens another window on the document, each with its own caret and view; previously trivial: mail merge: First Record, Last Record and a record number box in Preview Results; Finish & Merge asks which records to merge or print, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: read only and comments-only protection grey out edits; previously trivial: the Font dialog previews "NaN" or "inf" in the Size box at 12 pt, #3663; 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). @@ -78,10 +78,13 @@ Find selects the Results tab, including when it prefills selected text. Editing Footnote and endnote editing keeps body and note text at normal opacity, on light and dark pages. Headers and footers still dim outside their editing context (#2545). +Labels → New Document with “One label per recipient” includes all filtered/sorted recipients across product-sized sheets (#4880). The last sheet keeps unused labels blank. Fixed text and Single label still produce one sheet. Native Windows interaction and comparison with Microsoft Word remain unverified; this change does not add Update Labels or change Finish & Merge templates. + ## Revision history | Date | Change | Summary | |---|---|---| +| 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 › Window › New Window opens another window on the document, focused and cascaded; two windows on one document are titled `Name:1` and `Name:2` (one window: the plain name). Each window keeps its own selection, scroll position, zoom, view mode, ruler and panes; the text, undo history, unsaved state and file are the document's, so an edit or Undo in either window shows in both, and a caret in text the other window deleted moves to the nearest place left. Closing one of a document's windows asks nothing; closing its last asks about unsaved changes, and quitting asks once per document. Switch Windows lists every window. The web app keeps one window | | 2026-10-22 | trivial | One native window per open document on the desktop (the web app keeps one window): New and Open open the document in a window of its own, focused and cascaded from the last; Open replaces an untouched blank document in its window and brings an already-open file's window forward; each window keeps its own ribbon tab, File page, dialogs, panes and composition; View › Window › Switch Windows lists the windows and brings the chosen one forward; File › Close and the window's close button close the window (asking about unsaved changes) and the window focused before comes forward, while the last window stays open with no document; quitting asks Save / Don't Save / Cancel about each document in its own window | | 2026-10-22 | trivial | Several open documents in one window (one window per document comes next): View › Window › Switch Windows lists the open documents, the shown one marked and unsaved ones dotted, and shows the one chosen, with its own scroll position, zoom, comment drafts and AutoSave file; File › New, Open, Envelopes, Labels, Finish & Merge and personal templates open beside the open documents without asking about unsaved changes; File › Close shows the next open document; the window's close button asks Save / Don't Save / Cancel about each document with unsaved changes, showing it, and Cancel keeps the app open. Untitled documents are numbered (Document2) in the interface language | From 01a1bf39210810b4497e62365af0f98cb1f46e45 Mon Sep 17 00:00:00 2001 From: OPUZZLES <109076338+OPUZZLES@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:14:46 +0100 Subject: [PATCH 2/6] M9: assert unused recipient labels are empty (#4880) --- crates/engine/src/cmd/mailings/tests.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/mailings/tests.rs b/crates/engine/src/cmd/mailings/tests.rs index b16214b8b7..7dff4f22e2 100644 --- a/crates/engine/src/cmd/mailings/tests.rs +++ b/crates/engine/src/cmd/mailings/tests.rs @@ -399,17 +399,18 @@ fn recipient_labels_continue_on_product_sheets() { }) .collect(); assert_eq!(tables.len(), sheets); - let names: Vec<_> = tables + let label_text: Vec<_> = tables .iter() .flat_map(|t| t.rows.iter()) .flat_map(|r| &r.cells) .flat_map(|c| &c.blocks) .filter_map(|b| match &**b { - Block::Para(p) if p.text.starts_with("Recipient") => Some(p.text.clone()), + Block::Para(p) if !p.text.is_empty() => Some(p.text.clone()), _ => None, }) .collect(); - assert_eq!(names, (0..count).map(|i| format!("Recipient{i:03}")).collect::>()); + let expected: Vec<_> = (0..count).flat_map(|i| [format!("Recipient{i:03}"), "Original Street".to_string()]).collect(); + assert_eq!(label_text, expected); assert!(tables.windows(2).all(|t| t[0].grid == t[1].grid && t[0].props == t[1].props)); } } From ccb8ce84947c3a2005cdf71de268698c472c6948 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 29 Oct 2026 18:48:31 -0400 Subject: [PATCH 3/6] packaging: Flatpak finds and prints to CUPS printers (#4909) * packaging: Flatpak finds and prints to CUPS printers The Print dialog listed no printers in the Flatpak: the runtime has libcups but not lpstat/lp, the sandbox couldn't reach the CUPS socket, and driverless network printers (lpstat -e) need Avahi. Bundle lpstat/lp/lpoptions from CUPS 2.4.20 (Apache-2.0, statically linked, licence installed) and grant --socket=cups and --system-talk-name=org.freedesktop.Avahi in both manifests. * packaging: Flatpak reads the user's CUPS settings (~/.cups, read-only) Review (CodeRabbit): without it the sandbox's lp/lpstat ignore the user's default printer and saved options (lpoptions) and a print server named in their client.conf. * packaging: Flatpak CUPS tools reach the host socket when client.conf names a custom path Review: Flatpak mounts the host's CUPS socket at /var/run/cups/cups.sock whatever path ~/.cups/client.conf or CUPS_SERVER names, so lp/lpstat/lpoptions now run through a wrapper that points a socket path missing in the sandbox there. Server names (remote servers) and sockets that exist are left alone. Tested in the sandbox: CUPS_SERVER=/run/custom/cups.sock lists the host's printers through the wrapper and none without it; a host name is passed through unchanged. * packaging: redirect a custom CUPS socket only when it is the one Flatpak mounted Review (CodeRabbit): Flatpak picks the socket it mounts at /var/run/cups/cups.sock with stricter rules than CUPS (flatpak-run-cups.c: a socket CUPS_SERVER, else the first line spelled exactly "ServerName /path" in ~/.cups/client.conf, else the default), while CUPS reads the keyword in any case and takes the last ServerName. The wrapper now redirects only when CUPS' socket is the one Flatpak chose, so a job can't reach a different server; otherwise CUPS fails on the missing path. * packaging: never redirect a CUPS_SERVER the sandbox was given Review (CodeRabbit): Flatpak picks the socket it mounts from the host's CUPS_SERVER, so one set by flatpak run --env or an override may not be what it mounted. The wrapper now leaves any CUPS_SERVER alone and redirects only a client.conf socket that matches Flatpak's choice; otherwise CUPS fails on the missing path instead of reaching a different server. * packaging: point CUPS at the mounted socket only when it is the one Flatpak chose, else fail Review (CodeRabbit): with a custom socket listed first and the default last in ~/.cups/client.conf, Flatpak mounts the custom one at /var/run/cups/cups.sock while CUPS picks the last line, finds that path, and talks to the custom server. The wrapper now compares CUPS' socket with Flatpak's choice even when the path exists: equal, CUPS is pointed at the mount; different, the tool fails with an error instead of reaching another server. --- .../ai.storyteller.wordcraft.bundle.yml | 52 +++++++++++++++++++ .../flatpak/ai.storyteller.wordcraft.yml | 52 +++++++++++++++++++ 2 files changed, 104 insertions(+) diff --git a/packaging/linux/flatpak/ai.storyteller.wordcraft.bundle.yml b/packaging/linux/flatpak/ai.storyteller.wordcraft.bundle.yml index 0e23bafec0..00cd75f155 100644 --- a/packaging/linux/flatpak/ai.storyteller.wordcraft.bundle.yml +++ b/packaging/linux/flatpak/ai.storyteller.wordcraft.bundle.yml @@ -24,6 +24,14 @@ finish-args: - --share=ipc # GPU access for the wgpu renderer (Vulkan, or GL as a fallback). - --device=dri + # Printing: lpstat/lp (the cups-client module) reach the host's CUPS through its socket and + # find driverless network printers through Avahi (`lpstat -e`). Without these the Print + # dialog lists no printers. + - --socket=cups + - --system-talk-name=org.freedesktop.Avahi + # The user's CUPS settings, read-only: their default printer and saved options (lpoptions) + # and a print server named in their client.conf, which lp reaches over the network. + - --filesystem=~/.cups:ro # Open/Save dialogs go through the file-chooser portal (rfd's xdg-portal backend) and # drag-and-drop through the document portal, so picked files work anywhere without broad # filesystem access. Documents and Pictures are granted so files passed by path (the command @@ -35,6 +43,50 @@ finish-args: - --share=network # Deliberately not granted: home/host filesystem access. modules: + # CUPS client tools for craft-print: the runtime has libcups but not lpstat/lp/lpoptions. + # Linked statically against this release's libcups, so a runtime update can't break them; + # the socket path matches the host's, which --socket=cups mounts. + - name: cups-client + buildsystem: simple + build-commands: + - ./configure --prefix=/app --sysconfdir=/etc --localstatedir=/var --with-rundir=/run/cups + --with-domainsocket=/run/cups/cups.sock --disable-shared --with-components=libcups + --with-dnssd=avahi --with-tls=gnutls --disable-pam --disable-dbus + - make -C cups libs + - make -C systemv lp lpoptions lpstat + - install -Dm755 -t /app/libexec/cups systemv/lp systemv/lpoptions systemv/lpstat + - for tool in lp lpoptions lpstat; do install -Dm755 cups-socket.sh "/app/bin/$tool"; done + - install -Dm644 -t /app/share/licenses/cups LICENSE NOTICE + sources: + - type: archive + url: https://github.com/OpenPrinting/cups/releases/download/v2.4.20/cups-2.4.20-source.tar.gz + sha256: ab4d9cd7f3e58060091d2b24972223d6401675f11c49b65abf4f6ef31dea22ff + # Runs each tool. Flatpak mounts the host's CUPS socket at /var/run/cups/cups.sock, choosing + # it as flatpak-run-cups.c does from the host's CUPS_SERVER, else the first line spelled + # exactly `ServerName /path` in ~/.cups/client.conf, else the default; it mounts nothing + # when that socket is missing. CUPS reads the keyword in any case and takes the last + # ServerName. When CUPS' socket from client.conf is the one Flatpak chose, it is pointed at + # the mount; when it isn't, the tool fails rather than reach a different server. A + # CUPS_SERVER is left alone: one set by `flatpak run --env` may not be what was mounted. + - type: script + dest-filename: cups-socket.sh + commands: + - 'conf="$HOME/.cups/client.conf"' + - 'if [ -z "${CUPS_SERVER:-}" ] && [ -r "$conf" ]; then' + - ' server=$(sed -n ''s/^[[:space:]]*[Ss][Ee][Rr][Vv][Ee][Rr][Nn][Aa][Mm][Ee][[:space:]]\{1,\}\([^[:space:]]*\).*/\1/p'' "$conf" | tail -n 1)' + - ' case "$server" in' + - ' /*)' + - ' mounted=$(sed -n ''s/^[[:space:]]*ServerName \(.*\)$/\1/p'' "$conf" | sed ''s/^[[:space:]]*//'' | grep -m 1 ''^/[^:]*$'')' + - ' if [ "$mounted" = "$server" ]; then' + - ' export CUPS_SERVER=/var/run/cups/cups.sock' + - ' else' + - ' echo "${0##*/}: ~/.cups/client.conf names the CUPS socket $server, but Flatpak gave this app ${mounted:-a different one}; give each socket one ServerName line, spelled ServerName" >&2' + - ' exit 1' + - ' fi' + - ' ;;' + - ' esac' + - 'fi' + - 'exec "/app/libexec/cups/${0##*/}" "$@"' - name: wordcraft buildsystem: simple build-commands: diff --git a/packaging/linux/flatpak/ai.storyteller.wordcraft.yml b/packaging/linux/flatpak/ai.storyteller.wordcraft.yml index 83fb9f6cc5..01935727b7 100644 --- a/packaging/linux/flatpak/ai.storyteller.wordcraft.yml +++ b/packaging/linux/flatpak/ai.storyteller.wordcraft.yml @@ -25,6 +25,14 @@ finish-args: - --share=ipc # GPU access for the wgpu renderer (Vulkan, or GL as a fallback). - --device=dri + # Printing: lpstat/lp (the cups-client module) reach the host's CUPS through its socket and + # find driverless network printers through Avahi (`lpstat -e`). Without these the Print + # dialog lists no printers. + - --socket=cups + - --system-talk-name=org.freedesktop.Avahi + # The user's CUPS settings, read-only: their default printer and saved options (lpoptions) + # and a print server named in their client.conf, which lp reaches over the network. + - --filesystem=~/.cups:ro # Open/Save dialogs go through the file-chooser portal (rfd's xdg-portal backend) and # drag-and-drop through the document portal, so picked files work anywhere without broad # filesystem access. Documents and Pictures are granted so files passed by path (the command @@ -38,6 +46,50 @@ finish-args: build-options: append-path: /usr/lib/sdk/rust-stable/bin modules: + # CUPS client tools for craft-print: the runtime has libcups but not lpstat/lp/lpoptions. + # Linked statically against this release's libcups, so a runtime update can't break them; + # the socket path matches the host's, which --socket=cups mounts. + - name: cups-client + buildsystem: simple + build-commands: + - ./configure --prefix=/app --sysconfdir=/etc --localstatedir=/var --with-rundir=/run/cups + --with-domainsocket=/run/cups/cups.sock --disable-shared --with-components=libcups + --with-dnssd=avahi --with-tls=gnutls --disable-pam --disable-dbus + - make -C cups libs + - make -C systemv lp lpoptions lpstat + - install -Dm755 -t /app/libexec/cups systemv/lp systemv/lpoptions systemv/lpstat + - for tool in lp lpoptions lpstat; do install -Dm755 cups-socket.sh "/app/bin/$tool"; done + - install -Dm644 -t /app/share/licenses/cups LICENSE NOTICE + sources: + - type: archive + url: https://github.com/OpenPrinting/cups/releases/download/v2.4.20/cups-2.4.20-source.tar.gz + sha256: ab4d9cd7f3e58060091d2b24972223d6401675f11c49b65abf4f6ef31dea22ff + # Runs each tool. Flatpak mounts the host's CUPS socket at /var/run/cups/cups.sock, choosing + # it as flatpak-run-cups.c does from the host's CUPS_SERVER, else the first line spelled + # exactly `ServerName /path` in ~/.cups/client.conf, else the default; it mounts nothing + # when that socket is missing. CUPS reads the keyword in any case and takes the last + # ServerName. When CUPS' socket from client.conf is the one Flatpak chose, it is pointed at + # the mount; when it isn't, the tool fails rather than reach a different server. A + # CUPS_SERVER is left alone: one set by `flatpak run --env` may not be what was mounted. + - type: script + dest-filename: cups-socket.sh + commands: + - 'conf="$HOME/.cups/client.conf"' + - 'if [ -z "${CUPS_SERVER:-}" ] && [ -r "$conf" ]; then' + - ' server=$(sed -n ''s/^[[:space:]]*[Ss][Ee][Rr][Vv][Ee][Rr][Nn][Aa][Mm][Ee][[:space:]]\{1,\}\([^[:space:]]*\).*/\1/p'' "$conf" | tail -n 1)' + - ' case "$server" in' + - ' /*)' + - ' mounted=$(sed -n ''s/^[[:space:]]*ServerName \(.*\)$/\1/p'' "$conf" | sed ''s/^[[:space:]]*//'' | grep -m 1 ''^/[^:]*$'')' + - ' if [ "$mounted" = "$server" ]; then' + - ' export CUPS_SERVER=/var/run/cups/cups.sock' + - ' else' + - ' echo "${0##*/}: ~/.cups/client.conf names the CUPS socket $server, but Flatpak gave this app ${mounted:-a different one}; give each socket one ServerName line, spelled ServerName" >&2' + - ' exit 1' + - ' fi' + - ' ;;' + - ' esac' + - 'fi' + - 'exec "/app/libexec/cups/${0##*/}" "$@"' - name: wordcraft buildsystem: simple build-options: From a066fe5f134e106c84298ebf5b18899c4564400e Mon Sep 17 00:00:00 2001 From: Fin Warman Date: Fri, 30 Oct 2026 01:38:01 +0000 Subject: [PATCH 4/6] Keep zero-sized paragraph frames in normal flow (#2810) * 411: Keep zero-sized paragraph frames in normal flow * M2.1: keep frame controls consistent with document defaults (#2810) * M2.1: check the final frame round trip (#2810) --------- Co-authored-by: Brandon Thomas --- crates/doc/src/resolve.rs | 7 +++- crates/docx/src/read/props.rs | 4 +-- crates/docx/tests/it/fixtures.rs | 62 ++++++++++++++++++++++++++++++++ 3 files changed, 70 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/resolve.rs b/crates/doc/src/resolve.rs index 49b6904822..af3a8f2abb 100644 --- a/crates/doc/src/resolve.rs +++ b/crates/doc/src/resolve.rs @@ -270,7 +270,12 @@ impl ResolvedPara { drop_cap_margin: p.drop_cap_margin.unwrap_or(false), drop_cap_distance: p.drop_cap_distance.filter(|d| d.is_finite()).unwrap_or(0.0).clamp(0.0, MAX_DROP_CAP_DISTANCE), drop_cap_font: p.drop_cap_font.clone().filter(|f| !f.trim().is_empty()), - frame: p.frame.clone().filter(|_| p.drop_cap.unwrap_or(0) == 0), + // Explicit zero dimensions cancel a frame; omitted dimensions still fit its text. + frame: p.frame.clone().filter(|f| p.drop_cap.unwrap_or(0) == 0 && (f.w != Some(0.0) || f.h != Some(0.0))).map(|mut f| { + f.w = f.w.filter(|v| *v != 0.0); + f.h = f.h.filter(|v| *v != 0.0); + f + }), suppress_hyphens: p.suppress_hyphens.unwrap_or(false), suppress_line_numbers: p.suppress_line_numbers.unwrap_or(false), kinsoku: p.kinsoku.unwrap_or(true), diff --git a/crates/docx/src/read/props.rs b/crates/docx/src/read/props.rs index acd56b2ef4..57223c22f2 100644 --- a/crates/docx/src/read/props.rs +++ b/crates/docx/src/read/props.rs @@ -23,8 +23,8 @@ fn text_frame(k: &El) -> wordcraft_doc::props::TextFrame { let word = |name: &str, allowed: &[&str], default: &str| k.attr(name).filter(|v| allowed.contains(v)).unwrap_or(default).to_string(); let align = |name: &str, allowed: &[&str]| k.attr(name).filter(|v| allowed.contains(v)).map(str::to_string); wordcraft_doc::props::TextFrame { - w: len("w:w").filter(|v| *v > 0.0), - h: len("w:h").map(f32::abs).filter(|v| *v > 0.0), + w: len("w:w").filter(|v| *v >= 0.0), + h: len("w:h").map(f32::abs), h_exact: k.attr("w:hRule") == Some("exact"), x: len("w:x").unwrap_or(0.0), y: len("w:y").unwrap_or(0.0), diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index 5d9e128fba..34b3bd0746 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -114,6 +114,68 @@ fn paragraph_default_presence_survives_repeated_saves() { } } +#[test] +fn zero_frame_keeps_normal_flow() { + const ROUND_TRIPS: usize = 2; + let zero = r#""#; + let sized = r#""#; + for frame in [zero, sized] { + let styles = format!( + r#"{frame} + {sized}"# + ); + let header = format!(r#"Header alphaHeader beta"#); + let footer = format!(r#"Footer delta"#); + let body = format!( + r#"Body one + {sized}Direct frame + Styled frame + {zero}Frame reset + "# + ); + let mut document = wordcraft_docx::read(&docx( + &body, + &[("styles", "styles", "styles.xml"), ("header", "header", "header1.xml"), ("footer", "footer", "footer1.xml")], + &[("word/styles.xml", &styles), ("word/header1.xml", &header), ("word/footer1.xml", &footer)], + )) + .unwrap(); + for pass in 0..=ROUND_TRIPS { + let body = paras(&document); + let resolved = document.styles.resolve_para(&body[0].props); + assert!(resolved.frame.is_none(), "document defaults never create a frame"); + assert!(document.styles.default_para.frame.is_none()); + let reset = body[3].props.frame.as_ref().unwrap(); + assert_eq!((reset.w, reset.h), (Some(0.0), Some(0.0)), "the direct reset survives saving"); + assert_eq!(resolved.space_after, 8.0); + assert!(document.styles.resolve_para(&body[1].props).frame.is_some()); + assert!(document.styles.resolve_para(&body[2].props).frame.is_some()); + assert!(document.styles.resolve_para(&body[3].props).frame.is_none()); + for id in [document.last_section.headers.default, document.last_section.footers.default] { + for block in &document.parts.get(&id.unwrap()).unwrap().blocks { + let paragraph = block.as_para().unwrap(); + assert!(document.styles.resolve_para(¶graph.props).frame.is_none(), "defaults do not frame headers or footers"); + } + } + if pass == ROUND_TRIPS { + break; + } + document = wordcraft_docx::read(&wordcraft_docx::write(&document).unwrap()).unwrap(); + } + } +} + +#[test] +fn frame_zero_side_is_automatic() { + for (attrs, width, height) in + [(r#"w:w="0" w:h="1200""#, None, Some(60.0)), (r#"w:w="2400" w:h="0" w:hRule="exact""#, Some(120.0), None), ("", None, None)] + { + let document = read_body(&format!(r#"Original automatic frame"#)); + let paragraph = paras(&document)[0]; + let frame = document.styles.resolve_para(¶graph.props).frame.unwrap(); + assert_eq!((frame.w, frame.h), (width, height)); + } +} + #[test] fn omitted_paragraph_defaults_can_be_edited() { let styles = From f658c872a23a13cd1a5a81d63f12993f51a4f938 Mon Sep 17 00:00:00 2001 From: Fin Warman Date: Fri, 30 Oct 2026 01:40:41 +0000 Subject: [PATCH 5/6] Tables: share spanning minima by preferred widths (#1883) * Tables: share span minima by preferred widths (#1883) * 1222: Match nested preferred span weights * docs: word the #1883 layout-parity entries --------- Co-authored-by: Brandon Thomas --- crates/layout/src/table.rs | 42 ++++++++++++--- crates/layout/src/tests.rs | 108 +++++++++++++++++++++++++++++++++++++ docs/layout-parity.md | 5 +- 3 files changed, 147 insertions(+), 8 deletions(-) diff --git a/crates/layout/src/table.rs b/crates/layout/src/table.rs index 8cbc414585..701aad2fff 100644 --- a/crates/layout/src/table.rs +++ b/crates/layout/src/table.rs @@ -391,9 +391,9 @@ struct TableFrame { x: f32, } -fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option<&TableStyleProps>) -> TableFrame { +// Nested measurement needs the same preferred weights as layout before sharing span minima. +fn preferred_grid(t: &Table, avail: f32) -> Vec { let ncols = grid_cols(t).max(1); - // Column widths. let mut grid: Vec = if t.grid.len() == ncols { // Grid units can be narrower than a text box, including omitted row-end columns. t.grid @@ -408,6 +408,12 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option vec![avail / ncols as f32; ncols] }; apply_cell_widths(t, &mut grid); + grid +} + +fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option<&TableStyleProps>) -> TableFrame { + let ncols = grid_cols(t).max(1); + let mut grid = preferred_grid(t, avail); let mut total: f32 = grid.iter().sum(); // A top-level table in an inherited header or footer takes its share of the defining // section's width (`Ctx::pct_base`). @@ -437,7 +443,7 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option if !t.props.fixed { // Measuring lays paragraphs out once more; it mustn't count their equations twice. let eq_count = ctx.eq_count; - let content = column_content(ctx, t, style, depth); + let content = column_content(ctx, t, style, depth, &grid); ctx.eq_count = eq_count; if let Some(content) = content { autofit(&mut grid, &content, t, avail); @@ -1167,7 +1173,7 @@ fn region_text(st: &TableStyleProps, region: Region) -> CellText { /// Each column's narrowest and widest content, cell margins included: its longest word and its /// longest line. A cell spanning columns shares what they lack between them; nested tables count /// with their own. `None` when every cell is empty. -fn column_content(ctx: &mut Ctx, t: &Table, style: Option<&TableStyleProps>, depth: usize) -> Option> { +fn column_content(ctx: &mut Ctx, t: &Table, style: Option<&TableStyleProps>, depth: usize, grid: &[f32]) -> Option> { let margins_def = default_margins(t, style); // The grid's width once: counting it walks every row. let ncols = grid_cols(t); @@ -1196,15 +1202,36 @@ fn column_content(ctx: &mut Ctx, t: &Table, style: Option<&TableStyleProps>, dep for (g, span, need) in spanning { let Some(cs) = cols.get_mut(g..g.saturating_add(span).min(ncols)) else { continue }; let n = cs.len().max(1) as f32; - let (have_lo, have_hi) = cs.iter().fold((0.0, 0.0), |(l, h), c| (l + c.0, h + c.1)); + let have_hi: f32 = cs.iter().map(|c| c.1).sum(); + let preferred = (!is_automatic(t)).then(|| grid.get(g..g + cs.len())).flatten(); + share_span_min(cs, preferred, need.0); for c in cs { - c.0 += (need.0 - have_lo).max(0.0) / n; c.1 += (need.1 - have_hi).max(0.0) / n; } } any.then_some(cols) } +// Share a span's extra minimum in preferred-column proportions. Each column keeps +// its own text minimum; automatic tables share the extra equally. +fn share_span_min(cols: &mut [(f32, f32)], grid: Option<&[f32]>, need: f32) { + let extra = (need - cols.iter().map(|c| c.0).sum::()).max(0.0); + let weight = |w: &f32| if w.is_finite() { w.clamp(0.0, UNBOUNDED) } else { 0.0 }; + let total = grid.map_or(0.0, |grid| grid.iter().take(cols.len()).map(weight).sum::()); + if total > 0.0 { + if let Some(grid) = grid { + for (c, w) in cols.iter_mut().zip(grid) { + c.0 += extra * weight(w) / total; + } + } + return; + } + let share = extra / cols.len().max(1) as f32; + for c in cols { + c.0 += share; + } +} + /// The grid columns row `row` leaves empty before its first cell and after its last one (which /// ends at grid column `end`) when it gives their width (`w:wBefore`, `w:wAfter`): (first column, /// columns, width in points). Column widths make room for them like for an empty cell. @@ -1234,7 +1261,8 @@ fn blocks_content(ctx: &mut Ctx, blocks: &Blocks, text: Option<&CellText>, depth (width, width) } else { let style = table_style(ctx, nt); - let cols = column_content(ctx, nt, style.as_ref(), depth + 1).unwrap_or_default(); + let weights = preferred_grid(nt, width); + let cols = column_content(ctx, nt, style.as_ref(), depth + 1, &weights).unwrap_or_default(); let (l, h) = cols.iter().fold((0.0, 0.0), |(l, h), c| (l + c.0, h + c.1)); (width.max(l), width.max(h)) } diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 2c904e9a62..85d44c13a2 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -11232,6 +11232,114 @@ fn caret_height_ignores_line_spacing() { } } +enum SpanWidth { + Preferred, + Automatic, + TextOnly, +} + +fn banner_layout(width: SpanWidth) -> DocLayout { + let widths = [150.0, 100.0, 25.0, 25.0]; + let mut d = Document::new(); + let mut t = Table::new(2, widths.len(), 300.0); + t.grid = widths.to_vec(); + t.props.width = match width { + SpanWidth::Preferred => Some(300.0), + SpanWidth::Automatic | SpanWidth::TextOnly => None, + }; + t.props.cell_margins = Some([0.0; 4]); + t.rows[0].cells.truncate(1); + t.rows[0].cells[0].props.span = 4; + t.rows[0].cells[0].props.width = t.props.width; + let mut banner = wordcraft_doc::Paragraph::new(); + if !matches!(width, SpanWidth::TextOnly) { + banner.insert_object(0, picture(300.0, 30.0, Default::default()), &Default::default()).unwrap(); + } + t.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(banner)]; + for (i, cell) in t.rows[1].cells.iter_mut().enumerate() { + cell.props.width = match width { + SpanWidth::Preferred => Some(widths[i]), + SpanWidth::Automatic | SpanWidth::TextOnly => None, + }; + cell.blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("A", Default::default()))]; + } + d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap(); + lay(&d) +} + +#[test] +fn spanning_banner_uses_weights() { + let text = banner_layout(SpanWidth::TextOnly); + let minimum = text.pages[0] + .items + .iter() + .find_map(|item| match item { + Placed::Cell { rect, row: 1, .. } => Some(rect.w), + _ => None, + }) + .unwrap(); + let widths = [150.0 - minimum, 100.0 - minimum / 3.0, 25.0 + 2.0 * minimum / 3.0, 25.0 + 2.0 * minimum / 3.0]; + let l = banner_layout(SpanWidth::Preferred); + let actual: Vec<_> = + l.pages[0].items.iter().filter_map(|it| if let Placed::Cell { rect, row: 1, .. } = it { Some(rect.w) } else { None }).collect(); + assert_eq!(actual.len(), widths.len()); + for (got, want) in actual.iter().zip(widths) { + assert!((got - want).abs() < 0.01, "spanning banner changed columns: {actual:?}"); + } +} + +#[test] +fn automatic_banner_shares_width() { + let l = banner_layout(SpanWidth::Automatic); + let widths: Vec<_> = + l.pages[0].items.iter().filter_map(|it| if let Placed::Cell { rect, row: 1, .. } = it { Some(rect.w) } else { None }).collect(); + assert_eq!(widths.len(), 4); + assert!(widths.iter().all(|w| (w - 75.0).abs() < 0.01), "automatic widths: {widths:?}"); +} + +#[test] +fn nested_spans_use_grid_weights() { + const NESTED_WIDTH: f32 = 40.0; + const IMAGE_WIDTH: f32 = 50.0; + const OUTER_WIDTH: f32 = 51.0; + let widths: Vec<_> = [0.0, 4.0] + .into_iter() + .map(|first| { + let mut nested = Table::new(2, 3, NESTED_WIDTH); + nested.props.style = None; + nested.props.width = Some(NESTED_WIDTH); + nested.props.cell_margins = Some([0.0; 4]); + nested.grid = vec![first, 100.0, 100.0]; + for (index, row) in nested.rows.iter_mut().enumerate() { + row.cells.truncate(1); + row.props.grid_before = index as u32; + row.cells[0].props.span = 2; + row.cells[0].props.width = None; + let mut p = Paragraph::new(); + p.insert_object(0, picture(IMAGE_WIDTH, 10.0, Default::default()), &Default::default()).unwrap(); + row.cells[0].blocks = vec![wordcraft_doc::para_block(p)]; + } + let mut outer = Table::new(1, 1, OUTER_WIDTH); + outer.props.style = None; + outer.props.width = Some(OUTER_WIDTH); + outer.props.cell_margins = Some([0.0; 4]); + outer.rows[0].cells[0].blocks = vec![Arc::new(Block::Table(nested))]; + let mut d = Document::new(); + d.body = vec![Arc::new(Block::Table(outer))]; + lay(&d).pages[0] + .items + .iter() + .find_map(|item| match item { + Placed::Cell { rect, table, .. } if table.0 == [0] => Some(rect.w), + _ => None, + }) + .unwrap() + }) + .collect(); + assert!(widths[1] > OUTER_WIDTH + 0.5, "overlapping spans must expand the outer table: {widths:?}"); + assert!((widths[0] - widths[1]).abs() < 0.01, "equivalent nested grids changed outer fitting: {widths:?}"); +} + /// #2048: a picture anchored in a later paragraph but placed higher up the page (fixed on the /// page, or moved up from its paragraph) keeps the text of the paragraphs above its anchor clear /// too, as in Word, not just its own paragraph's. diff --git a/docs/layout-parity.md b/docs/layout-parity.md index db93a1c0d6..be964d4c5b 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-27 · **Change:** trivial (continuous sections one after another go onto new pages instead of running off the page; empty marks after another empty section mark take a line each until the page is full, then stay at its bottom drawing nothing, not even a list label; an empty mark that takes no room draws no list label either; a kept-together paragraph is measured against the page it would move to, so a tall different first-page header no longer splits it, #3907; previously trivial: a justified line ending in a manual line break is stretched to the margin unless `w:doNotExpandShiftReturn` is set, #3924; previously trivial: a no-break space is as wide as a space, #4192; previously trivial: a bookmark or other zero-width marker is no line-break opportunity, #4193; previously trivial: Arabic list labels: `arabicAlpha` and `arabicAbjad` draw the 28 Arabic letters (alphabetical and abjad order), doubling past the last letter; Hebrew, Hindi, Thai and Vietnamese still show decimal (`doc::section::tests::arabic_letters_count_in_both_orders`); previously trivial: Preserve grapheme edit/wrap boundaries across independently drawn font/style pieces; Exact-spacing table contact uses the specified line height rather than paragraph-mark metrics (#3977); previously trivial: cu20we: restrict pre-spacing float origins to paragraph anchors; document cap helpers and regressions; previously trivial: cu20we: outline caps; previously trivial: cu20we: box float paragraph origin; previously trivial: group connector rerouting preserves transformed free and unresolved endpoints under nonuniform scaling; readiness estimates unchanged; previously trivial: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: an empty paragraph whose mark is hidden shows nothing, not even its list number, which is still counted, #3982; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: symbol fonts keep their line height without the font; previously trivial: an equation-array row without `&` is centred, #2617; previously trivial: a superscript or subscript sizes its line at the full font size, without its raise or drop, as Word does; previously trivial: an object dragged near the bottom of a page lands where it is dropped, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: fixed font inputs in four layout controls; previously trivial: justified lines shrink their spaces by Word's measured limits; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: a click below a floating table goes to the text beside or after it, not to a cell of its last row, #2038; previously trivial: shapes drawn with their gradients and transparency, #1500; previously trivial: paragraphs above a float's anchor wrap around it, also when that pushes the anchor onto the next page, #2048; previously trivial: triple borders draw three lines, #1740; previously trivial: the caret, clicks and selection edges fall between the letters of a ligature, #1974; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: VML header-cell floats always on the page, user-checked in Word for Mac, #1775; previously trivial: an at-least row with no room for its minimum starts the next page whole, #1742; previously trivial: AutoFit donors lose equal widths down to their content minima; previously trivial: automatic space between Asian text and Latin text or digits, #2358; previously trivial: hint-reliant CJK outlines; previously trivial: positional tabs go to the margins or indents, #2367; previously trivial: field results with right-to-left text read right to left, #1670; previously trivial: a list bullet no installed font can draw shows the level's default bullet, #1683; previously trivial: a missing Thai font is drawn in one Thai face for the whole run, #1549; previously trivial: the caret after spaces hanging past the margin stays at the margin, #2146; previously trivial: covered black-circle fallback before UI sans; previously trivial: resolved split-cell continuation top insets; previously trivial: Symbol PCL6 alias uses Symbol encoding; previously trivial: exact full font names select their installed face; previously trivial: Arial Unicode MS uses proportional fallbacks; previously trivial: DrawingML outline dashes, including zero-width paths; previously trivial: TOCs include table-cell headings and retain full targets; previously trivial: kept table rows follow the next row; previously trivial: consistent cell widths override a stale table grid; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: floating-table overlap ignores empty line-break lines; previously trivial: paragraph spacing adds up when the document turns HTML auto spacing off; previously trivial: an inherited footer sizes its percentage tables by its own section; previously trivial: an empty section mark stays on a full page; previously trivial: a fitting row with less room than its minimum height moves on whole; oversized rows still split; previously trivial: text past an exact-height row is cut off; previously trivial: a list number stays with text after a leading page break; previously trivial: a bookmark after a page break takes no line; previously trivial: a page break followed by a page break before or a next-page section starts one page; previously trivial: All Caps and Small Caps draw ß as SS, #1581; previously trivial: justified vertical page alignment, #1320; previously trivial: page numbers restart at 0; previously trivial: a list label moves with its first line when the paragraph is centred or end-aligned (#1159); previously trivial: PAGE fields in a paragraph split across pages show the page they are on, #1352; previously trivial: a dragged floating object anchors in the column it lands in, #884; previously trivial: a paragraph ending on a page with footnotes keeps its space after above the separator, #1116; previously trivial: symbol-font text drawn as Unicode symbols, #776; previously trivial: large-table scrolling measured and fixed, #811; previously trivial: text boxes use their own margins; Resize shape to fit text never cuts text, #743; previously trivial: complex-script shaping and Myanmar line breaking, #604; previously trivial: body page totals, table-cell footnotes and bookmark link pages fixed, #450 #451 #455; previously major: first version; line breaking, pagination and object placement checked against Word's behaviour from the layout source on origin/main) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** 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, @@ -236,6 +236,8 @@ Footer flow-table strokes reserve their drawn top edge, including the half-width Page-relative footer tables keep their physical wrap bounds without adding to footer text height. Body text resumes below the table. Original native controls cover empty, text-bearing and minimum-height tables. Body textbox boundaries and nested footer painting remain separate gaps. +Spanning cell minima retain each column's text minimum and share extra width in preferred-column proportions; automatic tables share equally. Nested measurement normalizes preferred grid weights as layout does. + ## Validation fonts The deleted/hidden-text wrapping, ellipse wrapping and widow-control regressions request Source Sans 3 explicitly. Their fixed widths and word counts use that font's metrics. This changes test inputs only, not renderer font substitution or Word parity claims. @@ -266,6 +268,7 @@ layout suite are pending; this is not a new Word/native-IME acceptance claim. | Date | Change | Summary | |---|---|---| +| 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 | 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-24 | trivial | Preserve grapheme edit/wrap boundaries across independently drawn font/style pieces; original emoji regression retained, new mixed-style/bundled-font LTR/bidi controls pending managed validation | | 2026-10-24 | trivial | Exact-spacing table contact uses the specified line height in row selection and word skipping; large/small mark regressions in modes 11/12/14/15 (#3977); shape estimates unchanged | From 22e99fc2b7cedf351b65a14c879feddaac5653ac Mon Sep 17 00:00:00 2001 From: Dmitrii Khlapov Date: Fri, 30 Oct 2026 02:47:27 +0100 Subject: [PATCH 6/6] Tables can be copied and cut: whole tables, rows and cells (#1744) (#1784) * #1744: WIP * #1744: Select Table copies and cuts the whole table Copy of a whole-table selection used to keep only the cells' paragraphs (copy_blocks flattened a cross-cell range), and Cut only cleared the text. Now Copy puts the table on the clipboard and Cut removes the table. Co-Authored-By: Claude Opus 5.5 * #1744: selected table rows and cells copy as a table; Cut clears their text Copy of whole rows, cells of a row or a block of cells puts a table of just those cells on the clipboard (Table::slice). Cut of rows or cells clears their text and keeps the rows and cells, as in Word (Word check A). Co-Authored-By: Claude Opus 5.5 * #1744: review fixes Table::slice widens every row to a merged cell partly selected (no ragged copy); an empty selected table or cell copies and cuts; a text selection over exactly a nested table copies it; one selected_table per Cut; tests for slice merges/widths/controls, tracked and locked cuts, and the text route. Co-Authored-By: Claude Opus 5.5 * #1744: Cut clears every cell Copy takes; Spike stays off for empty cell selections Co-Authored-By: Claude Sonnet 5.5 * #1744: a copied part of a percentage-width table keeps a point width Co-Authored-By: Claude Sonnet 5.5 * ROADMAP: tidy merged header Co-Authored-By: Claude Sonnet 5.5 * ROADMAP: keep only the #1744 rows over main's version Co-Authored-By: Claude Sonnet 5.5 * ROADMAP: remove conflict markers; keep only the #1744 rows over main's version Co-Authored-By: Claude Sonnet 5.5 * #1744: rename the range Cut helper clear_range_cells (main added clear_cells) Co-Authored-By: Claude Sonnet 5.5 * Remove conflict markers from ROADMAP.md; leave main's header line alone Co-Authored-By: Claude Sonnet 5.5 * cargo fmt Co-Authored-By: Claude Sonnet 5.5 * Import Path in table structure after merging main --------- Co-authored-by: Dmitrii Khlapov <19991457+dkhlapov@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- ROADMAP.md | 4 + crates/doc/src/edit.rs | 64 +++++ crates/doc/src/table.rs | 137 +++++++++++ crates/engine/src/cmd/column.rs | 2 + crates/engine/src/cmd/edit.rs | 56 ++++- crates/engine/src/cmd/table.rs | 2 + crates/engine/src/cmd/table/clear.rs | 24 ++ crates/engine/src/cmd/table/structure.rs | 20 ++ crates/engine/src/tests.rs | 285 +++++++++++++++++++++++ 9 files changed, 585 insertions(+), 9 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index a794c35fc4..aaafccf460 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -255,6 +255,8 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target | 2026-10-16 | DOCX: a `HYPERLINK` field (complex or simple) reads as a link, as a `w:hyperlink` does: its result stays ordinary text carrying the link (`url`, `url#bookmark` or `#bookmark`), so a tab in it reaches its tab stop and a `PAGEREF` in it stays a field (#2174). A table of contents from Word for the web, whose entries are such fields, showed a box for each tab and no dot leaders; the entries now open as in Word and their links work | | 2026-10-17 | The document's right-click menu offers the ribbon's Paste menu, item for item (#2583): Paste (the clipboard's formatting kept, Word's Keep Source Formatting), Keep Text Only, Merge Formatting and Paste Special…, where it had a single Paste. Same commands and shortcuts, with the system clipboard | | 2026-10-17 | SmartArt Text Pane: Tab demotes and Shift+Tab promotes the focused item, as Word's pane does (#2701). The row keeps its focus, so a second Tab acts on the same item; an item that can't go down a level is left alone | +| 2026-10-15 | Selected table rows and cells copy as a table (#1744): Copy of whole rows, of cells in a row, or of a block of cells over several rows, then Paste outside the table, inserts a table of just those cells; Cut of rows or cells clears their text and leaves the rows and cells in place (the clipboard still gets the table), as Word does. Copy used to take only the cells' paragraphs | +| 2026-10-14 | Tables can be copied and cut (#1744): with the whole table selected (Select Table, or a drag over all of it), Copy puts the table itself on the clipboard, so Paste outside it inserts a copy of the table with its formatting (the plain text is tab and newline separated); Cut removes the table in one undo step, as in Word. Copy used to keep only the cells' paragraphs and Cut left the table in place | | 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-19 | Typing no longer starts render threads on every repaint (#3027): page, area and icon renders share one kept vello_cpu context, reset to each size, instead of building a multi-threaded one (and its thread pool) per render. Typing about 150 characters in 15 s created 295–388 threads before and none now; CPU time while typing fell by about a third (Windows, debug build). | | 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 | @@ -803,6 +805,8 @@ Footer page-table height and body wrapping are corrected. Other pagination gaps | 2026-10-16 | trivial | Progress log: a text frame in the paragraph defaults frames nothing (#2360) | | 2026-10-16 | trivial | Progress log: a text file saved over itself closes without asking (#2376) | | 2026-10-15 | trivial | Progress log: recovery copies and .json files store pictures as base64 (#586 follow-up) | +| 2026-10-15 | trivial | Progress log: selected table rows and cells copy as a table; Cut clears their text (#1744) | +| 2026-10-14 | trivial | Progress log: Select Table copies and cuts the whole table (#1744) | | 2026-10-17 | trivial | Progress log: Scale Font Sizes command (#1475) | | 2026-10-14 | trivial | Progress log: row table border exceptions | | 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/crates/doc/src/edit.rs b/crates/doc/src/edit.rs index b823d892dc..833c3878d2 100644 --- a/crates/doc/src/edit.rs +++ b/crates/doc/src/edit.rs @@ -792,6 +792,63 @@ impl Document { Fragment { blocks, parts } } + /// A copy of the block at `path` (a whole table, say) as a fragment, with its text boxes. + pub fn copy_block(&self, story: crate::StoryRef, path: &Path) -> Option { + Some(self.fragment_of(vec![self.block(story, path)?.clone()])) + } + + /// A copy of rows `rows` of the table at `tp`, with the cells of each that reach into grid + /// columns `cols` (see [`crate::Table::slice`]), as a fragment holding that table. + pub fn copy_table_cells(&self, story: crate::StoryRef, tp: &Path, rows: (usize, usize), cols: (usize, usize)) -> Option { + let t = self.table(story, tp)?.slice(rows, cols); + if t.rows.is_empty() { + return None; + } + Some(self.fragment_of(vec![Block::Table(t)])) + } + + /// `blocks` as a fragment: half content controls dropped, text boxes copied along. + fn fragment_of(&self, mut blocks: Vec) -> Fragment { + crate::control::balance_blocks(&mut blocks); + let parts = self.text_box_parts(&blocks); + Fragment { blocks, parts } + } + + /// The table whose whole text `a..b` covers when the range runs across its cells: from the + /// start of its first paragraph to the end of its last. Of the tables holding both ends, the + /// outermost one covered whole (a table nested in a cell when the range covers just it). + /// `None` for a range inside one cell, or one that doesn't cover a whole table. + pub fn whole_table(&self, a: &Pos, b: &Pos) -> Option { + let (a, b) = order(a, b); + if a.story != b.story || a.off != 0 || a.path.parent() == b.path.parent() { + return None; + } + let mut paths: Option> = None; + // Table block paths are the prefixes of a cell paragraph's path one block deep, then + // every three steps (block, row, cell) deeper. + let mut n = 1usize; + while n.saturating_add(3) <= a.path.0.len() { + let pre = a.path.0.get(..n)?; + if !b.path.0.starts_with(pre) { + return None; + } + let tp = Path(pre.to_vec()); + if self.table(a.story, &tp).is_some() { + let paths = paths.get_or_insert_with(|| self.para_paths(a.story)); + let mut inside = paths.iter().filter(|p| p.0.starts_with(pre)); + if let Some(first) = inside.next() { + let last = inside.next_back().unwrap_or(first); + let end = self.para(a.story, last).map_or(0, Paragraph::len); + if *first == a.path && *last == b.path && b.off >= end { + return Some(tp); + } + } + } + n = n.saturating_add(3); + } + None + } + /// The whole body as a fragment (with its text boxes), to insert into another document. pub fn body_fragment(&self) -> Fragment { let blocks: Vec = self.body.iter().map(|b| (**b).clone()).collect(); @@ -846,6 +903,13 @@ impl Document { } return out; } + // Across the cells of a whole table: the table itself, not its cells' paragraphs (#1744). + if let Some(tp) = self.whole_table(&a, &b) + && let Some(blk) = self.block(a.story, &tp) + { + out.push(blk.clone()); + return out; + } for p in self.paths_between(&a, &b) { if let Some(para) = self.para(a.story, &p) { let mut q = para.clone(); diff --git a/crates/doc/src/table.rs b/crates/doc/src/table.rs index 76911dd4f8..abdda89241 100644 --- a/crates/doc/src/table.rs +++ b/crates/doc/src/table.rs @@ -77,6 +77,80 @@ pub const MAX_COLS: usize = 63; pub const MAX_TABLE_DEPTH: usize = 24; impl Table { + /// Grid columns `lo..hi` that [`Table::slice`] copies for `rows`/`cols` (widened over merged cells), + /// and whether any cell touches them (Cut clears the same cells it copies). + pub fn slice_bounds(&self, rows: (usize, usize), cols: (usize, usize)) -> (usize, usize, bool) { + let ((r0, r1), (g0, g1)) = (rows, cols); + let kept = || self.rows.iter().take(r1.saturating_add(1)).skip(r0); + // Grid columns `lo..hi` the cells touching them cover: a cell merged across that is partly + // in them widens them, for every row, so the copy isn't ragged. Each round only widens + // (at most once per grid column), so a bound of the grid's width plus one round is enough. + let (mut lo, mut hi) = (g0, g1.saturating_add(1)); + let mut any = false; + for _ in 0..=MAX_COLS.saturating_add(1) { + let (mut nlo, mut nhi, mut found) = (lo, hi, false); + for row in kept() { + let mut g = 0usize; + for cell in &row.cells { + let end = g.saturating_add(cell.span()); + if g < hi && end > lo { + (nlo, nhi, found) = (nlo.min(g), nhi.max(end), true); + } + g = end; + } + } + any = found; + if (nlo, nhi) == (lo, hi) { + break; + } + (lo, hi) = (nlo, nhi); + } + (lo, hi, any) + } + + /// A copy of rows `rows` of this table holding, of each row, the cells that reach into grid + /// columns `cols` (both inclusive): what Copy takes from selected rows or cells. Content + /// controls around rows and the table aren't copied (they'd lose their other end); a cell + /// that continues a vertical merge from a row left out starts the merge instead. + pub fn slice(&self, rows: (usize, usize), cols: (usize, usize)) -> Table { + let (r0, r1) = rows; + let kept = || self.rows.iter().take(r1.saturating_add(1)).skip(r0); + let (lo, hi, any) = self.slice_bounds(rows, cols); + let mut out_rows = Vec::new(); + for row in kept() { + let mut g = 0usize; + let mut cells = Vec::new(); + for cell in &row.cells { + let end = g.saturating_add(cell.span()); + if any && g < hi && end > lo { + cells.push(cell.clone()); + } + g = end; + } + if !cells.is_empty() { + out_rows.push(Row { props: row.props.clone(), cells, controls: ControlWrap::default() }); + } + } + if let Some(first) = out_rows.first_mut() { + for c in &mut first.cells { + if c.props.vmerge == VMerge::Continue { + c.props.vmerge = VMerge::Restart; + } + } + } + let whole = lo == 0 && hi >= self.grid.len(); + let grid = if whole { self.grid.clone() } else { self.grid.get(lo..hi.min(self.grid.len())).map(<[f32]>::to_vec).unwrap_or_default() }; + let mut props = self.props.clone(); + if !whole { + // Part of the columns: as wide as they are, not the whole table's width. + if props.width.is_some() || props.width_pct.is_some() { + props.width = Some(grid.iter().sum()); + } + props.width_pct = None; + } + Table { props, grid, rows: out_rows, controls: ControlWrap::default() } + } + /// A `rows × cols` table spanning `width` points, "Table Grid" style. pub fn new(rows: usize, cols: usize, width: f32) -> Table { let rows = rows.clamp(1, MAX_ROWS); @@ -566,6 +640,69 @@ impl Table { mod tests { use super::*; + /// A 3×3 table, 100 pt columns: (0,0)–(0,1) merged across, (1,2)–(2,2) merged down. + fn merged() -> Table { + let mut t = Table::new(3, 3, 300.0); + t.merge(0, 0, 0, 1); + t.merge(1, 2, 2, 2); + assert_eq!(t.rows[0].cells.iter().map(Cell::span).collect::>(), [2, 1]); + assert_eq!((t.rows[1].cells[2].props.vmerge, t.rows[2].cells[2].props.vmerge), (VMerge::Restart, VMerge::Continue)); + t + } + + fn spans(t: &Table) -> Vec> { + t.rows.iter().map(|r| r.cells.iter().map(Cell::span).collect()).collect() + } + + /// #1744 review: a cell merged across that is partly selected takes its whole width, and the + /// other rows widen with it, so the copy isn't ragged. + #[test] + fn slice_widens_to_a_merged_cell_in_every_row() { + let t = merged().slice((0, 1), (1, 2)); + assert_eq!(t.grid, [100.0, 100.0, 100.0]); + assert_eq!(spans(&t), [vec![2, 1], vec![1, 1, 1]]); + // Rows without the merged cell: just the selected columns. + let t = merged().slice((1, 2), (1, 2)); + assert_eq!(t.grid, [100.0, 100.0]); + assert_eq!(spans(&t), [vec![1, 1], vec![1, 1]]); + } + + /// #1744 review: a cell continuing a vertical merge from a row left out starts it instead. + #[test] + fn slice_starts_a_vertical_merge_whose_first_row_is_left_out() { + let t = merged().slice((2, 2), (0, 2)); + assert_eq!(t.rows.len(), 1); + assert_eq!(t.rows[0].cells[2].props.vmerge, VMerge::Restart); + // Both rows kept: the merge is kept as it is. + let t = merged().slice((1, 2), (2, 2)); + assert_eq!((t.rows[0].cells[0].props.vmerge, t.rows[1].cells[0].props.vmerge), (VMerge::Restart, VMerge::Continue)); + } + + /// #1744 review: part of the columns is as wide as they are; content controls around rows + /// and the table aren't copied. + #[test] + fn slice_width_and_controls() { + let mut t = Table::new(3, 3, 300.0); + (t.props.width, t.props.width_pct) = (Some(300.0), Some(50.0)); + let wrap = ControlWrap { open: vec![crate::control::ContentControl::default()], close: 1 }; + t.controls = wrap.clone(); + t.rows[1].controls = wrap; + let part = t.slice((0, 2), (2, 2)); + assert_eq!((part.grid.len(), part.props.width, part.props.width_pct), (1, Some(100.0), None)); + let whole = t.slice((0, 2), (0, 2)); + assert_eq!((whole.props.width, whole.props.width_pct), (Some(300.0), Some(50.0)), "all columns keep the table's width"); + let row = t.slice((1, 1), (0, 2)); + assert!(row.controls.is_empty() && row.rows[0].controls.is_empty()); + // A table sized only by a percentage keeps a width for the part. + let mut pct = Table::new(3, 3, 300.0); + (pct.props.width, pct.props.width_pct) = (None, Some(50.0)); + let part = pct.slice((0, 2), (2, 2)); + assert_eq!((part.props.width, part.props.width_pct), (Some(100.0), None)); + // Nothing in range: no rows. + assert!(t.slice((5, 6), (0, 2)).rows.is_empty()); + assert!(t.slice((0, 2), (9, 9)).rows.is_empty()); + } + #[test] fn grid_before_shifts_the_row() { let mut t = Table::new(2, 3, 300.0); diff --git a/crates/engine/src/cmd/column.rs b/crates/engine/src/cmd/column.rs index cd68024d6e..6d6c83b805 100644 --- a/crates/engine/src/cmd/column.rs +++ b/crates/engine/src/cmd/column.rs @@ -180,6 +180,8 @@ pub(crate) fn dispatch(s: &mut Session, id: &str, mutates: bool, run: fn(&mut Se // Whole cells: table commands take the rectangle between the corners, and Tab moves on // from it without clearing it, as in Word. _ if cells && (id.starts_with("table.") || matches!(id, "text.tab" | "text.backTab")) => run(s, v), + // Copy and Cut of whole cells take a table of them (#1744). + "edit.copy" | "edit.cut" if cells => run(s, v), "edit.copy" => copy(s, &segs), "edit.cut" => { let r = copy(s, &segs)?; diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 641fe1f1f0..42388f392b 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -2,7 +2,7 @@ use serde_json::{Value, json}; use wordcraft_doc::edit::Fragment; -use wordcraft_doc::{Pos, StoryRef}; +use wordcraft_doc::{Path, Pos, StoryRef}; use super::{delete_selection, find_pattern, pos_json, sel_result}; use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p}; @@ -27,10 +27,16 @@ fn undo_to(s: &mut Session, v: &Value) -> CmdResult { Ok(r) } -fn has_sel(s: &Session) -> Option<&'static str> { +/// Something the Spike can collect: text (it doesn't take empty cells). +fn has_text_sel(s: &Session) -> Option<&'static str> { if s.sel.is_collapsed() { Some("nothing is selected") } else { None } } +/// Something to cut: text, or whole table cells (an empty cell's selection has no length, #1744). +fn has_sel(s: &Session) -> Option<&'static str> { + if s.sel.is_collapsed() && s.cell_range().is_none() { Some("nothing is selected") } else { None } +} + pub fn specs() -> Vec { vec![ CommandSpec::new("edit.undo", "Undo", "Quick Access Toolbar", |s, _| { @@ -63,7 +69,7 @@ pub fn specs() -> Vec { CommandSpec::new("edit.copy", "Copy", "Home › Clipboard", copy).key("Mod+C / Mod+Insert").pure(), // Word's Spike (Ctrl+F3, Ctrl+Shift+F3; ⌘ on the Mac): the AutoText entry "Spike", so Quick // Parts and AutoText insert it without emptying it, as in Word. - CommandSpec::new("edit.spike", "Spike", "Editing", spike).key("Mod+F3").when(has_sel), + CommandSpec::new("edit.spike", "Spike", "Editing", spike).key("Mod+F3").when(has_text_sel), CommandSpec::new("edit.insertSpike", "Insert Spike", "Editing", insert_spike).key("Mod+Shift+F3").when(|s| { if s.math.is_some() { Some("leave the equation first") @@ -167,11 +173,25 @@ pub fn specs() -> Vec { } fn copy(s: &mut Session, _: &Value) -> CmdResult { + let whole = super::table::selected_table(s); + copy_with(s, whole.as_ref()) +} + +/// Copy, `whole` being the table the selection covers whole, if it does. +fn copy_with(s: &mut Session, whole: Option<&Path>) -> CmdResult { let (a, b) = s.sel.ordered(); - if a == b { - return Ok(json!({"text": ""})); - } - let f = s.doc.copy_range(&a, &b); + // Whole table cells selected copy as a table, even empty ones (their selection has no + // length): the whole table, or a table of just the selected rows or cells (#1744). + let table = match (whole, s.cell_range()) { + (Some(tp), _) => s.doc.copy_block(a.story, tp), + (None, Some(r)) => s.doc.copy_table_cells(r.story, &r.table, r.rows, r.cols), + (None, None) => None, + }; + let f = match table { + Some(f) => f, + None if a == b => return Ok(json!({"text": ""})), + None => s.doc.copy_range(&a, &b), + }; s.clipboard_text = f.clipboard_text(); s.clip_history.push(&f, &s.clipboard_text); s.clipboard = Some(f); @@ -200,8 +220,26 @@ pub(crate) fn copy_result(s: &mut Session) -> Value { r } -fn cut(s: &mut Session, v: &Value) -> CmdResult { - let r = copy(s, v)?; +fn cut(s: &mut Session, _: &Value) -> CmdResult { + let whole = super::table::selected_table(s); + let r = copy_with(s, whole.as_ref())?; + // A whole table selected: Cut removes the table, as Delete Table does (#1744). With Track + // Changes on, the cut below marks its text deleted (a tracked cut may become a move). + if !s.doc.settings.track_changes + && let Some(tp) = &whole + { + super::table::delete_table_at(s, tp)?; + super::controls::restore_placeholder(s)?; + return Ok(r); + } + // Whole rows or some cells: their text goes, the rows and cells stay, as in Word. + if whole.is_none() + && let Some(range) = s.cell_range().cloned() + { + super::table::clear_range_cells(s, &range)?; + super::controls::restore_placeholder(s)?; + return Ok(r); + } // A tracked cut of a paragraph or sentence may become a move when pasted. if !super::moves::cut_tracked(s)? { delete_selection(s)?; diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rs index c471ead45e..edaeab194c 100644 --- a/crates/engine/src/cmd/table.rs +++ b/crates/engine/src/cmd/table.rs @@ -20,6 +20,7 @@ pub(super) use cells::grid_cols; pub use cells::selected_cells; use cells::{cell, with_cells, with_table}; pub(crate) use cells::{cell_text, row_ends}; +pub(super) use clear::clear_range_cells; pub(crate) use clear::{backspace_cells, clear_cells}; use clear::{cell_prefix, guard_delete, text_spans}; use convert::{formula, from_text, quick_table, sort_table, to_text}; @@ -31,6 +32,7 @@ use select::{select_cells, select_column}; pub use structure::split_targets; pub(super) use structure::{col, row}; use structure::{del_col, del_row, del_table, merge, split, split_table}; +pub(super) use structure::{delete_table_at, selected_table}; fn in_table(s: &Session) -> Option<&'static str> { if s.sel.focus.path.cell().is_some() { None } else { Some("the cursor isn't in a table") } diff --git a/crates/engine/src/cmd/table/clear.rs b/crates/engine/src/cmd/table/clear.rs index a25bea6b18..2412366050 100644 --- a/crates/engine/src/cmd/table/clear.rs +++ b/crates/engine/src/cmd/table/clear.rs @@ -30,6 +30,30 @@ pub(crate) fn backspace_cells(s: &mut Session) -> Option { Some(r) } +/// Clear the text of the cells `range` selects, leaving the cells (Cut of rows or cells, #1744); +/// tracked when Track Changes is on. The caret goes to the first cell. +pub(in crate::cmd) fn clear_range_cells(s: &mut Session, range: &crate::CellRange) -> Result<(), CmdError> { + let Some(t) = s.doc.table(range.story, &range.table) else { return Ok(()) }; + // The cells Copy takes: columns widened over merged cells, as `Table::slice` does. + let (lo, hi, any) = t.slice_bounds(range.rows, range.cols); + let cells = if any { crate::CellRange { cols: (lo, hi.saturating_sub(1)), ..range.clone() }.cells(t) } else { Vec::new() }; + let prefixes: Vec> = cells.into_iter().map(|(r, c)| cell_prefix(&range.table, r, c)).collect(); + let spans = text_spans(s, range.story, &prefixes); + let first = spans.first().map(|(a, _)| a.clone()); + if guard_delete(s, &spans)?.is_none() { + for (a, b) in spans.iter().rev() { + if a != b { + s.doc.delete_range(a, b)?; + } + } + } + s.column = None; + if let Some(a) = first { + s.sel = Selection::caret(s.doc.clamp(&a)); + } + Ok(()) +} + /// Delete with whole cells selected (#2802): each cell is emptied to one empty paragraph, as in /// Word, nested tables included. That paragraph keeps the formatting of the cell's last one (its /// mark is the end-of-cell mark). `None` without whole cells, and with Track Changes on (the text diff --git a/crates/engine/src/cmd/table/structure.rs b/crates/engine/src/cmd/table/structure.rs index f1818c8daa..bb5e293315 100644 --- a/crates/engine/src/cmd/table/structure.rs +++ b/crates/engine/src/cmd/table/structure.rs @@ -2,6 +2,7 @@ use super::cells::{cell, selected_cells}; use super::clear::{cell_prefix, guard_delete, text_spans}; use super::layout::{fix_caret, sync_cell_widths}; use super::{Block, CmdError, CmdResult, Paragraph, Pos, Selection, Session, Value, json, p, sel_result}; +use wordcraft_doc::Path; /// Insert Above / Below: rows like the caret's, as many as the selection spans; the caret goes into the first. pub(in crate::cmd) fn row(s: &mut Session, below: bool) -> CmdResult { @@ -104,6 +105,25 @@ pub(super) fn del_col(s: &mut Session, _: &Value) -> CmdResult { pub(super) fn del_table(s: &mut Session, _: &Value) -> CmdResult { let (tp, _, _) = cell(s)?; + delete_table_at(s, &tp) +} + +/// The table the selection covers whole (Select Table, a drag over all of it), if it does (#1744). +pub(in crate::cmd) fn selected_table(s: &Session) -> Option { + if let Some(r) = s.cell_range() + && let Some(t) = s.doc.table(r.story, &r.table) + && r.rows == (0, t.rows.len().saturating_sub(1)) + && r.cols == (0, t.cols().saturating_sub(1)) + { + return Some(r.table.clone()); + } + let (a, b) = s.sel.ordered(); + s.doc.whole_table(&a, &b) +} + +/// Delete Table for the table at `tp` (in the selection's story): tracked when Track Changes is on. +pub(in crate::cmd) fn delete_table_at(s: &mut Session, tp: &Path) -> CmdResult { + let tp = tp.clone(); let story = s.sel.focus.story; let spans = text_spans(s, story, std::slice::from_ref(&tp.0)); if let Some(done) = guard_delete(s, &spans)? { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a61b696af5..ab72f5e6be 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1943,6 +1943,291 @@ fn tables_commands() { assert!(s.run("table.merge", &json!({})).is_err()); } +/// A 2×2 table "A1 B1 / A2 B2" after an "Intro" paragraph, the caret in its first cell. +fn table_doc() -> Session { + let mut s = s(); + run(&mut s, "document.setText", json!({"text": "Intro"})); + run(&mut s, "caret.docEnd", json!({})); + run(&mut s, "insert.table", json!({"rows": 2, "cols": 2})); + for (i, t) in ["A1", "B1", "A2", "B2"].iter().enumerate() { + if i > 0 { + run(&mut s, "text.tab", json!({})); + } + run(&mut s, "text.insert", json!({"text": t})); + } + s +} + +fn body_table_cells(s: &Session) -> Vec> { + s.doc + .body + .iter() + .filter_map(|b| b.as_table()) + .map(|t| { + t.rows + .iter() + .flat_map(|r| r.cells.iter()) + .map(|c| c.blocks.iter().filter_map(|b| b.as_para()).map(|p| p.plain_text()).collect::()) + .collect() + }) + .collect() +} + +/// #1744: Select Table → Copy → Paste outside the table pastes a copy of the whole table. +#[test] +fn copy_whole_table_pastes_a_table() { + let mut s = table_doc(); + run(&mut s, "table.selectTable", json!({})); + let r = run(&mut s, "edit.copy", json!({})); + assert!(r["text"].as_str().unwrap().contains("A1\tB1"), "clipboard text is tab separated: {r}"); + assert!(matches!(s.clipboard.as_ref().unwrap().blocks.as_slice(), [wordcraft_doc::Block::Table(_)]), "the copy is the table"); + run(&mut s, "caret.docStart", json!({})); + run(&mut s, "edit.paste", json!({})); + let want = vec!["A1".to_string(), "B1".into(), "A2".into(), "B2".into()]; + assert_eq!(body_table_cells(&s), vec![want.clone(), want]); +} + +/// #1744: Select Table → Cut removes the whole table, and one Undo brings it back. +#[test] +fn cut_whole_table_removes_it_and_undoes() { + let mut s = table_doc(); + run(&mut s, "table.selectTable", json!({})); + run(&mut s, "edit.cut", json!({})); + assert!(body_table_cells(&s).is_empty(), "the table is gone"); + assert!(s.sel.focus.path.cell().is_none(), "the caret left the table"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(body_table_cells(&s), vec![vec!["A1".to_string(), "B1".into(), "A2".into(), "B2".into()]]); + // Paste puts it back as a table. + run(&mut s, "table.selectTable", json!({})); + run(&mut s, "edit.cut", json!({})); + run(&mut s, "edit.paste", json!({})); + assert_eq!(body_table_cells(&s).len(), 1); +} + +/// A 3×3 table "A1 B1 C1 / A2 B2 C2 / A3 B3 C3" after an "Intro" paragraph (#1744). +fn table3_doc() -> Session { + let mut s = s(); + run(&mut s, "document.setText", json!({"text": "Intro"})); + run(&mut s, "caret.docEnd", json!({})); + run(&mut s, "insert.table", json!({"rows": 3, "cols": 3})); + for (i, t) in ["A1", "B1", "C1", "A2", "B2", "C2", "A3", "B3", "C3"].iter().enumerate() { + if i > 0 { + run(&mut s, "text.tab", json!({})); + } + run(&mut s, "text.insert", json!({"text": t})); + } + s +} + +/// Select whole cells of the body's table: rows and grid columns, both inclusive. +fn select_table_cells(s: &mut Session, rows: (usize, usize), cols: (usize, usize)) { + let tp = wordcraft_doc::Path(vec![1]); + crate::cmd::table::select_range(s, StoryRef::Body, &tp, rows, cols).unwrap(); + assert_eq!(s.cell_range().map(|r| (r.rows, r.cols)), Some((rows, cols))); +} + +fn row_cells(texts: &[&str]) -> Vec { + texts.iter().map(|t| t.to_string()).collect() +} + +/// #1744 (Word check A): copying whole rows, two cells of a row, or a block of cells over +/// several rows, then pasting outside the table, pastes a table of just those cells. +#[test] +fn copy_rows_and_cells_pastes_a_table_of_them() { + let full = row_cells(&["A1", "B1", "C1", "A2", "B2", "C2", "A3", "B3", "C3"]); + for (rows, cols, want) in [ + ((1, 1), (0, 2), row_cells(&["A2", "B2", "C2"])), + ((0, 0), (0, 1), row_cells(&["A1", "B1"])), + ((1, 2), (1, 2), row_cells(&["B2", "C2", "B3", "C3"])), + ] { + let mut s = table3_doc(); + select_table_cells(&mut s, rows, cols); + run(&mut s, "edit.copy", json!({})); + let Some([wordcraft_doc::Block::Table(t)]) = s.clipboard.as_ref().map(|f| f.blocks.as_slice()) else { + panic!("{rows:?} {cols:?}: the copy is a table, not {:?}", s.clipboard_text); + }; + assert_eq!(t.rows.len(), rows.1 - rows.0 + 1, "{rows:?} {cols:?}"); + assert_eq!(t.grid.len(), cols.1 - cols.0 + 1, "{rows:?} {cols:?}: the grid has the copied columns"); + run(&mut s, "caret.docStart", json!({})); + run(&mut s, "edit.paste", json!({})); + assert_eq!(body_table_cells(&s), vec![want, full.clone()], "{rows:?} {cols:?}"); + } +} + +/// #1744 (Word check A): Cut of whole rows, or of some cells, clears their text and leaves +/// the rows and cells; the clipboard still gets a table of them. One Undo brings the text back. +#[test] +fn cut_rows_and_cells_clears_their_text() { + let full = row_cells(&["A1", "B1", "C1", "A2", "B2", "C2", "A3", "B3", "C3"]); + for (rows, cols, left, copied) in [ + ((1, 1), (0, 2), row_cells(&["A1", "B1", "C1", "", "", "", "A3", "B3", "C3"]), row_cells(&["A2", "B2", "C2"])), + ((0, 0), (0, 1), row_cells(&["", "", "C1", "A2", "B2", "C2", "A3", "B3", "C3"]), row_cells(&["A1", "B1"])), + ((1, 2), (1, 2), row_cells(&["A1", "B1", "C1", "A2", "", "", "A3", "", ""]), row_cells(&["B2", "C2", "B3", "C3"])), + ] { + let mut s = table3_doc(); + select_table_cells(&mut s, rows, cols); + run(&mut s, "edit.cut", json!({})); + assert_eq!(body_table_cells(&s), vec![left.clone()], "{rows:?} {cols:?}: rows and cells stay"); + assert!(s.sel.is_collapsed(), "{rows:?} {cols:?}"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(body_table_cells(&s), vec![full.clone()], "{rows:?} {cols:?}: one undo step"); + select_table_cells(&mut s, rows, cols); + run(&mut s, "edit.cut", json!({})); + run(&mut s, "caret.docStart", json!({})); + run(&mut s, "edit.paste", json!({})); + assert_eq!(body_table_cells(&s), vec![copied, left], "{rows:?} {cols:?}: the cut pastes as a table"); + } +} + +/// #1744 review: Cut clears every cell Copy takes: a cell merged across the selected columns +/// widens them, so the cell below the merge's second column is copied and cleared too. +#[test] +fn cut_clears_the_cells_a_merged_cell_widens_the_copy_to() { + let mut s = table3_doc(); + select_table_cells(&mut s, (0, 0), (0, 1)); + run(&mut s, "table.merge", json!({})); + select_table_cells(&mut s, (0, 1), (0, 0)); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "edit.cut", json!({})); + let cells = body_table_cells(&s).remove(0); + assert_eq!(cells.len(), 8, "one merged cell and seven others: {cells:?}"); + assert_eq!(cells[1], "C1"); + assert!(cells[2..4].iter().all(String::is_empty), "A2 and B2 are cleared: {cells:?}"); + assert_eq!(cells[4..], ["C2", "A3", "B3", "C3"], "the rest stays"); +} + +/// #1744 review: an empty cell's selection enables Cut but not the Spike, which takes text only. +#[test] +fn spike_stays_disabled_on_an_empty_cell_selection() { + let mut s = s(); + run(&mut s, "document.setText", json!({"text": "Intro"})); + run(&mut s, "caret.docEnd", json!({})); + run(&mut s, "insert.table", json!({"rows": 2, "cols": 2})); + select_table_cells(&mut s, (0, 0), (0, 0)); + let r = s.run("edit.spike", &json!({})); + assert!(matches!(r, Err(crate::CmdError::Disabled(_))), "{r:?}"); +} + +fn clip_is_table(s: &Session) -> bool { + matches!(s.clipboard.as_ref().map(|f| f.blocks.as_slice()), Some([wordcraft_doc::Block::Table(_)])) +} + +/// The body table's cells as they read with every change accepted. +fn body_table_final(s: &Session) -> Vec { + let t = s.doc.body.iter().find_map(|b| b.as_table()).expect("a table"); + t.rows.iter().flat_map(|r| r.cells.iter()).map(|c| c.blocks.iter().filter_map(|b| b.as_para()).map(|p| p.final_text()).collect()).collect() +} + +/// #1744 review: an empty table or cell selected whole still copies, and Cut of the empty +/// table removes it, as in Word. +#[test] +fn copy_and_cut_of_an_empty_table_or_cell() { + let mut s = s(); + run(&mut s, "document.setText", json!({"text": "Intro"})); + run(&mut s, "caret.docEnd", json!({})); + run(&mut s, "insert.table", json!({"rows": 1, "cols": 1})); + run(&mut s, "table.selectTable", json!({})); + run(&mut s, "edit.copy", json!({})); + assert!(clip_is_table(&s), "an empty 1×1 table copies: {:?}", s.clipboard); + run(&mut s, "edit.cut", json!({})); + assert!(body_table_cells(&s).is_empty(), "Cut removes the empty table"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(body_table_cells(&s), vec![vec![String::new()]]); + + let mut s = Session::new(wordcraft_doc::Document::new()); + run(&mut s, "document.setText", json!({"text": "Intro"})); + run(&mut s, "caret.docEnd", json!({})); + run(&mut s, "insert.table", json!({"rows": 2, "cols": 2})); + select_table_cells(&mut s, (0, 0), (0, 0)); + run(&mut s, "edit.copy", json!({})); + assert!(clip_is_table(&s), "an empty cell copies as a one-cell table"); + run(&mut s, "edit.cut", json!({})); + assert_eq!(body_table_cells(&s).len(), 1, "Cut of an empty cell leaves the table"); +} + +/// #1744 review: a text selection over exactly a whole table (no whole-cell record) copies the +/// table; so does one over exactly a table nested in a cell. Other users of the copied range +/// read it as a table too: the selected text is tab separated, a Quick Part saved from it +/// inserts a table. +#[test] +fn text_selection_of_a_whole_table_copies_the_table() { + let mut s = table_doc(); + let at = |path: Vec, off: usize| json!({"story": "body", "path": path, "off": off}); + run(&mut s, "select.range", json!({"anchor": at(vec![1, 0, 0, 0], 0), "focus": at(vec![1, 1, 1, 0], 2)})); + assert!(s.cell_range().is_none(), "a text selection"); + assert_eq!(s.selected_text(), "A1\tB1\nA2\tB2"); + run(&mut s, "edit.copy", json!({})); + assert!(clip_is_table(&s)); + run(&mut s, "insert.quickParts", json!({"save": "grid"})); + run(&mut s, "caret.docStart", json!({})); + run(&mut s, "insert.quickParts", json!({"insert": "grid"})); + assert_eq!(body_table_cells(&s).len(), 2, "the Quick Part is a table"); + + // A table nested in cell A1: selecting its text whole copies just it. + let mut s = table_doc(); + run(&mut s, "select.range", json!({"anchor": at(vec![1, 0, 0, 0], 2), "focus": at(vec![1, 0, 0, 0], 2)})); + run(&mut s, "insert.table", json!({"rows": 2, "cols": 1})); + run(&mut s, "text.insert", json!({"text": "N1"})); + run(&mut s, "text.tab", json!({})); + run(&mut s, "text.insert", json!({"text": "N2"})); + let (inner, _, _) = s.sel.focus.path.cell().unwrap(); + assert_eq!(inner.0.len(), 4, "nested in a cell"); + let first = [inner.0.clone(), vec![0, 0, 0]].concat(); + let last = [inner.0.clone(), vec![1, 0, 0]].concat(); + run(&mut s, "select.range", json!({"anchor": at(first, 0), "focus": at(last, 2)})); + assert!(s.cell_range().is_none(), "a text selection"); + run(&mut s, "edit.copy", json!({})); + let Some([wordcraft_doc::Block::Table(t)]) = s.clipboard.as_ref().map(|f| f.blocks.as_slice()) else { panic!("{:?}", s.clipboard_text) }; + assert_eq!(t.rows.len(), 2, "the nested table, not the outer one"); +} + +/// #1744 review: with Track Changes on, Cut of the whole table or of a row marks the text +/// deleted and keeps the table; one Undo takes the marks back. +#[test] +fn tracked_cut_of_a_table_or_row_marks_text_deleted() { + let full = row_cells(&["A1", "B1", "C1", "A2", "B2", "C2", "A3", "B3", "C3"]); + let mut s = table3_doc(); + s.doc.settings.track_changes = true; + run(&mut s, "table.selectTable", json!({})); + run(&mut s, "edit.cut", json!({})); + assert!(clip_is_table(&s)); + assert_eq!(body_table_cells(&s), vec![full.clone()], "the table and its text stay, marked"); + assert!(body_table_final(&s).iter().all(String::is_empty), "{:?}", body_table_final(&s)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(body_table_final(&s), full); + + select_table_cells(&mut s, (1, 1), (0, 2)); + run(&mut s, "edit.cut", json!({})); + assert!(clip_is_table(&s)); + assert_eq!(body_table_cells(&s), vec![full.clone()]); + assert_eq!(body_table_final(&s), row_cells(&["A1", "B1", "C1", "", "", "", "A3", "B3", "C3"])); + run(&mut s, "edit.undo", json!({})); + assert_eq!(body_table_final(&s), full); +} + +/// #1744 review: Cut of a table, or of cells, holding a content control locked against deletion +/// is refused and changes nothing in the document; the copy is made first, so the clipboard +/// holds the table, as for any refused Cut. +#[test] +fn cut_of_cells_with_a_locked_control_is_refused() { + for whole in [true, false] { + let mut s = table3_doc(); + run(&mut s, "edit.find", json!({"text": "B2"})); + run(&mut s, "developer.richText", json!({"tag": "keep"})); + run(&mut s, "developer.properties", json!({"control": "keep", "lockDelete": true})); + if whole { + run(&mut s, "table.selectTable", json!({})); + } else { + select_table_cells(&mut s, (1, 1), (0, 2)); + } + let before = s.doc.clone(); + assert!(s.run("edit.cut", &json!({})).is_err(), "whole table: {whole}"); + assert_eq!(s.doc, before, "whole table: {whole}"); + assert!(s.status.contains("can't be deleted"), "{}", s.status); + assert!(clip_is_table(&s), "whole table: {whole}"); + } +} + #[test] fn inserting_a_column_keeps_cell_widths_in_step_with_the_grid() { let mut s = s();