From 12a840f6539dfd6b174b2163b9310bea3042b7aa Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Thu, 5 Nov 2026 02:14:03 -0600 Subject: [PATCH] Preserve section settings when saving DOCX (#5311) * DOCX: preserve section print and note settings * docs: record chapter style byte range * fix: accept XML integer syntax for tray codes * fix: preserve automatic footnote columns --- Cargo.lock | 1 + ROADMAP.md | 2 + crates/doc/src/section.rs | 50 ++++++++++++++ crates/docx/Cargo.toml | 1 + crates/docx/src/read/props.rs | 18 +++++ crates/docx/src/write/story/section.rs | 53 ++++++++++++--- crates/docx/tests/it/main.rs | 1 + .../tests/it/section_metadata_preservation.rs | 66 +++++++++++++++++++ docs/file-format-parity.md | 3 + docs/gaps.md | 2 + 10 files changed, 189 insertions(+), 8 deletions(-) create mode 100644 crates/docx/tests/it/section_metadata_preservation.rs diff --git a/Cargo.lock b/Cargo.lock index 666b2a033f..64ed59e285 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6880,6 +6880,7 @@ dependencies = [ "log", "proptest", "quick-xml 0.41.0", + "serde_json", "sha1 0.11.0", "sha2 0.11.1", "thiserror 2.0.21", diff --git a/ROADMAP.md b/ROADMAP.md index d285bad32a..60c01c8cac 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -758,6 +758,8 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target Footer page-table height and body wrapping are corrected. Other pagination gaps remain open. +Section page-numbering settings preserve `w:chapStyle` values across the full unsigned-byte range. + ## Revision history > 2026-11-03 · Arabic dialogs read right to left (rtl::Table); recorded in the progress log, readiness unchanged. diff --git a/crates/doc/src/section.rs b/crates/doc/src/section.rs index 7541c35d02..1d72468f6f 100644 --- a/crates/doc/src/section.rs +++ b/crates/doc/src/section.rs @@ -115,6 +115,40 @@ pub enum NumFormat { DollarText, } +/// Chapter separator for page numbers (`w:chapSep`, ECMA-376 §17.18.12). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ChapterSep { + Hyphen, + Period, + Colon, + EmDash, + EnDash, +} + +impl ChapterSep { + pub fn from_ooxml(value: &str) -> Option { + match value { + "hyphen" => Some(Self::Hyphen), + "period" => Some(Self::Period), + "colon" => Some(Self::Colon), + "emDash" => Some(Self::EmDash), + "enDash" => Some(Self::EnDash), + _ => None, + } + } + + pub const fn ooxml(self) -> &'static str { + match self { + Self::Hyphen => "hyphen", + Self::Period => "period", + Self::Colon => "colon", + Self::EmDash => "emDash", + Self::EnDash => "enDash", + } + } +} + impl NumFormat { /// Every format, in the order ST_NumberFormat lists them (which is also the order of the /// binary .doc number format codes up to 0x27). @@ -749,6 +783,9 @@ pub struct SectionProps { pub title_page: bool, pub page_num_start: Option, pub page_num_format: NumFormat, + /// Chapter heading level and separator in `w:pgNumType`. + pub chapter_style: Option, + pub chapter_sep: Option, /// The file carries a `w:pgNumType` element that sets nothing else (no start, decimal /// format), so saving writes it back rather than dropping it. #[serde(skip_serializing_if = "std::ops::Not::not")] @@ -779,6 +816,13 @@ pub struct SectionProps { pub footnote_pr: NoteProps, #[serde(skip_serializing_if = "NoteProps::is_empty")] pub endnote_pr: NoteProps, + /// First-page and other-page printer trays (`w:paperSrc`). + pub paper_src_first: Option, + pub paper_src_other: Option, + /// Section-specific suppression of endnotes (`w:noEndnote`). + pub no_endnote: Option, + /// Independent footnote column count (`w15:footnoteColumns`). + pub footnote_columns: Option, /// Whether its columns end balanced (an ODF section's `text:dont-balance-text-columns`): /// `None` is Word's rule, balanced when a continuous section follows; `Some(true)` also at /// the end of the document, `Some(false)` never. @@ -809,6 +853,8 @@ impl Default for SectionProps { title_page: false, page_num_start: None, page_num_format: NumFormat::Decimal, + chapter_style: None, + chapter_sep: None, page_num_set: false, line_numbers: None, valign: PageVAlign::Top, @@ -821,6 +867,10 @@ impl Default for SectionProps { doc_grid: None, footnote_pr: NoteProps::default(), endnote_pr: NoteProps::default(), + paper_src_first: None, + paper_src_other: None, + no_endnote: None, + footnote_columns: None, balance_columns: None, } } diff --git a/crates/docx/Cargo.toml b/crates/docx/Cargo.toml index 5e16d7e4c2..6f7f1b3860 100644 --- a/crates/docx/Cargo.toml +++ b/crates/docx/Cargo.toml @@ -32,6 +32,7 @@ getrandom = { workspace = true, features = ["wasm_js"] } [dev-dependencies] wordcraft-doc = { workspace = true, features = ["test-support"] } +serde_json = { workspace = true } proptest = { workspace = true } image = { workspace = true } zip = { workspace = true } diff --git a/crates/docx/src/read/props.rs b/crates/docx/src/read/props.rs index 5aa683f9c0..12a15dad10 100644 --- a/crates/docx/src/read/props.rs +++ b/crates/docx/src/read/props.rs @@ -763,8 +763,26 @@ pub fn sectpr(pc: &PropCtx, e: &El) -> (SectionProps, Vec) { if let Some(f) = k.attr("w:fmt") { s.page_num_format = NumFormat::from_ooxml(f); } + s.chapter_style = k.attr("w:chapStyle").and_then(u32_of).filter(|v| *v <= u8::MAX as u32).map(|v| v as u8); + s.chapter_sep = k.attr("w:chapSep").and_then(wordcraft_doc::section::ChapterSep::from_ooxml); s.page_num_set = s.page_num_start.is_none() && s.page_num_format == NumFormat::Decimal; } + "w:paperSrc" => { + let tray = |name| { + let value = k.attr(name)?.trim(); + let digits = value.strip_prefix('+').unwrap_or(value); + if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + u32_of(digits).filter(|v| *v <= u16::MAX as u32).map(|v| v as u16) + }; + s.paper_src_first = tray("w:first"); + s.paper_src_other = tray("w:other"); + } + "w:noEndnote" => s.no_endnote = Some(on_off(k)), + "w15:footnoteColumns" => { + s.footnote_columns = k.attr("w:val").and_then(u32_of).filter(|v| (1..=45).contains(v)); + } "w:lnNumType" => { let mut l = LineNumbering::default(); if let Some(v) = k.attr("w:countBy").and_then(u32_of) { diff --git a/crates/docx/src/write/story/section.rs b/crates/docx/src/write/story/section.rs index e9712ddcc5..f08377ba72 100644 --- a/crates/docx/src/write/story/section.rs +++ b/crates/docx/src/write/story/section.rs @@ -87,6 +87,7 @@ fn sectpr_body(w: &mut W, s: &SectionProps) { ("w:gutter", &twips(s.gutter.max(0.0))), ], ); + paper_source(w, s); if let Some(b) = &s.page_borders { borders(w, "w:pgBorders", b, None, &[("w:offsetFrom", "text")]); } @@ -107,14 +108,7 @@ fn sectpr_body(w: &mut W, s: &SectionProps) { let refs: Vec<(&str, &str)> = a.iter().map(|(k, v)| (*k, v.as_str())).collect(); w.empty("w:lnNumType", &refs); } - if s.page_num_set || s.page_num_start.is_some() || s.page_num_format != wordcraft_doc::section::NumFormat::Decimal { - let mut a = vec![("w:fmt", s.page_num_format.ooxml().to_string())]; - if let Some(st) = s.page_num_start { - a.push(("w:start", st.to_string())); - } - let refs: Vec<(&str, &str)> = a.iter().map(|(k, v)| (*k, v.as_str())).collect(); - w.empty("w:pgNumType", &refs); - } + page_number_type(w, s); let c = &s.columns; let count = c.count.clamp(1, 45); let mut ca = vec![("w:space", twips(c.space.max(0.0))), ("w:num", n(count as i64))]; @@ -134,6 +128,9 @@ fn sectpr_body(w: &mut W, s: &SectionProps) { let refs: Vec<(&str, &str)> = ca.iter().map(|(k, v)| (*k, v.as_str())).collect(); w.empty("w:cols", &refs); } + if let Some(count) = s.footnote_columns.filter(|count| *count > 0) { + w.empty("w15:footnoteColumns", &[("w:val", &count.clamp(1, 45).to_string())]); + } if let Some(on) = s.form_prot { w.empty("w:formProt", if on { &[] } else { &[("w:val", "0")] }); } @@ -143,6 +140,9 @@ fn sectpr_body(w: &mut W, s: &SectionProps) { wordcraft_doc::section::PageVAlign::Justify => w.val("w:vAlign", "both"), wordcraft_doc::section::PageVAlign::Bottom => w.val("w:vAlign", "bottom"), } + if let Some(on) = s.no_endnote { + w.empty("w:noEndnote", if on { &[] } else { &[("w:val", "0")] }); + } if s.title_page { w.empty("w:titlePg", &[]); } @@ -167,6 +167,43 @@ fn sectpr_body(w: &mut W, s: &SectionProps) { } } +fn paper_source(w: &mut W, s: &SectionProps) { + let mut attrs = Vec::new(); + if let Some(first) = s.paper_src_first { + attrs.push(("w:first", first.to_string())); + } + if let Some(other) = s.paper_src_other { + attrs.push(("w:other", other.to_string())); + } + if !attrs.is_empty() { + let refs: Vec<(&str, &str)> = attrs.iter().map(|(k, v)| (*k, v.as_str())).collect(); + w.empty("w:paperSrc", &refs); + } +} + +fn page_number_type(w: &mut W, s: &SectionProps) { + if !(s.page_num_set + || s.page_num_start.is_some() + || s.page_num_format != wordcraft_doc::section::NumFormat::Decimal + || s.chapter_style.is_some() + || s.chapter_sep.is_some()) + { + return; + } + let mut attrs = vec![("w:fmt", s.page_num_format.ooxml().to_string())]; + if let Some(start) = s.page_num_start { + attrs.push(("w:start", start.to_string())); + } + if let Some(style) = s.chapter_style { + attrs.push(("w:chapStyle", style.to_string())); + } + if let Some(separator) = s.chapter_sep { + attrs.push(("w:chapSep", separator.ooxml().to_string())); + } + let refs: Vec<(&str, &str)> = attrs.iter().map(|(k, v)| (*k, v.as_str())).collect(); + w.empty("w:pgNumType", &refs); +} + /// The children of a `w:footnotePr` / `w:endnotePr` in schema order (`w:pos`, `w:numFmt`, /// `w:numStart`, `w:numRestart`; ECMA-376 §17.11.11), for the fields that are set. pub(in super::super) fn note_pr_inner(w: &mut W, pr: &NoteProps) { diff --git a/crates/docx/tests/it/main.rs b/crates/docx/tests/it/main.rs index b6c60dcce3..e54afbd5f5 100644 --- a/crates/docx/tests/it/main.rs +++ b/crates/docx/tests/it/main.rs @@ -29,6 +29,7 @@ mod roundtrip; mod row_property_exceptions; mod run_props; mod section_form_protection; +mod section_metadata_preservation; mod section_page_number_type; mod section_text_direction; mod section_valign; diff --git a/crates/docx/tests/it/section_metadata_preservation.rs b/crates/docx/tests/it/section_metadata_preservation.rs new file mode 100644 index 0000000000..c3b10fe8c8 --- /dev/null +++ b/crates/docx/tests/it/section_metadata_preservation.rs @@ -0,0 +1,66 @@ +//! Section printer, note and chapter-number metadata survives DOCX and native JSON saves. + +use std::io::{Read, Write}; + +fn docx(body: &str) -> Vec { + let root = r#""#; + let doc = format!( + r#"{body}"# + ); + let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] { + zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + zw.write_all(bytes).unwrap(); + } + zw.finish().unwrap().into_inner() +} + +fn document_xml(bytes: &[u8]) -> String { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut s = String::new(); + z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap(); + s +} + +#[test] +fn section_metadata_survives_native_json_and_two_docx_save_reopen_cycles() { + let input = docx( + r#"First sectionSecond section"#, + ); + let mut document = wordcraft_docx::read(&input).unwrap(); + let json = serde_json::to_vec(&document).unwrap(); + document = serde_json::from_slice(&json).unwrap(); + for cycle in 0..2 { + let bytes = wordcraft_docx::write(&document).unwrap(); + let xml = document_xml(&bytes); + assert!(xml.contains(r#""#), "cycle {cycle}: {xml}"); + assert!(xml.contains(r#""#), "cycle {cycle}: {xml}"); + assert!(xml.contains(""), "cycle {cycle}: {xml}"); + assert!(xml.contains(r#""#), "cycle {cycle}: {xml}"); + assert!(xml.contains(r#""#), "cycle {cycle}: {xml}"); + assert!(xml.contains(r#""#), "cycle {cycle}: {xml}"); + assert!(xml.contains(r#"w:chapStyle="1" w:chapSep="hyphen""#), "cycle {cycle}: {xml}"); + assert!(xml.contains(r#"w:chapStyle="10" w:chapSep="colon""#), "cycle {cycle}: {xml}"); + assert!(xml.contains("xmlns:w15=") && xml.contains("mc:Ignorable=\"w14 w15 wp14\""), "cycle {cycle}: {xml}"); + document = wordcraft_docx::read(&bytes).unwrap(); + let json = serde_json::to_vec(&document).unwrap(); + document = serde_json::from_slice(&json).unwrap(); + } +} + +#[test] +fn invalid_section_metadata_is_ignored_and_missing_values_stay_missing() { + let bytes = docx( + r#"Text"#, + ); + let mut d = wordcraft_docx::read(&bytes).unwrap(); + let xml = document_xml(&wordcraft_docx::write(&d).unwrap()); + assert!(!xml.contains("paperSrc"), "{xml}"); + assert!(!xml.contains("footnoteColumns"), "{xml}"); + assert!(!xml.contains("chapStyle") && !xml.contains("chapSep"), "{xml}"); + assert!(!xml.contains("noEndnote"), "{xml}"); + + d.last_section.footnote_columns = Some(0); + let xml = document_xml(&wordcraft_docx::write(&d).unwrap()); + assert!(!xml.contains("footnoteColumns"), "{xml}"); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 5c8fc85609..8f1df33cb5 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -289,6 +289,9 @@ Table rows and cells inside `mc:AlternateContent` use the same selected-branch p ## Revision history +> 2026-11-03 · Section `w:chapStyle` values preserve the full unsigned-byte range, including 10, while values above 255 are rejected. + +| 2026-10-30 | trivial | DOCX section metadata now preserves independent printer trays, section endnote suppression, chapter numbering settings, and footnote columns through native JSON and repeated save/reopen | > 2026-10-28 · Charts and SmartArt: text the font lacks (Chinese axis labels and legends) is drawn in a fallback face instead of boxes, one face per run as in body text (#4720, `layout::tests::chart_text_the_font_lacks_is_drawn_in_a_fallback_face`). > 2026-10-25 · 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`). diff --git a/docs/gaps.md b/docs/gaps.md index d1ea35ebc2..b8f97f22c8 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -150,6 +150,8 @@ Table rows and cells inside `mc:AlternateContent` use the same selected-branch p ## Revision history +> 2026-11-03 · Section `w:chapStyle` values now preserve the complete unsigned-byte range, including 10; values above 255 are rejected. + > 2026-11-03 · Gap 11: the Arabic dialogs, tables and galleries read right to left (rtl::Table); readiness unchanged. > > 2026-10-27 · Technical synchronization: existing Proofing pane hooks and regression tests follow the extracted engine/UI modules on main `436d444`; compact context menus remain upstream. New-SHA validation is pending; readiness unchanged.