From a12bea6ada6b01f86c2a0f47a26cf5416a88109f Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Tue, 24 Nov 2026 21:08:17 +0530 Subject: [PATCH 01/23] 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 02/23] 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 03/23] 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 04/23] 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 37031ecda2c66a5fda8806efb1d127497b6a7e5a Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:45:38 +0530 Subject: [PATCH 05/23] font-manager: a right-click on a glyph cell names that cell The host hangs the menu from the grid response. The panel does not open it. Co-authored-by: Cursor --- crates/font-manager/src/glyphs.rs | 28 ++++++++++++++++++++++++-- crates/font-manager/tests/it/glyphs.rs | 22 +++++++++++++++++++- 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/crates/font-manager/src/glyphs.rs b/crates/font-manager/src/glyphs.rs index aa0ae75021..77ac77f458 100644 --- a/crates/font-manager/src/glyphs.rs +++ b/crates/font-manager/src/glyphs.rs @@ -1,6 +1,8 @@ //! [`GlyphsPanel`]: Photoshop's Glyphs panel. A family and style picker, a category list (Entire Font, Punctuation, //! Currency, ...), a grid of glyph cells drawn by the app's text engine, a zoom slider, and the recently used //! glyphs in a row at the top. Double-click or Enter inserts the glyph where the app can insert. +//! A secondary click on a grid cell reports that cell ([`GlyphsPanelOutput::menu`]); the app opens +//! the menu from the grid response. #[cfg(feature = "suite")] pub(crate) mod stories; @@ -209,6 +211,19 @@ pub struct GlyphsPanelOutput { pub alternate: Option, /// The family or style changed in the panel's own pickers. pub font_changed: bool, + /// The grid cell a context menu was asked for, with the grid response the menu hangs from. + /// Reported on the secondary click and on every later pass while that menu stays open. + pub menu: Option, +} + +/// A grid cell's context menu: the cell, and the grid response the app hangs the menu from. +#[derive(Debug)] +#[non_exhaustive] +pub struct GlyphCellMenu { + /// The cell. + pub cell: GlyphCell, + /// The grid the menu hangs from. + pub opener: Response, } /// The cell whose popup was used and the picked glyph. @@ -483,12 +498,13 @@ impl<'a> GlyphsPanel<'a> { }); }); craft_ui::runtime::frame::request_repaint_after(ui.ctx(), SCAN_POLL_SECONDS); - return GlyphsPanelOutput { response: shown.output, activated: None, alternate: None, font_changed: false }; + return GlyphsPanelOutput { response: shown.output, activated: None, alternate: None, font_changed: false, menu: None }; } let ctx = ui.ctx().clone(); let mut activated_out: Option = None; let mut picked: Option = None; let mut font_changed = false; + let mut menu: Option = None; let shown = Stack::new().label(label).command_scope(GlyphsCommand::SCOPE).show(ui, |ui, cx| { cx.publish(GlyphsCommand::Alternates, CommandState::new()); let mut state = read_bind(&mut settings, cx).unwrap_or_default(); @@ -608,6 +624,14 @@ impl<'a> GlyphsPanel<'a> { None => tile, } }); + // The collection keeps the request while the menu hung from this response stays open. + let opener = shown_grid.response.response.clone(); + menu = shown_grid + .response + .menu + .as_ref() + .and_then(|request| cells.get(request.key).copied()) + .map(|cell| GlyphCellMenu { cell, opener }); for event in shown_grid.response.events { match event { CollectionEvent::Activate(key) => activated = cells.get(key).copied().or(activated), @@ -693,6 +717,6 @@ impl<'a> GlyphsPanel<'a> { write_bind(&mut settings, cx, state, "Glyphs panel"); } }); - GlyphsPanelOutput { response: shown.output, activated: activated_out, alternate: picked, font_changed } + GlyphsPanelOutput { response: shown.output, activated: activated_out, alternate: picked, font_changed, menu } } } diff --git a/crates/font-manager/tests/it/glyphs.rs b/crates/font-manager/tests/it/glyphs.rs index 2a92952e90..787f780977 100644 --- a/crates/font-manager/tests/it/glyphs.rs +++ b/crates/font-manager/tests/it/glyphs.rs @@ -6,6 +6,7 @@ use std::rc::Rc; use craft_font_manager::glyphs::{CellInfo, GlyphCell, GlyphSource, GlyphsPanel, GlyphsPanelSettings}; use craft_ui::contract::Bind; +use craft_ui::testing::pointer; use craft_ui::testing::{Fixture, Room, trial}; use egui::{ColorImage, Event}; @@ -43,6 +44,8 @@ struct Seen { marked: Option, reveal: Option, picks: Vec<(GlyphCell, GlyphCell)>, + /// Cells a secondary click asked for a menu on, in order. + menu: Vec, } fn rig() -> (Fixture, Rc>) { @@ -62,9 +65,13 @@ fn rig() -> (Fixture, Rc>) { if let Some(cell) = reveal { panel = panel.reveal(cell); } - if let Some(pick) = panel.show(ui).alternate { + let out = panel.show(ui); + if let Some(pick) = out.alternate { shown.borrow_mut().picks.push((pick.cell, pick.glyph)); } + if let Some(menu) = out.menu { + shown.borrow_mut().menu.push(menu.cell); + } }); fx.in_room(Room::Window); fx.settle(); @@ -125,6 +132,19 @@ fn a_corner_pick_reports_the_cell_and_the_glyph() { assert!(!visible(&fx, 'Ⓑ'), "a pick closes the popup"); } +#[trial] +fn a_secondary_click_reports_the_cell_the_menu_is_for() { + let (mut fx, seen) = rig(); + let cell = fx.by_label(&name(FIRST)).expect("the first cell"); + let at = cell.center(); + fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]); + fx.frame(vec![pointer::secondary(at, false)]); + fx.settle(); + let menu = seen.borrow().menu.clone(); + assert!(!menu.is_empty(), "the secondary click names the cell"); + assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the menu is for the clicked cell: {menu:?}"); +} + #[trial] fn glyphs_panel_alternates() { let (mut fx, _seen) = rig(); From a3a06160ae49ed29eea39d0adfba80f14843edba Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:02:46 +0530 Subject: [PATCH 06/23] font-manager: an open glyph menu keeps the cell that was clicked A later pass remembers the glyph, not the row, so a same-length list cannot move the menu onto another glyph. Co-authored-by: Cursor --- crates/font-manager/src/glyphs.rs | 27 +++++++++--- crates/font-manager/tests/it/glyphs.rs | 60 +++++++++++++++++++++++++- 2 files changed, 79 insertions(+), 8 deletions(-) diff --git a/crates/font-manager/src/glyphs.rs b/crates/font-manager/src/glyphs.rs index 77ac77f458..6eaf8bdd40 100644 --- a/crates/font-manager/src/glyphs.rs +++ b/crates/font-manager/src/glyphs.rs @@ -325,6 +325,11 @@ struct CellsCache { #[derive(Clone, Default)] struct Marked(Selection); +/// The glyph a context menu was opened on. Later passes keep this glyph: the grid remembers the row, and another +/// glyph of a same-length list must not take the menu over. +#[derive(Clone, Copy, Default)] +struct HeldMenu(Option); + /// The alternates popup: whether it is open, the cell it was opened for and that cell's alternates, read once when /// it opened. #[derive(Clone, Default)] @@ -624,14 +629,22 @@ impl<'a> GlyphsPanel<'a> { None => tile, } }); - // The collection keeps the request while the menu hung from this response stays open. + // The click names the glyph. Later passes keep that glyph: the grid remembers the row, so a + // same-length list must not move the open menu onto whatever glyph is there now. + let clicked = shown_grid.response.events.iter().find_map(|event| match event { + CollectionEvent::ContextMenu(request) => cells.get(request.key).copied(), + _ => None, + }); + let mut held = *cx.memory::(); + if let Some(cell) = clicked { + held = HeldMenu(Some(cell)); + } let opener = shown_grid.response.response.clone(); - menu = shown_grid - .response - .menu - .as_ref() - .and_then(|request| cells.get(request.key).copied()) - .map(|cell| GlyphCellMenu { cell, opener }); + menu = shown_grid.response.menu.is_some().then_some(held.0).flatten().map(|cell| GlyphCellMenu { cell, opener }); + if shown_grid.response.menu.is_none() { + held = HeldMenu(None); + } + *cx.memory::() = held; for event in shown_grid.response.events { match event { CollectionEvent::Activate(key) => activated = cells.get(key).copied().or(activated), diff --git a/crates/font-manager/tests/it/glyphs.rs b/crates/font-manager/tests/it/glyphs.rs index 787f780977..e4845907ef 100644 --- a/crates/font-manager/tests/it/glyphs.rs +++ b/crates/font-manager/tests/it/glyphs.rs @@ -3,9 +3,12 @@ use std::cell::RefCell; use std::rc::Rc; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use craft_font_manager::glyphs::{CellInfo, GlyphCell, GlyphSource, GlyphsPanel, GlyphsPanelSettings}; -use craft_ui::contract::Bind; +use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; +use craft_ui::menu::{Menu, MenuItem}; use craft_ui::testing::pointer; use craft_ui::testing::{Fixture, Room, trial}; use egui::{ColorImage, Event}; @@ -145,6 +148,61 @@ fn a_secondary_click_reports_the_cell_the_menu_is_for() { assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the menu is for the clicked cell: {menu:?}"); } +/// A list whose first cell changes, at the same length, when `swapped` is set. The revision changes with it, so the +/// panel reads the list again. +struct Swap(Arc); + +impl GlyphSource for Swap { + fn cells(&self, _: &str, _: &str, _: &str) -> Vec { + let first = if self.0.load(Ordering::Relaxed) { '\u{0102}' } else { FIRST }; + std::iter::once(GlyphCell::Char(first)).chain((1..300).filter_map(|i| char::from_u32(0x100 + i).map(GlyphCell::Char))).collect() + } + + fn glyph(&self, _: &str, _: &str, _: GlyphCell, _: u32) -> Option { + None + } + + fn revision(&self) -> u64 { + u64::from(self.0.load(Ordering::Relaxed)) + } +} + +#[trial] +fn an_open_menu_keeps_the_clicked_cell_when_that_row_changes() { + let swapped = Arc::new(AtomicBool::new(false)); + let source = Swap(Arc::clone(&swapped)); + let seen = Rc::new(RefCell::new(Vec::::new())); + let shown = Rc::clone(&seen); + let (mut family, mut style, mut settings) = ("Plain".to_owned(), "Regular".to_owned(), GlyphsPanelSettings::default()); + let mut fx = Fixture::new(move |ui| { + let out = GlyphsPanel::new("Glyphs", &source, Bind::bound(&mut family), Bind::bound(&mut style), Bind::bound(&mut settings)) + .can_insert(true) + .show(ui); + if let Some(menu) = out.menu { + shown.borrow_mut().push(menu.cell); + Menu::context("Glyph", &menu.opener).show(ui, |ui, _| { + MenuItem::new("Insert Glyph").show(ui); + }); + } + }); + fx.in_room(Room::Window); + fx.settle(); + let cell = fx.by_label(&name(FIRST)).expect("the first cell"); + let at = cell.center(); + fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]); + fx.frame(vec![pointer::secondary(at, false)]); + fx.settle(); + assert!(seen.borrow().contains(&GlyphCell::Char(FIRST)), "the click names the cell"); + + seen.borrow_mut().clear(); + swapped.store(true, Ordering::Relaxed); + fx.frame(Vec::new()); + fx.settle(); + let menu = seen.borrow().clone(); + assert!(!menu.is_empty(), "the menu stays open"); + assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the row's new glyph does not take the menu: {menu:?}"); +} + #[trial] fn glyphs_panel_alternates() { let (mut fx, _seen) = rig(); From 830521eb00f98484e06adbba7b57ac2911da623a Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 27 Nov 2026 06:16:59 +0530 Subject: [PATCH 07/23] 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 14:47:13 +0530 Subject: [PATCH 08/23] font-manager: an open glyph menu lets go of its cell when the face changes A glyph id names a glyph only in the face it was clicked in. The held menu cell now keeps its family and style, and a pass in another face drops it, so the menu never reports the same id against a different glyph. Co-Authored-By: Claude Opus 5.5 --- crates/font-manager/src/glyphs.rs | 30 ++++++++++----- crates/font-manager/tests/it/glyphs.rs | 51 ++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 9 deletions(-) diff --git a/crates/font-manager/src/glyphs.rs b/crates/font-manager/src/glyphs.rs index 6eaf8bdd40..14eee5ac87 100644 --- a/crates/font-manager/src/glyphs.rs +++ b/crates/font-manager/src/glyphs.rs @@ -325,10 +325,19 @@ struct CellsCache { #[derive(Clone, Default)] struct Marked(Selection); -/// The glyph a context menu was opened on. Later passes keep this glyph: the grid remembers the row, and another -/// glyph of a same-length list must not take the menu over. -#[derive(Clone, Copy, Default)] -struct HeldMenu(Option); +/// The glyph a context menu was opened on, and the face it was opened in. Later passes keep this glyph: the grid +/// remembers the row, and another glyph of a same-length list must not take the menu over. A glyph id names a glyph +/// only in its own face, so the menu holds the cell only while that face is shown. +#[derive(Clone, Default)] +struct HeldMenu(Option); + +/// A held menu's cell and the family and style it was clicked in. +#[derive(Clone)] +struct MenuCell { + cell: GlyphCell, + family: String, + style: String, +} /// The alternates popup: whether it is open, the cell it was opened for and that cell's alternates, read once when /// it opened. @@ -635,15 +644,18 @@ impl<'a> GlyphsPanel<'a> { CollectionEvent::ContextMenu(request) => cells.get(request.key).copied(), _ => None, }); - let mut held = *cx.memory::(); + let mut held = std::mem::take(cx.memory::()); if let Some(cell) = clicked { - held = HeldMenu(Some(cell)); + held = HeldMenu(Some(MenuCell { cell, family: face.0.to_owned(), style: face.1.to_owned() })); } - let opener = shown_grid.response.response.clone(); - menu = shown_grid.response.menu.is_some().then_some(held.0).flatten().map(|cell| GlyphCellMenu { cell, opener }); - if shown_grid.response.menu.is_none() { + // A closed menu lets go of its cell, and so does another face: the same glyph id there is + // another glyph. + let other_face = held.0.as_ref().is_some_and(|held| (held.family.as_str(), held.style.as_str()) != face); + if shown_grid.response.menu.is_none() || other_face { held = HeldMenu(None); } + let opener = shown_grid.response.response.clone(); + menu = held.0.as_ref().map(|held| GlyphCellMenu { cell: held.cell, opener }); *cx.memory::() = held; for event in shown_grid.response.events { match event { diff --git a/crates/font-manager/tests/it/glyphs.rs b/crates/font-manager/tests/it/glyphs.rs index e4845907ef..b4fd930390 100644 --- a/crates/font-manager/tests/it/glyphs.rs +++ b/crates/font-manager/tests/it/glyphs.rs @@ -203,6 +203,57 @@ fn an_open_menu_keeps_the_clicked_cell_when_that_row_changes() { assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the row's new glyph does not take the menu: {menu:?}"); } +/// Unencoded glyphs 1 to 300 in every face: the same id names another glyph in another face. +struct Unencoded; + +impl GlyphSource for Unencoded { + fn cells(&self, _: &str, _: &str, _: &str) -> Vec { + (1..=300).map(GlyphCell::Glyph).collect() + } + + fn glyph(&self, _: &str, _: &str, _: GlyphCell, _: u32) -> Option { + None + } +} + +#[trial] +fn an_open_menu_does_not_report_a_glyph_id_from_another_face() { + let family = Rc::new(RefCell::new("Plain".to_owned())); + let host_family = Rc::clone(&family); + let seen = Rc::new(RefCell::new(Vec::::new())); + let shown = Rc::clone(&seen); + let (mut style, mut settings) = ("Regular".to_owned(), GlyphsPanelSettings::default()); + let mut fx = Fixture::new(move |ui| { + let out = { + let mut family = host_family.borrow_mut(); + GlyphsPanel::new("Glyphs", &Unencoded, Bind::bound(&mut *family), Bind::bound(&mut style), Bind::bound(&mut settings)) + .can_insert(true) + .show(ui) + }; + if let Some(menu) = out.menu { + shown.borrow_mut().push(menu.cell); + Menu::context("Glyph", &menu.opener).show(ui, |ui, _| { + MenuItem::new("Insert Glyph").show(ui); + }); + } + }); + fx.in_room(Room::Window); + fx.settle(); + let cell = fx.by_label("1, glyph 1").expect("the first glyph"); + let at = cell.center(); + fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]); + fx.frame(vec![pointer::secondary(at, false)]); + fx.settle(); + assert!(seen.borrow().contains(&GlyphCell::Glyph(1)), "the click names the glyph"); + + seen.borrow_mut().clear(); + *family.borrow_mut() = "Other".to_owned(); + fx.frame(Vec::new()); + fx.settle(); + let menu = seen.borrow().clone(); + assert!(menu.is_empty(), "the clicked id names another glyph in the new face, so the menu reports none: {menu:?}"); +} + #[trial] fn glyphs_panel_alternates() { let (mut fx, _seen) = rig(); From 079da658b332194d566c1dd7837d4591531178c9 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Fri, 27 Nov 2026 17:32:06 +0530 Subject: [PATCH 09/23] 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 c2d8c9e2e3963d658f01affbddd7b7e7c53e5c95 Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:48:08 +0530 Subject: [PATCH 10/23] font-manager: an open glyph menu lets go of a glyph id when the source changes The source may replace a face under the same family and style, and its revision is the signal. The held menu cell now keeps the revision it was clicked at, and a glyph id is dropped at a new revision; a character still names the same character there, so it stays held. Co-Authored-By: Claude Opus 5.5 --- crates/font-manager/src/glyphs.rs | 17 +++++--- crates/font-manager/tests/it/glyphs.rs | 54 +++++++++++++++++++------- 2 files changed, 53 insertions(+), 18 deletions(-) diff --git a/crates/font-manager/src/glyphs.rs b/crates/font-manager/src/glyphs.rs index 14eee5ac87..232b94c641 100644 --- a/crates/font-manager/src/glyphs.rs +++ b/crates/font-manager/src/glyphs.rs @@ -327,16 +327,18 @@ struct Marked(Selection); /// The glyph a context menu was opened on, and the face it was opened in. Later passes keep this glyph: the grid /// remembers the row, and another glyph of a same-length list must not take the menu over. A glyph id names a glyph -/// only in its own face, so the menu holds the cell only while that face is shown. +/// only in its own face, so the menu holds the cell only while that face is shown: the same family and style, and for +/// a glyph id the same source revision, since the source may replace a face under the same names. #[derive(Clone, Default)] struct HeldMenu(Option); -/// A held menu's cell and the family and style it was clicked in. +/// A held menu's cell, the family and style it was clicked in, and the source's revision then. #[derive(Clone)] struct MenuCell { cell: GlyphCell, family: String, style: String, + revision: u64, } /// The alternates popup: whether it is open, the cell it was opened for and that cell's alternates, read once when @@ -644,13 +646,18 @@ impl<'a> GlyphsPanel<'a> { CollectionEvent::ContextMenu(request) => cells.get(request.key).copied(), _ => None, }); + let revision = source.revision(); let mut held = std::mem::take(cx.memory::()); if let Some(cell) = clicked { - held = HeldMenu(Some(MenuCell { cell, family: face.0.to_owned(), style: face.1.to_owned() })); + held = HeldMenu(Some(MenuCell { cell, family: face.0.to_owned(), style: face.1.to_owned(), revision })); } // A closed menu lets go of its cell, and so does another face: the same glyph id there is - // another glyph. - let other_face = held.0.as_ref().is_some_and(|held| (held.family.as_str(), held.style.as_str()) != face); + // another glyph. A new revision may be another face under the same names; a character still + // names the same character there, a glyph id does not. + let other_face = held.0.as_ref().is_some_and(|held| { + (held.family.as_str(), held.style.as_str()) != face + || (matches!(held.cell, GlyphCell::Glyph(_)) && held.revision != revision) + }); if shown_grid.response.menu.is_none() || other_face { held = HeldMenu(None); } diff --git a/crates/font-manager/tests/it/glyphs.rs b/crates/font-manager/tests/it/glyphs.rs index b4fd930390..51bace6c19 100644 --- a/crates/font-manager/tests/it/glyphs.rs +++ b/crates/font-manager/tests/it/glyphs.rs @@ -4,7 +4,7 @@ use std::cell::RefCell; use std::rc::Rc; use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use craft_font_manager::glyphs::{CellInfo, GlyphCell, GlyphSource, GlyphsPanel, GlyphsPanelSettings}; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; @@ -203,8 +203,9 @@ fn an_open_menu_keeps_the_clicked_cell_when_that_row_changes() { assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the row's new glyph does not take the menu: {menu:?}"); } -/// Unencoded glyphs 1 to 300 in every face: the same id names another glyph in another face. -struct Unencoded; +/// Unencoded glyphs 1 to 300 in every face: the same id names another glyph in another face. Its revision is the +/// shared counter, so a test can replace the faces under the same names. +struct Unencoded(Arc); impl GlyphSource for Unencoded { fn cells(&self, _: &str, _: &str, _: &str) -> Vec { @@ -214,19 +215,32 @@ impl GlyphSource for Unencoded { fn glyph(&self, _: &str, _: &str, _: GlyphCell, _: u32) -> Option { None } + + fn revision(&self) -> u64 { + self.0.load(Ordering::Relaxed) + } } -#[trial] -fn an_open_menu_does_not_report_a_glyph_id_from_another_face() { +/// The host's family and the source's revision, which a test changes between passes, and the cells the panel +/// reported a menu for. +struct OpenMenu { + fx: Fixture, + family: Rc>, + revision: Arc, + seen: Rc>>, +} + +/// A panel over [`Unencoded`] whose host hangs a menu from every menu it reports, with that menu opened on glyph 1. +fn open_menu_on_glyph_1() -> OpenMenu { let family = Rc::new(RefCell::new("Plain".to_owned())); - let host_family = Rc::clone(&family); + let revision = Arc::new(AtomicU64::new(0)); let seen = Rc::new(RefCell::new(Vec::::new())); - let shown = Rc::clone(&seen); + let (host_family, source, shown) = (Rc::clone(&family), Unencoded(Arc::clone(&revision)), Rc::clone(&seen)); let (mut style, mut settings) = ("Regular".to_owned(), GlyphsPanelSettings::default()); let mut fx = Fixture::new(move |ui| { let out = { let mut family = host_family.borrow_mut(); - GlyphsPanel::new("Glyphs", &Unencoded, Bind::bound(&mut *family), Bind::bound(&mut style), Bind::bound(&mut settings)) + GlyphsPanel::new("Glyphs", &source, Bind::bound(&mut *family), Bind::bound(&mut style), Bind::bound(&mut settings)) .can_insert(true) .show(ui) }; @@ -245,15 +259,29 @@ fn an_open_menu_does_not_report_a_glyph_id_from_another_face() { fx.frame(vec![pointer::secondary(at, false)]); fx.settle(); assert!(seen.borrow().contains(&GlyphCell::Glyph(1)), "the click names the glyph"); - seen.borrow_mut().clear(); - *family.borrow_mut() = "Other".to_owned(); - fx.frame(Vec::new()); - fx.settle(); - let menu = seen.borrow().clone(); + OpenMenu { fx, family, revision, seen } +} + +#[trial] +fn an_open_menu_does_not_report_a_glyph_id_from_another_face() { + let mut open = open_menu_on_glyph_1(); + *open.family.borrow_mut() = "Other".to_owned(); + open.fx.frame(Vec::new()); + open.fx.settle(); + let menu = open.seen.borrow().clone(); assert!(menu.is_empty(), "the clicked id names another glyph in the new face, so the menu reports none: {menu:?}"); } +#[trial] +fn an_open_menu_does_not_report_a_glyph_id_from_a_replaced_face() { + let mut open = open_menu_on_glyph_1(); + open.revision.fetch_add(1, Ordering::Relaxed); + open.fx.frame(Vec::new()); + open.fx.settle(); + let menu = open.seen.borrow().clone(); + assert!(menu.is_empty(), "the same names and ids at a new revision may be another face, so the menu reports none: {menu:?}"); +} #[trial] fn glyphs_panel_alternates() { let (mut fx, _seen) = rig(); From 323db9809e3b2a2ebd2e08e2cd038c07d02c67b5 Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:49:28 +0530 Subject: [PATCH 11/23] font-manager: an open glyph menu lets go of a glyph id when the source replaces its faces The source can replace a face under the same family and style, and says so through its revision. The held menu cell now keeps the revision it was clicked at, and a glyph id is dropped once the revision changes. A character names the same glyph in the read-again face, so it stays held. Co-Authored-By: Claude Opus 5.5 --- crates/font-manager/src/glyphs.rs | 24 +++--- crates/font-manager/tests/it/glyphs.rs | 100 +++++++++++++------------ 2 files changed, 67 insertions(+), 57 deletions(-) diff --git a/crates/font-manager/src/glyphs.rs b/crates/font-manager/src/glyphs.rs index 232b94c641..692c7fcb03 100644 --- a/crates/font-manager/src/glyphs.rs +++ b/crates/font-manager/src/glyphs.rs @@ -327,12 +327,12 @@ struct Marked(Selection); /// The glyph a context menu was opened on, and the face it was opened in. Later passes keep this glyph: the grid /// remembers the row, and another glyph of a same-length list must not take the menu over. A glyph id names a glyph -/// only in its own face, so the menu holds the cell only while that face is shown: the same family and style, and for -/// a glyph id the same source revision, since the source may replace a face under the same names. +/// only in its own face, so the menu holds the cell only while that face is shown: the same family and style, and +/// for a glyph id the same source revision, since the source can replace a face under the same names. #[derive(Clone, Default)] struct HeldMenu(Option); -/// A held menu's cell, the family and style it was clicked in, and the source's revision then. +/// A held menu's cell, the family and style it was clicked in, and the source revision then. #[derive(Clone)] struct MenuCell { cell: GlyphCell, @@ -341,6 +341,14 @@ struct MenuCell { revision: u64, } +impl MenuCell { + /// Whether the cell still names the glyph it was clicked on in `face` at `revision`. A character names the same + /// glyph after the source reads its faces again; a glyph id may not. + fn holds_in(&self, face: (&str, &str), revision: u64) -> bool { + (self.family.as_str(), self.style.as_str()) == face && (matches!(self.cell, GlyphCell::Char(_)) || self.revision == revision) + } +} + /// The alternates popup: whether it is open, the cell it was opened for and that cell's alternates, read once when /// it opened. #[derive(Clone, Default)] @@ -651,13 +659,9 @@ impl<'a> GlyphsPanel<'a> { if let Some(cell) = clicked { held = HeldMenu(Some(MenuCell { cell, family: face.0.to_owned(), style: face.1.to_owned(), revision })); } - // A closed menu lets go of its cell, and so does another face: the same glyph id there is - // another glyph. A new revision may be another face under the same names; a character still - // names the same character there, a glyph id does not. - let other_face = held.0.as_ref().is_some_and(|held| { - (held.family.as_str(), held.style.as_str()) != face - || (matches!(held.cell, GlyphCell::Glyph(_)) && held.revision != revision) - }); + // A closed menu lets go of its cell, and so does another face, or a glyph id after the source + // replaced its faces: the same id there is another glyph. + let other_face = held.0.as_ref().is_some_and(|held| !held.holds_in(face, revision)); if shown_grid.response.menu.is_none() || other_face { held = HeldMenu(None); } diff --git a/crates/font-manager/tests/it/glyphs.rs b/crates/font-manager/tests/it/glyphs.rs index 51bace6c19..4972047be6 100644 --- a/crates/font-manager/tests/it/glyphs.rs +++ b/crates/font-manager/tests/it/glyphs.rs @@ -203,8 +203,8 @@ fn an_open_menu_keeps_the_clicked_cell_when_that_row_changes() { assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the row's new glyph does not take the menu: {menu:?}"); } -/// Unencoded glyphs 1 to 300 in every face: the same id names another glyph in another face. Its revision is the -/// shared counter, so a test can replace the faces under the same names. +/// Unencoded glyphs 1 to 300 in every face and at every revision: the same id names another glyph in another face, +/// or in a face the source replaced under the same names. struct Unencoded(Arc); impl GlyphSource for Unencoded { @@ -221,67 +221,73 @@ impl GlyphSource for Unencoded { } } -/// The host's family and the source's revision, which a test changes between passes, and the cells the panel -/// reported a menu for. -struct OpenMenu { +/// A host menu open on glyph 1 of an [`Unencoded`] source, with the family and the revision the test can change. +struct GlyphMenu { fx: Fixture, family: Rc>, revision: Arc, seen: Rc>>, } -/// A panel over [`Unencoded`] whose host hangs a menu from every menu it reports, with that menu opened on glyph 1. -fn open_menu_on_glyph_1() -> OpenMenu { - let family = Rc::new(RefCell::new("Plain".to_owned())); - let revision = Arc::new(AtomicU64::new(0)); - let seen = Rc::new(RefCell::new(Vec::::new())); - let (host_family, source, shown) = (Rc::clone(&family), Unencoded(Arc::clone(&revision)), Rc::clone(&seen)); - let (mut style, mut settings) = ("Regular".to_owned(), GlyphsPanelSettings::default()); - let mut fx = Fixture::new(move |ui| { - let out = { - let mut family = host_family.borrow_mut(); - GlyphsPanel::new("Glyphs", &source, Bind::bound(&mut *family), Bind::bound(&mut style), Bind::bound(&mut settings)) - .can_insert(true) - .show(ui) - }; - if let Some(menu) = out.menu { - shown.borrow_mut().push(menu.cell); - Menu::context("Glyph", &menu.opener).show(ui, |ui, _| { - MenuItem::new("Insert Glyph").show(ui); - }); - } - }); - fx.in_room(Room::Window); - fx.settle(); - let cell = fx.by_label("1, glyph 1").expect("the first glyph"); - let at = cell.center(); - fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]); - fx.frame(vec![pointer::secondary(at, false)]); - fx.settle(); - assert!(seen.borrow().contains(&GlyphCell::Glyph(1)), "the click names the glyph"); - seen.borrow_mut().clear(); - OpenMenu { fx, family, revision, seen } +impl GlyphMenu { + fn open() -> Self { + let revision = Arc::new(AtomicU64::new(0)); + let source = Unencoded(Arc::clone(&revision)); + let family = Rc::new(RefCell::new("Plain".to_owned())); + let host_family = Rc::clone(&family); + let seen = Rc::new(RefCell::new(Vec::::new())); + let shown = Rc::clone(&seen); + let (mut style, mut settings) = ("Regular".to_owned(), GlyphsPanelSettings::default()); + let mut fx = Fixture::new(move |ui| { + let out = { + let mut family = host_family.borrow_mut(); + GlyphsPanel::new("Glyphs", &source, Bind::bound(&mut *family), Bind::bound(&mut style), Bind::bound(&mut settings)) + .can_insert(true) + .show(ui) + }; + if let Some(menu) = out.menu { + shown.borrow_mut().push(menu.cell); + Menu::context("Glyph", &menu.opener).show(ui, |ui, _| { + MenuItem::new("Insert Glyph").show(ui); + }); + } + }); + fx.in_room(Room::Window); + fx.settle(); + let cell = fx.by_label("1, glyph 1").expect("the first glyph"); + let at = cell.center(); + fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]); + fx.frame(vec![pointer::secondary(at, false)]); + fx.settle(); + assert!(seen.borrow().contains(&GlyphCell::Glyph(1)), "the click names the glyph"); + seen.borrow_mut().clear(); + GlyphMenu { fx, family, revision, seen } + } + + /// The cells the menu reported over the next passes. + fn reported(&mut self) -> Vec { + self.fx.frame(Vec::new()); + self.fx.settle(); + self.seen.borrow().clone() + } } #[trial] fn an_open_menu_does_not_report_a_glyph_id_from_another_face() { - let mut open = open_menu_on_glyph_1(); + let mut open = GlyphMenu::open(); *open.family.borrow_mut() = "Other".to_owned(); - open.fx.frame(Vec::new()); - open.fx.settle(); - let menu = open.seen.borrow().clone(); + let menu = open.reported(); assert!(menu.is_empty(), "the clicked id names another glyph in the new face, so the menu reports none: {menu:?}"); } #[trial] -fn an_open_menu_does_not_report_a_glyph_id_from_a_replaced_face() { - let mut open = open_menu_on_glyph_1(); - open.revision.fetch_add(1, Ordering::Relaxed); - open.fx.frame(Vec::new()); - open.fx.settle(); - let menu = open.seen.borrow().clone(); - assert!(menu.is_empty(), "the same names and ids at a new revision may be another face, so the menu reports none: {menu:?}"); +fn an_open_menu_does_not_report_a_glyph_id_after_the_source_replaces_the_face() { + let mut open = GlyphMenu::open(); + open.revision.store(1, Ordering::Relaxed); + let menu = open.reported(); + assert!(menu.is_empty(), "the face behind the same names changed, so the clicked id names another glyph: {menu:?}"); } + #[trial] fn glyphs_panel_alternates() { let (mut fx, _seen) = rig(); From d14a23d33b74f0b43e77e2348fc036dffe44fb79 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Fri, 27 Nov 2026 19:53:19 +0530 Subject: [PATCH 12/23] proof: hyphenate Gujarati between aksharas Gujarati words fell to the English rules and got no break. They now break only between orthographic syllables (aksharas): never inside a conjunct, never before a vowel sign or mark, and never before a dead final consonant. The rules come from the script's Unicode encoding (the shared Brahmic block layout), so no pattern file is read. A `gu` Language pack's patterns still come first. The new `indic` module also carries the Devanagari table, so Hindi and the other Devanagari languages need only a `Script::of` mapping. Part of storytold/vectorcraft#4947. Co-Authored-By: Claude Opus 5.5 --- crates/proof/README.md | 1 + crates/proof/src/gu/mod.rs | 2 +- crates/proof/src/hyphen.rs | 12 +- crates/proof/src/hyphen/tests.rs | 15 +++ crates/proof/src/indic.rs | 225 +++++++++++++++++++++++++++++++ crates/proof/src/lang.rs | 4 +- crates/proof/src/lib.rs | 1 + 7 files changed, 256 insertions(+), 4 deletions(-) create mode 100644 crates/proof/src/indic.rs diff --git a/crates/proof/README.md b/crates/proof/README.md index bbf39f7be8..661b246cf0 100644 --- a/crates/proof/README.md +++ b/crates/proof/README.md @@ -19,6 +19,7 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = " | French (fr-FR, fr-CA and other French pack locales) | the installed Language pack or Hunspell dictionary; dictionary-driven elisions and accent-oriented suggestions | conservative typography and basic checks, with Quebec punctuation spacing in fr-CA | the Language pack (generic fr fallback) | | German | — | — | TeX patterns (embedded, or a Language pack) | | Bulgarian | — | — | syllable rules | +| Gujarati | the installed Hunspell dictionary | generic checks | akshara rules (or a Language pack) | Grammar rules, suggestion tuning and the rule-based hyphenation are code: they work in every build. diff --git a/crates/proof/src/gu/mod.rs b/crates/proof/src/gu/mod.rs index e72089a4ca..619f75ab58 100644 --- a/crates/proof/src/gu/mod.rs +++ b/crates/proof/src/gu/mod.rs @@ -1,6 +1,6 @@ //! Gujarati proofing using the installed Hunspell `gu_IN` dictionary (never bundled). //! Suggestions use its runtime MAP/REP/TRY/KEY tables. Generic grammar checks have Gujarati -//! messages; hyphenation keeps the existing fallback. +//! messages. Hyphenation is by akshara ([`crate::indic`]). pub mod grammar; pub(crate) mod suggest; diff --git a/crates/proof/src/hyphen.rs b/crates/proof/src/hyphen.rs index 862526bb58..f62cd7b027 100644 --- a/crates/proof/src/hyphen.rs +++ b/crates/proof/src/hyphen.rs @@ -15,6 +15,9 @@ //! //! **Bulgarian**: the Bulgarian syllable rules ([`crate::bg`]); no pattern file or word list. //! +//! **Gujarati**: breaks between aksharas, never inside a conjunct or between a consonant and its +//! vowel sign ([`crate::indic`], rules from the script's Unicode encoding); no pattern file. +//! //! **German**: the TeX German patterns for the reformed spelling ([`Patterns::de`]), also for //! Swiss text, whose `ss` the patterns split like any double consonant (`Stras-se`). //! @@ -116,7 +119,7 @@ pub enum Source { Patterns, /// A heuristic for a language without a dictionary or patterns. Heuristic, - /// A language's syllable rules (Bulgarian, [`crate::bg`]). + /// A language's syllable rules (Bulgarian [`crate::bg`], Turkish, Gujarati [`crate::indic`]). Rules, /// No break points: the word is too short or no source applies. None, @@ -156,6 +159,13 @@ fn core_breaks(core: &[char], lang: ProofLang) -> (Vec, Source) { if lang == ProofLang::Bg && core.iter().all(|&c| crate::bg::is_letter(c)) { return (crate::bg::points(core), Source::Rules); } + // Gujarati words break between aksharas ([`crate::indic`]); other words in a Gujarati run + // (`WordCraft`) are hyphenated as English. + if let Some(script) = crate::indic::Script::of(lang) + && core.iter().all(|&c| script.is_letter(c)) + { + return (crate::indic::points(script, core), Source::Rules); + } // A suffix written after an apostrophe (`Ankara'dan`, `Türkiye'nin`) is hyphenated part by // part; no break goes next to the apostrophe ([`word_breaks_in`] drops those). if lang == ProofLang::Tr && core.iter().all(|&c| c == '\'' || crate::tr::hyphen::is_letter(c)) { diff --git a/crates/proof/src/hyphen/tests.rs b/crates/proof/src/hyphen/tests.rs index d8f8cf4318..9fa483fab3 100644 --- a/crates/proof/src/hyphen/tests.rs +++ b/crates/proof/src/hyphen/tests.rs @@ -194,3 +194,18 @@ fn gujarati_pack_patterns_fit_checks_script_and_exceptions() { let en_word: Vec = "hyphenation".chars().collect(); assert!(!pack_patterns_fit(ProofLang::Gu, &pats, &en_word)); } + +/// storytold/vectorcraft#4947: Gujarati text breaks between aksharas, within the paragraph's +/// limits, where it used to fall to the English rules and get no break at all; a Latin word in +/// a Gujarati run is still hyphenated as English. +#[test] +fn gujarati_breaks_between_aksharas_within_the_limits() { + let lim = Limits::default(); + let gu = |w: &str| hyphenate_word_in(w, &lim, ProofLang::Gu); + assert_eq!(gu("વિદ્યાર્થી"), "વિ-દ્યા-ર્થી", "a conjunct is never split"); + assert_eq!(word_breaks_in("વિદ્યાર્થી", ProofLang::Gu).1, Source::Rules); + // A lone consonant at either end is fewer letters than `after_first`/`before_last` allow. + assert_eq!(gu("અમદાવાદ"), "અમ-દા-વાદ"); + assert_eq!(gu("«ગુજરાતી»"), "«ગુ-જ-રા-તી»", "punctuation around the word"); + assert_eq!(gu("Typography"), hyphenate_word_in("Typography", &lim, ProofLang::En)); +} diff --git a/crates/proof/src/indic.rs b/crates/proof/src/indic.rs new file mode 100644 index 0000000000..d333d6ec53 --- /dev/null +++ b/crates/proof/src/indic.rs @@ -0,0 +1,225 @@ +//! Hyphenation of Indic scripts by rule: a word breaks only between its orthographic syllables +//! (aksharas), never inside one. +//! +//! An akshara is a consonant with what is written on it — its vowel sign, nukta, anusvara, +//! candrabindu or visarga — and the consonants joined to it by a virama (a conjunct: `દ્ય`, `ર્થ`, +//! `न्द`), or an independent vowel with its marks. So a break goes only before a consonant or an +//! independent vowel that does not follow a virama: `ગુ-જ-રા-તી`, `વિ-દ્યા-ર્થી`, `સં-સ્કૃત`, +//! `हि-न्दी`. A vowel sign, a mark or the second consonant of a conjunct never starts a line. +//! Nor does a dead consonant — one ending in a virama with no consonant after it (`વાક્`) — since +//! it has no vowel of its own and is the end of the syllable before. +//! +//! The rules come from the scripts' Unicode encoding alone; no pattern file or word list is +//! read (and none is borrowed). The Brahmic blocks share one layout (the ISCII order), so a +//! script is its block's start and a few script-specific code points ([`Script::kind`]). +//! Gujarati ([`ProofLang::Gu`](crate::ProofLang::Gu)) uses them; Devanagari is ready for Hindi +//! and the other Devanagari languages: map the language to [`Script::Devanagari`] in +//! [`Script::of`]. +//! +//! A single akshara left at the end or start of a line is ruled out by the paragraph's +//! [`Limits`](crate::hyphen::Limits), which count letters (vowel signs and anusvara count, +//! viramas and nuktas don't), so a bare consonant (`…-ત`) is not carried over with the default +//! limits but a consonant with its vowel sign (`…-તી`) is. + +use crate::ProofLang; + +/// An Indic script hyphenated by [`points`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Script { + /// Devanagari (U+0900..=U+097F): Hindi, Marathi, Nepali… + Devanagari, + /// Gujarati (U+0A80..=U+0AFF). + Gujarati, +} + +/// What a code point is in an akshara. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + /// An independent vowel: starts an akshara. + Vowel, + /// A consonant: starts an akshara, unless a virama joins it to the consonant before. + Consonant, + /// The virama: joins the consonant before it to the next one, or kills its vowel. + Virama, + /// A vowel sign, nukta, anusvara, candrabindu, visarga or other mark (and the avagraha): + /// belongs to the akshara before it. + Mark, +} + +impl Script { + /// The script whose rules hyphenate `lang`'s words, if any. + pub fn of(lang: ProofLang) -> Option