Merge pull request #2192 from Morzilla/docx-grid-from-cells

craft-docx: a table without w:tblGrid takes its grid from its cells, as Word rebuilds it
This commit is contained in:
FredApps
2026-11-20 13:33:59 +07:00
committed by GitHub
2 changed files with 161 additions and 2 deletions
+64 -2
View File
@@ -416,8 +416,8 @@ impl Reader<'_> {
return None;
}
if table.grid.is_empty() {
let cols = table.cols().clamp(1, MAX_COLS);
table.grid = vec![72.0; cols];
// A file with an empty `w:tblGrid` keeps the inch per column it always had.
table.grid = if t.child("w:tblGrid").is_none() { grid_from_cells(&table) } else { vec![72.0; table.cols().clamp(1, MAX_COLS)] };
}
// The cells' paragraphs, with the run formatting the table style gives each cell (a
// table inside has marked its own).
@@ -436,3 +436,65 @@ impl Reader<'_> {
Some(table)
}
}
/// The narrowest column Word rebuilds for a table without `w:tblGrid`: 26 twips, for a cell of
/// 10 twips and for 10 twips left over by a spanning cell alike (measured: Word re-saves both as
/// `w:gridCol w:w="26"`). Content still widens a column when laid out.
const MIN_GRID_COL: f32 = 1.3;
/// The column grid of a table without `w:tblGrid` (a file written by a template library), the
/// way Word rebuilds it on opening: each column as wide as the widest preferred width
/// (`w:tcW` in twips) among the cells that occupy it alone, a spanning cell's width shared out
/// among its columns that no cell sets, what it still lacks going to its last column, and an inch
/// for a column no cell sizes at all; never narrower than [`MIN_GRID_COL`]. Spanning cells are
/// taken from the left, whatever row they are in (measured: Word gives the same grid in any row
/// order, and never narrows a column for a spanning cell).
fn grid_from_cells(table: &Table) -> Vec<f32> {
let cols = table.cols().clamp(1, MAX_COLS);
let mut grid: Vec<Option<f32>> = vec![None; cols];
let mut spanning = Vec::new();
for row in &table.rows {
// After `w:gridBefore` the row's first cell is not in the first column.
let mut g = row.first_grid();
for cell in &row.cells {
let span = cell.span();
if let Some(w) = cell.props.width.filter(|w| w.is_finite() && *w > 0.0) {
// The narrowest column counts before a span shares out what it lacks.
let w = w.max(MIN_GRID_COL);
if span == 1 {
if let Some(slot) = grid.get_mut(g) {
*slot = Some(slot.map_or(w, |cur| cur.max(w)));
}
} else {
spanning.push((g, span, w));
}
}
g += span;
}
}
spanning.sort_by(|a: &(usize, usize, f32), b| (a.0 + a.1, a.0).cmp(&(b.0 + b.1, b.0)).then(a.2.total_cmp(&b.2)));
for (g, span, w) in spanning {
let end = (g + span).min(cols);
let Some(cs) = grid.get_mut(g..end) else { continue };
// A span cut off at the last column the reader keeps sizes only its kept columns, by
// their share of it, and has no last column to give the rest to.
let clipped = end < g + span;
let w = if clipped { w * cs.len() as f32 / span as f32 } else { w };
let known: f32 = cs.iter().flatten().sum();
let unknown = cs.iter().filter(|c| c.is_none()).count();
if unknown > 0 {
let each = ((w - known) / unknown as f32).max(MIN_GRID_COL);
for c in cs.iter_mut().filter(|c| c.is_none()) {
*c = Some(each);
}
}
let lacking = w - cs.iter().flatten().sum::<f32>();
if lacking > 0.0
&& !clipped
&& let Some(Some(last)) = cs.last_mut()
{
*last += lacking;
}
}
grid.into_iter().map(|w| w.unwrap_or(72.0).clamp(MIN_GRID_COL, crate::units::MAX_LEN_PT)).collect()
}
+97
View File
@@ -612,6 +612,103 @@ fn table_look_bitmask_and_legacy_merges() {
assert!(!l.header_row && l.total_row && l.first_column && !l.last_column && !l.banded_rows && l.banded_columns);
}
/// A table without `w:tblGrid` (template libraries leave it out) gets its grid from the cells'
/// preferred widths, as Word rebuilds it on opening: the widest `w:tcW` among the cells that
/// occupy a column alone, a spanning cell's width shared among the columns no cell sizes, and an
/// inch for a column nothing sizes. A row after `w:gridBefore` starts at its own column.
#[test]
fn a_table_without_a_grid_takes_its_columns_from_the_cells() {
let body = r#"
<w:tbl><w:tblPr><w:tblW w:w="5000" w:type="auto"/></w:tblPr>
<w:tr><w:tc><w:tcPr><w:tcW w:w="6000" w:type="dxa"/></w:tcPr><w:p/></w:tc><w:tc><w:tcPr><w:tcW w:w="24000" w:type="dxa"/></w:tcPr><w:p/></w:tc></w:tr>
<w:tr><w:tc><w:tcPr><w:tcW w:w="30000" w:type="dxa"/><w:gridSpan w:val="2"/></w:tcPr><w:p/></w:tc></w:tr>
</w:tbl>
<w:tbl><w:tblPr/>
<w:tr><w:tc><w:tcPr><w:tcW w:w="1000" w:type="dxa"/></w:tcPr><w:p/></w:tc><w:tc><w:tcPr><w:tcW w:w="5000" w:type="dxa"/><w:gridSpan w:val="2"/></w:tcPr><w:p/></w:tc></w:tr>
<w:tr><w:tc><w:p/></w:tc><w:tc><w:p/></w:tc><w:tc><w:p/></w:tc></w:tr>
</w:tbl>
<w:tbl><w:tblPr/><w:tr><w:tc><w:p/></w:tc><w:tc><w:p/></w:tc></w:tr></w:tbl>
<w:tbl><w:tblPr/>
<w:tr><w:tc><w:tcPr><w:tcW w:w="1440" w:type="dxa"/></w:tcPr><w:p/></w:tc><w:tc><w:tcPr><w:tcW w:w="2880" w:type="dxa"/></w:tcPr><w:p/></w:tc></w:tr>
<w:tr><w:trPr><w:gridBefore w:val="1"/></w:trPr><w:tc><w:tcPr><w:tcW w:w="4320" w:type="dxa"/></w:tcPr><w:p/></w:tc></w:tr>
</w:tbl>
<w:tbl><w:tblPr/>
<w:tr><w:tc><w:tcPr><w:tcW w:w="10" w:type="dxa"/></w:tcPr><w:p/></w:tc><w:tc><w:tcPr><w:tcW w:w="3000" w:type="dxa"/></w:tcPr><w:p/></w:tc></w:tr>
</w:tbl>
<w:p/>"#;
let d = read_body(body);
let Block::Table(t) = &*d.body[0] else { panic!() };
assert_eq!(t.grid, vec![300.0, 1200.0]);
let Block::Table(t) = &*d.body[1] else { panic!() };
assert_eq!(t.grid, vec![50.0, 125.0, 125.0]);
let Block::Table(t) = &*d.body[2] else { panic!() };
assert_eq!(t.grid, vec![72.0, 72.0]);
// A row after `w:gridBefore` starts at its own column: its cell sizes the second one.
let Block::Table(t) = &*d.body[3] else { panic!() };
assert_eq!(t.grid, vec![72.0, 216.0]);
// A tiny width is kept down to Word's narrowest column, 26 twips (measured), not 4 pt.
let Block::Table(t) = &*d.body[4] else { panic!() };
assert_eq!(t.grid, vec![1.3, 150.0]);
}
/// Spanning cells of a table without `w:tblGrid`, against the grid Word saves for the same cells
/// (points; Word also merges columns no cell edge separates, which draws the same).
#[test]
fn spanning_cells_size_a_gridless_table_as_in_word() {
let tc = |w: u32, span: u32| format!(r#"<w:tc><w:tcPr><w:tcW w:w="{}" w:type="dxa"/><w:gridSpan w:val="{span}"/></w:tcPr><w:p/></w:tc>"#, w * 20);
let grid = |rows: &[&[(u32, u32)]]| {
let rows: String = rows.iter().map(|r| format!("<w:tr>{}</w:tr>", r.iter().map(|&(w, s)| tc(w, s)).collect::<String>())).collect();
let d = read_body(&format!("<w:tbl><w:tblPr/>{rows}</w:tbl><w:p/>"));
let Block::Table(t) = &*d.body[0] else { panic!() };
t.grid.clone()
};
// What a span lacks goes to its last column, in whichever order the rows come.
assert_eq!(grid(&[&[(100, 1), (100, 1)], &[(300, 2)]]), [100.0, 200.0]);
assert_eq!(grid(&[&[(300, 2)], &[(100, 1), (100, 1)]]), [100.0, 200.0]);
assert_eq!(grid(&[&[(50, 1), (50, 1)], &[(300, 2)], &[(50, 1), (70, 1)]]), [50.0, 250.0]);
// The widest of several spans over the same columns decides (Word: one column, 300).
assert_eq!(grid(&[&[(100, 2)], &[(300, 2)]]).iter().sum::<f32>(), 300.0);
assert_eq!(grid(&[&[(300, 2)], &[(100, 2)]]), grid(&[&[(100, 2)], &[(300, 2)]]));
assert_eq!(grid(&[&[(100, 2), (100, 1)], &[(300, 2), (100, 1)]]).iter().sum::<f32>(), 400.0);
// Overlapping spans are taken from the left.
assert_eq!(grid(&[&[(100, 2), (100, 1)], &[(50, 1), (300, 2)]]), [50.0, 50.0, 250.0]);
assert_eq!(grid(&[&[(100, 2), (100, 2)], &[(40, 1), (200, 2), (40, 1)]]), [40.0, 60.0, 140.0, 40.0]);
assert_eq!(grid(&[&[(40, 1), (200, 2), (40, 1)], &[(100, 2), (100, 2)]]), [40.0, 60.0, 140.0, 40.0]);
assert_eq!(grid(&[&[(300, 3)], &[(100, 2), (50, 1)], &[(30, 1), (30, 1), (30, 1)]]), [30.0, 70.0, 200.0]);
// A span narrower than its columns narrows nothing.
assert_eq!(grid(&[&[(100, 1), (100, 1)], &[(50, 2)]]), [100.0, 100.0]);
// A span past the last column, and a width that means nothing, break nothing.
assert!((grid(&[&[(100, 1), (100, 1)], &[(500, 9)]]).iter().sum::<f32>() - 500.0).abs() < 0.01);
let d = read_body(
r#"<w:tbl><w:tblPr/><w:tr><w:tc><w:tcPr><w:tcW w:w="NaN" w:type="dxa"/></w:tcPr><w:p/></w:tc><w:tc><w:tcPr><w:tcW w:w="-40" w:type="dxa"/></w:tcPr><w:p/></w:tc></w:tr></w:tbl><w:p/>"#,
);
let Block::Table(t) = &*d.body[0] else { panic!() };
assert_eq!(t.grid, vec![72.0, 72.0]);
// An empty `w:tblGrid` is a grid all the same: the columns keep their inch.
let d =
read_body(r#"<w:tbl><w:tblPr/><w:tblGrid/><w:tr><w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr><w:p/></w:tc></w:tr></w:tbl><w:p/>"#);
let Block::Table(t) = &*d.body[0] else { panic!() };
assert_eq!(t.grid, vec![72.0]);
// The narrowest column counts before a span shares out what it lacks: the span keeps its width.
let d = read_body(
r#"<w:tbl><w:tblPr/><w:tr><w:tc><w:tcPr><w:tcW w:w="10" w:type="dxa"/></w:tcPr><w:p/></w:tc><w:tc><w:p/></w:tc></w:tr><w:tr><w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/><w:gridSpan w:val="2"/></w:tcPr><w:p/></w:tc></w:tr></w:tbl><w:p/>"#,
);
let Block::Table(t) = &*d.body[0] else { panic!() };
assert_eq!(t.grid[0], 1.3);
assert!((t.grid.iter().sum::<f32>() - 100.0).abs() < 0.01, "{:?}", t.grid);
// A span cut off at the last column kept gives the rest to no other column.
let ones = tc(20, 1).repeat(62);
let d = read_body(&format!("<w:tbl><w:tblPr/><w:tr>{ones}{}</w:tr><w:tr>{ones}{}</w:tr></w:tbl><w:p/>", tc(50, 1), tc(300, 2)));
let Block::Table(t) = &*d.body[0] else { panic!() };
assert_eq!(t.grid.len(), 63);
assert_eq!(t.grid[62], 50.0);
// With no width of its own there, the kept column takes its share of the span, not all of it.
let d = read_body(&format!("<w:tbl><w:tblPr/><w:tr>{ones}</w:tr><w:tr>{ones}{}</w:tr></w:tbl><w:p/>", tc(300, 2)));
let Block::Table(t) = &*d.body[0] else { panic!() };
assert_eq!(t.grid.len(), 63);
assert_eq!(t.grid[62], 150.0);
}
#[test]
fn styles_numbering_settings_notes_comments_from_parts() {
let styles = format!(