diff --git a/crates/docx/src/read/styles.rs b/crates/docx/src/read/styles.rs index 9d47207454..2160dbc1dc 100644 --- a/crates/docx/src/read/styles.rs +++ b/crates/docx/src/read/styles.rs @@ -283,6 +283,15 @@ impl Reader<'_> { } t.fill = tp.child("w:shd").and_then(|e| self.pc.shd_fill(e)); t.cell_margins = tp.child("w:tblCellMar").map(props::margins); + // Only a twips indent (`dxa`, the default) is a length: `nil` is no indent, and `pct` + // or `auto` have no meaning for an indent (ECMA-376 §17.4.50), so the style sets none. + // A `w:w` left out is 0 (`CT_TblWidth`), which still overrides a based-on style's. + t.indent = tp.child("w:tblInd").and_then(|e| match e.attr("w:type").unwrap_or("dxa") { + "dxa" if e.attr("w:w").is_none() => Some(0.0), + "dxa" => tw(e, "w:w").map(|i| i.clamp(-1584.0, 1584.0)), + "nil" => Some(0.0), + _ => None, + }); t.band_size = tp.child_val("w:tblStyleRowBandSize").and_then(u32_of).map(|n| n.min(1000)); t.col_band_size = tp.child_val("w:tblStyleColBandSize").and_then(u32_of).map(|n| n.min(1000)); } diff --git a/crates/docx/src/write/styles.rs b/crates/docx/src/write/styles.rs index 0fddf33b49..4b555b1e27 100644 --- a/crates/docx/src/write/styles.rs +++ b/crates/docx/src/write/styles.rs @@ -1,6 +1,7 @@ use super::{Level, LevelSuffix, ParaProps, Style, StyleKind, TablePart, VAlign, W, Writer, props, xml}; use crate::write::props::open_change; use craft_wordmodel::Document; +use craft_wordmodel::styles::TableStyleParts; /// Built-in names Word keeps in lower case in styles.xml. fn file_style_name(name: &str) -> String { @@ -61,6 +62,31 @@ pub(super) fn styles_xml(wr: &mut Writer<'_>) -> Vec { /// One `w:style` element. A tracked change of its paragraph/run properties is nested in the /// corresponding property element as `w:pPrChange` / `w:rPrChange`. +/// A table style's own table properties (`w:tblPr`), in ECMA-376 order. +fn table_style_tblpr(w: &mut W, t: &TableStyleParts) { + if t.borders.is_none() && t.cell_margins.is_none() && t.indent.is_none() && t.band_size.is_none() && t.col_band_size.is_none() { + return; + } + w.open("w:tblPr", &[]); + if let Some(n) = t.band_size { + w.val("w:tblStyleRowBandSize", &n.min(1000).to_string()); + } + if let Some(n) = t.col_band_size { + w.val("w:tblStyleColBandSize", &n.min(1000).to_string()); + } + // Kept even at 0: Word places a table whose style chain sets no indent differently. + if let Some(i) = t.indent { + w.empty("w:tblInd", &[("w:w", &crate::units::twips(i)), ("w:type", "dxa")]); + } + if let Some(b) = &t.borders { + props::borders(w, "w:tblBorders", b, Some("w:insideH"), &[]); + } + if let Some(m) = &t.cell_margins { + props::margins(w, "w:tblCellMar", m); + } + w.close("w:tblPr"); +} + fn style_xml(wr: &mut Writer<'_>, w: &mut W, st: &Style, flagged: &[StyleKind]) { let ty = match st.kind { StyleKind::Paragraph => "paragraph", @@ -114,22 +140,7 @@ fn style_xml(wr: &mut Writer<'_>, w: &mut W, st: &Style, flagged: &[StyleKind]) } style_property_xml(wr, w, st); if let Some(t) = &st.table { - if t.borders.is_some() || t.cell_margins.is_some() || t.band_size.is_some() || t.col_band_size.is_some() { - w.open("w:tblPr", &[]); - if let Some(n) = t.band_size { - w.val("w:tblStyleRowBandSize", &n.min(1000).to_string()); - } - if let Some(n) = t.col_band_size { - w.val("w:tblStyleColBandSize", &n.min(1000).to_string()); - } - if let Some(b) = &t.borders { - props::borders(w, "w:tblBorders", b, Some("w:insideH"), &[]); - } - if let Some(m) = &t.cell_margins { - props::margins(w, "w:tblCellMar", m); - } - w.close("w:tblPr"); - } + table_style_tblpr(w, t); // The conditional formatting parts (ECMA-376 §17.7.6): paragraph and run properties, // then cell borders, shading and vertical alignment. The whole table's text formatting // is the style's own (above). diff --git a/crates/docx/tests/it/main.rs b/crates/docx/tests/it/main.rs index f55fe7729d..2c44700ec5 100644 --- a/crates/docx/tests/it/main.rs +++ b/crates/docx/tests/it/main.rs @@ -47,6 +47,7 @@ mod section_text_direction; mod section_valign; mod settings_merge; mod strict_drawings; +mod table_style_indent; mod text_alignment; mod text_boxes; mod theme_font_slots; diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 26b318039c..758538e908 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -571,6 +571,7 @@ fn table_style_formatting_round_trips() { borders: Some(Borders { top: Some(Border::single(1.0)), ..Default::default() }), fill: Some(Rgb(0xDD, 0xEB, 0xF7)), cell_margins: Some([1.0, 14.4, 0.0, 14.4]), + indent: Some(0.0), header_chr: CharProps { italic: Some(true), ..Default::default() }, header_fill: Some(Rgb(0xFF, 0xFF, 0)), header_borders: Some(Borders::all(Border::single(1.5))), diff --git a/crates/docx/tests/it/table_style_indent.rs b/crates/docx/tests/it/table_style_indent.rs new file mode 100644 index 0000000000..79e9ea7990 --- /dev/null +++ b/crates/docx/tests/it/table_style_indent.rs @@ -0,0 +1,93 @@ +//! The indent of a table style (`w:tblStyle/w:tblPr/w:tblInd`, ECMA-376 §17.4.50). pandoc's +//! "Table" style sets it to 0; dropped on save, Word for Mac moved every table of a manuscript +//! about 5.4 pt to the right (it places a table whose style chain sets no indent at the margin, +//! but one set to 0 with its first cell's text at the margin). + +use std::io::{Read, Write}; + +fn docx(body: &str, styles: &str) -> Vec { + let root = r#""#; + let doc_rels = r#""#; + let doc = format!( + r#"{body}"# + ); + let styles = format!( + r#"{styles}"# + ); + let parts = [ + ("_rels/.rels", root.to_string()), + ("word/document.xml", doc), + ("word/_rels/document.xml.rels", doc_rels.to_string()), + ("word/styles.xml", styles), + ]; + let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, xml) in &parts { + zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap(); + zw.write_all(xml.as_bytes()).unwrap(); + } + zw.finish().unwrap().into_inner() +} + +fn style_xml(bytes: &[u8], id: &str) -> String { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut s = String::new(); + z.by_name("word/styles.xml").unwrap().read_to_string(&mut s).unwrap(); + let key = format!(r#"w:styleId="{id}""#); + let style = s.split("").next().unwrap_or(style).to_string() +} + +const BODY: &str = r#"Cell"#; + +#[test] +fn a_table_style_indent_of_zero_survives_a_save() { + let styles = r#""#; + let d = craft_docx::read(&docx(BODY, styles)).unwrap(); + let parts = |id: &str| d.styles.get(id).and_then(|s| s.table.clone()).unwrap_or_default(); + assert_eq!(parts("Table").indent, Some(0.0)); + assert_eq!(parts("Indented").indent, Some(36.0)); + assert_eq!(parts("Plain").indent, None, "no w:tblInd stays unset"); + + let out = craft_docx::write(&d).unwrap(); + let table = style_xml(&out, "Table"); + assert!(table.contains(r#""#), "{table}"); + let indented = style_xml(&out, "Indented"); + assert!(indented.contains(r#""#), "{indented}"); + let plain = style_xml(&out, "Plain"); + assert!(!plain.contains("w:tblInd"), "{plain}"); + // ECMA-376 order in w:tblPr: w:tblInd before w:tblCellMar. + assert!(table.find("w:tblInd") < table.find("w:tblCellMar"), "{table}"); +} + +#[test] +fn a_table_style_indent_that_is_no_length_sets_none() { + // `pct` and `auto` are no lengths for an indent; `nil` is none. + let style = |ty: &str| { + format!( + r#""# + ) + }; + for (ty, want) in [("pct", None), ("auto", None), ("nil", Some(0.0)), ("dxa", Some(36.0))] { + let d = craft_docx::read(&docx(BODY, &style(ty))).unwrap(); + let got = d.styles.get("Indented").and_then(|s| s.table.clone()).unwrap_or_default().indent; + assert_eq!(got, want, "w:type={ty}"); + } +} + +#[test] +fn a_table_style_indent_without_a_width_is_zero_and_overrides_its_base() { + // `CT_TblWidth`'s `w:w` defaults to 0, so a based-on style's indent is reset, not inherited. + let styles = r#""#; + let d = craft_docx::read(&docx(BODY, styles)).unwrap(); + let own_of = |d: &craft_wordmodel::Document, id: &str| d.styles.get(id).and_then(|s| s.table.clone()).unwrap_or_default().indent; + let own = |d: &craft_wordmodel::Document| own_of(d, "Indented"); + assert_eq!(own_of(&d, "Base"), Some(36.0), "the base sets an indent to override"); + assert_eq!(d.styles.table_style("Base").map(|s| s.parts.indent), Some(Some(36.0))); + assert_eq!(own(&d), Some(0.0)); + assert_eq!(d.styles.table_style("Indented").map(|s| s.parts.indent), Some(Some(0.0)), "the base's 36 pt is overridden"); + + let out = craft_docx::write(&d).unwrap(); + let indented = style_xml(&out, "Indented"); + assert!(indented.contains(r#""#), "{indented}"); + assert_eq!(own(&craft_docx::read(&out).unwrap()), Some(0.0)); +} diff --git a/crates/wordmodel/src/styles.rs b/crates/wordmodel/src/styles.rs index 1d725efa2a..45883c1f40 100644 --- a/crates/wordmodel/src/styles.rs +++ b/crates/wordmodel/src/styles.rs @@ -69,6 +69,10 @@ pub struct TableStyleParts { pub fill: Option, /// Cell margins, points: [top, left, bottom, right] (`w:tblCellMar`). pub cell_margins: Option<[f32; 4]>, + /// Indent of the table from the leading margin, points (`w:tblInd`). Kept even when 0: + /// Word places a table whose style chain sets no indent differently from one set to 0. + #[serde(skip_serializing_if = "Option::is_none")] + pub indent: Option, pub header_fill: Option, pub header_chr: CharProps, /// Cell borders of the header row (`firstRow` region's `w:tcBorders`): `between` is the @@ -326,6 +330,7 @@ impl TableStyleParts { self.band_chr.overlay(&patch.band_chr); self.fill = patch.fill.or(self.fill); self.cell_margins = patch.cell_margins.or(self.cell_margins); + self.indent = patch.indent.or(self.indent); self.header_fill = patch.header_fill.or(self.header_fill); self.header_chr.overlay(&patch.header_chr); self.band_fill = patch.band_fill.or(self.band_fill);