From a12bea6ada6b01f86c2a0f47a26cf5416a88109f Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Tue, 24 Nov 2026 21:08:17 +0530 Subject: [PATCH 1/7] fix(docx): preserve absent compatibilityMode and hyperlink history (#3308, #3305) - Fix #3308: Represent absent compatibilityMode as Option (None = omitted). Do not synthesize or empty when omitted from input. In merged settings, support removing compatibilityMode across paired tags, alternate quotes, whitespace, and foreign vendor elements. - Fix #3305: Retain authored presence and boolean value of w:history on (Option) from read to write, defaulting newly authored links to 1. - Add comprehensive unit and integration tests across craft-docx, craft-wordmodel, and craft-doc-binary. --- crates/doc-binary/src/lib.rs | 4 +- crates/doc-binary/src/tests.rs | 2 +- crates/docx/src/read.rs | 3 +- crates/docx/src/read/meta.rs | 2 +- crates/docx/src/read/story.rs | 1 + crates/docx/src/read/story/runs.rs | 11 +- crates/docx/src/write/settings.rs | 13 +- crates/docx/src/write/settings_merge.rs | 111 +++++++++++++-- crates/docx/src/write/story/para.rs | 22 ++- crates/docx/tests/it/fixtures.rs | 20 +-- crates/docx/tests/it/picture_links.rs | 2 +- crates/docx/tests/it/roundtrip.rs | 168 ++++++++++++++++++++++- crates/docx/tests/it/settings_merge.rs | 31 +++++ crates/wordmodel/src/props/char_props.rs | 12 +- crates/wordmodel/src/settings.rs | 15 +- crates/wordmodel/src/tests.rs | 21 +++ 16 files changed, 392 insertions(+), 46 deletions(-) diff --git a/crates/doc-binary/src/lib.rs b/crates/doc-binary/src/lib.rs index b8c1c5c468..770376f0d1 100644 --- a/crates/doc-binary/src/lib.rs +++ b/crates/doc-binary/src/lib.rs @@ -283,7 +283,7 @@ fn read_limited(bytes: &[u8], password: Option<&str>, max_paragraphs: usize) -> let mut doc = Document::new(); // Word opens Word 97-2003 files in compatibility mode 11 (Word 2003); the model's default // 15 would apply Word 2013+ justification and line-breaking rules to them. - doc.settings.compat_mode = 11; + doc.settings.compat_mode = Some(11); if let Some(core) = metadata::read(&comp) { doc.core = core; } @@ -455,7 +455,7 @@ fn read_word6(comp: &craft_cfb::CompoundFile<'_>, word: &[u8], max_paragraphs: u let content = word6::content(word, &fib)?; let mut doc = Document::new(); // Word opens these files in compatibility mode 11 too. - doc.settings.compat_mode = 11; + doc.settings.compat_mode = Some(11); if let Some(core) = metadata::read(comp) { doc.core = core; } diff --git a/crates/doc-binary/src/tests.rs b/crates/doc-binary/src/tests.rs index 8c1025eb27..2f380ca84a 100644 --- a/crates/doc-binary/src/tests.rs +++ b/crates/doc-binary/src/tests.rs @@ -347,7 +347,7 @@ fn a_doc_opens_in_word_97_2003_compatibility_mode() { let doc = read(&f).expect("opens"); // Word 97-2003 files are mode 11 in Word 2013+; mode 15 would change justification and // line breaking. - assert_eq!(doc.settings.compat_mode, 11); + assert_eq!(doc.settings.compat_mode, Some(11)); } #[test] diff --git a/crates/docx/src/read.rs b/crates/docx/src/read.rs index 18c9ea47a0..a563e755e1 100644 --- a/crates/docx/src/read.rs +++ b/crates/docx/src/read.rs @@ -254,7 +254,8 @@ fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize, lenient("numbering", r.read_numbering(&p)); } // Without a stated mode (or settings at all) Word lays a document out as Word 2007 did. - r.doc.settings.compat_mode = craft_wordmodel::LEGACY_COMPAT_MODE; + // Retain `compat_mode` as `None` when omitted from the source file to preserve XML fidelity on save (#3308). + r.doc.settings.compat_mode = None; if let Some(p) = part(rt::SETTINGS) { lenient("settings", r.read_settings(&p)); } diff --git a/crates/docx/src/read/meta.rs b/crates/docx/src/read/meta.rs index 9cc23be27c..8855d87229 100644 --- a/crates/docx/src/read/meta.rs +++ b/crates/docx/src/read/meta.rs @@ -45,7 +45,7 @@ impl Reader<'_> { }) .and_then(|c| c.attr("w:val")); if let Some(m) = mode.and_then(u32_of) { - s.compat_mode = m.clamp(11, 99); + s.compat_mode = Some(m.clamp(11, 99)); } s.sum_paragraph_spacing = k.children("w:doNotUseHTMLParagraphAutoSpacing").any(on_off); s.do_not_expand_shift_return = k.children("w:doNotExpandShiftReturn").any(on_off); diff --git a/crates/docx/src/read/story.rs b/crates/docx/src/read/story.rs index 9b5b04300a..c0b98aa917 100644 --- a/crates/docx/src/read/story.rs +++ b/crates/docx/src/read/story.rs @@ -49,6 +49,7 @@ const MAX_FORM: usize = 64 * 1024; pub struct RunCtx { link: Option, link_tooltip: Option>, + link_history: Option, ins: Option, del: Option, } diff --git a/crates/docx/src/read/story/runs.rs b/crates/docx/src/read/story/runs.rs index 0c8b699949..47e1ef36e3 100644 --- a/crates/docx/src/read/story/runs.rs +++ b/crates/docx/src/read/story/runs.rs @@ -32,6 +32,7 @@ impl Reader<'_> { if let Some(link) = link { c.link = Some(link); c.link_tooltip = k.attr("w:tooltip").and_then(crate::bounded_link_tooltip).map(std::sync::Arc::from); + c.link_history = k.attr("w:history").map(|v| !matches!(v, "0" | "false" | "off")); } self.read_inline_children(sc, pb, k, rels, &c, depth + 1); } @@ -138,6 +139,7 @@ impl Reader<'_> { let mut p = self.pc.rpr(rpr); p.link = ctx.link.clone(); p.link_tooltip = ctx.link_tooltip.clone(); + p.link_history = ctx.link_history; p.ins = ctx.ins; p.del = ctx.del; p.fmt_change = self.rpr_change(rpr); @@ -145,7 +147,14 @@ impl Reader<'_> { } fn run_props_none(&self, ctx: &RunCtx) -> CharProps { - CharProps { link: ctx.link.clone(), link_tooltip: ctx.link_tooltip.clone(), ins: ctx.ins, del: ctx.del, ..Default::default() } + CharProps { + link: ctx.link.clone(), + link_tooltip: ctx.link_tooltip.clone(), + link_history: ctx.link_history, + ins: ctx.ins, + del: ctx.del, + ..Default::default() + } } fn read_run(&mut self, sc: &mut StoryCtx, pb: &mut PB, r: &El, rels: &Rels, ctx: &RunCtx, depth: usize) { diff --git a/crates/docx/src/write/settings.rs b/crates/docx/src/write/settings.rs index 2d97e4a01c..6458f05f84 100644 --- a/crates/docx/src/write/settings.rs +++ b/crates/docx/src/write/settings.rs @@ -144,6 +144,13 @@ fn write_note_settings( } fn write_compatibility_settings(w: &mut W, doc: &Document) { + let has_compat = doc.settings.do_not_expand_shift_return + || doc.settings.sum_paragraph_spacing + || doc.settings.allow_space_of_same_style_in_table + || doc.settings.compat_mode.is_some(); + if !has_compat { + return; + } w.open("w:compat", &[]); // CT_Compat: the older switches come before the `w:compatSetting`s. if doc.settings.do_not_expand_shift_return { @@ -155,8 +162,10 @@ fn write_compatibility_settings(w: &mut W, doc: &Document) { if doc.settings.allow_space_of_same_style_in_table { w.empty("w:allowSpaceOfSameStyleInTable", &[]); } - let mode = doc.settings.compat_mode.clamp(11, 15).to_string(); - w.empty("w:compatSetting", &[("w:name", "compatibilityMode"), ("w:uri", "http://schemas.microsoft.com/office/word"), ("w:val", &mode)]); + if let Some(mode) = doc.settings.compat_mode { + let mode = mode.clamp(11, 15).to_string(); + w.empty("w:compatSetting", &[("w:name", "compatibilityMode"), ("w:uri", "http://schemas.microsoft.com/office/word"), ("w:val", &mode)]); + } w.close("w:compat"); } diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index 6add6f0ebb..c8ff49b4d3 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -230,16 +230,74 @@ fn children(xml: &str, root: &str) -> Option<(usize, usize, Vec)> { Some((open_end, close, out)) } -/// The original `w:compat` with its `compatibilityMode` taken from the generated one. -fn merge_compat(orig: &str, generated: &str) -> Option { +const WML: &[u8] = b"http://schemas.openxmlformats.org/wordprocessingml/2006/main"; +const WML_STRICT: &[u8] = b"http://purl.oclc.org/ooxml/wordprocessingml/main"; + +/// The original `w:compat` with its `compatibilityMode` taken from the generated one, +/// or removed if the generated settings omit it. +fn merge_compat(root_tag: &str, orig: &str, generated: &str) -> Option { let mode = |s: &str| -> Option<(usize, usize)> { - let at = s.find("w:name=\"compatibilityMode\"")?; - let tag_start = s.get(..at)?.rfind('<')?; - let tag_end = tag_start + s.get(tag_start..)?.find('>')? + 1; - Some((tag_start, tag_end)) + let (_, _, kids) = children(s, "w:compat")?; + let root = if root_tag.starts_with('<') { + root_tag + } else { + r#""# + }; + for k in kids { + let child_str = s.get(k.start..k.end)?; + let mut xml = String::with_capacity(root.len() + child_str.len() + 16); + xml.push_str(root); + xml.push_str(child_str); + xml.push_str(""); + let mut reader = quick_xml::NsReader::from_str(&xml); + loop { + match reader.read_resolved_event().ok()? { + (_, quick_xml::events::Event::Start(_)) => break, + (_, quick_xml::events::Event::Eof) => return None, + _ => {} + } + } + let w_ns = match reader.resolver().resolve_element(quick_xml::name::QName(b"w:dummy")).0 { + quick_xml::name::ResolveResult::Bound(ns) => Some(ns.as_ref().to_vec()), + _ => None, + }; + if let Ok((res, quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e))) = reader.read_resolved_event() { + let is_wml_elem = match res { + quick_xml::name::ResolveResult::Bound(ref ns) => { + w_ns.as_deref().is_some_and(|w| ns.as_ref() == w) || ns.as_ref() == WML || ns.as_ref() == WML_STRICT + } + _ => false, + }; + if !is_wml_elem || e.local_name().as_ref() != b"compatSetting" { + continue; + } + let mut is_compat_mode = false; + let mut uri_ok = true; + for attr in e.attributes().with_checks(false).flatten() { + let (ares, local) = reader.resolver().resolve_attribute(attr.key); + let is_wml_attr = match ares { + quick_xml::name::ResolveResult::Bound(ref ns) => { + w_ns.as_deref().is_some_and(|w| ns.as_ref() == w) || ns.as_ref() == WML || ns.as_ref() == WML_STRICT + } + quick_xml::name::ResolveResult::Unbound => true, + _ => false, + }; + if is_wml_attr && local.as_ref() == b"name" && attr.value.as_ref() == b"compatibilityMode" { + is_compat_mode = true; + } else if is_wml_attr && local.as_ref() == b"uri" && attr.value.as_ref() != b"http://schemas.microsoft.com/office/word" { + uri_ok = false; + } + } + if is_compat_mode && uri_ok { + return Some((k.start, k.end)); + } + } + } + None }; match (mode(orig), mode(generated)) { (Some((a, b)), Some((c, d))) => Some(format!("{}{}{}", orig.get(..a)?, generated.get(c..d)?, orig.get(b..)?)), + (Some((a, b)), None) => Some(format!("{}{}", orig.get(..a)?, orig.get(b..)?)), (None, Some((c, d))) => { // No mode in the original: add the generated one before ``, or expand a self-closing ``. if let Some(close) = orig.rfind("") { @@ -251,7 +309,7 @@ fn merge_compat(orig: &str, generated: &str) -> Option { None } } - _ => Some(orig.to_string()), + (None, None) => Some(orig.to_string()), } } @@ -356,10 +414,8 @@ pub fn merge(original: &[u8], generated: &[u8]) -> Option> { out.push((k.name.clone(), g_text(g_kids.get(gi)?)?)); } } else if k.name == "w:compat" { - let merged = match mark("w:compat", &mut used) { - Some(gi) => merge_compat(text, &g_text(g_kids.get(gi)?)?)?, - None => text.to_string(), - }; + let g_compat = mark("w:compat", &mut used).and_then(|gi| g_text(g_kids.get(gi)?)); + let merged = merge_compat(root_tag, text, g_compat.as_deref().unwrap_or(""))?; out.push((k.name.clone(), merged)); } else if !text.contains("r:id=") { out.push((k.name.clone(), text.to_string())); @@ -473,4 +529,37 @@ mod tests { // A file whose only extra setting is this one has nothing foreign to keep. assert!(!has_unowned(br#""#)); } + + #[test] + fn compatibility_mode_removal_handles_paired_tags_quotes_and_whitespace() { + let gen_no_mode = r#""#; + + // Paired tag with closing + let orig_paired = r#""#; + assert!(has_unowned(orig_paired.as_bytes())); + let out_paired = String::from_utf8(merge(orig_paired.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out_paired.contains("compatibilityMode"), "{out_paired}"); + assert!(!out_paired.contains(""), "{out_paired}"); + assert!(out_paired.contains("overrideTableStyleFontSizeAndJustification"), "{out_paired}"); + + // Single quotes + let orig_single_quotes = r#""#; + let out_sq = String::from_utf8(merge(orig_single_quotes.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out_sq.contains("compatibilityMode"), "{out_sq}"); + assert!(out_sq.contains("overrideTableStyleFontSizeAndJustification"), "{out_sq}"); + + // Whitespace around equals + let orig_spaces = r#""#; + let out_sp = String::from_utf8(merge(orig_spaces.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out_sp.contains("compatibilityMode"), "{out_sp}"); + assert!(out_sp.contains("overrideTableStyleFontSizeAndJustification"), "{out_sp}"); + + // Foreign vendor compatSetting element is preserved + let orig_foreign = r#""#; + let gen_foreign = + r#""#; + let out_foreign = String::from_utf8(merge(orig_foreign.as_bytes(), gen_foreign.as_bytes()).unwrap()).unwrap(); + assert!(out_foreign.contains("x:compatSetting"), "{out_foreign}"); + assert!(!out_foreign.contains(r#"w:name="compatibilityMode""#), "{out_foreign}"); + } } diff --git a/crates/docx/src/write/story/para.rs b/crates/docx/src/write/story/para.rs index babed9de51..c4f763bc85 100644 --- a/crates/docx/src/write/story/para.rs +++ b/crates/docx/src/write/story/para.rs @@ -213,17 +213,17 @@ impl Writer<'_> { i += 1; continue; } - // Hyperlinks with different ScreenTips stay separate even if their target is shared. + // Hyperlinks with different ScreenTips or history settings stay separate even if their target is shared. let link = props .link .as_deref() .filter(|target| !target.is_empty()) - .map(|target| (target, props.link_tooltip.as_deref().and_then(crate::bounded_link_tooltip))); + .map(|target| (target, props.link_tooltip.as_deref().and_then(crate::bounded_link_tooltip), props.link_history)); if link != open_link { if open_link.is_some() { w.close("w:hyperlink"); } - if let Some((link, tip)) = link { + if let Some((link, tip, hist)) = link { let id; let target = if let Some(anchor) = link.strip_prefix('#') { ("w:anchor", anchor) @@ -231,11 +231,19 @@ impl Writer<'_> { id = rels.add(rt::HYPERLINK, link, true); ("r:id", id.as_str()) }; - if let Some(tip) = tip { - w.open("w:hyperlink", &[target, ("w:history", "1"), ("w:tooltip", tip)]); - } else { - w.open("w:hyperlink", &[target, ("w:history", "1")]); + let mut attrs = [("", ""); 3]; + let mut n = 0; + attrs[n] = target; + n += 1; + if let Some(h) = hist { + attrs[n] = ("w:history", if h { "1" } else { "0" }); + n += 1; } + if let Some(tip) = tip { + attrs[n] = ("w:tooltip", tip); + n += 1; + } + w.open("w:hyperlink", &attrs[..n]); } open_link = link; } diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index 4f2b9de277..821d890b2a 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -1280,17 +1280,17 @@ fn compatibility_mode_is_read_and_defaults_to_word_2007() { let compat = |v: &str| { format!(r#""#) }; - assert_eq!(with_settings(Some(&compat("15"))).settings.compat_mode, 15); - assert_eq!(with_settings(Some(&compat("14"))).settings.compat_mode, 14); + assert_eq!(with_settings(Some(&compat("15"))).settings.compat_mode, Some(15)); + assert_eq!(with_settings(Some(&compat("14"))).settings.compat_mode, Some(14)); // Unnamed, out of range or junk values. - assert_eq!(with_settings(Some("")).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); - assert_eq!(with_settings(None).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); - assert_eq!(with_settings(Some(&compat("-3"))).settings.compat_mode, 11); - assert_eq!(with_settings(Some(&compat("99999"))).settings.compat_mode, 99); - assert_eq!(with_settings(Some(&compat("abc"))).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); + assert_eq!(with_settings(Some("")).settings.compat_mode, None); + assert_eq!(with_settings(None).settings.compat_mode, None); + assert_eq!(with_settings(Some(&compat("-3"))).settings.compat_mode, Some(11)); + assert_eq!(with_settings(Some(&compat("99999"))).settings.compat_mode, Some(99)); + assert_eq!(with_settings(Some(&compat("abc"))).settings.compat_mode, None); // Another vendor's setting of the same name is ignored. let other = r#""#; - assert_eq!(with_settings(Some(other)).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); + assert_eq!(with_settings(Some(other)).settings.compat_mode, None); } #[test] @@ -1458,7 +1458,9 @@ fn anchor_stacking_order_is_read_and_kept() { #[test] fn documents_without_a_compatibility_mode_are_laid_out_as_word_2007() { - assert_eq!(read_body("").settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); + let d = read_body(""); + assert_eq!(d.settings.compat_mode, None); + assert_eq!(d.settings.effective_compat_mode(), craft_wordmodel::LEGACY_COMPAT_MODE); } #[test] diff --git a/crates/docx/tests/it/picture_links.rs b/crates/docx/tests/it/picture_links.rs index dc5f53e19c..e84ccb10c5 100644 --- a/crates/docx/tests/it/picture_links.rs +++ b/crates/docx/tests/it/picture_links.rs @@ -107,7 +107,7 @@ fn a_linked_picture_is_saved_with_its_link_on_the_drawing_too() { let back = craft_docx::read(&bytes).unwrap(); assert_eq!(picture_links(&back), [Some("https://example.com/saved".to_string()), Some("#Spot".to_string())]); // The drawing's link alone (as Word writes it) reads back the same. - let without_run_link = xml.replace(&format!(r#""#), "").replacen("", "", 1); + let without_run_link = xml.replace(&format!(r#""#), "").replacen("", "", 1); assert_ne!(without_run_link, xml); let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap(); let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 4927cd09c8..21dfd82505 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -143,6 +143,7 @@ fn every_char_prop_round_trips() { }), link: None, link_tooltip: None, + link_history: None, ins: None, del: None, fmt_change: None, @@ -1487,11 +1488,11 @@ fn table_contextual_spacing_compatibility_flag_round_trips() { for mode in [11, 12, 14, 15] { for allow in [false, true] { let mut d = Document::new(); - d.settings.compat_mode = mode; + d.settings.compat_mode = Some(mode); d.settings.allow_space_of_same_style_in_table = allow; let r = rt(&d); assert_eq!(r.settings.allow_space_of_same_style_in_table, allow); - assert_eq!(r.settings.compat_mode, mode); + assert_eq!(r.settings.compat_mode, Some(mode)); if allow { let bytes = craft_docx::write(&d).unwrap(); let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); @@ -1508,14 +1509,171 @@ fn table_contextual_spacing_compatibility_flag_round_trips() { fn compatibility_mode_round_trips() { // New documents are Word 2013+ documents; an older file keeps its mode, so saving it doesn't // change how Word lays it out. - assert_eq!(rt(&Document::new()).settings.compat_mode, craft_wordmodel::COMPAT_MODE_CURRENT); + assert_eq!(rt(&Document::new()).settings.compat_mode, Some(craft_wordmodel::COMPAT_MODE_CURRENT)); for mode in [11, 12, 14, 15] { let mut d = Document::new(); - d.settings.compat_mode = mode; - assert_eq!(rt(&d).settings.compat_mode, mode); + d.settings.compat_mode = Some(mode); + assert_eq!(rt(&d).settings.compat_mode, Some(mode)); } } +/// #3308: A document without `` or without `` +/// round-trips without synthesizing the tag on save. +#[test] +fn compatibility_mode_omitted_round_trips_without_synthesizing() { + let settings_xml_of = |bytes: &[u8]| { + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut xml = String::new(); + match zip.by_name("word/settings.xml") { + Ok(mut file) => { + std::io::Read::read_to_string(&mut file, &mut xml).unwrap(); + Some(xml) + } + Err(zip::result::ZipError::FileNotFound) => None, + Err(e) => panic!("zip error: {e:?}"), + } + }; + + // Case 1: settings.xml without `` at all. + let base_docx = craft_docx::write(&Document::new()).unwrap(); + let original_settings = settings_xml_of(&base_docx).unwrap(); + let without_compat = original_settings.replace( + "", + "", + ); + assert_ne!(original_settings, without_compat); + let docx_without_compat = replace_part(&base_docx, "word/settings.xml", without_compat.as_bytes()); + + let doc = craft_docx::read(&docx_without_compat).unwrap(); + assert_eq!(doc.settings.compat_mode, None); + assert_eq!(doc.settings.effective_compat_mode(), craft_wordmodel::LEGACY_COMPAT_MODE); + + let saved_bytes = craft_docx::write(&doc).unwrap(); + let saved_settings = settings_xml_of(&saved_bytes).unwrap(); + assert!(!saved_settings.contains(", got: {saved_settings}"); + assert!(!saved_settings.contains("compatibilityMode"), "expected no compatibilityMode, got: {saved_settings}"); + + let read_back = craft_docx::read(&saved_bytes).unwrap(); + assert_eq!(read_back.settings.compat_mode, None); + + // Case 2: settings.xml with `` but without `` + // (e.g. only legacy compatibility flags like ``). + let with_other_compat = original_settings.replace( + "", + "", + ); + assert_ne!(original_settings, with_other_compat); + let docx_with_other = replace_part(&base_docx, "word/settings.xml", with_other_compat.as_bytes()); + + let doc2 = craft_docx::read(&docx_with_other).unwrap(); + assert_eq!(doc2.settings.compat_mode, None); + assert!(doc2.settings.do_not_expand_shift_return); + + let saved_bytes2 = craft_docx::write(&doc2).unwrap(); + let saved_settings2 = settings_xml_of(&saved_bytes2).unwrap(); + assert!(saved_settings2.contains(""), "expected , got: {saved_settings2}"); + assert!(saved_settings2.contains(""), "expected doNotExpandShiftReturn, got: {saved_settings2}"); + assert!(!saved_settings2.contains("compatibilityMode"), "expected no compatibilityMode, got: {saved_settings2}"); + + let read_back2 = craft_docx::read(&saved_bytes2).unwrap(); + assert_eq!(read_back2.settings.compat_mode, None); + assert!(read_back2.settings.do_not_expand_shift_return); +} + +/// #3305: Hyperlinks without `w:history`, with `w:history="0"`, or with `w:history="1"` +/// round-trip with the exact attribute state preserved. +#[test] +fn hyperlink_history_attribute_preservation_round_trips() { + let doc_xml_of = |bytes: &[u8]| { + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut xml = String::new(); + std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap(); + xml + }; + + // 1. In-memory / programmatic round-trip with different history settings: + // a) omitted (`None`) + let mut p_none = Paragraph::new(); + p_none + .insert_text( + 0, + "link without history", + &CharProps { link: Some("https://example.com/no-hist".into()), link_history: None, ..Default::default() }, + ) + .unwrap(); + let d_none = doc_with(vec![p_none]); + let bytes_none = craft_docx::write(&d_none).unwrap(); + let xml_none = doc_xml_of(&bytes_none); + assert!(xml_none.contains(""), "{s}"); assert!(!craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap().settings.track_moves); } + +#[test] +fn cleared_compatibility_mode_removes_it_from_merged_settings() { + let mut doc = craft_docx::read(&with_settings(SETTINGS)).unwrap(); + assert_eq!(doc.settings.compat_mode, Some(15)); + assert!(doc.passthrough.contains_key("wordcraft:settings.orig")); + + // Case 1: compat_mode is set to None, and no other compat switch is enabled. + doc.settings.compat_mode = None; + let files = save(&doc); + let s = text(&files, "word/settings.xml"); + assert!(!s.contains("compatibilityMode"), "expected mode removed: {s}"); + assert!(s.contains(""), "expected w:compat preserved for unowned settings: {s}"); + assert!(s.contains("overrideTableStyleFontSizeAndJustification"), "{s}"); + assert!(s.contains("enableOpenTypeFeatures"), "{s}"); + + let reopened = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + assert_eq!(reopened.settings.compat_mode, None); + + // Case 2: compat_mode is set to None, but another switch is enabled. + doc.settings.do_not_expand_shift_return = true; + let files2 = save(&doc); + let s2 = text(&files2, "word/settings.xml"); + assert!(!s2.contains("compatibilityMode"), "expected mode removed: {s2}"); + assert!(s2.contains(""), "{s2}"); + assert!(s2.contains("overrideTableStyleFontSizeAndJustification"), "{s2}"); + assert!(s2.contains("enableOpenTypeFeatures"), "{s2}"); + + let reopened2 = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + assert_eq!(reopened2.settings.compat_mode, None); +} diff --git a/crates/wordmodel/src/props/char_props.rs b/crates/wordmodel/src/props/char_props.rs index 556d035406..f6949d3c98 100644 --- a/crates/wordmodel/src/props/char_props.rs +++ b/crates/wordmodel/src/props/char_props.rs @@ -435,6 +435,10 @@ pub struct CharProps { /// Optional ScreenTip for the hyperlink. Runs from one link can share its text. #[serde(skip_serializing_if = "Option::is_none")] pub link_tooltip: Option>, + /// Whether to add the hyperlink to the browser's/Word's history (`w:history`). + /// `None` indicates the attribute was omitted from the source document. + #[serde(skip_serializing_if = "Option::is_none")] + pub link_history: Option, /// Tracked insertion: index into `Document::revisions`. #[serde(skip_serializing_if = "Option::is_none")] pub ins: Option, @@ -572,6 +576,7 @@ impl CharProps { c.style = None; } c.link_tooltip = None; + c.link_history = None; c } @@ -632,9 +637,10 @@ impl CharProps { } fn minus_document_marks(&mut self, base: &CharProps) { - if self.link == base.link && self.link_tooltip == base.link_tooltip { + if self.link == base.link && self.link_tooltip == base.link_tooltip && self.link_history == base.link_history { self.link = None; self.link_tooltip = None; + self.link_history = None; } drop_same_fields!(self, base; ins, del, ligatures); } @@ -689,6 +695,7 @@ impl CharProps { if let Some(link) = &patch.link { self.link = Some(link.clone()); self.link_tooltip = patch.link_tooltip.clone(); + self.link_history = patch.link_history; } overlay_fields!(self, patch; ins, del, fmt_change, ligatures); } @@ -716,6 +723,7 @@ impl CharProps { CharProps { link: self.link.clone(), link_tooltip: self.link_tooltip.clone(), + link_history: self.link_history, ins: self.ins, del: self.del, fmt_change: self.fmt_change.clone(), @@ -726,6 +734,6 @@ impl CharProps { } /// Just the formatting: without the link, revision marks and tracked formatting change. pub fn formatting(&self) -> CharProps { - CharProps { link: None, link_tooltip: None, ins: None, del: None, fmt_change: None, ..self.clone() } + CharProps { link: None, link_tooltip: None, link_history: None, ins: None, del: None, fmt_change: None, ..self.clone() } } } diff --git a/crates/wordmodel/src/settings.rs b/crates/wordmodel/src/settings.rs index 1f75af2626..64df9e1885 100644 --- a/crates/wordmodel/src/settings.rs +++ b/crates/wordmodel/src/settings.rs @@ -124,8 +124,9 @@ pub struct Settings { pub protect_hash: Vec<(String, String)>, /// Word compatibility mode the document is laid out in (`compatibilityMode`): 15 for Word /// 2013 and later, which places a table's border at the margin rather than its text and lets - /// justified lines shrink their spaces to fit more text. - pub compat_mode: u32, + /// justified lines shrink their spaces to fit more text. `None` when omitted from the file. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compat_mode: Option, /// Fonts the document's font table classes as roman (serif, `w:family w:val="roman"`): Word /// draws one that isn't installed in a serif face. #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -319,7 +320,7 @@ impl Default for Settings { protection: None, protect_formatting: false, protect_hash: Vec::new(), - compat_mode: COMPAT_MODE_CURRENT, + compat_mode: Some(COMPAT_MODE_CURRENT), roman_fonts: Vec::new(), sum_paragraph_spacing: false, do_not_expand_shift_return: false, @@ -337,3 +338,11 @@ impl Default for Settings { } } } + +impl Settings { + /// The effective compatibility mode: the authored mode, or Word 2007 (`LEGACY_COMPAT_MODE` = 12) + /// when omitted from the file. + pub fn effective_compat_mode(&self) -> u32 { + self.compat_mode.unwrap_or(LEGACY_COMPAT_MODE) + } +} diff --git a/crates/wordmodel/src/tests.rs b/crates/wordmodel/src/tests.rs index b4d1b17dd4..f5ab928c7f 100644 --- a/crates/wordmodel/src/tests.rs +++ b/crates/wordmodel/src/tests.rs @@ -309,6 +309,27 @@ fn json_round_trip() { assert_eq!(back.para(StoryRef::Body, &Path::top(0)).unwrap().runs[0].props.bold, Some(true)); } +#[test] +fn settings_compat_mode_serde_round_trip() { + let mut s = Settings::default(); + assert_eq!(s.compat_mode, Some(COMPAT_MODE_CURRENT)); + s.compat_mode = None; + let json = serde_json::to_string(&s).unwrap(); + assert!(!json.contains("compatMode"), "expected compatMode omitted: {json}"); + let back: Settings = serde_json::from_str(&json).unwrap(); + assert_eq!(back.compat_mode, None); + assert_eq!(back.effective_compat_mode(), LEGACY_COMPAT_MODE); + + let from_empty: Settings = serde_json::from_str("{}").unwrap(); + assert_eq!(from_empty.compat_mode, None); + + s.compat_mode = Some(14); + let json14 = serde_json::to_string(&s).unwrap(); + assert!(json14.contains(r#""compatMode":14"#), "{json14}"); + let back14: Settings = serde_json::from_str(&json14).unwrap(); + assert_eq!(back14.compat_mode, Some(14)); +} + #[test] fn ensure_nonempty_repairs() { let mut d = Document::new(); From 7f16b42210af6aa09b7c712978d80817834165ae Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Tue, 24 Nov 2026 21:25:20 +0530 Subject: [PATCH 2/7] fix(docx): address CodeRabbit review feedback on settings merge and ruby links - Copy link_history in read_ruby alongside link, preserving None when omitted. - Include w:compat opening tag in settings merge NsReader reconstruction to preserve namespaces declared on w:compat. - Normalize attribute values using normalized_value() before comparing name and uri. - Update GEN test fixture w:uri to standard Microsoft Word URI. - Add regression tests covering w:compat-level namespace declarations and escaped attribute entities. --- crates/docx/src/read/story/runs.rs | 2 +- crates/docx/src/write/settings_merge.rs | 38 +++++++++++++++++++++---- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/crates/docx/src/read/story/runs.rs b/crates/docx/src/read/story/runs.rs index 47e1ef36e3..6ade0f9019 100644 --- a/crates/docx/src/read/story/runs.rs +++ b/crates/docx/src/read/story/runs.rs @@ -363,7 +363,7 @@ impl Reader<'_> { let (base, base_props) = part("w:rubyBase"); let (ruby, ruby_props) = part("w:rt"); let mut bp = base_props.unwrap_or_default(); - (bp.link, bp.ins, bp.del) = (props.link.clone(), props.ins, props.del); + (bp.link, bp.link_history, bp.ins, bp.del) = (props.link.clone(), props.link_history, props.ins, props.del); if base.is_empty() { return; } diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index c8ff49b4d3..4fbdda3cfa 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -243,16 +243,25 @@ fn merge_compat(root_tag: &str, orig: &str, generated: &str) -> Option { } else { r#""# }; + let compat_open_end = tag_end(s)? + 1; + let compat_open = s.get(..compat_open_end)?; for k in kids { let child_str = s.get(k.start..k.end)?; - let mut xml = String::with_capacity(root.len() + child_str.len() + 16); + let mut xml = String::with_capacity(root.len() + compat_open.len() + child_str.len() + 32); xml.push_str(root); + xml.push_str(compat_open); xml.push_str(child_str); - xml.push_str(""); + xml.push_str(""); let mut reader = quick_xml::NsReader::from_str(&xml); + let mut depth = 0; loop { match reader.read_resolved_event().ok()? { - (_, quick_xml::events::Event::Start(_)) => break, + (_, quick_xml::events::Event::Start(_)) => { + depth += 1; + if depth == 2 { + break; + } + } (_, quick_xml::events::Event::Eof) => return None, _ => {} } @@ -282,9 +291,13 @@ fn merge_compat(root_tag: &str, orig: &str, generated: &str) -> Option { quick_xml::name::ResolveResult::Unbound => true, _ => false, }; - if is_wml_attr && local.as_ref() == b"name" && attr.value.as_ref() == b"compatibilityMode" { + if !is_wml_attr { + continue; + } + let val = attr.normalized_value(quick_xml::XmlVersion::Explicit1_0).ok(); + if local.as_ref() == b"name" && val.as_deref() == Some("compatibilityMode") { is_compat_mode = true; - } else if is_wml_attr && local.as_ref() == b"uri" && attr.value.as_ref() != b"http://schemas.microsoft.com/office/word" { + } else if local.as_ref() == b"uri" && val.as_deref() != Some("http://schemas.microsoft.com/office/word") { uri_ok = false; } } @@ -443,7 +456,7 @@ pub fn merge(original: &[u8], generated: &[u8]) -> Option> { mod tests { use super::*; - const GEN: &str = r#""#; + const GEN: &str = r#""#; #[test] fn odd_or_hostile_originals_fall_back_or_merge_without_panicking() { @@ -561,5 +574,18 @@ mod tests { let out_foreign = String::from_utf8(merge(orig_foreign.as_bytes(), gen_foreign.as_bytes()).unwrap()).unwrap(); assert!(out_foreign.contains("x:compatSetting"), "{out_foreign}"); assert!(!out_foreign.contains(r#"w:name="compatibilityMode""#), "{out_foreign}"); + + // Namespace declared directly on w:compat (not root) with mode replacement + let orig_compat_ns = r#""#; + let gen_new_mode = r#""#; + let out_ns = String::from_utf8(merge(orig_compat_ns.as_bytes(), gen_new_mode.as_bytes()).unwrap()).unwrap(); + assert_eq!(out_ns.matches("compatibilityMode").count(), 1, "{out_ns}"); + assert!(out_ns.contains(r#"w:val="14""#), "{out_ns}"); + + // Escaped XML entities in attribute values + let orig_escaped = r#""#; + let out_esc = String::from_utf8(merge(orig_escaped.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out_esc.contains("compatibility"), "{out_esc}"); + assert!(out_esc.contains("overrideTableStyleFontSizeAndJustification"), "{out_esc}"); } } From c0024b06a97d143e5691f78e478ca3a3a33e3565 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Wed, 25 Nov 2026 00:29:48 +0530 Subject: [PATCH 3/7] fix(docx): preserve compat block namespaces and handle whitespace in on-off (#3308, #3305) --- crates/docx/src/read/story.rs | 2 +- crates/docx/src/read/story/runs.rs | 2 +- crates/docx/src/units.rs | 7 +- crates/docx/src/write/settings_merge.rs | 986 +++++++++++++++++++++--- crates/docx/tests/it/roundtrip.rs | 11 + crates/docx/tests/it/settings_merge.rs | 30 + 6 files changed, 929 insertions(+), 109 deletions(-) diff --git a/crates/docx/src/read/story.rs b/crates/docx/src/read/story.rs index c0b98aa917..15ab338e10 100644 --- a/crates/docx/src/read/story.rs +++ b/crates/docx/src/read/story.rs @@ -213,5 +213,5 @@ fn placeholder_of(s: &str) -> String { } fn on_off_attr(e: &El, name: &str) -> bool { - e.attr(name).is_some_and(|v| !matches!(v, "0" | "false" | "off")) + e.attr(name).is_some_and(|v| !crate::units::is_off_val(v)) } diff --git a/crates/docx/src/read/story/runs.rs b/crates/docx/src/read/story/runs.rs index 6ade0f9019..4efd07cac7 100644 --- a/crates/docx/src/read/story/runs.rs +++ b/crates/docx/src/read/story/runs.rs @@ -32,7 +32,7 @@ impl Reader<'_> { if let Some(link) = link { c.link = Some(link); c.link_tooltip = k.attr("w:tooltip").and_then(crate::bounded_link_tooltip).map(std::sync::Arc::from); - c.link_history = k.attr("w:history").map(|v| !matches!(v, "0" | "false" | "off")); + c.link_history = k.attr("w:history").map(|v| !crate::units::is_off_val(v)); } self.read_inline_children(sc, pb, k, rels, &c, depth + 1); } diff --git a/crates/docx/src/units.rs b/crates/docx/src/units.rs index 295fe76215..cefd1977c7 100644 --- a/crates/docx/src/units.rs +++ b/crates/docx/src/units.rs @@ -141,11 +141,16 @@ pub fn tw_u16(e: &El, attr: &str) -> Option { } } +/// Return whether an XML attribute value for an `ST_OnOff` represents "off" / false. +pub fn is_off_val(v: &str) -> bool { + matches!(v.trim(), "0" | "false" | "off" | "False" | "FALSE") +} + /// ST_OnOff: absent `w:val` = on; `0`, `false`, `off` = off. pub fn on_off(e: &El) -> bool { match e.attr("w:val") { None => true, - Some(v) => !matches!(v.trim(), "0" | "false" | "off" | "False" | "FALSE"), + Some(v) => !is_off_val(v), } } diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index 4fbdda3cfa..61c096b565 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -179,16 +179,15 @@ fn children(xml: &str, root: &str) -> Option<(usize, usize, Vec)> { if xml.get(open_end - 2..open_end)? == "/>" { return None; } - let close = xml.rfind(&format!(""))?; let mut out = Vec::new(); let mut depth = 0usize; let mut i = open_end; let mut cur: Option<(String, usize)> = None; - while i < close { - let rest = xml.get(i..close)?; - let Some(lt) = rest.find('<') else { break }; + let close = loop { + let rest = xml.get(i..)?; + let lt = rest.find('<')?; let at = i + lt; - let tail = xml.get(at..close)?; + let tail = xml.get(at..)?; if tail.starts_with("")? + 3; continue; @@ -203,6 +202,13 @@ fn children(xml: &str, root: &str) -> Option<(usize, usize, Vec)> { let gt = at + tag_end(tail)? + 1; let tag = xml.get(at..gt)?; if tag.starts_with(" Option<(usize, usize, Vec)> { } } i = gt; - } + }; if depth != 0 { return None; } - Some((open_end, close, out)) + Some((open, open_end, close, out)) +} + +fn find_close_tag(xml: &str, tag_name: &str) -> Option { + children(xml, tag_name).map(|(_, _, close, _)| close) } const WML: &[u8] = b"http://schemas.openxmlformats.org/wordprocessingml/2006/main"; const WML_STRICT: &[u8] = b"http://purl.oclc.org/ooxml/wordprocessingml/main"; +const REL_NS: &[u8] = b"http://schemas.openxmlformats.org/officeDocument/2006/relationships"; +const REL_STRICT_NS: &[u8] = b"http://purl.oclc.org/ooxml/officeDocument/relationships"; + +fn is_rel_ns(ns: &[u8]) -> bool { + let unesc = unescaped_ns(ns); + unesc.as_ref() == REL_NS || unesc.as_ref() == REL_STRICT_NS +} + +fn unescaped_ns(ns: &[u8]) -> std::borrow::Cow<'_, [u8]> { + if ns.contains(&b'&') + && let Ok(s) = std::str::from_utf8(ns) + && let Ok(unesc) = quick_xml::escape::unescape(s) + { + return std::borrow::Cow::Owned(unesc.into_owned().into_bytes()); + } + std::borrow::Cow::Borrowed(ns) +} + +fn is_wml_ns(ns: &[u8], root_w: &[u8]) -> bool { + let unesc_ns = unescaped_ns(ns); + let unesc_root = unescaped_ns(root_w); + (!unesc_root.is_empty() && unesc_ns.as_ref() == unesc_root.as_ref()) || unesc_ns.as_ref() == WML || unesc_ns.as_ref() == WML_STRICT +} + +const OWNED_COMPAT_SWITCHES: &[&str] = &["doNotExpandShiftReturn", "doNotUseHTMLParagraphAutoSpacing", "allowSpaceOfSameStyleInTable"]; + +fn check_compat_child(root_tag: &str, compat_s: &str, k: &Child, check: F) -> bool +where + F: FnOnce(&quick_xml::events::BytesStart<'_>, &quick_xml::NsReader<&[u8]>, &[u8]) -> bool, +{ + let Some(child_str) = compat_s.get(k.start..k.end) else { return false }; + let root = if root_tag.starts_with('<') { + root_tag + } else { + r#""# + }; + let Some(compat_open_end) = tag_end(compat_s).map(|e| e + 1) else { return false }; + let Some(compat_open) = compat_s.get(..compat_open_end) else { return false }; + let mut xml = String::with_capacity(root.len() + compat_open.len() + child_str.len() + 32); + xml.push_str(root); + xml.push_str(compat_open); + xml.push_str(child_str); + xml.push_str(""); + let mut reader = quick_xml::NsReader::from_str(&xml); + let mut depth = 0; + let mut root_w_ns = None; + loop { + match reader.read_resolved_event() { + Ok((_, quick_xml::events::Event::Start(_))) => { + depth += 1; + if depth == 1 { + root_w_ns = match reader.resolver().resolve_element(quick_xml::name::QName(b"w:dummy")).0 { + quick_xml::name::ResolveResult::Bound(ns) => Some(ns.as_ref().to_vec()), + _ => None, + }; + } else if depth == 2 { + break; + } + } + Ok((_, quick_xml::events::Event::Eof)) | Err(_) => return false, + _ => {} + } + } + if let Ok((res, quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e))) = reader.read_resolved_event() { + let is_wml_elem = match res { + quick_xml::name::ResolveResult::Bound(ref ns) => is_wml_ns(ns.as_ref(), root_w_ns.as_deref().unwrap_or(b"")), + _ => false, + }; + if !is_wml_elem { + return false; + } + check(e, &reader, root_w_ns.as_deref().unwrap_or(b"")) + } else { + false + } +} + +fn is_compat_mode_child(root_tag: &str, compat_s: &str, k: &Child) -> bool { + check_compat_child(root_tag, compat_s, k, |e, reader, root_w| { + if e.local_name().as_ref() != b"compatSetting" { + return false; + } + let mut w_name = None; + let mut un_name = None; + let mut w_uri = None; + let mut un_uri = None; + + for attr in e.attributes().with_checks(false).flatten() { + let (ares, local) = reader.resolver().resolve_attribute(attr.key); + let val = attr.normalized_value(quick_xml::XmlVersion::Explicit1_0).ok(); + let is_wml = match ares { + quick_xml::name::ResolveResult::Bound(ref ns) => is_wml_ns(ns.as_ref(), root_w), + _ => false, + }; + let is_unbound = matches!(ares, quick_xml::name::ResolveResult::Unbound); + + if local.as_ref() == b"name" { + if is_wml { + w_name = val; + } else if is_unbound { + un_name = val; + } + } else if local.as_ref() == b"uri" { + if is_wml { + w_uri = val; + } else if is_unbound { + un_uri = val; + } + } + } + + let name = w_name.or(un_name); + let uri = w_uri.or(un_uri); + name.as_deref() == Some("compatibilityMode") && uri.as_deref().is_none_or(|u| u == "http://schemas.microsoft.com/office/word") + }) +} + +fn is_wml_switch_child(root_tag: &str, compat_s: &str, k: &Child, sw_local: &str) -> bool { + check_compat_child(root_tag, compat_s, k, |e, _reader, _root_w| e.local_name().as_ref() == sw_local.as_bytes()) +} + +const CT_COMPAT_ORDER: &[&str] = &[ + "useSingleBorderforContiguousCells", + "wpJustification", + "noTabHangInd", + "noLeading", + "spaceForUL", + "noColumnBalance", + "balanceSingleByteDoubleByteWidth", + "noExtraLineSpacing", + "doNotLeaveBackslashAlone", + "ulTrailSpace", + "doNotExpandShiftReturn", + "spacingInWholePoints", + "lineWrapLikeWord6", + "printBodyTextBeforeHeader", + "printColBlack", + "wpSpaceWidth", + "showBreaksInFrames", + "subFontBySize", + "suppressBottomSpacing", + "suppressTopSpacing", + "suppressSpacingAtTopOfPage", + "suppressTopSpacingWP", + "suppressSpBfAfterPgBrk", + "swapBordersFacingPages", + "convMailMergeEsc", + "truncateFontHeightsLikeWP6", + "mwSmallCaps", + "usePrinterMetrics", + "doNotSuppressParagraphBorders", + "wrapTrailSpaces", + "footnoteLayoutLikeWW8", + "shapeLayoutLikeWW8", + "alignTablesRowByRow", + "forgetLastTabAlignment", + "adjustLineHeightInTable", + "autoSpaceLikeWord95", + "noSpaceRaiseLower", + "doNotUseHTMLParagraphAutoSpacing", + "layoutRawTableWidth", + "layoutTableRowsApart", + "useWord97LineBreakRules", + "doNotBreakWrappedTables", + "doNotSnapToGridInCell", + "selectFldWithFirstOrLastChar", + "applyBreakingRules", + "doNotWrapTextWithPunct", + "doNotUseEastAsianBreakRules", + "useWord2002TableStyleRules", + "growAutofit", + "useFELayout", + "useNormalStyleForList", + "doNotUseIndentAsNumberingTabStop", + "useAltKinsokuLineBreakRules", + "allowSpaceOfSameStyleInTable", + "doNotSuppressIndentation", + "doNotAutofitConstrainedTables", + "autofitToFirstFixedWidthCell", + "underlineTabInNumList", + "displayHangulFixedWidth", + "splitPgBreakAndParaMark", + "doNotVertAlignCellWithSp", + "doNotBreakConstrainedForcedTable", + "doNotVertAlignInTxbx", + "useAnsiKerningPairs", + "cachedColBalance", + "compatSetting", +]; + +fn compat_child_rank(name: &str) -> usize { + let local = name.rsplit(':').next().unwrap_or(name); + CT_COMPAT_ORDER.iter().position(|&n| n == local).unwrap_or(CT_COMPAT_ORDER.len()) +} + +fn recognized_compat_child_rank(root_tag: &str, compat_s: &str, k: &Child) -> Option { + let local = k.name.rsplit(':').next().unwrap_or(&k.name); + let rank = CT_COMPAT_ORDER.iter().position(|&n| n == local)?; + if check_compat_child(root_tag, compat_s, k, |_, _, _| true) { Some(rank) } else { None } +} + +fn is_wml_compat_switch(root_tag: &str, compat_s: &str, k: &Child) -> bool { + OWNED_COMPAT_SWITCHES.iter().any(|sw| is_wml_switch_child(root_tag, compat_s, k, sw)) +} + +fn is_wml_compat_container(root_tag: &str, orig: &str, k: &Child) -> bool { + let Some(child_str) = orig.get(k.start..k.end) else { return false }; + let root = if root_tag.starts_with('<') { + root_tag + } else { + r#""# + }; + let Some(open_end) = tag_end(child_str).map(|e| e + 1) else { return false }; + let Some(open_tag) = child_str.get(..open_end) else { return false }; + let mut xml = String::with_capacity(root.len() + open_tag.len() + 64); + xml.push_str(root); + if open_tag.ends_with("/>") { + xml.push_str(open_tag); + } else { + let tag_name = &k.name; + xml.push_str(open_tag); + xml.push_str(&format!("")); + } + xml.push_str(""); + let mut reader = quick_xml::NsReader::from_str(&xml); + let mut depth = 0; + let mut root_w_ns = None; + loop { + match reader.read_resolved_event() { + Ok((_, quick_xml::events::Event::Start(_))) if depth == 0 => { + depth = 1; + root_w_ns = match reader.resolver().resolve_element(quick_xml::name::QName(b"w:dummy")).0 { + quick_xml::name::ResolveResult::Bound(ns) => Some(ns.as_ref().to_vec()), + _ => None, + }; + } + Ok((res, quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e))) if depth == 1 => { + let is_wml_elem = match res { + quick_xml::name::ResolveResult::Bound(ref ns) => is_wml_ns(ns.as_ref(), root_w_ns.as_deref().unwrap_or(b"")), + _ => false, + }; + return is_wml_elem && e.local_name().as_ref() == b"compat"; + } + Ok((_, quick_xml::events::Event::Eof)) | Err(_) => return false, + _ => {} + } + } +} + +fn compat_destination_and_w_ns(root_tag: &str, compat_s: &str) -> (Vec, Option>) { + let root = if root_tag.trim_start().starts_with('<') { + root_tag + } else { + r#""# + }; + let Some(open_end) = tag_end(compat_s).map(|e| e + 1) else { + return (WML.to_vec(), Some(WML.to_vec())); + }; + let Some(compat_open) = compat_s.get(..open_end) else { + return (WML.to_vec(), Some(WML.to_vec())); + }; + let mut xml = String::with_capacity(root.len() + compat_open.len() + 64); + xml.push_str(root); + xml.push_str(compat_open); + if !compat_open.ends_with("/>") { + xml.push_str(""); + } + xml.push_str(""); + let mut reader = quick_xml::NsReader::from_str(&xml); + let mut depth = 0; + let mut compat_ns = WML.to_vec(); + let mut w_ns = None; + while let Ok((res, ev)) = reader.read_resolved_event() { + match ev { + quick_xml::events::Event::Start(_) => depth += 1, + quick_xml::events::Event::Empty(_) if depth == 1 => depth = 2, + quick_xml::events::Event::Eof => break, + _ => {} + } + if depth == 2 { + if let quick_xml::name::ResolveResult::Bound(ns) = res { + compat_ns = unescaped_ns(ns.as_ref()).into_owned(); + } + if let quick_xml::name::ResolveResult::Bound(ns) = reader.resolver().resolve_element(quick_xml::name::QName(b"w:dummy")).0 { + w_ns = Some(unescaped_ns(ns.as_ref()).into_owned()); + } + break; + } + } + (compat_ns, w_ns) +} + +fn qualify_wml_child(g_text: &str, root_tag: &str, compat_s: &str) -> String { + let (compat_ns, w_ns) = compat_destination_and_w_ns(root_tag, compat_s); + if w_ns.as_deref() == Some(&compat_ns) { + g_text.to_string() + } else { + let uri_str = std::str::from_utf8(&compat_ns).unwrap_or("http://schemas.openxmlformats.org/wordprocessingml/2006/main"); + if let Some(space_pos) = g_text.find(|c: char| c.is_whitespace() || c == '/' || c == '>') { + let mut s = g_text.to_string(); + s.insert_str(space_pos, &format!(r#" xmlns:w="{uri_str}""#)); + s + } else { + g_text.to_string() + } + } +} + +fn enable_switch_element(elem_str: &str, root_tag: &str, compat_s: &str) -> String { + let root = if root_tag.trim_start().starts_with('<') { + root_tag + } else { + r#""# + }; + let Some(open_end) = tag_end(compat_s).map(|e| e + 1) else { return elem_str.to_string() }; + let Some(compat_open) = compat_s.get(..open_end) else { return elem_str.to_string() }; + let elem_offset_in_xml = root.len() + compat_open.len(); + let mut xml = String::with_capacity(root.len() + compat_open.len() + elem_str.len() + 64); + xml.push_str(root); + xml.push_str(compat_open); + xml.push_str(elem_str); + if !elem_str.ends_with("/>") { + xml.push_str(""); + } + if !compat_open.ends_with("/>") { + xml.push_str(""); + } + xml.push_str(""); + let mut reader = quick_xml::NsReader::from_str(&xml); + let mut depth = 0; + let mut root_w_ns = None; + let mut disabled_val_range: Option<(usize, usize)> = None; + + while let Ok((_, ev)) = reader.read_resolved_event() { + match ev { + quick_xml::events::Event::Start(_) if depth == 0 => { + depth = 1; + root_w_ns = match reader.resolver().resolve_element(quick_xml::name::QName(b"w:dummy")).0 { + quick_xml::name::ResolveResult::Bound(ns) => Some(ns.as_ref().to_vec()), + _ => None, + }; + } + quick_xml::events::Event::Start(_) if depth == 1 => { + depth = 2; + } + quick_xml::events::Event::Empty(ref e) | quick_xml::events::Event::Start(ref e) if depth >= 2 => { + let mut w_val = None; + let mut un_val = None; + let root_w = root_w_ns.as_deref().unwrap_or(b""); + for attr in e.attributes().with_checks(false).flatten() { + let (ares, local) = reader.resolver().resolve_attribute(attr.key); + if local.as_ref() == b"val" { + let is_wml = match ares { + quick_xml::name::ResolveResult::Bound(ref ns) => is_wml_ns(ns.as_ref(), root_w), + _ => false, + }; + let is_unbound = matches!(ares, quick_xml::name::ResolveResult::Unbound); + let val_str = attr.normalized_value(quick_xml::XmlVersion::Explicit1_0).ok(); + let start_in_xml = attr.value.as_ptr() as usize - xml.as_ptr() as usize; + if start_in_xml >= elem_offset_in_xml { + let start = start_in_xml - elem_offset_in_xml; + let end = start + attr.value.len(); + if is_wml { + w_val = Some((val_str, (start, end))); + } else if is_unbound { + un_val = Some((val_str, (start, end))); + } + } + } + } + let chosen = w_val.or(un_val); + if let Some((Some(v), span)) = chosen + && crate::units::is_off_val(&v) + { + disabled_val_range = Some(span); + } + break; + } + quick_xml::events::Event::Eof => break, + _ => {} + } + } + + if let Some((start, end)) = disabled_val_range + && start < end + && end <= elem_str.len() + { + let mut s = elem_str.to_string(); + s.replace_range(start..end, "1"); + return s; + } + elem_str.to_string() +} + +fn sync_compat_switch(root_tag: &str, orig: &mut String, orig_tag: &str, generated: &str, sw_local: &str) -> Option<()> { + let gen_sw = children(generated, "w:compat").and_then(|(_, _, _, g_kids)| { + g_kids.into_iter().find(|k| is_wml_switch_child(root_tag, generated, k, sw_local)).and_then(|k| generated.get(k.start..k.end)) + }); + + let (_, _, o_close, o_kids) = children(orig, orig_tag)?; + let orig_matches: Vec<(usize, usize)> = + o_kids.iter().filter(|k| is_wml_switch_child(root_tag, orig, k, sw_local)).map(|k| (k.start, k.end)).collect(); + + match (orig_matches.as_slice(), gen_sw) { + ([], None) => {} + (matches, None) => { + for &(a, b) in matches.iter().rev() { + orig.replace_range(a..b, ""); + } + } + ([], Some(g_text)) => { + let my_rank = compat_child_rank(sw_local); + let at = o_kids + .iter() + .find(|k| recognized_compat_child_rank(root_tag, orig, k).is_some_and(|r| r > my_rank)) + .map(|k| k.start) + .unwrap_or(o_close); + let child = qualify_wml_child(g_text, root_tag, orig); + orig.insert_str(at, &child); + } + (matches, Some(_g_text)) => { + for &(a, b) in matches[1..].iter().rev() { + orig.replace_range(a..b, ""); + } + let (first_a, first_b) = matches[0]; + let orig_elem = &orig[first_a..first_b]; + let updated = enable_switch_element(orig_elem, root_tag, orig); + orig.replace_range(first_a..first_b, &updated); + } + } + Some(()) +} /// The original `w:compat` with its `compatibilityMode` taken from the generated one, /// or removed if the generated settings omit it. -fn merge_compat(root_tag: &str, orig: &str, generated: &str) -> Option { - let mode = |s: &str| -> Option<(usize, usize)> { - let (_, _, kids) = children(s, "w:compat")?; - let root = if root_tag.starts_with('<') { - root_tag - } else { - r#""# - }; - let compat_open_end = tag_end(s)? + 1; - let compat_open = s.get(..compat_open_end)?; - for k in kids { - let child_str = s.get(k.start..k.end)?; - let mut xml = String::with_capacity(root.len() + compat_open.len() + child_str.len() + 32); - xml.push_str(root); - xml.push_str(compat_open); - xml.push_str(child_str); - xml.push_str(""); - let mut reader = quick_xml::NsReader::from_str(&xml); - let mut depth = 0; - loop { - match reader.read_resolved_event().ok()? { - (_, quick_xml::events::Event::Start(_)) => { - depth += 1; - if depth == 2 { - break; - } - } - (_, quick_xml::events::Event::Eof) => return None, - _ => {} - } - } - let w_ns = match reader.resolver().resolve_element(quick_xml::name::QName(b"w:dummy")).0 { - quick_xml::name::ResolveResult::Bound(ns) => Some(ns.as_ref().to_vec()), - _ => None, - }; - if let Ok((res, quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e))) = reader.read_resolved_event() { - let is_wml_elem = match res { - quick_xml::name::ResolveResult::Bound(ref ns) => { - w_ns.as_deref().is_some_and(|w| ns.as_ref() == w) || ns.as_ref() == WML || ns.as_ref() == WML_STRICT - } - _ => false, - }; - if !is_wml_elem || e.local_name().as_ref() != b"compatSetting" { - continue; - } - let mut is_compat_mode = false; - let mut uri_ok = true; - for attr in e.attributes().with_checks(false).flatten() { - let (ares, local) = reader.resolver().resolve_attribute(attr.key); - let is_wml_attr = match ares { - quick_xml::name::ResolveResult::Bound(ref ns) => { - w_ns.as_deref().is_some_and(|w| ns.as_ref() == w) || ns.as_ref() == WML || ns.as_ref() == WML_STRICT - } - quick_xml::name::ResolveResult::Unbound => true, - _ => false, - }; - if !is_wml_attr { - continue; - } - let val = attr.normalized_value(quick_xml::XmlVersion::Explicit1_0).ok(); - if local.as_ref() == b"name" && val.as_deref() == Some("compatibilityMode") { - is_compat_mode = true; - } else if local.as_ref() == b"uri" && val.as_deref() != Some("http://schemas.microsoft.com/office/word") { - uri_ok = false; - } - } - if is_compat_mode && uri_ok { - return Some((k.start, k.end)); - } - } - } - None +fn merge_compat(root_tag: &str, orig: &str, orig_tag: &str, generated: &str) -> Option { + let mode_spans = |s: &str, tag: &str| -> Vec<(usize, usize)> { + children(s, tag) + .map(|(_, _, _, kids)| kids.into_iter().filter(|k| is_compat_mode_child(root_tag, s, k)).map(|k| (k.start, k.end)).collect()) + .unwrap_or_default() }; - match (mode(orig), mode(generated)) { - (Some((a, b)), Some((c, d))) => Some(format!("{}{}{}", orig.get(..a)?, generated.get(c..d)?, orig.get(b..)?)), - (Some((a, b)), None) => Some(format!("{}{}", orig.get(..a)?, orig.get(b..)?)), - (None, Some((c, d))) => { - // No mode in the original: add the generated one before ``, or expand a self-closing ``. - if let Some(close) = orig.rfind("") { - Some(format!("{}{}{}", orig.get(..close)?, generated.get(c..d)?, orig.get(close..)?)) - } else if let Some(slash) = orig.rfind("/>") { - let open = orig.get(..slash)?.trim_end(); - Some(format!("{open}>{}", generated.get(c..d)?)) - } else { - None + + let has_any_gen_switch = + children(generated, "w:compat").is_some_and(|(_, _, _, g_kids)| g_kids.iter().any(|k| is_wml_compat_switch(root_tag, generated, k))); + + let open_end = tag_end(orig)? + 1; + let is_self_closing = orig.get(open_end - 2..open_end) == Some("/>"); + let compat_open = orig.get(..open_end)?; + + if tag_has_rel_id(root_tag, compat_open) { + return children(generated, "w:compat").is_some().then(|| generated.to_string()).or_else(|| Some(String::new())); + } + + let gen_modes = mode_spans(generated, "w:compat"); + if is_self_closing && gen_modes.is_empty() && !has_any_gen_switch { + return Some(orig.to_string()); + } + + let mut out = if is_self_closing { + let open = orig.get(..open_end - 2)?.trim_end(); + format!("{open}>") + } else { + orig.to_string() + }; + + // Omit relationship-bearing children whose relationships cannot be remapped in settings.xml.rels + if let Some((_, _, _, kids)) = children(&out, orig_tag) { + for k in kids.into_iter().rev() { + if let Some(child_str) = out.get(k.start..k.end) + && child_has_rel_id(root_tag, compat_open, child_str) + { + out.replace_range(k.start..k.end, ""); } } - (None, None) => Some(orig.to_string()), } + + for sw in OWNED_COMPAT_SWITCHES { + sync_compat_switch(root_tag, &mut out, orig_tag, generated, sw)?; + } + + let o_modes = mode_spans(&out, orig_tag); + match (o_modes.as_slice(), gen_modes.first()) { + ([], None) => {} + (matches, None) => { + for &(a, b) in matches.iter().rev() { + out.replace_range(a..b, ""); + } + } + ([], Some(&(c, d))) => { + let g_text = generated.get(c..d)?; + let close = find_close_tag(&out, orig_tag)?; + let child = qualify_wml_child(g_text, root_tag, &out); + out.insert_str(close, &child); + } + (matches, Some(&(c, d))) => { + let g_text = generated.get(c..d)?; + for &(a, b) in matches[1..].iter().rev() { + out.replace_range(a..b, ""); + } + let (first_a, first_b) = matches[0]; + let child = qualify_wml_child(g_text, root_tag, &out); + out.replace_range(first_a..first_b, &child); + } + } + + if let Some((c_start, c_open, _, remaining_kids)) = children(&out, orig_tag) + && remaining_kids.is_empty() + && !compat_has_unmodeled_attrs(root_tag, &out[c_start..c_open]) + { + return Some(String::new()); + } + + Some(out) +} + +fn tag_has_rel_id(root_tag: &str, tag_str: &str) -> bool { + let root = if root_tag.starts_with('<') { + root_tag + } else { + r#""# + }; + let mut xml = String::with_capacity(root.len() + tag_str.len() + 32); + xml.push_str(root); + xml.push_str(tag_str); + if !tag_str.ends_with("/>") { + xml.push_str(""); + } else { + xml.push_str(""); + } + let mut reader = quick_xml::NsReader::from_str(&xml); + let mut depth = 0; + loop { + match reader.read_resolved_event() { + Ok((_, quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e))) => { + depth += 1; + if depth == 2 { + for attr in e.attributes().with_checks(false).flatten() { + let (res, local) = reader.resolver().resolve_attribute(attr.key); + if local.as_ref() == b"id" + && let quick_xml::name::ResolveResult::Bound(ns) = res + && is_rel_ns(ns.as_ref()) + { + return true; + } + } + break; + } + } + Ok((_, quick_xml::events::Event::Eof)) | Err(_) => break, + _ => {} + } + } + false +} + +fn child_has_rel_id(root_tag: &str, compat_open: &str, child_str: &str) -> bool { + let root = if root_tag.starts_with('<') { + root_tag + } else { + r#""# + }; + let mut xml = String::with_capacity(root.len() + compat_open.len() + child_str.len() + 32); + xml.push_str(root); + xml.push_str(compat_open); + xml.push_str(child_str); + xml.push_str(""); + let mut reader = quick_xml::NsReader::from_str(&xml); + let mut depth = 0; + loop { + match reader.read_resolved_event() { + Ok((_, quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e))) => { + depth += 1; + if depth >= 3 { + for attr in e.attributes().with_checks(false).flatten() { + let (res, local) = reader.resolver().resolve_attribute(attr.key); + if local.as_ref() == b"id" + && let quick_xml::name::ResolveResult::Bound(ns) = res + && is_rel_ns(ns.as_ref()) + { + return true; + } + } + } + } + Ok((_, quick_xml::events::Event::End(_))) => { + depth -= 1; + } + Ok((_, quick_xml::events::Event::Eof)) | Err(_) => break, + _ => {} + } + } + false +} + +fn compat_has_unmodeled_attrs(root_tag: &str, compat_tag: &str) -> bool { + let root = if root_tag.starts_with('<') { + root_tag + } else { + r#""# + }; + let mut xml = String::with_capacity(root.len() + compat_tag.len() + 32); + xml.push_str(root); + xml.push_str(compat_tag); + if !compat_tag.ends_with("/>") { + xml.push_str(""); + } else { + xml.push_str(""); + } + let mut reader = quick_xml::NsReader::from_str(&xml); + let mut depth = 0; + loop { + match reader.read_resolved_event() { + Ok((_, quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e))) => { + depth += 1; + if depth == 2 { + for attr in e.attributes().with_checks(false).flatten() { + let key = attr.key.as_ref(); + if key.starts_with(b"xmlns:") || key == b"xmlns" { + continue; + } + let (res, local) = reader.resolver().resolve_attribute(attr.key); + if local.as_ref() == b"id" + && let quick_xml::name::ResolveResult::Bound(ns) = res + && is_rel_ns(ns.as_ref()) + { + continue; + } + return true; + } + break; + } + } + Ok((_, quick_xml::events::Event::Eof)) | Err(_) => break, + _ => {} + } + } + false } /// Does `original` (a settings part) hold anything the model doesn't write? Then the reader keeps /// it for [`merge`]. False for parts WordCraft wrote itself, and for anything it can't scan. pub fn has_unowned(original: &[u8]) -> bool { let Some(xml) = std::str::from_utf8(original).ok() else { return false }; - let Some((_, _, kids)) = children(xml, "w:settings") else { return false }; + let Some((o_start, open_end, _, kids)) = children(xml, "w:settings") else { return false }; + let root_tag = xml.get(o_start..open_end).unwrap_or(""); if kids.iter().any(|child| child.name == "w:mailMerge") { let Some(parsed) = crate::xml::parse(original).ok() else { return false }; if kids.len() == parsed.els().count() @@ -339,13 +895,26 @@ pub fn has_unowned(original: &[u8]) -> bool { return true; } } - kids.iter().any(|k| match k.name.as_str() { - // Anything in `w:compat` beyond its own tag and the compatibility mode. - "w:compat" => xml.get(k.start..k.end).is_some_and(|c| { - let mode = usize::from(c.contains("w:name=\"compatibilityMode\"")); - c.matches(" 0 - }), - n => !OWNED.contains(&n), + kids.iter().any(|k| { + if is_wml_compat_container(root_tag, xml, k) { + xml.get(k.start..k.end).is_some_and(|c| { + let open_end = tag_end(c).map(|e| e + 1).unwrap_or(0); + let compat_open = c.get(..open_end).unwrap_or(""); + if tag_has_rel_id(root_tag, compat_open) { + return false; + } + if compat_has_unmodeled_attrs(root_tag, compat_open) { + return true; + } + let Some((_, _, _, compat_kids)) = children(c, &k.name) else { return false }; + compat_kids.iter().any(|kid| { + !is_compat_mode_child(root_tag, c, kid) + && c.get(kid.start..kid.end).is_some_and(|child_str| !child_has_rel_id(root_tag, compat_open, child_str)) + }) + }) + } else { + !OWNED.contains(&k.name.as_str()) && !xml.get(k.start..k.end).is_some_and(|s| s.contains("r:id=")) + } }) } @@ -353,8 +922,8 @@ pub fn has_unowned(original: &[u8]) -> bool { pub fn merge(original: &[u8], generated: &[u8]) -> Option> { let orig = std::str::from_utf8(original).ok()?; let gen_s = std::str::from_utf8(generated).ok()?; - let (o_open, o_close, mut o_kids) = children(orig, "w:settings")?; - let (_, _, g_kids) = children(gen_s, "w:settings")?; + let (o_start, o_open, o_close, mut o_kids) = children(orig, "w:settings")?; + let (_, _, _, g_kids) = children(gen_s, "w:settings")?; // Mail merge is regenerated from the namespace-aware tree. Recognise the same children // here, including local/default aliases, so a recovered save can remove the original too. // Keep every other child's existing byte-preserving merge policy. @@ -370,7 +939,8 @@ pub fn merge(original: &[u8], generated: &[u8]) -> Option> { } } // Prefixes the generated children use must be declared by the original root. - let root_tag = orig.get(..o_open)?; + let root_tag = orig.get(o_start..o_open)?; + let preamble = orig.get(..o_start)?; for p in ["w", "m", "r"] { if g_kids.iter().any(|k| k.name.starts_with(&format!("{p}:"))) && !root_tag.contains(&format!("xmlns:{p}=")) { return None; @@ -426,10 +996,12 @@ pub fn merge(original: &[u8], generated: &[u8]) -> Option> { if let Some(gi) = mark(&k.name, &mut used) { out.push((k.name.clone(), g_text(g_kids.get(gi)?)?)); } - } else if k.name == "w:compat" { + } else if is_wml_compat_container(root_tag, orig, k) { let g_compat = mark("w:compat", &mut used).and_then(|gi| g_text(g_kids.get(gi)?)); - let merged = merge_compat(root_tag, text, g_compat.as_deref().unwrap_or(""))?; - out.push((k.name.clone(), merged)); + let merged = merge_compat(root_tag, text, &k.name, g_compat.as_deref().unwrap_or(""))?; + if !merged.is_empty() { + out.push(("w:compat".to_string(), merged)); + } } else if !text.contains("r:id=") { out.push((k.name.clone(), text.to_string())); } @@ -444,6 +1016,7 @@ pub fn merge(original: &[u8], generated: &[u8]) -> Option> { out.insert(at, (g.name.clone(), g_text(g)?)); } let mut s = String::with_capacity(orig.len() + 256); + s.push_str(preamble); s.push_str(root_tag); for (_, t) in &out { s.push_str(t); @@ -587,5 +1160,206 @@ mod tests { let out_esc = String::from_utf8(merge(orig_escaped.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); assert!(!out_esc.contains("compatibility"), "{out_esc}"); assert!(out_esc.contains("overrideTableStyleFontSizeAndJustification"), "{out_esc}"); + + // Leading whitespace before w:settings and root-declared alias + let orig_ws = r#" + "#; + let out_ws = String::from_utf8(merge(orig_ws.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out_ws.contains("compatibilityMode"), "{out_ws}"); + assert!(out_ws.contains("overrideTableStyleFontSizeAndJustification"), "{out_ws}"); + } + + #[test] + fn compat_block_closing_tag_with_whitespace_preserves_unowned_children() { + let orig = r#""#; + assert!(has_unowned(orig.as_bytes()), "expected has_unowned with "); + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(""), "{merged}"); + assert!(!merged.contains("compatibilityMode"), "{merged}"); + } + + #[test] + fn compat_mode_matching_ignores_unqualified_attributes() { + // A compatSetting with unqualified name="compatibilityMode" (no namespace) and w:name="vendorOption" + let orig = r#""#; + // Since it's not a true compatibilityMode, has_unowned treats it as unowned vendor setting + assert!(has_unowned(orig.as_bytes())); + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + // The vendor setting is preserved on save + assert!(merged.contains(r#"w:name="vendorOption""#), "{merged}"); + } + + #[test] + fn repeated_compat_switches_are_all_removed_when_disabled_and_deduplicated_when_enabled() { + let orig_two = r#""#; + // Disabled in generated: both must be removed + let gen_disabled = + r#""#; + let out_disabled = String::from_utf8(merge(orig_two.as_bytes(), gen_disabled.as_bytes()).unwrap()).unwrap(); + assert!(!out_disabled.contains("doNotExpandShiftReturn"), "{out_disabled}"); + assert!(out_disabled.contains(""), "{out_disabled}"); + + // Enabled in generated: exactly one occurrence emitted + let gen_enabled = r#""#; + let out_enabled = String::from_utf8(merge(orig_two.as_bytes(), gen_enabled.as_bytes()).unwrap()).unwrap(); + assert_eq!(out_enabled.matches("doNotExpandShiftReturn").count(), 1, "{out_enabled}"); + assert!(out_enabled.contains(""), "{out_enabled}"); + } + + #[test] + fn new_compat_switches_are_inserted_in_schema_order() { + // spacingInWholePoints is ranked after doNotExpandShiftReturn in CT_Compat + let orig = r#""#; + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + let idx_shift = merged.find("").unwrap(); + let idx_spacing = merged.find("").unwrap(); + assert!(idx_shift < idx_spacing, "doNotExpandShiftReturn must precede spacingInWholePoints: {merged}"); + } + + #[test] + fn aliased_compat_container_and_switches_synchronize() { + // Document uses aliased prefix a: for WordprocessingML + let orig = r#""#; + // User disabled switch + let gen_disabled = + r#""#; + let out_disabled = String::from_utf8(merge(orig.as_bytes(), gen_disabled.as_bytes()).unwrap()).unwrap(); + assert!(!out_disabled.contains("doNotExpandShiftReturn"), "{out_disabled}"); + assert!(out_disabled.contains(""), "{out_disabled}"); + } + + #[test] + fn clearing_mode_removes_every_matching_word_mode() { + // Multiple Word mode entries (e.g. 15 and 14) and one vendor entry + let orig = r#""#; + let gen_no_mode = + r#""#; + let out = String::from_utf8(merge(orig.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out.contains(r#"w:val="15""#), "{out}"); + assert!(!out.contains(r#"w:val="14""#), "{out}"); + assert!(out.contains(r#"w:uri="urn:vendor""#), "{out}"); + } + + #[test] + fn mode_attribute_lookup_precedence_matches_reader() { + // Fallback to unqualified uri="urn:vendor" excludes vendor entry + let orig_vendor_uri = r#""#; + assert!(has_unowned(orig_vendor_uri.as_bytes())); + + // Fallback to unqualified name="compatibilityMode" when w:name is absent recognizes mode + let orig_unqual_name = r#""#; + let gen_no_mode = + r#""#; + let out = String::from_utf8(merge(orig_unqual_name.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out.contains("compatibilityMode"), "{out}"); + assert!(out.contains(""), "{out}"); + } + + #[test] + fn aliased_compat_container_orders_before_math_pr() { + let orig = r#""#; + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + let idx_compat = merged.find("").unwrap(); + let idx_math = merged.find("").unwrap(); + assert!(idx_compat < idx_math, "a:compat must precede m:mathPr: {merged}"); + } + + #[test] + fn comment_with_closing_tag_syntax_does_not_interfere() { + let orig = r#""#; + assert!(has_unowned(orig.as_bytes())); + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(""), "{merged}"); + } + + #[test] + fn foreign_child_is_ignored_when_finding_switch_insertion_point() { + // x:spacingInWholePoints precedes w:ulTrailSpace + let orig = r#""#; + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + let idx_custom = merged.find("").unwrap(); + let idx_trail = merged.find("").unwrap(); + let idx_shift = merged.find("").unwrap(); + let idx_spacing = merged.find("").unwrap(); + assert!(idx_custom < idx_trail, "custom before trail: {merged}"); + assert!(idx_trail < idx_shift, "trail before shift: {merged}"); + assert!(idx_shift < idx_spacing, "shift before spacing: {merged}"); + } + + #[test] + fn self_closing_compat_container_with_unmodeled_attr_is_retained() { + let orig = r#""#; + assert!(has_unowned(orig.as_bytes()), "expected self-closing compat with unmodeled attr to be retained"); + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(r#"x:layout="legacy""#), "{merged}"); + } + + #[test] + fn unmodeled_attributes_on_enabled_switch_are_preserved() { + let orig = r#""#; + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(r#"x:vendor="custom""#), "{merged}"); + } + + #[test] + fn generated_compat_child_in_vendor_rebound_w_prefix_declares_wml_namespace() { + // Document binds prefix 'w' locally to urn:vendor on a:compat + let orig = r#""#; + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(r#""#), "{merged}"); + assert!(merged.contains(""), "{merged}"); + } + + #[test] + fn aliased_compat_drops_unremapped_relationship_markup_while_preserving_relationship_free_markup() { + let orig = r#""#; + assert!(has_unowned(orig.as_bytes())); + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(""), "{merged}"); + assert!(merged.contains(r#"x:note="example r:id=text""#), "text mentioning r:id= must be preserved: {merged}"); + assert!(!merged.contains("rId5"), "expected unremapped r:id to be omitted: {merged}"); + assert!(!merged.contains("rId6"), "expected unremapped rel:id to be omitted: {merged}"); + assert!(!merged.contains("rId7"), "expected unremapped spaced r:id to be omitted: {merged}"); + } + + #[test] + fn switch_with_padded_zero_value_is_enabled_when_model_enables_it() { + let orig = r#""#; + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(r#"w:val="1""#), "{merged}"); + assert!(merged.contains(r#"x:vendor="custom""#), "{merged}"); + } + + #[test] + fn aliased_compat_container_with_bom_and_cleared_mode_removes_old_mode() { + let orig = "\u{FEFF}"; + assert!(has_unowned(orig.as_bytes())); + let gen_xml = r#""#; + let merged_bytes = merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap(); + let merged = String::from_utf8(merged_bytes).unwrap(); + assert!(merged.starts_with('\u{FEFF}'), "expected BOM to be preserved in output: {merged}"); + assert!(merged.contains(""), "{merged}"); + assert!(!merged.contains("compatibilityMode"), "expected compatibilityMode to be removed: {merged}"); + } + + #[test] + fn aliased_compat_drops_strict_relationship_markup() { + let orig = r#""#; + assert!(has_unowned(orig.as_bytes())); + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(""), "{merged}"); + assert!(!merged.contains("rId8"), "expected Strict r:id to be omitted: {merged}"); } } diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 21dfd82505..8e735a0903 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -1672,6 +1672,17 @@ fn hyperlink_history_attribute_preservation_round_trips() { let saved_zero = craft_docx::write(&read_zero).unwrap(); let resaved_zero_xml = doc_xml_of(&saved_zero); assert!(resaved_zero_xml.contains(r#"w:history="0""#), "expected w:history=\"0\" on save, got: {resaved_zero_xml}"); + + // Replace the hyperlink in document.xml to have w:history=" 0 " (whitespace-padded false) + let xml_padded_zero = orig_doc_xml.replace(r#"w:history="1""#, r#"w:history=" 0 ""#); + assert_ne!(orig_doc_xml, xml_padded_zero); + let file_padded = replace_part(&base, "word/document.xml", xml_padded_zero.as_bytes()); + + let read_padded = craft_docx::read(&file_padded).unwrap(); + assert_eq!(paras(&read_padded)[0].props_of_char(0).link_history, Some(false)); + let saved_padded = craft_docx::write(&read_padded).unwrap(); + let resaved_padded_xml = doc_xml_of(&saved_padded); + assert!(resaved_padded_xml.contains(r#"w:history="0""#), "expected w:history=\"0\" on save, got: {resaved_padded_xml}"); } /// Tools › Templates and Add-ins: the attached template (an external relationship of the settings diff --git a/crates/docx/tests/it/settings_merge.rs b/crates/docx/tests/it/settings_merge.rs index 553d23b7d3..5c1ccf3dff 100644 --- a/crates/docx/tests/it/settings_merge.rs +++ b/crates/docx/tests/it/settings_merge.rs @@ -229,9 +229,39 @@ fn cleared_compatibility_mode_removes_it_from_merged_settings() { let s2 = text(&files2, "word/settings.xml"); assert!(!s2.contains("compatibilityMode"), "expected mode removed: {s2}"); assert!(s2.contains(""), "{s2}"); + assert!(s2.contains(""), "expected switch preserved: {s2}"); assert!(s2.contains("overrideTableStyleFontSizeAndJustification"), "{s2}"); assert!(s2.contains("enableOpenTypeFeatures"), "{s2}"); let reopened2 = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); assert_eq!(reopened2.settings.compat_mode, None); + assert!(reopened2.settings.do_not_expand_shift_return); +} + +#[test] +fn foreign_namespace_compat_child_is_preserved_through_round_trip() { + let settings = r#" +"#; + let pkg = with_settings(settings); + let doc = craft_docx::read(&pkg).unwrap(); + assert!(doc.passthrough.contains_key("wordcraft:settings.orig")); + let saved = save(&doc); + let s = text(&saved, "word/settings.xml"); + assert!(s.contains(" +"#; + let pkg = with_settings(settings); + let mut doc = craft_docx::read(&pkg).unwrap(); + assert!(doc.passthrough.contains_key("wordcraft:settings.orig")); + doc.settings.compat_mode = None; + let saved = save(&doc); + let s = text(&saved, "word/settings.xml"); + assert!(s.contains(""), "expected unowned setting preserved: {s}"); + assert!(!s.contains("compatibilityMode"), "expected mode removed: {s}"); } From 18d3d383c3581ec1fbe9c5518de960861832d316 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Wed, 25 Nov 2026 00:31:02 +0530 Subject: [PATCH 4/7] style(docx): format settings_merge.rs --- crates/docx/src/write/settings_merge.rs | 41 ++++++++----------------- 1 file changed, 13 insertions(+), 28 deletions(-) diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index 61c096b565..5437aece4a 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -171,9 +171,9 @@ fn tag_end(s: &str) -> Option { None } -/// The root start tag's span end and the root's direct children, or `None` for anything the -/// scanner doesn't expect (CDATA, DOCTYPE, a different root). -fn children(xml: &str, root: &str) -> Option<(usize, usize, Vec)> { +/// The root start tag's span start, span end, close tag start, and the root's direct children, +/// or `None` for anything the scanner doesn't expect (CDATA, DOCTYPE, a different root). +fn children(xml: &str, root: &str) -> Option<(usize, usize, usize, Vec)> { let open = xml.find(&format!("<{root}"))?; let open_end = open + tag_end(xml.get(open..)?)? + 1; if xml.get(open_end - 2..open_end)? == "/>" { @@ -273,11 +273,8 @@ where F: FnOnce(&quick_xml::events::BytesStart<'_>, &quick_xml::NsReader<&[u8]>, &[u8]) -> bool, { let Some(child_str) = compat_s.get(k.start..k.end) else { return false }; - let root = if root_tag.starts_with('<') { - root_tag - } else { - r#""# - }; + let root = + if root_tag.starts_with('<') { root_tag } else { r#""# }; let Some(compat_open_end) = tag_end(compat_s).map(|e| e + 1) else { return false }; let Some(compat_open) = compat_s.get(..compat_open_end) else { return false }; let mut xml = String::with_capacity(root.len() + compat_open.len() + child_str.len() + 32); @@ -449,11 +446,8 @@ fn is_wml_compat_switch(root_tag: &str, compat_s: &str, k: &Child) -> bool { fn is_wml_compat_container(root_tag: &str, orig: &str, k: &Child) -> bool { let Some(child_str) = orig.get(k.start..k.end) else { return false }; - let root = if root_tag.starts_with('<') { - root_tag - } else { - r#""# - }; + let root = + if root_tag.starts_with('<') { root_tag } else { r#""# }; let Some(open_end) = tag_end(child_str).map(|e| e + 1) else { return false }; let Some(open_tag) = child_str.get(..open_end) else { return false }; let mut xml = String::with_capacity(root.len() + open_tag.len() + 64); @@ -758,11 +752,8 @@ fn merge_compat(root_tag: &str, orig: &str, orig_tag: &str, generated: &str) -> } fn tag_has_rel_id(root_tag: &str, tag_str: &str) -> bool { - let root = if root_tag.starts_with('<') { - root_tag - } else { - r#""# - }; + let root = + if root_tag.starts_with('<') { root_tag } else { r#""# }; let mut xml = String::with_capacity(root.len() + tag_str.len() + 32); xml.push_str(root); xml.push_str(tag_str); @@ -798,11 +789,8 @@ fn tag_has_rel_id(root_tag: &str, tag_str: &str) -> bool { } fn child_has_rel_id(root_tag: &str, compat_open: &str, child_str: &str) -> bool { - let root = if root_tag.starts_with('<') { - root_tag - } else { - r#""# - }; + let root = + if root_tag.starts_with('<') { root_tag } else { r#""# }; let mut xml = String::with_capacity(root.len() + compat_open.len() + child_str.len() + 32); xml.push_str(root); xml.push_str(compat_open); @@ -837,11 +825,8 @@ fn child_has_rel_id(root_tag: &str, compat_open: &str, child_str: &str) -> bool } fn compat_has_unmodeled_attrs(root_tag: &str, compat_tag: &str) -> bool { - let root = if root_tag.starts_with('<') { - root_tag - } else { - r#""# - }; + let root = + if root_tag.starts_with('<') { root_tag } else { r#""# }; let mut xml = String::with_capacity(root.len() + compat_tag.len() + 32); xml.push_str(root); xml.push_str(compat_tag); From 830521eb00f98484e06adbba7b57ac2911da623a Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 27 Nov 2026 06:16:59 +0530 Subject: [PATCH 5/7] Match DOCX settings reader semantics and retain disabled switch extensions --- crates/docx/src/write/settings_merge.rs | 77 +++++++++++++++---------- crates/docx/tests/it/settings_merge.rs | 64 ++++++++++++++++++++ 2 files changed, 111 insertions(+), 30 deletions(-) diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index d94cf5c7d4..9ab1d8201b 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -176,11 +176,20 @@ fn tag_end(s: &str) -> Option { /// The root start tag's span start, span end, close tag start, and the root's direct children, /// or `None` for anything the scanner doesn't expect (CDATA, DOCTYPE, a different root). fn children(xml: &str, root: &str) -> Option<(usize, usize, usize, Vec)> { - let open = xml.find(&format!("<{root}"))?; - let open_end = open + tag_end(xml.get(open..)?)? + 1; - if xml.get(open_end - 2..open_end)? == "/>" { - return None; - } + use quick_xml::events::Event; + let body = xml.strip_prefix('\u{feff}').unwrap_or(xml); + let mut reader = quick_xml::Reader::from_str(body); + let (open, open_end) = loop { + match reader.read_event().ok()? { + Event::Start(e) if e.name().as_ref() == root.as_bytes() => { + let end = xml.len() - body.len() + usize::try_from(reader.buffer_position()).ok()?; + break (end.checked_sub(e.len() + 2)?, end); + } + Event::Decl(_) | Event::PI(_) | Event::Comment(_) => {} + Event::Text(t) if t.iter().all(u8::is_ascii_whitespace) => {} + _ => return None, + } + }; let mut out = Vec::new(); let mut depth = 0usize; let mut i = open_end; @@ -338,15 +347,15 @@ fn is_compat_mode_child(root_tag: &str, compat_s: &str, k: &Child) -> bool { let is_unbound = matches!(ares, quick_xml::name::ResolveResult::Unbound); if local.as_ref() == b"name" { - if is_wml { + if is_wml && w_name.is_none() { w_name = val; - } else if is_unbound { + } else if is_unbound && un_name.is_none() { un_name = val; } } else if local.as_ref() == b"uri" { - if is_wml { + if is_wml && w_uri.is_none() { w_uri = val; - } else if is_unbound { + } else if is_unbound && un_uri.is_none() { un_uri = val; } } @@ -546,7 +555,7 @@ fn qualify_wml_child(g_text: &str, root_tag: &str, compat_s: &str) -> String { } } -fn enable_switch_element(elem_str: &str, root_tag: &str, compat_s: &str) -> String { +fn updated_switch(elem_str: &str, root_tag: &str, compat_s: &str, enabled: bool) -> String { let root = if root_tag.trim_start().starts_with('<') { root_tag } else { @@ -569,7 +578,9 @@ fn enable_switch_element(elem_str: &str, root_tag: &str, compat_s: &str) -> Stri let mut reader = quick_xml::NsReader::from_str(&xml); let mut depth = 0; let mut root_w_ns = None; - let mut disabled_val_range: Option<(usize, usize)> = None; + let mut value_edit = None; + let mut has_extra = + tag_end(elem_str).and_then(|end| elem_str[end + 1..].rsplit_once(" Stri let root_w = root_w_ns.as_deref().unwrap_or(b""); for attr in e.attributes().with_checks(false).flatten() { let (ares, local) = reader.resolver().resolve_attribute(attr.key); - if local.as_ref() == b"val" { - let is_wml = match ares { - quick_xml::name::ResolveResult::Bound(ref ns) => is_wml_ns(ns.as_ref(), root_w), - _ => false, - }; - let is_unbound = matches!(ares, quick_xml::name::ResolveResult::Unbound); + let is_wml = matches!(&ares, quick_xml::name::ResolveResult::Bound(ns) if is_wml_ns(ns.as_ref(), root_w)); + let is_unbound = matches!(ares, quick_xml::name::ResolveResult::Unbound); + if local.as_ref() == b"val" && (is_wml || is_unbound) { let val_str = attr.normalized_value(quick_xml::XmlVersion::Explicit1_0).ok(); let start_in_xml = attr.value.as_ptr() as usize - xml.as_ptr() as usize; if start_in_xml >= elem_offset_in_xml { let start = start_in_xml - elem_offset_in_xml; let end = start + attr.value.len(); - if is_wml { + if is_wml && w_val.is_none() { w_val = Some((val_str, (start, end))); - } else if is_unbound { + } else if is_unbound && un_val.is_none() { un_val = Some((val_str, (start, end))); } } + } else if attr.key.as_ref() != b"xmlns" && !attr.key.as_ref().starts_with(b"xmlns:") { + has_extra = true; } } let chosen = w_val.or(un_val); - if let Some((Some(v), span)) = chosen - && crate::units::is_off_val(&v) - { - disabled_val_range = Some(span); + if let Some((Some(v), span)) = chosen { + if crate::units::is_off_val(&v) == enabled { + value_edit = Some((span, if enabled { "1".to_owned() } else { "0".to_owned() })); + } + } else if !enabled { + let name = e.name(); + let name = std::str::from_utf8(name.as_ref()).unwrap_or_default(); + let prefix = name.rfind(':').map_or("", |i| &name[..=i]); + let pos = 1 + name.len(); + value_edit = Some(((pos, pos), format!(" {prefix}val=\"0\""))); } break; } @@ -621,12 +637,12 @@ fn enable_switch_element(elem_str: &str, root_tag: &str, compat_s: &str) -> Stri } } - if let Some((start, end)) = disabled_val_range - && start < end - && end <= elem_str.len() - { + if !enabled && !has_extra { + return String::new(); + } + if let Some(((start, end), value)) = value_edit { let mut s = elem_str.to_string(); - s.replace_range(start..end, "1"); + s.replace_range(start..end, &value); return s; } elem_str.to_string() @@ -645,7 +661,8 @@ fn sync_compat_switch(root_tag: &str, orig: &mut String, orig_tag: &str, generat ([], None) => {} (matches, None) => { for &(a, b) in matches.iter().rev() { - orig.replace_range(a..b, ""); + let updated = updated_switch(&orig[a..b], root_tag, orig, false); + orig.replace_range(a..b, &updated); } } ([], Some(g_text)) => { @@ -664,7 +681,7 @@ fn sync_compat_switch(root_tag: &str, orig: &mut String, orig_tag: &str, generat } let (first_a, first_b) = matches[0]; let orig_elem = &orig[first_a..first_b]; - let updated = enable_switch_element(orig_elem, root_tag, orig); + let updated = updated_switch(orig_elem, root_tag, orig, true); orig.replace_range(first_a..first_b, &updated); } } diff --git a/crates/docx/tests/it/settings_merge.rs b/crates/docx/tests/it/settings_merge.rs index 4fe770c6a4..167d55fa12 100644 --- a/crates/docx/tests/it/settings_merge.rs +++ b/crates/docx/tests/it/settings_merge.rs @@ -312,3 +312,67 @@ fn hidden_proofing_errors_round_trip() { let back = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); assert!(back.settings.hide_grammar_errors && !back.settings.hide_spelling_errors); } + +#[test] +fn root_example_in_prolog_comment_is_preserved_when_zoom_changes() { + let comment = ""; + let original = format!("\u{feff}{}", SETTINGS.replace(" Vec { + with_settings( + &SETTINGS + .replace("", &format!(r#"{child}"#)), + ) +} + +#[test] +fn mode_merge_keeps_settings_whose_first_qualified_name_or_uri_is_vendor_owned() { + for child in [ + r#""#, + r#""#, + ] { + let mut doc = craft_docx::read(&with_compat_child(child)).unwrap(); + assert_eq!(doc.settings.compat_mode, Some(15)); + doc.settings.compat_mode = None; + let saved = craft_docx::write(&doc).unwrap(); + assert!(text(&unzip(&saved), "word/settings.xml").contains(child)); + assert_eq!(craft_docx::read(&saved).unwrap().settings.compat_mode, None); + } +} + +#[test] +fn enabling_switch_updates_first_qualified_value() { + let child = r#""#; + let mut doc = craft_docx::read(&with_compat_child(child)).unwrap(); + assert!(!doc.settings.do_not_expand_shift_return); + doc.settings.do_not_expand_shift_return = true; + let saved = craft_docx::write(&doc).unwrap(); + assert!(craft_docx::read(&saved).unwrap().settings.do_not_expand_shift_return); + assert!(text(&unzip(&saved), "word/settings.xml").contains(&child.replace("w:val=\"0\"", "w:val=\"1\""))); +} + +#[test] +fn disabled_switch_keeps_vendor_markup_on_save_and_after_an_edit() { + for (child, was_on) in [ + (r#""#, false), + (r#""#, true), + (r#""#, true), + ] { + let mut doc = craft_docx::read(&with_compat_child(child)).unwrap(); + assert_eq!(doc.settings.do_not_expand_shift_return, was_on); + doc.settings.do_not_expand_shift_return = false; + let saved = craft_docx::write(&doc).unwrap(); + let xml = text(&unzip(&saved), "word/settings.xml"); + let expected = + if child.contains("s:val") { child.replace("s:val=\"1\"", "s:val=\"0\"") } else { child.replace("Return> Date: Fri, 27 Nov 2026 17:32:06 +0530 Subject: [PATCH 6/7] Keep vendor markup on deduplicated switches and drop bare compat blocks and all relationship attributes - An enabled compat switch that appears more than once now keeps the occurrences carrying markup the model doesn't write (e.g. x:vendor) and drops only plain duplicates; with none, the first stays. - A bare self-closing follows the empty-block rule, like ; one with unmodeled attributes is still kept. - Compat retention and pruning treat every attribute in the relationship namespace (r:embed, r:link, ...) as a reference, not only r:id; vendor attributes of the same local name stay. Each change has a regression test that fails without it. Co-Authored-By: Claude Opus 5.5 --- crates/docx/src/write/settings_merge.rs | 85 ++++++++++++++++++++----- 1 file changed, 69 insertions(+), 16 deletions(-) diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index 9ab1d8201b..9a4ab2efef 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -648,6 +648,12 @@ fn updated_switch(elem_str: &str, root_tag: &str, compat_s: &str, enabled: bool) elem_str.to_string() } +/// Does the switch element carry attributes or content besides its value? A disabled switch keeps +/// its element only then, so [`updated_switch`] answers this when asked to turn it off. +fn switch_has_extensions(elem_str: &str, root_tag: &str, compat_s: &str) -> bool { + !updated_switch(elem_str, root_tag, compat_s, false).is_empty() +} + fn sync_compat_switch(root_tag: &str, orig: &mut String, orig_tag: &str, generated: &str, sw_local: &str) -> Option<()> { let gen_sw = children(generated, "w:compat").and_then(|(_, _, _, g_kids)| { g_kids.into_iter().find(|k| is_wml_switch_child(root_tag, generated, k, sw_local)).and_then(|k| generated.get(k.start..k.end)) @@ -676,13 +682,19 @@ fn sync_compat_switch(root_tag: &str, orig: &mut String, orig_tag: &str, generat orig.insert_str(at, &child); } (matches, Some(_g_text)) => { - for &(a, b) in matches[1..].iter().rev() { - orig.replace_range(a..b, ""); + // Drop plain duplicates but never one carrying markup the model doesn't write; with + // no such occurrence, the first one stays. + let compat: &str = orig; + let extended: Vec = matches.iter().map(|&(a, b)| switch_has_extensions(&compat[a..b], root_tag, compat)).collect(); + let first_kept = extended.iter().position(|&e| e).unwrap_or(0); + for (i, (&(a, b), &keeps_markup)) in matches.iter().zip(&extended).enumerate().rev() { + if i == first_kept || keeps_markup { + let updated = updated_switch(&orig[a..b], root_tag, orig, true); + orig.replace_range(a..b, &updated); + } else { + orig.replace_range(a..b, ""); + } } - let (first_a, first_b) = matches[0]; - let orig_elem = &orig[first_a..first_b]; - let updated = updated_switch(orig_elem, root_tag, orig, true); - orig.replace_range(first_a..first_b, &updated); } } Some(()) @@ -710,7 +722,8 @@ fn merge_compat(root_tag: &str, orig: &str, orig_tag: &str, generated: &str) -> let gen_modes = mode_spans(generated, "w:compat"); if is_self_closing && gen_modes.is_empty() && !has_any_gen_switch { - return Some(orig.to_string()); + // An empty block goes, as `` does below, unless it carries markup. + return Some(if compat_has_unmodeled_attrs(root_tag, compat_open) { orig.to_string() } else { String::new() }); } let mut out = if is_self_closing { @@ -789,9 +802,8 @@ fn tag_has_rel_id(root_tag: &str, tag_str: &str) -> bool { depth += 1; if depth == 2 { for attr in e.attributes().with_checks(false).flatten() { - let (res, local) = reader.resolver().resolve_attribute(attr.key); - if local.as_ref() == b"id" - && let quick_xml::name::ResolveResult::Bound(ns) = res + let (res, _) = reader.resolver().resolve_attribute(attr.key); + if let quick_xml::name::ResolveResult::Bound(ns) = res && is_rel_ns(ns.as_ref()) { return true; @@ -823,9 +835,8 @@ fn child_has_rel_id(root_tag: &str, compat_open: &str, child_str: &str) -> bool depth += 1; if depth >= 3 { for attr in e.attributes().with_checks(false).flatten() { - let (res, local) = reader.resolver().resolve_attribute(attr.key); - if local.as_ref() == b"id" - && let quick_xml::name::ResolveResult::Bound(ns) = res + let (res, _) = reader.resolver().resolve_attribute(attr.key); + if let quick_xml::name::ResolveResult::Bound(ns) = res && is_rel_ns(ns.as_ref()) { return true; @@ -866,9 +877,8 @@ fn compat_has_unmodeled_attrs(root_tag: &str, compat_tag: &str) -> bool { if key.starts_with(b"xmlns:") || key == b"xmlns" { continue; } - let (res, local) = reader.resolver().resolve_attribute(attr.key); - if local.as_ref() == b"id" - && let quick_xml::name::ResolveResult::Bound(ns) = res + let (res, _) = reader.resolver().resolve_attribute(attr.key); + if let quick_xml::name::ResolveResult::Bound(ns) = res && is_rel_ns(ns.as_ref()) { continue; @@ -1366,4 +1376,47 @@ mod tests { assert!(merged.contains(""), "{merged}"); assert!(!merged.contains("rId8"), "expected Strict r:id to be omitted: {merged}"); } + + #[test] + fn deduplicating_an_enabled_switch_keeps_the_occurrence_with_vendor_markup() { + let orig = r#""#; + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(r#"x:vendor="kept""#), "{merged}"); + assert_eq!(merged.matches("doNotExpandShiftReturn").count(), 1, "{merged}"); + assert!(merged.contains(""), "{merged}"); + } + + #[test] + fn a_bare_self_closing_compat_block_goes_like_an_empty_paired_one() { + let gen_xml = r#""#; + let merged_with = |compat: &str| { + let orig = format!( + r#"{compat}"# + ); + String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap() + }; + let self_closing = merged_with(""); + assert!(!self_closing.contains("compat"), "{self_closing}"); + assert!(self_closing.contains(r#""#), "{self_closing}"); + assert_eq!(self_closing, merged_with("")); + } + + #[test] + fn compat_drops_every_relationship_attribute_but_keeps_vendor_ones_of_the_same_name() { + let gen_xml = r#""#; + let decls = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:x="urn:vendor""#; + // On a child of the block. + let orig = format!(r#""#); + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(!merged.contains("rId9"), "{merged}"); + assert!(merged.contains(r#"x:embed="keep""#) && merged.contains(""), "{merged}"); + // On the block itself. + let orig = format!(r#""#); + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(!merged.contains("rId4"), "{merged}"); + let orig = format!(r#""#); + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(r#"x:link="keep""#), "{merged}"); + } } From 5b571e52540fba9f4470a9c4e62181541216e3dc Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Fri, 27 Nov 2026 20:00:47 +0530 Subject: [PATCH 7/7] Write history on for app-made links and cut settings merge back to w: compat cases Review of storytold/craft-libs#3361 (bflatastic): 1. Links that didn't come from a .docx file lost w:history="1". Replace CharProps::link_history: Option with Option (Off, Omitted), set only by the .docx reader. None, which every other link has and which the reader also gives a link with history on, is written as w:history="1", as main does, so such a link reads back unchanged. Text with no value takes the history of the link it is in, so typing into a link doesn't split it. New test: a link made with a CharProps patch saves with w:history="1". main's picture_links test is back to expecting w:history="1". 2. settings_merge.rs is main's file plus a short merge_compat for the w:-prefixed cases real files have: the owned switches come from the generated part at their CT_Compat position, compatibilityMode is replaced, added or removed, and a block left empty goes. The rest (aliased and rebound prefixes, Strict and r:* relationship markup, escaped names, BOMs and comments, vendor markup on switches) is kept with its 22 tests on the fork branch docx-settings-merge-hardening (079da658b) for a later PR. Co-Authored-By: Claude Opus 5.5 --- crates/docx/src/read/story.rs | 2 +- crates/docx/src/read/story/runs.rs | 7 +- crates/docx/src/write/settings_merge.rs | 898 ++--------------------- crates/docx/src/write/story/para.rs | 37 +- crates/docx/tests/it/picture_links.rs | 2 +- crates/docx/tests/it/roundtrip.rs | 87 +-- crates/docx/tests/it/settings_merge.rs | 92 --- crates/wordmodel/src/props.rs | 4 +- crates/wordmodel/src/props/char_props.rs | 18 +- 9 files changed, 161 insertions(+), 986 deletions(-) diff --git a/crates/docx/src/read/story.rs b/crates/docx/src/read/story.rs index 15ab338e10..8d97db6afb 100644 --- a/crates/docx/src/read/story.rs +++ b/crates/docx/src/read/story.rs @@ -49,7 +49,7 @@ const MAX_FORM: usize = 64 * 1024; pub struct RunCtx { link: Option, link_tooltip: Option>, - link_history: Option, + link_history: Option, ins: Option, del: Option, } diff --git a/crates/docx/src/read/story/runs.rs b/crates/docx/src/read/story/runs.rs index 4efd07cac7..f28745bac1 100644 --- a/crates/docx/src/read/story/runs.rs +++ b/crates/docx/src/read/story/runs.rs @@ -32,7 +32,12 @@ impl Reader<'_> { if let Some(link) = link { c.link = Some(link); c.link_tooltip = k.attr("w:tooltip").and_then(crate::bounded_link_tooltip).map(std::sync::Arc::from); - c.link_history = k.attr("w:history").map(|v| !crate::units::is_off_val(v)); + // History on stays `None`: it is what the writer writes for a link with none. + c.link_history = match k.attr("w:history") { + Some(v) if crate::units::is_off_val(v) => Some(craft_wordmodel::props::LinkHistory::Off), + Some(_) => None, + None => Some(craft_wordmodel::props::LinkHistory::Omitted), + }; } self.read_inline_children(sc, pb, k, rels, &c, depth + 1); } diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index 9a4ab2efef..323e9b7cfa 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -8,7 +8,8 @@ //! tag (namespace declarations, `mc:Ignorable`) and every child the model doesn't own are kept //! byte for byte; owned children come from the generated part (or go, when the model turned //! them off); owned children the original lacks are inserted at their CT_Settings position; in -//! `w:compat` only the `compatibilityMode` setting is replaced. Kept children that refer to a +//! `w:compat` only the switches the model writes and the `compatibilityMode` setting come from the +//! generated part, and a block left empty goes. Kept children that refer to a //! relationship are dropped unless owned: mail merge is regenerated with remapped external //! sources by `mail_merge`. Anything unexpected returns `None`, and the generated part is written as before. @@ -173,32 +174,24 @@ fn tag_end(s: &str) -> Option { None } -/// The root start tag's span start, span end, close tag start, and the root's direct children, -/// or `None` for anything the scanner doesn't expect (CDATA, DOCTYPE, a different root). -fn children(xml: &str, root: &str) -> Option<(usize, usize, usize, Vec)> { - use quick_xml::events::Event; - let body = xml.strip_prefix('\u{feff}').unwrap_or(xml); - let mut reader = quick_xml::Reader::from_str(body); - let (open, open_end) = loop { - match reader.read_event().ok()? { - Event::Start(e) if e.name().as_ref() == root.as_bytes() => { - let end = xml.len() - body.len() + usize::try_from(reader.buffer_position()).ok()?; - break (end.checked_sub(e.len() + 2)?, end); - } - Event::Decl(_) | Event::PI(_) | Event::Comment(_) => {} - Event::Text(t) if t.iter().all(u8::is_ascii_whitespace) => {} - _ => return None, - } - }; +/// The root start tag's span end and the root's direct children, or `None` for anything the +/// scanner doesn't expect (CDATA, DOCTYPE, a different root). +fn children(xml: &str, root: &str) -> Option<(usize, usize, Vec)> { + let open = xml.find(&format!("<{root}"))?; + let open_end = open + tag_end(xml.get(open..)?)? + 1; + if xml.get(open_end - 2..open_end)? == "/>" { + return None; + } + let close = xml.rfind(&format!(""))?; let mut out = Vec::new(); let mut depth = 0usize; let mut i = open_end; let mut cur: Option<(String, usize)> = None; - let close = loop { - let rest = xml.get(i..)?; - let lt = rest.find('<')?; + while i < close { + let rest = xml.get(i..close)?; + let Some(lt) = rest.find('<') else { break }; let at = i + lt; - let tail = xml.get(at..)?; + let tail = xml.get(at..close)?; if tail.starts_with("")? + 3; continue; @@ -213,13 +206,6 @@ fn children(xml: &str, root: &str) -> Option<(usize, usize, usize, Vec)> let gt = at + tag_end(tail)? + 1; let tag = xml.get(at..gt)?; if tag.starts_with(" Option<(usize, usize, usize, Vec)> } } i = gt; - }; + } if depth != 0 { return None; } - Some((open, open_end, close, out)) + Some((open_end, close, out)) } -fn find_close_tag(xml: &str, tag_name: &str) -> Option { - children(xml, tag_name).map(|(_, _, close, _)| close) -} - -const WML: &[u8] = b"http://schemas.openxmlformats.org/wordprocessingml/2006/main"; -const WML_STRICT: &[u8] = b"http://purl.oclc.org/ooxml/wordprocessingml/main"; -const REL_NS: &[u8] = b"http://schemas.openxmlformats.org/officeDocument/2006/relationships"; -const REL_STRICT_NS: &[u8] = b"http://purl.oclc.org/ooxml/officeDocument/relationships"; - -fn is_rel_ns(ns: &[u8]) -> bool { - let unesc = unescaped_ns(ns); - unesc.as_ref() == REL_NS || unesc.as_ref() == REL_STRICT_NS -} - -fn unescaped_ns(ns: &[u8]) -> std::borrow::Cow<'_, [u8]> { - if ns.contains(&b'&') - && let Ok(s) = std::str::from_utf8(ns) - && let Ok(unesc) = quick_xml::escape::unescape(s) - { - return std::borrow::Cow::Owned(unesc.into_owned().into_bytes()); - } - std::borrow::Cow::Borrowed(ns) -} - -fn is_wml_ns(ns: &[u8], root_w: &[u8]) -> bool { - let unesc_ns = unescaped_ns(ns); - let unesc_root = unescaped_ns(root_w); - (!unesc_root.is_empty() && unesc_ns.as_ref() == unesc_root.as_ref()) || unesc_ns.as_ref() == WML || unesc_ns.as_ref() == WML_STRICT -} - -const OWNED_COMPAT_SWITCHES: &[&str] = &["doNotExpandShiftReturn", "doNotUseHTMLParagraphAutoSpacing", "allowSpaceOfSameStyleInTable"]; - -fn check_compat_child(root_tag: &str, compat_s: &str, k: &Child, check: F) -> bool -where - F: FnOnce(&quick_xml::events::BytesStart<'_>, &quick_xml::NsReader<&[u8]>, &[u8]) -> bool, -{ - let Some(child_str) = compat_s.get(k.start..k.end) else { return false }; - let root = - if root_tag.starts_with('<') { root_tag } else { r#""# }; - let Some(compat_open_end) = tag_end(compat_s).map(|e| e + 1) else { return false }; - let Some(compat_open) = compat_s.get(..compat_open_end) else { return false }; - let mut xml = String::with_capacity(root.len() + compat_open.len() + child_str.len() + 32); - xml.push_str(root); - xml.push_str(compat_open); - xml.push_str(child_str); - xml.push_str(""); - let mut reader = quick_xml::NsReader::from_str(&xml); - let mut depth = 0; - let mut root_w_ns = None; - loop { - match reader.read_resolved_event() { - Ok((_, quick_xml::events::Event::Start(_))) => { - depth += 1; - if depth == 1 { - root_w_ns = match reader.resolver().resolve_element(quick_xml::name::QName(b"w:dummy")).0 { - quick_xml::name::ResolveResult::Bound(ns) => Some(ns.as_ref().to_vec()), - _ => None, - }; - } else if depth == 2 { - break; - } - } - Ok((_, quick_xml::events::Event::Eof)) | Err(_) => return false, - _ => {} - } - } - if let Ok((res, quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e))) = reader.read_resolved_event() { - let is_wml_elem = match res { - quick_xml::name::ResolveResult::Bound(ref ns) => is_wml_ns(ns.as_ref(), root_w_ns.as_deref().unwrap_or(b"")), - _ => false, - }; - if !is_wml_elem { - return false; - } - check(e, &reader, root_w_ns.as_deref().unwrap_or(b"")) - } else { - false - } -} - -fn is_compat_mode_child(root_tag: &str, compat_s: &str, k: &Child) -> bool { - check_compat_child(root_tag, compat_s, k, |e, reader, root_w| { - if e.local_name().as_ref() != b"compatSetting" { - return false; - } - let mut w_name = None; - let mut un_name = None; - let mut w_uri = None; - let mut un_uri = None; - - for attr in e.attributes().with_checks(false).flatten() { - let (ares, local) = reader.resolver().resolve_attribute(attr.key); - let val = attr.normalized_value(quick_xml::XmlVersion::Explicit1_0).ok(); - let is_wml = match ares { - quick_xml::name::ResolveResult::Bound(ref ns) => is_wml_ns(ns.as_ref(), root_w), - _ => false, - }; - let is_unbound = matches!(ares, quick_xml::name::ResolveResult::Unbound); - - if local.as_ref() == b"name" { - if is_wml && w_name.is_none() { - w_name = val; - } else if is_unbound && un_name.is_none() { - un_name = val; - } - } else if local.as_ref() == b"uri" { - if is_wml && w_uri.is_none() { - w_uri = val; - } else if is_unbound && un_uri.is_none() { - un_uri = val; - } - } - } - - let name = w_name.or(un_name); - let uri = w_uri.or(un_uri); - name.as_deref() == Some("compatibilityMode") && uri.as_deref().is_none_or(|u| u == "http://schemas.microsoft.com/office/word") - }) -} - -fn is_wml_switch_child(root_tag: &str, compat_s: &str, k: &Child, sw_local: &str) -> bool { - check_compat_child(root_tag, compat_s, k, |e, _reader, _root_w| e.local_name().as_ref() == sw_local.as_bytes()) -} +/// The `w:compat` switches the model writes (`super::settings`). +const OWNED_COMPAT_SWITCHES: &[&str] = &["w:doNotExpandShiftReturn", "w:doNotUseHTMLParagraphAutoSpacing", "w:allowSpaceOfSameStyleInTable"]; +/// CT_Compat's sequence (ECMA-376 §17.15.3.9), for placing inserted switches. const CT_COMPAT_ORDER: &[&str] = &[ "useSingleBorderforContiguousCells", "wpJustification", @@ -440,467 +306,59 @@ const CT_COMPAT_ORDER: &[&str] = &[ "compatSetting", ]; -fn compat_child_rank(name: &str) -> usize { - let local = name.rsplit(':').next().unwrap_or(name); - CT_COMPAT_ORDER.iter().position(|&n| n == local).unwrap_or(CT_COMPAT_ORDER.len()) +/// Position of a `w:`-prefixed `w:compat` child in [`CT_COMPAT_ORDER`]; `None` for anything else. +fn compat_rank(name: &str) -> Option { + let local = name.strip_prefix("w:")?; + CT_COMPAT_ORDER.iter().position(|n| *n == local) } -fn recognized_compat_child_rank(root_tag: &str, compat_s: &str, k: &Child) -> Option { - let local = k.name.rsplit(':').next().unwrap_or(&k.name); - let rank = CT_COMPAT_ORDER.iter().position(|&n| n == local)?; - if check_compat_child(root_tag, compat_s, k, |_, _, _| true) { Some(rank) } else { None } +/// Is this `w:compat` child Word's `compatibilityMode` setting? +fn is_compat_mode(child: &str) -> bool { + let mut reader = quick_xml::Reader::from_str(child); + let Ok(quick_xml::events::Event::Start(e) | quick_xml::events::Event::Empty(e)) = reader.read_event() else { return false }; + e.name().as_ref() == b"w:compatSetting" + && e.attributes().with_checks(false).flatten().any(|a| a.key.as_ref() == b"w:name" && a.value.as_ref() == b"compatibilityMode") } -fn is_wml_compat_switch(root_tag: &str, compat_s: &str, k: &Child) -> bool { - OWNED_COMPAT_SWITCHES.iter().any(|sw| is_wml_switch_child(root_tag, compat_s, k, sw)) -} - -fn is_wml_compat_container(root_tag: &str, orig: &str, k: &Child) -> bool { - let Some(child_str) = orig.get(k.start..k.end) else { return false }; - let root = - if root_tag.starts_with('<') { root_tag } else { r#""# }; - let Some(open_end) = tag_end(child_str).map(|e| e + 1) else { return false }; - let Some(open_tag) = child_str.get(..open_end) else { return false }; - let mut xml = String::with_capacity(root.len() + open_tag.len() + 64); - xml.push_str(root); - if open_tag.ends_with("/>") { - xml.push_str(open_tag); - } else { - let tag_name = &k.name; - xml.push_str(open_tag); - xml.push_str(&format!("")); - } - xml.push_str(""); - let mut reader = quick_xml::NsReader::from_str(&xml); - let mut depth = 0; - let mut root_w_ns = None; - loop { - match reader.read_resolved_event() { - Ok((_, quick_xml::events::Event::Start(_))) if depth == 0 => { - depth = 1; - root_w_ns = match reader.resolver().resolve_element(quick_xml::name::QName(b"w:dummy")).0 { - quick_xml::name::ResolveResult::Bound(ns) => Some(ns.as_ref().to_vec()), - _ => None, - }; - } - Ok((res, quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e))) if depth == 1 => { - let is_wml_elem = match res { - quick_xml::name::ResolveResult::Bound(ref ns) => is_wml_ns(ns.as_ref(), root_w_ns.as_deref().unwrap_or(b"")), - _ => false, - }; - return is_wml_elem && e.local_name().as_ref() == b"compat"; - } - Ok((_, quick_xml::events::Event::Eof)) | Err(_) => return false, - _ => {} - } - } -} - -fn compat_destination_and_w_ns(root_tag: &str, compat_s: &str) -> (Vec, Option>) { - let root = if root_tag.trim_start().starts_with('<') { - root_tag - } else { - r#""# +/// The original `w:compat` with what the model owns in it taken from the generated one (`""` +/// when the model writes none): its switches, and the `compatibilityMode` setting. A block left +/// without children goes (`""`). +fn merge_compat(orig: &str, generated: &str) -> Option { + let g_kids = children(generated, "w:compat").map(|(_, _, kids)| kids).unwrap_or_default(); + let g_child = |pred: &dyn Fn(&Child, &str) -> bool| g_kids.iter().find_map(|k| generated.get(k.start..k.end).filter(|text| pred(k, text))); + let mut out = match orig.strip_suffix("/>") { + Some(open) => format!("{}>", open.trim_end()), + None => orig.to_string(), }; - let Some(open_end) = tag_end(compat_s).map(|e| e + 1) else { - return (WML.to_vec(), Some(WML.to_vec())); - }; - let Some(compat_open) = compat_s.get(..open_end) else { - return (WML.to_vec(), Some(WML.to_vec())); - }; - let mut xml = String::with_capacity(root.len() + compat_open.len() + 64); - xml.push_str(root); - xml.push_str(compat_open); - if !compat_open.ends_with("/>") { - xml.push_str(""); - } - xml.push_str(""); - let mut reader = quick_xml::NsReader::from_str(&xml); - let mut depth = 0; - let mut compat_ns = WML.to_vec(); - let mut w_ns = None; - while let Ok((res, ev)) = reader.read_resolved_event() { - match ev { - quick_xml::events::Event::Start(_) => depth += 1, - quick_xml::events::Event::Empty(_) if depth == 1 => depth = 2, - quick_xml::events::Event::Eof => break, - _ => {} - } - if depth == 2 { - if let quick_xml::name::ResolveResult::Bound(ns) = res { - compat_ns = unescaped_ns(ns.as_ref()).into_owned(); - } - if let quick_xml::name::ResolveResult::Bound(ns) = reader.resolver().resolve_element(quick_xml::name::QName(b"w:dummy")).0 { - w_ns = Some(unescaped_ns(ns.as_ref()).into_owned()); - } - break; - } - } - (compat_ns, w_ns) -} - -fn qualify_wml_child(g_text: &str, root_tag: &str, compat_s: &str) -> String { - let (compat_ns, w_ns) = compat_destination_and_w_ns(root_tag, compat_s); - if w_ns.as_deref() == Some(&compat_ns) { - g_text.to_string() - } else { - let uri_str = std::str::from_utf8(&compat_ns).unwrap_or("http://schemas.openxmlformats.org/wordprocessingml/2006/main"); - if let Some(space_pos) = g_text.find(|c: char| c.is_whitespace() || c == '/' || c == '>') { - let mut s = g_text.to_string(); - s.insert_str(space_pos, &format!(r#" xmlns:w="{uri_str}""#)); - s - } else { - g_text.to_string() - } - } -} - -fn updated_switch(elem_str: &str, root_tag: &str, compat_s: &str, enabled: bool) -> String { - let root = if root_tag.trim_start().starts_with('<') { - root_tag - } else { - r#""# - }; - let Some(open_end) = tag_end(compat_s).map(|e| e + 1) else { return elem_str.to_string() }; - let Some(compat_open) = compat_s.get(..open_end) else { return elem_str.to_string() }; - let elem_offset_in_xml = root.len() + compat_open.len(); - let mut xml = String::with_capacity(root.len() + compat_open.len() + elem_str.len() + 64); - xml.push_str(root); - xml.push_str(compat_open); - xml.push_str(elem_str); - if !elem_str.ends_with("/>") { - xml.push_str(""); - } - if !compat_open.ends_with("/>") { - xml.push_str(""); - } - xml.push_str(""); - let mut reader = quick_xml::NsReader::from_str(&xml); - let mut depth = 0; - let mut root_w_ns = None; - let mut value_edit = None; - let mut has_extra = - tag_end(elem_str).and_then(|end| elem_str[end + 1..].rsplit_once(" { - depth = 1; - root_w_ns = match reader.resolver().resolve_element(quick_xml::name::QName(b"w:dummy")).0 { - quick_xml::name::ResolveResult::Bound(ns) => Some(ns.as_ref().to_vec()), - _ => None, - }; - } - quick_xml::events::Event::Start(_) if depth == 1 => { - depth = 2; - } - quick_xml::events::Event::Empty(ref e) | quick_xml::events::Event::Start(ref e) if depth >= 2 => { - let mut w_val = None; - let mut un_val = None; - let root_w = root_w_ns.as_deref().unwrap_or(b""); - for attr in e.attributes().with_checks(false).flatten() { - let (ares, local) = reader.resolver().resolve_attribute(attr.key); - let is_wml = matches!(&ares, quick_xml::name::ResolveResult::Bound(ns) if is_wml_ns(ns.as_ref(), root_w)); - let is_unbound = matches!(ares, quick_xml::name::ResolveResult::Unbound); - if local.as_ref() == b"val" && (is_wml || is_unbound) { - let val_str = attr.normalized_value(quick_xml::XmlVersion::Explicit1_0).ok(); - let start_in_xml = attr.value.as_ptr() as usize - xml.as_ptr() as usize; - if start_in_xml >= elem_offset_in_xml { - let start = start_in_xml - elem_offset_in_xml; - let end = start + attr.value.len(); - if is_wml && w_val.is_none() { - w_val = Some((val_str, (start, end))); - } else if is_unbound && un_val.is_none() { - un_val = Some((val_str, (start, end))); - } - } - } else if attr.key.as_ref() != b"xmlns" && !attr.key.as_ref().starts_with(b"xmlns:") { - has_extra = true; - } - } - let chosen = w_val.or(un_val); - if let Some((Some(v), span)) = chosen { - if crate::units::is_off_val(&v) == enabled { - value_edit = Some((span, if enabled { "1".to_owned() } else { "0".to_owned() })); - } - } else if !enabled { - let name = e.name(); - let name = std::str::from_utf8(name.as_ref()).unwrap_or_default(); - let prefix = name.rfind(':').map_or("", |i| &name[..=i]); - let pos = 1 + name.len(); - value_edit = Some(((pos, pos), format!(" {prefix}val=\"0\""))); - } - break; - } - quick_xml::events::Event::Eof => break, - _ => {} - } - } - - if !enabled && !has_extra { - return String::new(); - } - if let Some(((start, end), value)) = value_edit { - let mut s = elem_str.to_string(); - s.replace_range(start..end, &value); - return s; - } - elem_str.to_string() -} - -/// Does the switch element carry attributes or content besides its value? A disabled switch keeps -/// its element only then, so [`updated_switch`] answers this when asked to turn it off. -fn switch_has_extensions(elem_str: &str, root_tag: &str, compat_s: &str) -> bool { - !updated_switch(elem_str, root_tag, compat_s, false).is_empty() -} - -fn sync_compat_switch(root_tag: &str, orig: &mut String, orig_tag: &str, generated: &str, sw_local: &str) -> Option<()> { - let gen_sw = children(generated, "w:compat").and_then(|(_, _, _, g_kids)| { - g_kids.into_iter().find(|k| is_wml_switch_child(root_tag, generated, k, sw_local)).and_then(|k| generated.get(k.start..k.end)) - }); - - let (_, _, o_close, o_kids) = children(orig, orig_tag)?; - let orig_matches: Vec<(usize, usize)> = - o_kids.iter().filter(|k| is_wml_switch_child(root_tag, orig, k, sw_local)).map(|k| (k.start, k.end)).collect(); - - match (orig_matches.as_slice(), gen_sw) { - ([], None) => {} - (matches, None) => { - for &(a, b) in matches.iter().rev() { - let updated = updated_switch(&orig[a..b], root_tag, orig, false); - orig.replace_range(a..b, &updated); - } - } - ([], Some(g_text)) => { - let my_rank = compat_child_rank(sw_local); - let at = o_kids - .iter() - .find(|k| recognized_compat_child_rank(root_tag, orig, k).is_some_and(|r| r > my_rank)) - .map(|k| k.start) - .unwrap_or(o_close); - let child = qualify_wml_child(g_text, root_tag, orig); - orig.insert_str(at, &child); - } - (matches, Some(_g_text)) => { - // Drop plain duplicates but never one carrying markup the model doesn't write; with - // no such occurrence, the first one stays. - let compat: &str = orig; - let extended: Vec = matches.iter().map(|&(a, b)| switch_has_extensions(&compat[a..b], root_tag, compat)).collect(); - let first_kept = extended.iter().position(|&e| e).unwrap_or(0); - for (i, (&(a, b), &keeps_markup)) in matches.iter().zip(&extended).enumerate().rev() { - if i == first_kept || keeps_markup { - let updated = updated_switch(&orig[a..b], root_tag, orig, true); - orig.replace_range(a..b, &updated); - } else { - orig.replace_range(a..b, ""); - } - } - } - } - Some(()) -} - -/// The original `w:compat` with its `compatibilityMode` taken from the generated one, -/// or removed if the generated settings omit it. -fn merge_compat(root_tag: &str, orig: &str, orig_tag: &str, generated: &str) -> Option { - let mode_spans = |s: &str, tag: &str| -> Vec<(usize, usize)> { - children(s, tag) - .map(|(_, _, _, kids)| kids.into_iter().filter(|k| is_compat_mode_child(root_tag, s, k)).map(|k| (k.start, k.end)).collect()) - .unwrap_or_default() - }; - - let has_any_gen_switch = - children(generated, "w:compat").is_some_and(|(_, _, _, g_kids)| g_kids.iter().any(|k| is_wml_compat_switch(root_tag, generated, k))); - - let open_end = tag_end(orig)? + 1; - let is_self_closing = orig.get(open_end - 2..open_end) == Some("/>"); - let compat_open = orig.get(..open_end)?; - - if tag_has_rel_id(root_tag, compat_open) { - return children(generated, "w:compat").is_some().then(|| generated.to_string()).or_else(|| Some(String::new())); - } - - let gen_modes = mode_spans(generated, "w:compat"); - if is_self_closing && gen_modes.is_empty() && !has_any_gen_switch { - // An empty block goes, as `` does below, unless it carries markup. - return Some(if compat_has_unmodeled_attrs(root_tag, compat_open) { orig.to_string() } else { String::new() }); - } - - let mut out = if is_self_closing { - let open = orig.get(..open_end - 2)?.trim_end(); - format!("{open}>") - } else { - orig.to_string() - }; - - // Omit relationship-bearing children whose relationships cannot be remapped in settings.xml.rels - if let Some((_, _, _, kids)) = children(&out, orig_tag) { - for k in kids.into_iter().rev() { - if let Some(child_str) = out.get(k.start..k.end) - && child_has_rel_id(root_tag, compat_open, child_str) - { - out.replace_range(k.start..k.end, ""); - } - } - } - for sw in OWNED_COMPAT_SWITCHES { - sync_compat_switch(root_tag, &mut out, orig_tag, generated, sw)?; - } - - let o_modes = mode_spans(&out, orig_tag); - match (o_modes.as_slice(), gen_modes.first()) { - ([], None) => {} - (matches, None) => { - for &(a, b) in matches.iter().rev() { - out.replace_range(a..b, ""); - } + let (_, _, kids) = children(&out, "w:compat")?; + for k in kids.iter().rev().filter(|k| k.name == *sw) { + out.replace_range(k.start..k.end, ""); } - ([], Some(&(c, d))) => { - let g_text = generated.get(c..d)?; - let close = find_close_tag(&out, orig_tag)?; - let child = qualify_wml_child(g_text, root_tag, &out); - out.insert_str(close, &child); - } - (matches, Some(&(c, d))) => { - let g_text = generated.get(c..d)?; - for &(a, b) in matches[1..].iter().rev() { - out.replace_range(a..b, ""); - } - let (first_a, first_b) = matches[0]; - let child = qualify_wml_child(g_text, root_tag, &out); - out.replace_range(first_a..first_b, &child); + if let Some(g) = g_child(&|k, _| k.name == *sw) { + let (_, close, kids) = children(&out, "w:compat")?; + let rank = compat_rank(sw); + let at = kids.iter().find(|k| compat_rank(&k.name) > rank).map_or(close, |k| k.start); + out.insert_str(at, g); } } - - if let Some((c_start, c_open, _, remaining_kids)) = children(&out, orig_tag) - && remaining_kids.is_empty() - && !compat_has_unmodeled_attrs(root_tag, &out[c_start..c_open]) - { - return Some(String::new()); + let (_, close, kids) = children(&out, "w:compat")?; + let o_mode = kids.iter().find(|k| out.get(k.start..k.end).is_some_and(is_compat_mode)).map(|k| k.start..k.end); + match (o_mode, g_child(&|_, text| is_compat_mode(text))) { + (Some(span), Some(g)) => out.replace_range(span, g), + (Some(span), None) => out.replace_range(span, ""), + (None, Some(g)) => out.insert_str(close, g), + (None, None) => {} } - - Some(out) -} - -fn tag_has_rel_id(root_tag: &str, tag_str: &str) -> bool { - let root = - if root_tag.starts_with('<') { root_tag } else { r#""# }; - let mut xml = String::with_capacity(root.len() + tag_str.len() + 32); - xml.push_str(root); - xml.push_str(tag_str); - if !tag_str.ends_with("/>") { - xml.push_str(""); - } else { - xml.push_str(""); - } - let mut reader = quick_xml::NsReader::from_str(&xml); - let mut depth = 0; - loop { - match reader.read_resolved_event() { - Ok((_, quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e))) => { - depth += 1; - if depth == 2 { - for attr in e.attributes().with_checks(false).flatten() { - let (res, _) = reader.resolver().resolve_attribute(attr.key); - if let quick_xml::name::ResolveResult::Bound(ns) = res - && is_rel_ns(ns.as_ref()) - { - return true; - } - } - break; - } - } - Ok((_, quick_xml::events::Event::Eof)) | Err(_) => break, - _ => {} - } - } - false -} - -fn child_has_rel_id(root_tag: &str, compat_open: &str, child_str: &str) -> bool { - let root = - if root_tag.starts_with('<') { root_tag } else { r#""# }; - let mut xml = String::with_capacity(root.len() + compat_open.len() + child_str.len() + 32); - xml.push_str(root); - xml.push_str(compat_open); - xml.push_str(child_str); - xml.push_str(""); - let mut reader = quick_xml::NsReader::from_str(&xml); - let mut depth = 0; - loop { - match reader.read_resolved_event() { - Ok((_, quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e))) => { - depth += 1; - if depth >= 3 { - for attr in e.attributes().with_checks(false).flatten() { - let (res, _) = reader.resolver().resolve_attribute(attr.key); - if let quick_xml::name::ResolveResult::Bound(ns) = res - && is_rel_ns(ns.as_ref()) - { - return true; - } - } - } - } - Ok((_, quick_xml::events::Event::End(_))) => { - depth -= 1; - } - Ok((_, quick_xml::events::Event::Eof)) | Err(_) => break, - _ => {} - } - } - false -} - -fn compat_has_unmodeled_attrs(root_tag: &str, compat_tag: &str) -> bool { - let root = - if root_tag.starts_with('<') { root_tag } else { r#""# }; - let mut xml = String::with_capacity(root.len() + compat_tag.len() + 32); - xml.push_str(root); - xml.push_str(compat_tag); - if !compat_tag.ends_with("/>") { - xml.push_str(""); - } else { - xml.push_str(""); - } - let mut reader = quick_xml::NsReader::from_str(&xml); - let mut depth = 0; - loop { - match reader.read_resolved_event() { - Ok((_, quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e))) => { - depth += 1; - if depth == 2 { - for attr in e.attributes().with_checks(false).flatten() { - let key = attr.key.as_ref(); - if key.starts_with(b"xmlns:") || key == b"xmlns" { - continue; - } - let (res, _) = reader.resolver().resolve_attribute(attr.key); - if let quick_xml::name::ResolveResult::Bound(ns) = res - && is_rel_ns(ns.as_ref()) - { - continue; - } - return true; - } - break; - } - } - Ok((_, quick_xml::events::Event::Eof)) | Err(_) => break, - _ => {} - } - } - false + let (_, _, kids) = children(&out, "w:compat")?; + Some(if kids.is_empty() { String::new() } else { out }) } /// Does `original` (a settings part) hold anything the model doesn't write? Then the reader keeps /// it for [`merge`]. False for parts WordCraft wrote itself, and for anything it can't scan. pub fn has_unowned(original: &[u8]) -> bool { let Some(xml) = std::str::from_utf8(original).ok() else { return false }; - let Some((o_start, open_end, _, kids)) = children(xml, "w:settings") else { return false }; - let root_tag = xml.get(o_start..open_end).unwrap_or(""); + let Some((_, _, kids)) = children(xml, "w:settings") else { return false }; if kids.iter().any(|child| child.name == "w:mailMerge") { let Some(parsed) = crate::xml::parse(original).ok() else { return false }; if kids.len() == parsed.els().count() @@ -909,26 +367,13 @@ pub fn has_unowned(original: &[u8]) -> bool { return true; } } - kids.iter().any(|k| { - if is_wml_compat_container(root_tag, xml, k) { - xml.get(k.start..k.end).is_some_and(|c| { - let open_end = tag_end(c).map(|e| e + 1).unwrap_or(0); - let compat_open = c.get(..open_end).unwrap_or(""); - if tag_has_rel_id(root_tag, compat_open) { - return false; - } - if compat_has_unmodeled_attrs(root_tag, compat_open) { - return true; - } - let Some((_, _, _, compat_kids)) = children(c, &k.name) else { return false }; - compat_kids.iter().any(|kid| { - !is_compat_mode_child(root_tag, c, kid) - && c.get(kid.start..kid.end).is_some_and(|child_str| !child_has_rel_id(root_tag, compat_open, child_str)) - }) - }) - } else { - !OWNED.contains(&k.name.as_str()) && !xml.get(k.start..k.end).is_some_and(|s| s.contains("r:id=")) - } + kids.iter().any(|k| match k.name.as_str() { + // Anything in `w:compat` beyond its own tag and the compatibility mode. + "w:compat" => xml.get(k.start..k.end).is_some_and(|c| { + let mode = usize::from(c.contains("w:name=\"compatibilityMode\"")); + c.matches(" 0 + }), + n => !OWNED.contains(&n), }) } @@ -936,8 +381,8 @@ pub fn has_unowned(original: &[u8]) -> bool { pub fn merge(original: &[u8], generated: &[u8]) -> Option> { let orig = std::str::from_utf8(original).ok()?; let gen_s = std::str::from_utf8(generated).ok()?; - let (o_start, o_open, o_close, mut o_kids) = children(orig, "w:settings")?; - let (_, _, _, g_kids) = children(gen_s, "w:settings")?; + let (o_open, o_close, mut o_kids) = children(orig, "w:settings")?; + let (_, _, g_kids) = children(gen_s, "w:settings")?; // Mail merge is regenerated from the namespace-aware tree. Recognise the same children // here, including local/default aliases, so a recovered save can remove the original too. // Keep every other child's existing byte-preserving merge policy. @@ -953,8 +398,7 @@ pub fn merge(original: &[u8], generated: &[u8]) -> Option> { } } // Prefixes the generated children use must be declared by the original root. - let root_tag = orig.get(o_start..o_open)?; - let preamble = orig.get(..o_start)?; + let root_tag = orig.get(..o_open)?; for p in ["w", "m", "r"] { if g_kids.iter().any(|k| k.name.starts_with(&format!("{p}:"))) && !root_tag.contains(&format!("xmlns:{p}=")) { return None; @@ -1010,11 +454,11 @@ pub fn merge(original: &[u8], generated: &[u8]) -> Option> { if let Some(gi) = mark(&k.name, &mut used) { out.push((k.name.clone(), g_text(g_kids.get(gi)?)?)); } - } else if is_wml_compat_container(root_tag, orig, k) { + } else if k.name == "w:compat" { let g_compat = mark("w:compat", &mut used).and_then(|gi| g_text(g_kids.get(gi)?)); - let merged = merge_compat(root_tag, text, &k.name, g_compat.as_deref().unwrap_or(""))?; + let merged = merge_compat(text, g_compat.as_deref().unwrap_or(""))?; if !merged.is_empty() { - out.push(("w:compat".to_string(), merged)); + out.push((k.name.clone(), merged)); } } else if !text.contains("r:id=") { out.push((k.name.clone(), text.to_string())); @@ -1030,7 +474,6 @@ pub fn merge(original: &[u8], generated: &[u8]) -> Option> { out.insert(at, (g.name.clone(), g_text(g)?)); } let mut s = String::with_capacity(orig.len() + 256); - s.push_str(preamble); s.push_str(root_tag); for (_, t) in &out { s.push_str(t); @@ -1043,7 +486,7 @@ pub fn merge(original: &[u8], generated: &[u8]) -> Option> { mod tests { use super::*; - const GEN: &str = r#""#; + const GEN: &str = r#""#; #[test] fn odd_or_hostile_originals_fall_back_or_merge_without_panicking() { @@ -1161,48 +604,6 @@ mod tests { let out_foreign = String::from_utf8(merge(orig_foreign.as_bytes(), gen_foreign.as_bytes()).unwrap()).unwrap(); assert!(out_foreign.contains("x:compatSetting"), "{out_foreign}"); assert!(!out_foreign.contains(r#"w:name="compatibilityMode""#), "{out_foreign}"); - - // Namespace declared directly on w:compat (not root) with mode replacement - let orig_compat_ns = r#""#; - let gen_new_mode = r#""#; - let out_ns = String::from_utf8(merge(orig_compat_ns.as_bytes(), gen_new_mode.as_bytes()).unwrap()).unwrap(); - assert_eq!(out_ns.matches("compatibilityMode").count(), 1, "{out_ns}"); - assert!(out_ns.contains(r#"w:val="14""#), "{out_ns}"); - - // Escaped XML entities in attribute values - let orig_escaped = r#""#; - let out_esc = String::from_utf8(merge(orig_escaped.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); - assert!(!out_esc.contains("compatibility"), "{out_esc}"); - assert!(out_esc.contains("overrideTableStyleFontSizeAndJustification"), "{out_esc}"); - - // Leading whitespace before w:settings and root-declared alias - let orig_ws = r#" - "#; - let out_ws = String::from_utf8(merge(orig_ws.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); - assert!(!out_ws.contains("compatibilityMode"), "{out_ws}"); - assert!(out_ws.contains("overrideTableStyleFontSizeAndJustification"), "{out_ws}"); - } - - #[test] - fn compat_block_closing_tag_with_whitespace_preserves_unowned_children() { - let orig = r#""#; - assert!(has_unowned(orig.as_bytes()), "expected has_unowned with "); - let gen_xml = r#""#; - let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); - assert!(merged.contains(""), "{merged}"); - assert!(!merged.contains("compatibilityMode"), "{merged}"); - } - - #[test] - fn compat_mode_matching_ignores_unqualified_attributes() { - // A compatSetting with unqualified name="compatibilityMode" (no namespace) and w:name="vendorOption" - let orig = r#""#; - // Since it's not a true compatibilityMode, has_unowned treats it as unowned vendor setting - assert!(has_unowned(orig.as_bytes())); - let gen_xml = r#""#; - let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); - // The vendor setting is preserved on save - assert!(merged.contains(r#"w:name="vendorOption""#), "{merged}"); } #[test] @@ -1233,64 +634,6 @@ mod tests { assert!(idx_shift < idx_spacing, "doNotExpandShiftReturn must precede spacingInWholePoints: {merged}"); } - #[test] - fn aliased_compat_container_and_switches_synchronize() { - // Document uses aliased prefix a: for WordprocessingML - let orig = r#""#; - // User disabled switch - let gen_disabled = - r#""#; - let out_disabled = String::from_utf8(merge(orig.as_bytes(), gen_disabled.as_bytes()).unwrap()).unwrap(); - assert!(!out_disabled.contains("doNotExpandShiftReturn"), "{out_disabled}"); - assert!(out_disabled.contains(""), "{out_disabled}"); - } - - #[test] - fn clearing_mode_removes_every_matching_word_mode() { - // Multiple Word mode entries (e.g. 15 and 14) and one vendor entry - let orig = r#""#; - let gen_no_mode = - r#""#; - let out = String::from_utf8(merge(orig.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); - assert!(!out.contains(r#"w:val="15""#), "{out}"); - assert!(!out.contains(r#"w:val="14""#), "{out}"); - assert!(out.contains(r#"w:uri="urn:vendor""#), "{out}"); - } - - #[test] - fn mode_attribute_lookup_precedence_matches_reader() { - // Fallback to unqualified uri="urn:vendor" excludes vendor entry - let orig_vendor_uri = r#""#; - assert!(has_unowned(orig_vendor_uri.as_bytes())); - - // Fallback to unqualified name="compatibilityMode" when w:name is absent recognizes mode - let orig_unqual_name = r#""#; - let gen_no_mode = - r#""#; - let out = String::from_utf8(merge(orig_unqual_name.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); - assert!(!out.contains("compatibilityMode"), "{out}"); - assert!(out.contains(""), "{out}"); - } - - #[test] - fn aliased_compat_container_orders_before_math_pr() { - let orig = r#""#; - let gen_xml = r#""#; - let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); - let idx_compat = merged.find("").unwrap(); - let idx_math = merged.find("").unwrap(); - assert!(idx_compat < idx_math, "a:compat must precede m:mathPr: {merged}"); - } - - #[test] - fn comment_with_closing_tag_syntax_does_not_interfere() { - let orig = r#""#; - assert!(has_unowned(orig.as_bytes())); - let gen_xml = r#""#; - let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); - assert!(merged.contains(""), "{merged}"); - } - #[test] fn foreign_child_is_ignored_when_finding_switch_insertion_point() { // x:spacingInWholePoints precedes w:ulTrailSpace @@ -1306,87 +649,6 @@ mod tests { assert!(idx_shift < idx_spacing, "shift before spacing: {merged}"); } - #[test] - fn self_closing_compat_container_with_unmodeled_attr_is_retained() { - let orig = r#""#; - assert!(has_unowned(orig.as_bytes()), "expected self-closing compat with unmodeled attr to be retained"); - let gen_xml = r#""#; - let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); - assert!(merged.contains(r#"x:layout="legacy""#), "{merged}"); - } - - #[test] - fn unmodeled_attributes_on_enabled_switch_are_preserved() { - let orig = r#""#; - let gen_xml = r#""#; - let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); - assert!(merged.contains(r#"x:vendor="custom""#), "{merged}"); - } - - #[test] - fn generated_compat_child_in_vendor_rebound_w_prefix_declares_wml_namespace() { - // Document binds prefix 'w' locally to urn:vendor on a:compat - let orig = r#""#; - let gen_xml = r#""#; - let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); - assert!(merged.contains(r#""#), "{merged}"); - assert!(merged.contains(""), "{merged}"); - } - - #[test] - fn aliased_compat_drops_unremapped_relationship_markup_while_preserving_relationship_free_markup() { - let orig = r#""#; - assert!(has_unowned(orig.as_bytes())); - let gen_xml = r#""#; - let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); - assert!(merged.contains(""), "{merged}"); - assert!(merged.contains(r#"x:note="example r:id=text""#), "text mentioning r:id= must be preserved: {merged}"); - assert!(!merged.contains("rId5"), "expected unremapped r:id to be omitted: {merged}"); - assert!(!merged.contains("rId6"), "expected unremapped rel:id to be omitted: {merged}"); - assert!(!merged.contains("rId7"), "expected unremapped spaced r:id to be omitted: {merged}"); - } - - #[test] - fn switch_with_padded_zero_value_is_enabled_when_model_enables_it() { - let orig = r#""#; - let gen_xml = r#""#; - let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); - assert!(merged.contains(r#"w:val="1""#), "{merged}"); - assert!(merged.contains(r#"x:vendor="custom""#), "{merged}"); - } - - #[test] - fn aliased_compat_container_with_bom_and_cleared_mode_removes_old_mode() { - let orig = "\u{FEFF}"; - assert!(has_unowned(orig.as_bytes())); - let gen_xml = r#""#; - let merged_bytes = merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap(); - let merged = String::from_utf8(merged_bytes).unwrap(); - assert!(merged.starts_with('\u{FEFF}'), "expected BOM to be preserved in output: {merged}"); - assert!(merged.contains(""), "{merged}"); - assert!(!merged.contains("compatibilityMode"), "expected compatibilityMode to be removed: {merged}"); - } - - #[test] - fn aliased_compat_drops_strict_relationship_markup() { - let orig = r#""#; - assert!(has_unowned(orig.as_bytes())); - let gen_xml = r#""#; - let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); - assert!(merged.contains(""), "{merged}"); - assert!(!merged.contains("rId8"), "expected Strict r:id to be omitted: {merged}"); - } - - #[test] - fn deduplicating_an_enabled_switch_keeps_the_occurrence_with_vendor_markup() { - let orig = r#""#; - let gen_xml = r#""#; - let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); - assert!(merged.contains(r#"x:vendor="kept""#), "{merged}"); - assert_eq!(merged.matches("doNotExpandShiftReturn").count(), 1, "{merged}"); - assert!(merged.contains(""), "{merged}"); - } - #[test] fn a_bare_self_closing_compat_block_goes_like_an_empty_paired_one() { let gen_xml = r#""#; @@ -1401,22 +663,4 @@ mod tests { assert!(self_closing.contains(r#""#), "{self_closing}"); assert_eq!(self_closing, merged_with("")); } - - #[test] - fn compat_drops_every_relationship_attribute_but_keeps_vendor_ones_of_the_same_name() { - let gen_xml = r#""#; - let decls = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:x="urn:vendor""#; - // On a child of the block. - let orig = format!(r#""#); - let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); - assert!(!merged.contains("rId9"), "{merged}"); - assert!(merged.contains(r#"x:embed="keep""#) && merged.contains(""), "{merged}"); - // On the block itself. - let orig = format!(r#""#); - let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); - assert!(!merged.contains("rId4"), "{merged}"); - let orig = format!(r#""#); - let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); - assert!(merged.contains(r#"x:link="keep""#), "{merged}"); - } } diff --git a/crates/docx/src/write/story/para.rs b/crates/docx/src/write/story/para.rs index 9aa365b204..15c23ee9f9 100644 --- a/crates/docx/src/write/story/para.rs +++ b/crates/docx/src/write/story/para.rs @@ -211,11 +211,18 @@ impl Writer<'_> { continue; } // Hyperlinks with different ScreenTips or history settings stay separate even if their target is shared. - let link = props - .link - .as_deref() - .filter(|target| !target.is_empty()) - .map(|target| (target, props.link_tooltip.as_deref().and_then(crate::bounded_link_tooltip), props.link_history)); + let base = link_target_and_tip; + // Text with no history of its own (typed into a link) takes the history of the link it + // is in: the open one, or else the first of the following text in the same link that has one. + let link = base(props).map(|(target, tip)| { + let history = match open_link { + Some((open_target, open_tip, open_history)) if (open_target, open_tip) == (target, tip) => props.link_history.or(open_history), + _ => props.link_history.or_else(|| { + pieces.iter().skip(i + 1).map(|(_, p)| *p).take_while(|p| base(p) == Some((target, tip))).find_map(|p| p.link_history) + }), + }; + (target, tip, history) + }); if link != open_link { if open_link.is_some() { w.close("w:hyperlink"); @@ -232,8 +239,8 @@ impl Writer<'_> { let mut n = 0; attrs[n] = target; n += 1; - if let Some(h) = hist { - attrs[n] = ("w:history", if h { "1" } else { "0" }); + if let Some(h) = link_history_val(hist) { + attrs[n] = ("w:history", h); n += 1; } if let Some(tip) = tip { @@ -363,3 +370,19 @@ impl Writer<'_> { } } } + +/// A run's hyperlink target and the ScreenTip it is written with, or `None` outside a link. +fn link_target_and_tip(p: &CharProps) -> Option<(&str, Option<&str>)> { + p.link.as_deref().filter(|target| !target.is_empty()).map(|target| (target, p.link_tooltip.as_deref().and_then(crate::bounded_link_tooltip))) +} + +/// The `w:history` value a hyperlink is written with: off or none when a .docx file gave that, +/// otherwise on, as Word writes it for a new link. +fn link_history_val(history: Option) -> Option<&'static str> { + use craft_wordmodel::props::LinkHistory; + match history { + None => Some("1"), + Some(LinkHistory::Off) => Some("0"), + Some(LinkHistory::Omitted) => None, + } +} diff --git a/crates/docx/tests/it/picture_links.rs b/crates/docx/tests/it/picture_links.rs index 0c9e19fa67..34cf625e1b 100644 --- a/crates/docx/tests/it/picture_links.rs +++ b/crates/docx/tests/it/picture_links.rs @@ -107,7 +107,7 @@ fn a_linked_picture_is_saved_with_its_link_on_the_drawing_too() { let back = craft_docx::read(&bytes).unwrap(); assert_eq!(picture_links(&back), [Some("https://example.com/saved".to_string()), Some("#Spot".to_string())]); // The drawing's link alone (as Word writes it) reads back the same. - let without_run_link = xml.replace(&format!(r#""#), "").replacen("", "", 1); + let without_run_link = xml.replace(&format!(r#""#), "").replacen("", "", 1); assert_ne!(without_run_link, xml); let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap(); let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 149aae3868..07a7b79888 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -1657,10 +1657,11 @@ fn compatibility_mode_omitted_round_trips_without_synthesizing() { assert!(read_back2.settings.do_not_expand_shift_return); } -/// #3305: Hyperlinks without `w:history`, with `w:history="0"`, or with `w:history="1"` -/// round-trip with the exact attribute state preserved. +/// #3305: a hyperlink keeps the `w:history` a .docx file gave it (on, off or none), and a link +/// with no value, as one made in the app has, is written with history on and reads back the same. #[test] fn hyperlink_history_attribute_preservation_round_trips() { + use craft_wordmodel::props::LinkHistory; let doc_xml_of = |bytes: &[u8]| { let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); let mut xml = String::new(); @@ -1668,61 +1669,29 @@ fn hyperlink_history_attribute_preservation_round_trips() { xml }; - // 1. In-memory / programmatic round-trip with different history settings: - // a) omitted (`None`) - let mut p_none = Paragraph::new(); - p_none - .insert_text( - 0, - "link without history", - &CharProps { link: Some("https://example.com/no-hist".into()), link_history: None, ..Default::default() }, - ) - .unwrap(); - let d_none = doc_with(vec![p_none]); - let bytes_none = craft_docx::write(&d_none).unwrap(); - let xml_none = doc_xml_of(&bytes_none); - assert!(xml_none.contains(" assert!(xml.contains(&format!(r#"w:history="{v}""#)), "{history:?}: {xml}"), + None => assert!(!xml.contains("w:history"), "{history:?}: {xml}"), + } + let read = craft_docx::read(&bytes).unwrap(); + assert_eq!(paras(&read)[0].props_of_char(0).link_history, history); + } let mut p_one = Paragraph::new(); p_one .insert_text( 0, "link with history 1", - &CharProps { link: Some("https://example.com/hist-one".into()), link_history: Some(true), ..Default::default() }, + &CharProps { link: Some("https://example.com/hist-one".into()), link_history: None, ..Default::default() }, ) .unwrap(); let d_one = doc_with(vec![p_one]); - let bytes_one = craft_docx::write(&d_one).unwrap(); - let xml_one = doc_xml_of(&bytes_one); - assert!(xml_one.contains(r#"w:history="1""#), "expected w:history=\"1\" in: {xml_one}"); - let r_one = craft_docx::read(&bytes_one).unwrap(); - let read_prop_one = paras(&r_one)[0].props_of_char(0); - assert_eq!(read_prop_one.link.as_deref(), Some("https://example.com/hist-one")); - assert_eq!(read_prop_one.link_history, Some(true)); // 2. Original XML fixture round-trip: // Verify that reading raw XML with omitted w:history and w:history="0" saves back identically. @@ -1734,7 +1703,7 @@ fn hyperlink_history_attribute_preservation_round_trips() { let file_omitted = replace_part(&base, "word/document.xml", xml_omitted_hist.as_bytes()); let read_omitted = craft_docx::read(&file_omitted).unwrap(); - assert_eq!(paras(&read_omitted)[0].props_of_char(0).link_history, None); + assert_eq!(paras(&read_omitted)[0].props_of_char(0).link_history, Some(LinkHistory::Omitted)); let saved_omitted = craft_docx::write(&read_omitted).unwrap(); let resaved_xml = doc_xml_of(&saved_omitted); assert!(!resaved_xml.contains("w:history"), "expected no w:history on save, got: {resaved_xml}"); @@ -1745,7 +1714,7 @@ fn hyperlink_history_attribute_preservation_round_trips() { let file_zero = replace_part(&base, "word/document.xml", xml_zero_hist.as_bytes()); let read_zero = craft_docx::read(&file_zero).unwrap(); - assert_eq!(paras(&read_zero)[0].props_of_char(0).link_history, Some(false)); + assert_eq!(paras(&read_zero)[0].props_of_char(0).link_history, Some(LinkHistory::Off)); let saved_zero = craft_docx::write(&read_zero).unwrap(); let resaved_zero_xml = doc_xml_of(&saved_zero); assert!(resaved_zero_xml.contains(r#"w:history="0""#), "expected w:history=\"0\" on save, got: {resaved_zero_xml}"); @@ -1756,12 +1725,26 @@ fn hyperlink_history_attribute_preservation_round_trips() { let file_padded = replace_part(&base, "word/document.xml", xml_padded_zero.as_bytes()); let read_padded = craft_docx::read(&file_padded).unwrap(); - assert_eq!(paras(&read_padded)[0].props_of_char(0).link_history, Some(false)); + assert_eq!(paras(&read_padded)[0].props_of_char(0).link_history, Some(LinkHistory::Off)); let saved_padded = craft_docx::write(&read_padded).unwrap(); let resaved_padded_xml = doc_xml_of(&saved_padded); assert!(resaved_padded_xml.contains(r#"w:history="0""#), "expected w:history=\"0\" on save, got: {resaved_padded_xml}"); } +/// #3305: a link the app makes, by laying a `CharProps` patch with a target over text, saves with +/// history on, as it did before `w:history` was kept from .docx files. +#[test] +fn a_link_made_with_a_char_props_patch_saves_with_history_on() { + let mut p = Paragraph::with_text("see the site", CharProps::default()); + let patch = CharProps { link: Some("https://example.com/".into()), ..Default::default() }; + p.format(4, 12, &|c| c.overlay(&patch)).unwrap(); + let bytes = craft_docx::write(&doc_with(vec![p])).unwrap(); + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut xml = String::new(); + std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap(); + assert!(xml.contains(" -"#; - let pkg = with_settings(settings); - let doc = craft_docx::read(&pkg).unwrap(); - assert!(doc.passthrough.contains_key("wordcraft:settings.orig")); - let saved = save(&doc); - let s = text(&saved, "word/settings.xml"); - assert!(s.contains(" -"#; - let pkg = with_settings(settings); - let mut doc = craft_docx::read(&pkg).unwrap(); - assert!(doc.passthrough.contains_key("wordcraft:settings.orig")); - doc.settings.compat_mode = None; - let saved = save(&doc); - let s = text(&saved, "word/settings.xml"); - assert!(s.contains(""), "expected unowned setting preserved: {s}"); - assert!(!s.contains("compatibilityMode"), "expected mode removed: {s}"); -} - /// Hide spelling errors and Hide grammar errors in this document only (`w:hideSpellingErrors`, /// `w:hideGrammaticalErrors`) are read, written once each (before `w:proofState` in a merged /// part), written in a generated part, and left out when they are turned off. @@ -312,67 +284,3 @@ fn hidden_proofing_errors_round_trip() { let back = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); assert!(back.settings.hide_grammar_errors && !back.settings.hide_spelling_errors); } - -#[test] -fn root_example_in_prolog_comment_is_preserved_when_zoom_changes() { - let comment = ""; - let original = format!("\u{feff}{}", SETTINGS.replace(" Vec { - with_settings( - &SETTINGS - .replace("", &format!(r#"{child}"#)), - ) -} - -#[test] -fn mode_merge_keeps_settings_whose_first_qualified_name_or_uri_is_vendor_owned() { - for child in [ - r#""#, - r#""#, - ] { - let mut doc = craft_docx::read(&with_compat_child(child)).unwrap(); - assert_eq!(doc.settings.compat_mode, Some(15)); - doc.settings.compat_mode = None; - let saved = craft_docx::write(&doc).unwrap(); - assert!(text(&unzip(&saved), "word/settings.xml").contains(child)); - assert_eq!(craft_docx::read(&saved).unwrap().settings.compat_mode, None); - } -} - -#[test] -fn enabling_switch_updates_first_qualified_value() { - let child = r#""#; - let mut doc = craft_docx::read(&with_compat_child(child)).unwrap(); - assert!(!doc.settings.do_not_expand_shift_return); - doc.settings.do_not_expand_shift_return = true; - let saved = craft_docx::write(&doc).unwrap(); - assert!(craft_docx::read(&saved).unwrap().settings.do_not_expand_shift_return); - assert!(text(&unzip(&saved), "word/settings.xml").contains(&child.replace("w:val=\"0\"", "w:val=\"1\""))); -} - -#[test] -fn disabled_switch_keeps_vendor_markup_on_save_and_after_an_edit() { - for (child, was_on) in [ - (r#""#, false), - (r#""#, true), - (r#""#, true), - ] { - let mut doc = craft_docx::read(&with_compat_child(child)).unwrap(); - assert_eq!(doc.settings.do_not_expand_shift_return, was_on); - doc.settings.do_not_expand_shift_return = false; - let saved = craft_docx::write(&doc).unwrap(); - let xml = text(&unzip(&saved), "word/settings.xml"); - let expected = - if child.contains("s:val") { child.replace("s:val=\"1\"", "s:val=\"0\"") } else { child.replace("Return>>, - /// Whether to add the hyperlink to the browser's/Word's history (`w:history`). - /// `None` indicates the attribute was omitted from the source document. + /// The hyperlink's `w:history` when a .docx file had it off or left it out. `None` writes it + /// on, as Word does for a new link. #[serde(skip_serializing_if = "Option::is_none")] - pub link_history: Option, + pub link_history: Option, /// Tracked insertion: index into `Document::revisions`. #[serde(skip_serializing_if = "Option::is_none")] pub ins: Option,