craft-docx: a table without w:tblGrid takes its grid from its cells, as Word rebuilds it

Template libraries write tables with no w:tblGrid. The reader gave every column an inch, so such a
table came out at the wrong width whatever its cells asked for. Word rebuilds the grid from the
cells on opening: each column as wide as the widest w:tcW among the cells that occupy it alone, a
spanning cell's width shared among the columns no cell sizes, what it still lacks going to its
last column, an inch for a column nothing sizes, never narrower than 26 twips. The rules were
measured on the grids Word saves for synthetic tables. A row after w:gridBefore starts at its
own column.

Moved from storytold/wordcraft#1630, whose reader half had no file left there after #6603.
This commit is contained in:
Daniele Mori committed 2026-11-19 10:55:38 +01:00
1 parent 56c3c833bb
commit befa8fd583
2 files changed
+129 -2

No files matched your search

+55 -2
View File
@@ -416,8 +416,7 @@ impl Reader<'_> {
return None;
}
if table.grid.is_empty() {
let cols = table.cols().clamp(1, MAX_COLS);
table.grid = vec![72.0; cols];
table.grid = grid_from_cells(&table);
}
// The cells' paragraphs, with the run formatting the table style gives each cell (a
// table inside has marked its own).
@@ -436,3 +435,57 @@ 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) {
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 Some(cs) = grid.get_mut(g..(g + span).min(cols)) else { continue };
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
&& 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()
}
+74
View File
@@ -612,6 +612,80 @@ 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]);
}
#[test]
fn styles_numbering_settings_notes_comments_from_parts() {
let styles = format!(