Merge remote-tracking branch 'upstream/main' into fix/builtin-styles-bcs-ics-4198

# Conflicts:
#	ROADMAP.md
This commit is contained in:
Oliwer Urbaniak
2026-10-30 02:55:23 +01:00
23 changed files with 1042 additions and 63 deletions
+8 -2
View File
File diff suppressed because one or more lines are too long
+64
View File
@@ -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<Fragment> {
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<Fragment> {
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<Block>) -> 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<Path> {
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<Vec<Path>> = 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<Block> = 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();
+6 -1
View File
@@ -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),
+137
View File
@@ -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::<Vec<_>>(), [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<Vec<usize>> {
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);
+2 -2
View File
@@ -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),
+62
View File
@@ -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#"<w:framePr w:w="0" w:h="0" w:xAlign="left" w:y="0" w:hRule="exact" w:vAnchor="margin"/>"#;
let sized = r#"<w:framePr w:w="2400" w:h="1200" w:x="1440" w:y="2880" w:hAnchor="page" w:vAnchor="page" w:hRule="exact"/>"#;
for frame in [zero, sized] {
let styles = format!(
r#"<w:styles {W_NS}><w:docDefaults><w:pPrDefault><w:pPr>{frame}<w:spacing w:after="160"/></w:pPr></w:pPrDefault></w:docDefaults>
<w:style w:type="paragraph" w:styleId="Framed"><w:name w:val="Framed"/><w:pPr>{sized}</w:pPr></w:style></w:styles>"#
);
let header = format!(r#"<w:hdr {W_NS}><w:p><w:r><w:t>Header alpha</w:t></w:r></w:p><w:p><w:r><w:t>Header beta</w:t></w:r></w:p></w:hdr>"#);
let footer = format!(r#"<w:ftr {W_NS}><w:p><w:r><w:t>Footer delta</w:t></w:r></w:p></w:ftr>"#);
let body = format!(
r#"<w:p><w:r><w:t>Body one</w:t></w:r></w:p>
<w:p><w:pPr>{sized}</w:pPr><w:r><w:t>Direct frame</w:t></w:r></w:p>
<w:p><w:pPr><w:pStyle w:val="Framed"/></w:pPr><w:r><w:t>Styled frame</w:t></w:r></w:p>
<w:p><w:pPr><w:pStyle w:val="Framed"/>{zero}</w:pPr><w:r><w:t>Frame reset</w:t></w:r></w:p>
<w:sectPr><w:headerReference w:type="default" r:id="header"/><w:footerReference w:type="default" r:id="footer"/></w:sectPr>"#
);
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(&paragraph.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#"<w:p><w:pPr><w:framePr {attrs}/></w:pPr><w:r><w:t>Original automatic frame</w:t></w:r></w:p>"#));
let paragraph = paras(&document)[0];
let frame = document.styles.resolve_para(&paragraph.props).frame.unwrap();
assert_eq!((frame.w, frame.h), (width, height));
}
}
#[test]
fn omitted_paragraph_defaults_can_be_edited() {
let styles =
+2
View File
@@ -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)?;
+47 -9
View File
@@ -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<CommandSpec> {
vec![
CommandSpec::new("edit.undo", "Undo", "Quick Access Toolbar", |s, _| {
@@ -63,7 +69,7 @@ pub fn specs() -> Vec<CommandSpec> {
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<CommandSpec> {
}
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)?;
+1 -1
View File
@@ -222,7 +222,7 @@ pub fn specs() -> Vec<CommandSpec> {
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}}"#,
),
]
}
+49 -36
View File
@@ -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<Option<usize>> = (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<Option<usize>> = (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}))
}
+69
View File
@@ -375,6 +375,75 @@ 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<Value> = (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 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.is_empty() => Some(p.text.clone()),
_ => None,
})
.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));
}
}
}
#[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<Value> = (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::<Vec<_>>());
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)
}
+2
View File
@@ -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") }
+24
View File
@@ -30,6 +30,30 @@ pub(crate) fn backspace_cells(s: &mut Session) -> Option<CmdResult> {
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<Vec<u32>> = 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
+20
View File
@@ -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<Path> {
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)? {
+285
View File
@@ -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<Vec<String>> {
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::<String>())
.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<String> {
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<String> {
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<u32>, 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();
+35 -7
View File
@@ -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<f32> {
let ncols = grid_cols(t).max(1);
// Column widths.
let mut grid: Vec<f32> = 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<Vec<(f32, f32)>> {
fn column_content(ctx: &mut Ctx, t: &Table, style: Option<&TableStyleProps>, depth: usize, grid: &[f32]) -> Option<Vec<(f32, f32)>> {
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::<f32>()).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::<f32>());
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))
}
+108
View File
@@ -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.
+5 -2
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+4 -1
View File
@@ -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) |
+4 -1
View File
File diff suppressed because one or more lines are too long
@@ -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:
@@ -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: