From 4b9d7fb2dfff9fc2b62c9c1ba7577eb1b80f2dde Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Sat, 31 Oct 2026 16:41:50 +0100 Subject: [PATCH 01/11] fix(math): write the m:deg a square root requires MathRadical::new left degree_present unset, so a square root from add_equation, from LaTeX \sqrt{x} or MathML , wrote an m:rad without m:deg. CT_Rad requires it (ECMA-376 Part 1, 22.1.2.88), and Word writes it empty. A radical read from a file keeps what it had. Part of #432, case 1. --- crates/rdocx-oxml/src/math.rs | 2 +- crates/rdocx/tests/regression_test.rs | 39 +++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/crates/rdocx-oxml/src/math.rs b/crates/rdocx-oxml/src/math.rs index 92d60080a..a99356d31 100644 --- a/crates/rdocx-oxml/src/math.rs +++ b/crates/rdocx-oxml/src/math.rs @@ -1028,7 +1028,7 @@ impl MathRadical { degree: MathArgument::default(), base, hide_degree: true, - degree_present: false, + degree_present: true, preservation: Preservation::default(), } } diff --git a/crates/rdocx/tests/regression_test.rs b/crates/rdocx/tests/regression_test.rs index d683e25d5..4212e366f 100644 --- a/crates/rdocx/tests/regression_test.rs +++ b/crates/rdocx/tests/regression_test.rs @@ -408406,3 +408406,42 @@ fn body_range_across_table_includes_cell_text() { } assert!(failures.is_empty(), "{failures:#?}"); } + +#[test] +fn issue432_a_square_root_equation_writes_the_degree_its_schema_requires() { + let mut document = Document::new(); + let sources = [ + rdocx::equation_from_latex(r"\sqrt{x}").unwrap().value, + rdocx::equation_from_latex(r"\sqrt[3]{x}").unwrap().value, + rdocx::equation_from_mathml( + r#"x"#, + ) + .unwrap() + .value, + ]; + for source in sources { + document + .add_paragraph("") + .add_equation(rdocx::OfficeMath::inline(source.expressions)) + .unwrap(); + } + let xml = document.part_xml("/word/document.xml").unwrap(); + let radicals = xml + .match_indices("") + .map(|(at, _)| &xml[at..]) + .collect::>(); + assert_eq!(radicals.len(), 3, "{xml}"); + for (index, radical) in radicals.into_iter().enumerate() { + let radical = &radical[..radical.find("").unwrap()]; + let properties_end = radical.find("").unwrap() + "".len(); + assert!( + radical[properties_end..].starts_with("").unwrap()..]; + assert!( + square.contains(r#""#), + "{square}" + ); +} From c6038cb3c6e908b6bf7bd8ee958c4bc13071dfbc Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Sat, 31 Oct 2026 16:41:51 +0100 Subject: [PATCH 02/11] fix(notes): write the note mark's run properties first, separators and a space create_footnote_at and create_endnote_at stored w:footnoteRef / w:endnoteRef as a raw run child at boundary 0, which the run writer puts before w:rPr, so footnotes.xml and endnotes.xml broke CT_R. The mark now sits after w:rPr and a space run follows it, as Word writes. A notes stream with no entry yet starts with the separator and continuation separator notes at ids -1 and 0, as Word 2010 and later write them. Note ids still start at 2, and a notes part that already has entries is left as it is. The text of a note rdocx creates now starts with that space, so tests reading it back, and fixtures that patched the first entry of the notes part, are updated. Part of #432, case 2. --- crates/rdocx-py/tests/test_core.py | 9 +- crates/rdocx/src/document.rs | 55 +++++++++- crates/rdocx/tests/integration_test.rs | 3 +- crates/rdocx/tests/regression_test.rs | 134 ++++++++++++++++++++----- 4 files changed, 168 insertions(+), 33 deletions(-) diff --git a/crates/rdocx-py/tests/test_core.py b/crates/rdocx-py/tests/test_core.py index 226fac421..8353f3207 100644 --- a/crates/rdocx-py/tests/test_core.py +++ b/crates/rdocx-py/tests/test_core.py @@ -5265,7 +5265,8 @@ def test_fx201_note_reference_creation_uses_checked_paragraph(): reference = document.add_paragraph("reference") retired_run = reference.runs[0] note = document.add_footnote(reference, "note content") - assert note.paragraphs[0].text == "note content" + # The space run Word writes after the note's reference mark. + assert note.paragraphs[0].text == " note content" assert reference.text == "reference" with pytest.raises(rdocx.StaleElementError): _ = retired_run.text @@ -5695,7 +5696,7 @@ def test_fx201_checked_note_cell_boundary_preserves_other_owners_and_refuses_sta table.cell(0, 0).text = "cell reference" reference = document.tables[0].cell(0, 0).paragraphs[0].runs[0] note = getattr(document, "add_" + family)(reference, family + " content") - assert note.paragraphs[0].text == family + " content" + assert note.paragraphs[0].text == " " + family + " content" before = document.to_bytes() with pytest.raises(rdocx.StaleElementError): getattr(document, "add_" + family)(reference, "stale refused") @@ -10048,7 +10049,7 @@ def test_form_protection_and_permission_composition(): (cell_run, "cell held"), (header, "header held"), (header_run, "header held"), - (note, "note held"), + (note, " note held"), (note_run, "note held"), ) before = document.to_bytes() @@ -10094,7 +10095,7 @@ def test_form_protection_and_permission_composition(): assert document.paragraphs[0].text == body.text == "body held" assert document.tables[0].cell(0, 0).text == cell.text == "cell held" assert document.section(0).header.paragraphs[0].text == header.text == "header held" - assert _story_paragraph(document, "footnote").text == note.text == "note held" + assert _story_paragraph(document, "footnote").text == note.text == " note held" removed = document.remove_document_protection() assert removed is not None and _protection_fields(removed) == _protection_fields(full) with pytest.raises(AttributeError): diff --git a/crates/rdocx/src/document.rs b/crates/rdocx/src/document.rs index 5065dcd8b..a2bc574bf 100644 --- a/crates/rdocx/src/document.rs +++ b/crates/rdocx/src/document.rs @@ -15192,6 +15192,39 @@ pub(crate) fn set_story_source_xml( Ok(()) } +/// The separator and continuation separator a new notes part starts with, at +/// the ids Word 2010 and later write. Ids from 2 stay free for notes, as before. +fn word_note_separators() -> [rdocx_oxml::footnotes::CT_Footnote; 2] { + use rdocx_oxml::footnotes::{CT_Footnote, NoteType}; + let entry = |id, note_type, mark: &[u8]| { + let mut run = CT_R::new(""); + run.content.clear(); + run.extra_xml.push(mark.to_vec()); + run.extra_xml_positions.push(0); + let mut paragraph = CT_P::new(); + paragraph.properties = Some(CT_PPr { + space_after: Some(Twips(0)), + line_spacing: Some(Twips(240)), + line_rule: Some("auto".into()), + ..Default::default() + }); + paragraph.runs.push(run); + CT_Footnote { + id, + note_type, + paragraphs: vec![paragraph], + } + }; + [ + entry(-1, NoteType::Separator, b""), + entry( + 0, + NoteType::ContinuationSeparator, + b"", + ), + ] +} + fn serialized_note_fragment( note: &rdocx_oxml::footnotes::CT_Footnote, kind: StoryKind, @@ -33297,10 +33330,15 @@ impl Document { ..Default::default() }); note_marker.content.clear(); + // After the typed `w:rPr`, which `CT_R` wants first. note_marker.extra_xml.push(b"".to_vec()); - note_marker.extra_xml_positions.push(0); + note_marker.extra_xml_positions.push(1); paragraph.runs.push(note_marker); + paragraph.add_run(" "); paragraph.add_run(text); + if candidate.footnotes.footnotes.is_empty() { + candidate.footnotes.footnotes = word_note_separators().to_vec(); + } candidate .footnotes .footnotes @@ -33405,18 +33443,25 @@ impl Document { ..Default::default() }); note_marker.content.clear(); + // After the typed `w:rPr`, which `CT_R` wants first. note_marker.extra_xml.push(b"".to_vec()); - note_marker.extra_xml_positions.push(0); + note_marker.extra_xml_positions.push(1); paragraph.runs.push(note_marker); + paragraph.add_run(" "); paragraph.add_run(text); let note = rdocx_oxml::footnotes::CT_Footnote { id, note_type: rdocx_oxml::footnotes::NoteType::Normal, paragraphs: vec![paragraph], }; - let fragment = serialized_note_fragment(¬e, StoryKind::Endnote)?; - let updated = - append_story_fragments_to_root(&source, b"endnotes", b"endnote", &[fragment])?; + let mut fragments = Vec::new(); + if existing.footnotes.is_empty() { + for separator in &word_note_separators() { + fragments.push(serialized_note_fragment(separator, StoryKind::Endnote)?); + } + } + fragments.push(serialized_note_fragment(¬e, StoryKind::Endnote)?); + let updated = append_story_fragments_to_root(&source, b"endnotes", b"endnote", &fragments)?; set_story_source_xml(&mut candidate, &part_name, updated)?; candidate.invalidate_layout(); let mut run = CT_R::new(""); diff --git a/crates/rdocx/tests/integration_test.rs b/crates/rdocx/tests/integration_test.rs index c643cac0f..256cf4d0e 100644 --- a/crates/rdocx/tests/integration_test.rs +++ b/crates/rdocx/tests/integration_test.rs @@ -24368,7 +24368,8 @@ fn rich_footnotes_match_word_after_create_edit_reorder_and_remove() { assert!(notes.contains("rich continuation")); document.remove_footnote(first).unwrap(); let mut reopened = Document::from_bytes(&document.to_bytes().unwrap()).unwrap(); - assert_eq!(reopened.footnotes(), vec![(second, "second".to_owned())]); + // The space run Word writes after the note's reference mark. + assert_eq!(reopened.footnotes(), vec![(second, " second".to_owned())]); let package = OpcPackage::from_reader(std::io::Cursor::new(reopened.to_bytes().unwrap())).unwrap(); let body = std::str::from_utf8(package.get_part("/word/document.xml").unwrap()).unwrap(); diff --git a/crates/rdocx/tests/regression_test.rs b/crates/rdocx/tests/regression_test.rs index 4212e366f..7343ea780 100644 --- a/crates/rdocx/tests/regression_test.rs +++ b/crates/rdocx/tests/regression_test.rs @@ -48143,7 +48143,8 @@ fn footnote_removal_clears_references_atomically() { let body = std::str::from_utf8(package.get_part("/word/document.xml").unwrap()).unwrap(); assert!(!body.contains(&format!("footnoteReference w:id=\"{first}\""))); assert!(body.contains(&format!("footnoteReference w:id=\"{second}\""))); - assert_eq!(document.footnotes(), vec![(second, "second".to_owned())]); + // The space run Word writes after the note's reference mark. + assert_eq!(document.footnotes(), vec![(second, " second".to_owned())]); } #[test] @@ -48668,9 +48669,11 @@ fn f276_complete_dependency_source() -> Document { ); package.set_part("/word/styles.xml", styles.into_bytes()); let binding = r#"combined binding"#; - let notes = std::str::from_utf8(package.get_part("/word/footnotes.xml").unwrap()) - .unwrap() - .replacen("", &format!("{binding}"), 1); + let notes = replace_in_first_note( + std::str::from_utf8(package.get_part("/word/footnotes.xml").unwrap()).unwrap(), + "", + &format!("{binding}"), + ); package.set_part("/word/footnotes.xml", notes.into_bytes()); package.set_part( "/customXml/item276.xml", @@ -49217,6 +49220,21 @@ fn fragment_import_preserves_nested_block_control_content() { } } +/// Replace the first `pattern` from the first normal note on, past the +/// separator notes a notes part rdocx creates starts with. A comments part, +/// which has no note, is searched from its start. +fn replace_in_first_note(xml: &str, pattern: &str, replacement: &str) -> String { + let start = xml + .find("", &format!("{comment_binding}"), 1); package.set_part("/word/comments.xml", comments.into_bytes()); - let footnotes = std::str::from_utf8(package.get_part("/word/footnotes.xml").unwrap()).unwrap() - .replacen("", &format!(""), 1) - .replacen("", &format!("{binding}{marker}{anchors}"), 1); + let footnotes = std::str::from_utf8(package.get_part("/word/footnotes.xml").unwrap()).unwrap(); + let footnotes = replace_in_first_note( + footnotes, + "", + &format!( + "" + ), + ); + let footnotes = replace_in_first_note( + &footnotes, + "", + &format!( + "{binding}{marker}{anchors}" + ), + ); let offset = footnotes.find("second companion").unwrap(); let footnotes = format!( "{}{}", @@ -49656,9 +49686,11 @@ fn fragment_import_numbering_maps_do_not_cascade_across_companions() { ("/word/footnotes.xml", ""), ("/word/comments.xml", ""), ] { - let xml = std::str::from_utf8(package.get_part(part).unwrap()) - .unwrap() - .replacen(end, &format!("{numbered}{end}"), 1); + let xml = replace_in_first_note( + std::str::from_utf8(package.get_part(part).unwrap()).unwrap(), + end, + &format!("{numbered}{end}"), + ); package.set_part(part, xml.into_bytes()); } let mut bytes = std::io::Cursor::new(Vec::new()); @@ -49845,16 +49877,14 @@ fn fragment_import_store_allocation_reserves_incoming_companion_identities() { 1, ); package.set_part("/word/document.xml", xml.into_bytes()); - let xml = std::str::from_utf8(package.get_part("/word/footnotes.xml").unwrap()) - .unwrap() - .replacen( - "", - &format!( - "{}", - binding("f2760000-0000-4000-8000-000000000001", "second store") - ), - 1, - ); + let xml = replace_in_first_note( + std::str::from_utf8(package.get_part("/word/footnotes.xml").unwrap()).unwrap(), + "", + &format!( + "{}", + binding("f2760000-0000-4000-8000-000000000001", "second store") + ), + ); package.set_part("/word/footnotes.xml", xml.into_bytes()); for (ordinal, id) in [(1, original), (2, companion)] { let item = format!("/customXml/itemF276{ordinal}.xml"); @@ -49979,7 +50009,13 @@ fn rich_merge_rejects_companion_external_edges_while_fragment_import_preserves_t oxml_opc::relationship::rel_types::HYPERLINK, "https://example.test/companion", ); - let xml = std::str::from_utf8(package.get_part(part).unwrap()).unwrap().replacen("", &format!(r#"companion link"#), 1); + let xml = replace_in_first_note( + std::str::from_utf8(package.get_part(part).unwrap()).unwrap(), + "", + &format!( + r#"companion link"# + ), + ); package.set_part(part, xml.into_bytes()); let mut bytes = std::io::Cursor::new(Vec::new()); package.write_to(&mut bytes).unwrap(); @@ -401725,7 +401761,8 @@ fn fx201_rich_related_paragraphs_and_note_boundaries_publish_atomically() { "checked note", ) .unwrap(); - assert_eq!(document.footnotes(), vec![(id, "checked note".to_owned())]); + // The space run Word writes after the note's reference mark. + assert_eq!(document.footnotes(), vec![(id, " checked note".to_owned())]); assert_eq!(document.paragraphs()[0].text(), "body"); let before = document.to_bytes().unwrap(); let body = document.paragraph_story_location(0).unwrap().unwrap(); @@ -401742,7 +401779,7 @@ fn fx201_rich_related_paragraphs_and_note_boundaries_publish_atomically() { ); assert_eq!(document.to_bytes().unwrap(), before); let mut reopened = Document::from_bytes(&before).unwrap(); - assert_eq!(reopened.footnotes(), vec![(id, "checked note".to_owned())]); + assert_eq!(reopened.footnotes(), vec![(id, " checked note".to_owned())]); reopened.remove_footnote(id).unwrap(); assert!(reopened.footnotes().is_empty()); assert_eq!(reopened.paragraphs()[0].text(), "body"); @@ -408445,3 +408482,54 @@ fn issue432_a_square_root_equation_writes_the_degree_its_schema_requires() { "{square}" ); } + +#[test] +fn issue432_notes_write_the_mark_run_properties_first_with_separators_and_a_space() { + let mut document = Document::new(); + document.add_paragraph("Body text"); + let location = document.paragraph_story_location(0).unwrap().unwrap(); + assert_eq!( + document.create_footnote(&location, "Source note").unwrap(), + 2 + ); + let location = document.paragraph_story_location(0).unwrap().unwrap(); + assert_eq!(document.create_endnote(&location, "End note").unwrap(), 2); + for (part, tag) in [ + ("/word/footnotes.xml", "footnote"), + ("/word/endnotes.xml", "endnote"), + ] { + let xml = document.part_xml(part).unwrap(); + let reference = if tag == "footnote" { + "FootnoteReference" + } else { + "EndnoteReference" + }; + let note = &xml[xml.find(&format!(r#"")).unwrap()]; + let mark = format!( + r#" "# + ); + assert!(note.contains(&mark), "{xml}"); + assert!( + xml.contains(&format!(r#""), + "{xml}" + ); + assert!( + xml.contains(&format!( + r#""), + "{xml}" + ); + } + // A second note neither adds separators again nor moves the first. + let location = document.paragraph_story_location(0).unwrap().unwrap(); + assert_eq!(document.create_footnote(&location, "Second").unwrap(), 3); + let xml = document.part_xml("/word/footnotes.xml").unwrap(); + assert_eq!(xml.matches(r#"w:type="separator""#).count(), 1, "{xml}"); + assert_eq!( + xml.matches(r#"w:type="continuationSeparator""#).count(), + 1, + "{xml}" + ); +} From 35242c0cb184d5fa9c1110cebcb45f51fe8ba565 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Sat, 31 Oct 2026 16:41:52 +0100 Subject: [PATCH 03/11] fix(hyperlink): give the links rdocx writes the Hyperlink character style Links written for the caller had no run properties, so they read as plain text in Word and LibreOffice. Document::ensure_hyperlink_style returns the character style with the id Hyperlink, or else named Hyperlink, and adds Word's built-in definition (colour 0563C1, single underline) when neither exists. Internal and heading links, add_hyperlink_to_story, the HTML and Markdown importer and the binding's Paragraph.add_hyperlink set it on the link run. The low-level Paragraph::add_hyperlink is unchanged. Part of #432, case 3. --- crates/rdocx-py/src/paragraph.rs | 14 ++++- crates/rdocx-py/tests/test_core.py | 32 ++++++++++++ crates/rdocx/src/document.rs | 49 ++++++++++++++++- crates/rdocx/src/html.rs | 55 +++++++++++++------- crates/rdocx/tests/regression_test.rs | 75 +++++++++++++++++++++++++++ 5 files changed, 202 insertions(+), 23 deletions(-) diff --git a/crates/rdocx-py/src/paragraph.rs b/crates/rdocx-py/src/paragraph.rs index 85a525928..16c56d6fc 100644 --- a/crates/rdocx-py/src/paragraph.rs +++ b/crates/rdocx-py/src/paragraph.rs @@ -621,11 +621,23 @@ impl PyParagraph { } None => None, }; + let link_style = match url { + Some(_) => Some( + candidate + .ensure_hyperlink_style() + .map_err(|error| crate::rdocx_to_pyerr(py, error))?, + ), + None => None, + }; let append = |paragraph: &mut rdocx::Paragraph<'_>| { let run_index = paragraph.run_count(); match &relationship_id { Some(relationship_id) => { - paragraph.add_hyperlink_with_tooltip(text, relationship_id, tooltip)?; + let mut run = + paragraph.add_hyperlink_with_tooltip(text, relationship_id, tooltip)?; + if let Some(link_style) = &link_style { + run.set_style(link_style); + } } None => { paragraph.add_run(text); diff --git a/crates/rdocx-py/tests/test_core.py b/crates/rdocx-py/tests/test_core.py index 8353f3207..dc2e74706 100644 --- a/crates/rdocx-py/tests/test_core.py +++ b/crates/rdocx-py/tests/test_core.py @@ -15252,3 +15252,35 @@ def test_fx268_picture_normalization_reuses_actual_checked_rounds(publisher, par assert staging[5] <= 3 * pieces + 20, staging assert picture.bytes == _one_pixel_png() assert len(rdocx.Document.from_bytes(document.to_bytes()).pictures()) == 1 + + +def test_issue432_python_links_take_the_hyperlink_character_style(): + import rdocx + + def link_runs(document): + xml = document.part_xml("word/document.xml") + return re.findall(r"", xml, re.S) + + styled = '' + document = rdocx.Document() + document.add_paragraph("See ").add_hyperlink("the site", "https://example.com") + document.add_heading("Target", 1) + document.add_paragraph("And ") + document.add_heading_hyperlink(document.paragraphs[2], document.paragraphs[1], "Target") + links = link_runs(document) + assert len(links) == 2 and all(styled in link for link in links), links + styles = document.part_xml("word/styles.xml") + assert styles.count('w:styleId="Hyperlink"') == 1, styles + + template = rdocx.Document() + template.add_style("Hyperlink", style_type="character", color="FF0000", underline=True) + for document in ( + rdocx.Document.from_markdown("See [the site](https://example.com).", template=template)[0], + rdocx.Document.from_html('

See the site.

')[0], + ): + links = link_runs(document) + assert links and all(styled in link for link in links), links + # The run of a plain add_run is left alone. + document = rdocx.Document() + document.add_paragraph("plain").add_run(" text") + assert "Hyperlink" not in document.part_xml("word/document.xml") diff --git a/crates/rdocx/src/document.rs b/crates/rdocx/src/document.rs index a2bc574bf..a3f7525fa 100644 --- a/crates/rdocx/src/document.rs +++ b/crates/rdocx/src/document.rs @@ -29749,9 +29749,12 @@ impl Document { .ok_or_else(|| Error::Other("hyperlink story disappeared".into()))?; let refreshed = ContentLocation::new(story, location.item_kind, location.index_path.clone()); + let link_style = self.ensure_hyperlink_style()?; let run_index = self.edit_story_paragraph(&refreshed, |paragraph| { let index = paragraph.run_count(); - paragraph.add_internal_hyperlink(text, bookmark, tooltip); + paragraph + .add_internal_hyperlink(text, bookmark, tooltip) + .set_style(&link_style); Ok(index) })?; let story = self @@ -29973,11 +29976,13 @@ impl Document { let owner = story.part_name.clone(); let relationship_id = candidate.add_external_relationship_checked(&owner, rel_types::HYPERLINK, url)?; + let link_style = candidate.ensure_hyperlink_style()?; let mut paragraph = CT_P::new(); crate::Paragraph { inner: &mut paragraph, } - .add_hyperlink(text, &relationship_id); + .add_hyperlink(text, &relationship_id) + .set_style(&link_style); paragraph .hyperlinks .last_mut() @@ -32734,6 +32739,46 @@ impl Document { Ok(()) } + /// The ID of the character style that marks hyperlink text, which links + /// rdocx writes take, as Word gives the runs of a link it inserts. + /// + /// A character style with the ID `Hyperlink`, or else one named + /// `Hyperlink`, is used as it is. Without one, Word's built-in Hyperlink + /// style (colour `0563C1`, single underline) is added. + pub fn ensure_hyperlink_style(&mut self) -> Result { + let character = |style: &&rdocx_oxml::styles::CT_Style| { + style.style_type == StyleType::Character && !style.style_id.is_empty() + }; + let existing = self + .styles + .styles + .iter() + .filter(character) + .find(|style| style.style_id == "Hyperlink") + .or_else(|| { + self.styles.styles.iter().filter(character).find(|style| { + style + .name + .as_deref() + .is_some_and(|name| name.trim().eq_ignore_ascii_case("Hyperlink")) + }) + }); + if let Some(style) = existing { + return Ok(style.style_id.clone()); + } + self.add_style( + StyleBuilder::character("Hyperlink", "Hyperlink") + .priority(99) + .unhide_when_used(true) + .run_properties(CT_RPr { + color: Some("0563C1".into()), + underline: Some(rdocx_oxml::shared::ST_Underline::Single), + ..Default::default() + }), + )?; + Ok("Hyperlink".to_owned()) + } + /// The character style IDs that mark hyperlink text: the built-in /// Hyperlink and FollowedHyperlink styles, by ID and by name. fn hyperlink_character_style_ids(&self) -> HashSet { diff --git a/crates/rdocx/src/html.rs b/crates/rdocx/src/html.rs index e8d8353ec..f4633adf1 100644 --- a/crates/rdocx/src/html.rs +++ b/crates/rdocx/src/html.rs @@ -4146,6 +4146,19 @@ impl Importer<'_> { hyperlink_ids.insert(url.clone(), relationship_id); } } + let link_style = if hyperlink_ids.is_empty() { + None + } else { + Some(self.document.ensure_hyperlink_style()?) + }; + let link_run_style = |run: &mut Run<'_>, style: &ComputedStyle| { + apply_run_style(run, style); + if style.character_style.is_none() + && let Some(id) = &link_style + { + run.set_style(id); + } + }; let mut output = CT_P::new(); { let mut paragraph = Paragraph { inner: &mut output }; @@ -4211,24 +4224,25 @@ impl Importer<'_> { run.set_text(&format!("{} ", run.text())); } else { self.bump_runs()?; - let mut run = if let Some(url) = &space.hyperlink { - paragraph.add_hyperlink(" ", &hyperlink_ids[url]) + if let Some(url) = &space.hyperlink { + let mut run = paragraph.add_hyperlink(" ", &hyperlink_ids[url]); + link_run_style(&mut run, &space); } else { - paragraph.add_run(" ") - }; - apply_run_style(&mut run, &space); + apply_run_style(&mut paragraph.add_run(" "), &space); + } } } let mut lines = text.split('\n').peekable(); while let Some(line) = lines.next() { if !line.is_empty() { self.bump_runs()?; - let mut run = if let Some(url) = &style.hyperlink { - paragraph.add_hyperlink(line, &hyperlink_ids[url]) + if let Some(url) = &style.hyperlink { + let mut run = + paragraph.add_hyperlink(line, &hyperlink_ids[url]); + link_run_style(&mut run, &style); } else { - paragraph.add_run(line) - }; - apply_run_style(&mut run, &style); + apply_run_style(&mut paragraph.add_run(line), &style); + } emitted = true; } if lines.peek().is_some() { @@ -4257,12 +4271,12 @@ impl Importer<'_> { run.set_text(&format!("{} ", run.text())); } else { self.bump_runs()?; - let mut run = if let Some(url) = &space.hyperlink { - paragraph.add_hyperlink(" ", &hyperlink_ids[url]) + if let Some(url) = &space.hyperlink { + let mut run = paragraph.add_hyperlink(" ", &hyperlink_ids[url]); + link_run_style(&mut run, &space); } else { - paragraph.add_run(" ") - }; - apply_run_style(&mut run, &space); + apply_run_style(&mut paragraph.add_run(" "), &space); + } } pending_space = false; text = text.trim_start_matches(|character: char| { @@ -4273,12 +4287,13 @@ impl Importer<'_> { let normalized = collapse_text(text, &mut pending_space, emitted); if !normalized.is_empty() { self.bump_runs()?; - let mut run = if let Some(url) = &style.hyperlink { - paragraph.add_hyperlink(&normalized, &hyperlink_ids[url]) + if let Some(url) = &style.hyperlink { + let mut run = + paragraph.add_hyperlink(&normalized, &hyperlink_ids[url]); + link_run_style(&mut run, &style); } else { - paragraph.add_run(&normalized) - }; - apply_run_style(&mut run, &style); + apply_run_style(&mut paragraph.add_run(&normalized), &style); + } emitted = true; } if pending_space && (!was_pending || !normalized.is_empty()) { diff --git a/crates/rdocx/tests/regression_test.rs b/crates/rdocx/tests/regression_test.rs index 7343ea780..4d95e11d1 100644 --- a/crates/rdocx/tests/regression_test.rs +++ b/crates/rdocx/tests/regression_test.rs @@ -408533,3 +408533,78 @@ fn issue432_notes_write_the_mark_run_properties_first_with_separators_and_a_spac "{xml}" ); } + +#[test] +fn issue432_links_written_by_rdocx_take_the_hyperlink_character_style() { + let link_runs = |document: &Document| { + let xml = document.part_xml("/word/document.xml").unwrap(); + xml.match_indices("").unwrap()].to_owned() + }) + .collect::>() + }; + let styled = r#""#; + + // A heading link adds the built-in style the document lacks. + let mut document = Document::new(); + document.add_paragraph("Target").style("Heading1"); + document.add_paragraph("See "); + let heading = document.paragraph_story_location(0).unwrap().unwrap(); + let source = document.paragraph_story_location(1).unwrap().unwrap(); + document + .add_heading_hyperlink_at(&source, &heading, "Target", None) + .unwrap(); + let links = link_runs(&document); + assert!(links.len() == 1 && links[0].contains(styled), "{links:?}"); + let style = document + .style("Hyperlink") + .expect("built-in Hyperlink style"); + assert_eq!(style.style_type(), StyleType::Character); + let styles = document.part_xml("/word/styles.xml").unwrap(); + assert!( + styles.contains(r#""#) + && styles.contains(r#""#), + "{styles}" + ); + + // Markdown and HTML links, with a template whose style is kept, and an + // external link appended to a story. + let mut template = Document::new(); + template + .add_style(StyleBuilder::character("Hyperlink", "Hyperlink").color("FF0000")) + .unwrap(); + let markdown = Document::from_markdown_with_options( + "See [the site](https://example.com).", + Some(&template), + &[], + ) + .unwrap() + .document; + let html = + Document::from_html(r#"

See the site.

"#).unwrap(); + let mut story = Document::new(); + let body = f254_story(&story, StoryKind::Body); + story + .add_hyperlink_to_story(&body, "the site", "https://example.com") + .unwrap(); + for (label, document) in [ + ("markdown", &markdown), + ("html", &html.document), + ("story", &story), + ] { + let links = link_runs(document); + assert!( + !links.is_empty() && links.iter().all(|link| link.contains(styled)), + "{label}: {links:?}" + ); + } + let styles = markdown.part_xml("/word/styles.xml").unwrap(); + assert_eq!( + styles.matches(r#"w:styleId="Hyperlink""#).count(), + 1, + "{styles}" + ); + assert!(styles.contains(r#""#), "{styles}"); +} From a3f22d3509a6d21754ffd8ea8c2ad05b6a72ec37 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Sat, 31 Oct 2026 16:41:53 +0100 Subject: [PATCH 04/11] fix(table): keep no blank paragraph when merging with an empty cell merge_cells concatenated the content of every merged cell, so the lone empty paragraph of an empty cell stayed as a blank line above or below the text. As Word does, an empty cell now adds nothing. When every merged cell is empty, the first cell's paragraph stays. Part of #432, case 4. --- crates/rdocx/src/table.rs | 23 ++++++++++++- crates/rdocx/tests/regression_test.rs | 47 +++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/crates/rdocx/src/table.rs b/crates/rdocx/src/table.rs index c690e42e3..67138a0b8 100644 --- a/crates/rdocx/src/table.rs +++ b/crates/rdocx/src/table.rs @@ -1114,12 +1114,19 @@ impl<'a> Table<'a> { selected.push((first, last)); } let mut candidate = self.inner.clone(); + // As Word does, an empty cell adds nothing to the merged content, so + // its lone empty paragraph does not stay as a blank line. let mut content = Vec::new(); for (offset, (first, last)) in selected.iter().enumerate() { for cell in &candidate.rows[top + offset].cells[*first..=*last] { - content.extend(cell.content.clone()); + if !holds_one_empty_paragraph(cell) { + content.extend(cell.content.clone()); + } } } + if content.is_empty() { + content = candidate.rows[top].cells[selected[0].0].content.clone(); + } let width = candidate .grid .as_ref() @@ -3253,6 +3260,20 @@ impl<'a> CellRef<'a> { } } +/// Whether a cell holds nothing but one paragraph without content, which is +/// what an empty cell is. Paragraph properties and the paragraph's own root +/// attributes do not count as content. +fn holds_one_empty_paragraph(cell: &CT_Tc) -> bool { + let [CellContent::Paragraph(paragraph)] = cell.content.as_slice() else { + return false; + }; + let mut bare = paragraph.clone(); + bare.properties = None; + bare.extra_xml + .retain(|(position, raw)| !CT_P::raw_is_root_attributes(*position, raw)); + bare == CT_P::new() +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/rdocx/tests/regression_test.rs b/crates/rdocx/tests/regression_test.rs index 4d95e11d1..2151e4d01 100644 --- a/crates/rdocx/tests/regression_test.rs +++ b/crates/rdocx/tests/regression_test.rs @@ -408608,3 +408608,50 @@ fn issue432_links_written_by_rdocx_take_the_hyperlink_character_style() { ); assert!(styles.contains(r#""#), "{styles}"); } + +#[test] +fn issue432_merging_with_an_empty_cell_keeps_no_blank_paragraph() { + let cases = [ + ( + "second cell empty", + (1, 2), + Some("Total"), + None, + vec!["Total"], + ), + ("first cell empty", (1, 2), None, Some("Sum"), vec!["Sum"]), + ( + "both with text", + (1, 2), + Some("Total"), + Some("Sum"), + vec!["Total", "Sum"], + ), + ("both empty", (1, 2), None, None, vec![""]), + ( + "vertical, second cell empty", + (2, 1), + Some("Total"), + None, + vec!["Total"], + ), + ]; + for (label, (rows, columns), first, second, expected) in cases { + let mut document = Document::new(); + let other = if columns == 2 { (0, 1) } else { (1, 0) }; + { + let mut table = document.add_table(rows, columns); + if let Some(text) = first { + table.cell(0, 0).unwrap().set_text(text); + } + if let Some(text) = second { + table.cell(other.0, other.1).unwrap().set_text(text); + } + table.merge_cells((0, 0), other).unwrap(); + } + let table = document.table(0).unwrap(); + let cell = table.cell(0, 0).unwrap(); + let texts = cell.paragraphs().map(|p| p.text()).collect::>(); + assert_eq!(texts, expected, "{label}"); + } +} From 2edcd80284145d0ce580c414c860c0460e99cf74 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Sat, 31 Oct 2026 16:41:53 +0100 Subject: [PATCH 05/11] fix(table): copy paragraph formatting into the cells add_row and insert_column make formatted_empty_cell copied w:tcPr only, so text set into a new cell lost the alignment and the bold of its row or column. The new paragraph now takes the w:pPr of the source cell's last paragraph, without list numbering and tracked changes, and its mark takes the mark's run properties, or else those of the paragraph's last run, as Word's Insert Row and Insert Column do. The cells split_cell adds follow the same rule. Part of #432, case 5. --- crates/rdocx/src/table.rs | 58 ++++++++++++++++++++++++++- crates/rdocx/tests/regression_test.rs | 38 ++++++++++++++++++ 2 files changed, 94 insertions(+), 2 deletions(-) diff --git a/crates/rdocx/src/table.rs b/crates/rdocx/src/table.rs index 67138a0b8..2dbcde3dc 100644 --- a/crates/rdocx/src/table.rs +++ b/crates/rdocx/src/table.rs @@ -2,7 +2,7 @@ use rdocx_oxml::borders::CT_BorderEdge; use rdocx_oxml::drawing::AnchorAlignH; -use rdocx_oxml::properties::CT_Shd; +use rdocx_oxml::properties::{CT_PPr, CT_RPr, CT_Shd}; use rdocx_oxml::shared::ST_Jc; pub use rdocx_oxml::table::VMerge; use rdocx_oxml::table::{ @@ -709,7 +709,9 @@ fn empty_grid_cell(width: i32) -> CT_Tc { /// /// Shading, borders, alignment, margins, wrapping, text direction and the /// conditional-format cache are copied. Merge state is not copied. Unmodelled formatting refuses before a new -/// owner can be created, and the cell holds one empty paragraph. +/// owner can be created, and the cell holds one empty paragraph. As in Word, +/// that paragraph takes the formatting of `source`'s last paragraph, see +/// [`new_cell_paragraph_properties`]. fn formatted_empty_cell(source: &CT_Tc, width: Option) -> Result { if source .properties @@ -729,9 +731,61 @@ fn formatted_empty_cell(source: &CT_Tc, width: Option) -> Result Option { + let paragraph = source + .content + .iter() + .rev() + .find_map(|content| match content { + CellContent::Paragraph(paragraph) => Some(paragraph), + _ => None, + })?; + let mut properties = paragraph.properties.clone().unwrap_or_default(); + properties.sect_pr = None; + properties.num_id = None; + properties.num_id_raw = None; + properties.num_ilvl = None; + properties.num_ilvl_raw = None; + properties.num_pr_extra_attributes.clear(); + properties.num_pr_extra_xml.clear(); + properties.numbering_revision = None; + properties.numbering_revision_xml.clear(); + properties.numbering_revision_xml_positions.clear(); + properties.numbering_revision_position = None; + properties.change = None; + properties.revision_xml.clear(); + properties.revision_xml_positions.clear(); + let mark = properties + .rpr + .take() + .or_else(|| paragraph.runs.last().and_then(|run| run.properties.clone())) + .map(|mut mark| { + mark.revision_markers.clear(); + mark.change = None; + mark.revision_xml.clear(); + mark.revision_xml_positions.clear(); + mark + }) + .filter(|mark| *mark != CT_RPr::default()); + properties.rpr = mark; + (properties != CT_PPr::default()).then_some(properties) +} + /// Add `amount` twips to a fixed width, never below zero, leaving `auto` and /// percentages alone. fn widen_fixed(width: &mut Option, amount: i32) -> Result<()> { diff --git a/crates/rdocx/tests/regression_test.rs b/crates/rdocx/tests/regression_test.rs index 2151e4d01..8004270bc 100644 --- a/crates/rdocx/tests/regression_test.rs +++ b/crates/rdocx/tests/regression_test.rs @@ -408655,3 +408655,41 @@ fn issue432_merging_with_an_empty_cell_keeps_no_blank_paragraph() { assert_eq!(texts, expected, "{label}"); } } + +#[test] +fn issue432_cells_added_by_insert_column_and_add_row_keep_paragraph_formatting() { + let mut document = Document::new(); + { + let mut table = document.add_table(2, 2); + for row in 0..2 { + for column in 0..2 { + let mut cell = table.cell(row, column).unwrap(); + cell.set_text(&format!("r{row}c{column}")); + cell.set_shading("D9E2F3"); + let mut paragraph = cell.paragraph_mut(0).unwrap(); + paragraph.set_alignment(Alignment::Center); + paragraph.run_mut(0).unwrap().set_bold(true); + } + } + table.insert_column(1, false, None).unwrap(); + table.add_row().unwrap(); + } + let xml = document.part_xml("/word/document.xml").unwrap(); + let cells = xml + .match_indices("") + .map(|(at, _)| { + let cell = &xml[at..]; + &cell[..cell.find("").unwrap()] + }) + .collect::>(); + // Three columns and three rows: (0, 2) comes from the column, (2, 1) from the row. + assert_eq!(cells.len(), 9, "{xml}"); + for (label, cell) in [("inserted column", cells[2]), ("added row", cells[7])] { + assert!(cell.contains(r#"w:fill="D9E2F3""#), "{label}: {cell}"); + assert!( + cell.contains(r#""#), + "{label}: {cell}" + ); + assert!(!cell.contains(""), "{label} holds no text: {cell}"); + } +} From b03b4cf6f747f370faf938e78e7207b587518ab1 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Sat, 31 Oct 2026 16:41:54 +0100 Subject: [PATCH 06/11] fix(numbering): renumber numbering ids only in the saved output prepare_staged_package renumbered authored definitions and instances by first use. A mutation that publishes its reopened candidate, such as create_footnote or add_picture, then committed the renumbered model, and an id add_numbering_definition had returned named the other definition, so a later bullet list came out numbered. The renumbering now runs in prepare_staged_output only, on the staged copy that is written, so equivalent construction orders still save identical packages and the live ids stay as returned. Part of #432, case 6. --- crates/rdocx/src/document.rs | 8 +++- crates/rdocx/tests/regression_test.rs | 56 +++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/crates/rdocx/src/document.rs b/crates/rdocx/src/document.rs index a3f7525fa..235e42165 100644 --- a/crates/rdocx/src/document.rs +++ b/crates/rdocx/src/document.rs @@ -22569,7 +22569,6 @@ impl Document { fn canonicalize_typed_identifiers(&mut self) -> Result<()> { self.canonicalize_bookmark_ids()?; - self.canonicalize_numbering_ids()?; Ok(()) } @@ -22683,6 +22682,12 @@ impl Document { Ok(()) } + /// Renumber authored numbering definitions and instances by first use in + /// the body, for a package that equivalent construction orders write + /// identically. Only the output paths run it, on their staged copy: the + /// ids `add_numbering_definition` and `add_numbering_instance` return + /// are handles the caller holds, and a mutation that publishes its + /// reopened candidate must not renumber them under the caller. fn canonicalize_numbering_ids(&mut self) -> Result<()> { let Some(numbering) = self.numbering.as_ref() else { return Ok(()); @@ -25064,6 +25069,7 @@ impl Document { .as_ref() != Some(comments); } + self.canonicalize_numbering_ids()?; self.prepare_staged_package() } diff --git a/crates/rdocx/tests/regression_test.rs b/crates/rdocx/tests/regression_test.rs index 8004270bc..eca8d76b8 100644 --- a/crates/rdocx/tests/regression_test.rs +++ b/crates/rdocx/tests/regression_test.rs @@ -408693,3 +408693,59 @@ fn issue432_cells_added_by_insert_column_and_add_row_keep_paragraph_formatting() assert!(!cell.contains(""), "{label} holds no text: {cell}"); } } + +#[test] +fn issue432_a_numbering_definition_id_names_its_definition_after_a_republishing_edit() { + let mut document = Document::new(); + let bullets = document + .add_numbering_definition(&[ListLevel::bullet()]) + .unwrap(); + let numbers = document + .add_numbering_definition(&[ListLevel::decimal()]) + .unwrap(); + let numbered = document.add_numbering_instance(numbers, &[]).unwrap(); + document + .add_paragraph("numbered item") + .numbering(numbered, 0); + let bulleted = document.add_numbering_instance(bullets, &[]).unwrap(); + document.add_paragraph("bullet item").numbering(bulleted, 0); + // A footnote publishes the package again, as a picture does. + document.add_paragraph("text"); + let location = document.paragraph_story_location(2).unwrap().unwrap(); + document.create_footnote(&location, "a note").unwrap(); + let later = document.add_numbering_instance(bullets, &[]).unwrap(); + let definition = |instance: u32| { + document + .numbering_instance(instance) + .expect("numbering instance") + .definition_id + }; + assert_eq!(definition(bulleted), bullets); + assert_eq!(definition(numbered), numbers); + assert_eq!(definition(later), bullets); + // The saved package renumbers by first use, and each list keeps its format. + document.add_paragraph("later bullet").numbering(later, 0); + let body = document.part_xml("/word/document.xml").unwrap(); + let numbering = document.part_xml("/word/numbering.xml").unwrap(); + let attribute = |xml: &str, from: usize, name: &str| { + let at = from + xml[from..].find(name).unwrap() + name.len(); + xml[at..at + xml[at..].find('"').unwrap()].to_owned() + }; + let format = |text: &str| { + let paragraph = body[..body.find(&format!("{text}")).unwrap()] + .rfind("") + .unwrap(); + let num = attribute(&body, paragraph, r#""#)) + .unwrap(); + let definition = attribute(&numbering, instance, r#" Date: Sat, 31 Oct 2026 16:41:55 +0100 Subject: [PATCH 07/11] fix(toc): end a TOC inserted before any heading in its own paragraph With no heading yet, insert_toc wrote the begin, separate and end marks in the title paragraph, and rebuild_toc, which replaces the result with whole paragraphs, refused it once headings existed. An empty paragraph after the title now holds the end mark, the shape insert_toc writes when there are headings. Harness: feature_showcase and report insert their TOC before their headings. Their word/document.xml gains that empty paragraph and their pdf/bytes entry changes with it. The pdf/pages and pdf/resources entries and the page-one PNG are unchanged, as the paragraph draws nothing. The baseline is updated in this commit for these four entries. Part of #432, case 7. --- crates/rdocx/src/document.rs | 5 +++++ crates/rdocx/tests/regression_test.rs | 17 +++++++++++++++++ scripts/hash_baseline.json | 10 +++++----- 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/crates/rdocx/src/document.rs b/crates/rdocx/src/document.rs index 235e42165..ecf9b31b7 100644 --- a/crates/rdocx/src/document.rs +++ b/crates/rdocx/src/document.rs @@ -43851,6 +43851,11 @@ impl Document { toc_paragraphs.push(p); } + if headings.is_empty() { + // The field still ends in a paragraph of its own, an empty one + // here, so `rebuild_toc` can fill it once headings exist. + toc_paragraphs.push(CT_P::new()); + } let field_run = |xml: String| { let mut run = CT_R::new(""); diff --git a/crates/rdocx/tests/regression_test.rs b/crates/rdocx/tests/regression_test.rs index eca8d76b8..ee96b2d67 100644 --- a/crates/rdocx/tests/regression_test.rs +++ b/crates/rdocx/tests/regression_test.rs @@ -408749,3 +408749,20 @@ fn issue432_a_numbering_definition_id_names_its_definition_after_a_republishing_ assert_eq!(format("bullet item"), "bullet", "{numbering}"); assert_eq!(format("later bullet"), "bullet", "{numbering}"); } + +#[test] +fn issue432_a_toc_inserted_before_any_heading_rebuilds_once_headings_exist() { + let mut document = Document::new(); + document.add_paragraph("Contents"); + document.insert_toc(1, 3).unwrap(); + document.add_paragraph("Introduction").style("Heading1"); + document.add_paragraph("Body text."); + document.add_paragraph("Methods").style("Heading1"); + let report = document.rebuild_toc().unwrap(); + assert_eq!(report.entry_count, 2, "{report:?}"); + let xml = document.part_xml("/word/document.xml").unwrap(); + let introduction = xml.find(r#"Introduction"#).unwrap(); + let methods = xml.find(r#"Methods"#).unwrap(); + assert!(xml[..introduction].contains(r#"w:anchor="_Toc"#), "{xml}"); + assert!(introduction < methods, "{xml}"); +} diff --git a/scripts/hash_baseline.json b/scripts/hash_baseline.json index 42733f26b..23a67d08b 100644 --- a/scripts/hash_baseline.json +++ b/scripts/hash_baseline.json @@ -8,10 +8,10 @@ "contract:word/numbering.xml": "831dc1977beaa48b4f2999f50751dc3b075418daabe1307cc7b3242267b7f1b4", "contract:word/styles.xml": "49687b10d19688bf634d4967a488eca42eec85ee54c4730af334e5fb1107a7f4", "feature_showcase:page1.png": "e1d30437e2618cff6da70163038427c32e1cd6523b0b58c5cd6376594ee742eb", - "feature_showcase:pdf/bytes": "bf88f82c69089f50449a578c58badf6fa0bfc8058484295ff5ad9d0a453974aa", + "feature_showcase:pdf/bytes": "ccd65f799e3b7bc7c67e8366b64d7c677819d93bfef8a488d91f6772f6fe0b5a", "feature_showcase:pdf/pages": "8a9ca895ba6e9ea3e81a999351c984bf3af9831aedebd99fb1ab9eabb2cea93d", "feature_showcase:pdf/resources": "3573cc6e7183b5e912bfde97f11edea4ec44bb40e1b8f066eeb9b4e5e7726d62", - "feature_showcase:word/document.xml": "9d3418ef8ef11cbcd64acb40b6f2d54648f985050138181bfb32531c8eecf48f", + "feature_showcase:word/document.xml": "ad275d2e793fadbea37ca8c4a8d02890cae85caa0ff4326432e61f582ec148d0", "feature_showcase:word/numbering.xml": "59283ab7d3fbd70ab110b2c9aa4b9f7f41443ef7c24bc6db3c248ee908e44232", "feature_showcase:word/styles.xml": "36e2057c493e6695e41dc5b96a369c72a31bc1f271f6bbafdd58899352450033", "invoice:page1.png": "7571c097759e08aa8239c188a979606bdb60228941b78d0b987b5db382bd7d97", @@ -43,12 +43,12 @@ "quote:word/numbering.xml": "7b1d7268c595b24ecd1ba22f9f48ed10266219a32f32058dfd45c0fcb204bb92", "quote:word/styles.xml": "49687b10d19688bf634d4967a488eca42eec85ee54c4730af334e5fb1107a7f4", "report:page1.png": "1f54ecad3bd19d8c7eb923c00a9f7cefd4760cbad489e7b9089a997d04646753", - "report:pdf/bytes": "bfcd417c614353041bb6a1af3167f83c07e1f9854b55566e435946da9f22d2c6", + "report:pdf/bytes": "4a8474f56091c60a6a3bb41a2a459bd5e221da6ebad101fb58da6d83fe326df6", "report:pdf/pages": "2f3bb9e62c5c9bb235d4a4191986b6b1ae14b9db5ec82c743c3034aaf297dc0c", "report:pdf/resources": "5010450bb7ad7cdb168bb355dc49ba50fc520faade505e391048c44f34d0bb00", - "report:word/document.xml": "8df95515887d2b7c7f5604db9c99f5cf2dcbce6a2ea2e202799adf6885c68ec4", + "report:word/document.xml": "33c069df26f72df9963e86ff8e050a57bd25c38ae05061098020a210d1c32824", "report:word/numbering.xml": "59283ab7d3fbd70ab110b2c9aa4b9f7f41443ef7c24bc6db3c248ee908e44232", "report:word/styles.xml": "49687b10d19688bf634d4967a488eca42eec85ee54c4730af334e5fb1107a7f4" }, - "reason": "F-X233 intentional paragraph border geometry and owned flow: exact18 reviewed entries, seven PDF bytes/page hashes and contract invoice proposal quote page1 PNGs. Native Word16.113.2 geometry, unchanged XML/resources and byte-identical unbordered Base control justify the delta." + "reason": "#432 case 7: insert_toc with no heading ends the TOC field in an empty paragraph after its title (feature_showcase, report)" } From e847cf5aba4879f40ab43c5f15177cf34f38c55b Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Sat, 31 Oct 2026 16:41:56 +0100 Subject: [PATCH 08/11] fix(replace): leave chart labels out of literal replacement replace_text, try_replace_text and rdocx replace also rewrote the strings of each chart's cache, which rdocx text does not show, so their count differed from the text and an --expect taken from it was refused. The cache then disagreed with the embedded workbook, which kept the old label. Literal replacement now searches what regex replacement already searched, and chart data stays with replace_chart_data. Part of #432, case 8. --- crates/rdocx/src/document.rs | 28 ++++++--------------- crates/rdocx/tests/regression_test.rs | 35 +++++++++++++++++++++++++++ docs/hld/10-bindings-spec.md | 11 +++++---- 3 files changed, 48 insertions(+), 26 deletions(-) diff --git a/crates/rdocx/src/document.rs b/crates/rdocx/src/document.rs index ecf9b31b7..f2386c6ea 100644 --- a/crates/rdocx/src/document.rs +++ b/crates/rdocx/src/document.rs @@ -43946,8 +43946,9 @@ impl Document { /// /// Searches body paragraphs, tables (including nested), headers, footers, /// footnotes, endnotes, the text boxes of the body, headers and footers, - /// and the chart labels of the body, and the content controls at every - /// level of them, inline controls included. It reads the text + /// and the content controls at every level of them, inline controls + /// included. Chart labels are not searched: they are a cache of the + /// chart's embedded workbook, which `rdocx text` does not show. It reads the text /// [`crate::Paragraph::text`] reads: the text of a tracked insertion or /// move destination, replaced inside that revision, and not deleted or /// moved-away text. A text box inside a deleted run is the exception, as @@ -45019,8 +45020,8 @@ impl Document { /// Replace all regex matches with `replacement` throughout the document. /// /// The `replacement` string supports capture groups: `$1`, `$2`, etc. - /// Searches the stories [`Self::replace_text`] searches, except chart - /// labels: body paragraphs, tables (including nested), headers, footers, + /// Searches the stories [`Self::replace_text`] searches: body + /// paragraphs, tables (including nested), headers, footers, /// footnotes, endnotes and text boxes, the content controls at every level /// of them and the text of tracked insertions. Returns the total number of replacements made, or an error if the /// regex is invalid. @@ -45350,12 +45351,11 @@ impl Document { } /// Run raw XML replacement on the text boxes of the body, header and footer - /// parts, on the chart parts, and on the notes of the footnotes and - /// endnotes parts. + /// parts, and on the notes of the footnotes and endnotes parts. /// /// This is called after the typed-model replacement and flush_to_package. fn replace_in_xml_parts(&mut self, pairs: &[(&str, &str)]) -> usize { - use rdocx_oxml::placeholder::{replace_many_in_chart_xml, replace_many_in_xml_part}; + use rdocx_oxml::placeholder::replace_many_in_xml_part; let mut count = 0; let mut changed = false; @@ -45377,20 +45377,6 @@ impl Document { } } - // Collect chart part names - for part_name in self.chart_part_names() { - if let Some(xml) = self.package.get_part(&part_name) { - let xml = xml.to_vec(); - if let Ok((new_xml, n)) = replace_many_in_chart_xml(&xml, pairs) - && n > 0 - { - self.package.set_part(&part_name, new_xml); - count += n; - changed = true; - } - } - } - // Re-parse document from the (possibly modified) package XML if changed && let Some(doc_xml) = self.package.get_part(&self.doc_part_name) diff --git a/crates/rdocx/tests/regression_test.rs b/crates/rdocx/tests/regression_test.rs index ee96b2d67..e80dd1b7e 100644 --- a/crates/rdocx/tests/regression_test.rs +++ b/crates/rdocx/tests/regression_test.rs @@ -408766,3 +408766,38 @@ fn issue432_a_toc_inserted_before_any_heading_rebuilds_once_headings_exist() { assert!(xml[..introduction].contains(r#"w:anchor="_Toc"#), "{xml}"); assert!(introduction < methods, "{xml}"); } + +#[test] +fn issue432_literal_replacement_leaves_chart_labels_to_their_workbook() { + let mut document = Document::new(); + document.add_paragraph("Sales in the North region rose."); + document + .add_chart( + ChartKind::Bar, + Length::inches(4.0), + Length::inches(3.0), + &ChartData { + categories: vec!["North".to_owned(), "South".to_owned()], + series: vec![("Sales".to_owned(), vec![3.0, 4.0])], + number_format: None, + ..ChartData::default() + }, + ) + .unwrap(); + let charts_before = document + .part_names() + .unwrap() + .into_iter() + .filter(|name| name.starts_with("/word/charts/")) + .map(|name| (name.clone(), document.part_xml(&name).unwrap())) + .collect::>(); + assert!(!charts_before.is_empty()); + assert_eq!(document.try_replace_text("North", "NORTH").unwrap(), 1); + assert_eq!( + document.paragraph(0).unwrap().text(), + "Sales in the NORTH region rose." + ); + for (name, before) in charts_before { + assert_eq!(document.part_xml(&name).unwrap(), before, "{name}"); + } +} diff --git a/docs/hld/10-bindings-spec.md b/docs/hld/10-bindings-spec.md index 6c18a1fc3..97d5173aa 100644 --- a/docs/hld/10-bindings-spec.md +++ b/docs/hld/10-bindings-spec.md @@ -2108,9 +2108,10 @@ method as `Document.try_replace_text`. The WASM binding keeps its infallible `replacePlaceholder`, which calls `replace_text`. Literal replacement reaches the body, tables, content controls at every level, -headers, footers, footnotes, endnotes, the text boxes of the body, headers, and -footers, and the labels of the charts in the body. Regex replacement reaches -the same stories except chart labels. Every normal note of the +headers, footers, footnotes, endnotes, and the text boxes of the body, headers, +and footers. Regex replacement reaches the same stories. Chart labels are not +searched, as they cache the chart's embedded workbook and `rdocx text` does not +show them, so the counts match the extracted text. Every normal note of the relationship-resolved footnotes and endnotes parts is searched, its tables and block controls included. The separator, continuation separator, and continuation notice entries are not, and neither is an untyped entry at id 0 or @@ -2126,8 +2127,8 @@ and `replace_all_regex`, the WASM replacement method, and `rdocx replace --expect` share these counts. Literal replacement reaches the body, tables, content controls at every level, -headers, footers, footnotes, endnotes, text boxes, and chart labels. Regex -replacement reaches the same stories except chart labels. Every normal note of +headers, footers, footnotes, endnotes, and text boxes, not chart labels. Regex +replacement reaches the same stories. Every normal note of the relationship-resolved footnotes and endnotes parts is searched, its tables and block controls included. The separator, continuation separator, and continuation notice entries are not, and neither is an untyped From 54e5351efd443faac6e1e21ffd351a0b68fc0985 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Sat, 31 Oct 2026 16:53:29 +0100 Subject: [PATCH 09/11] record the archive measurements The rdocx and rdocx-oxml archives change with #432. The other crates keep their rows. --- README.md | 2 +- crates/rdocx-oxml/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 252d3f986..8d250aef0 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ rows are the enforced release-mode bounds plus one dated observation. | Measurement | Value | Version | Platform | Build mode | Input | Command | Statistic | Measured on | |---|---|---|---|---|---|---|---|---| -| Crates.io archive: rdocx | 4,105,912 compressed bytes, 54,118,469 member bytes, 37 members | 0.16.4 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo publish --workspace --dry-run --allow-dirty --locked` | Tracked `rdocx` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-10-28 | +| Crates.io archive: rdocx | 4,112,132 compressed bytes, 54,140,737 member bytes, 37 members | 0.16.4 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo publish --workspace --dry-run --allow-dirty --locked` | Tracked `rdocx` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-10-28 | | Large-document layout throughput | minimum 250 pages/s, observed 31,019.1 pages/s | rdocx 0.14.0 | macOS 26.6.2, Apple M5 Max, arm64 | release, one test thread | 1,000 one-page paragraphs with deterministic fonts | `cargo test -p rdocx --test regression_test --release a_thousand_page_document_paginates_and_renders_within_the_declared_limits -- --ignored --exact --nocapture --test-threads=1` | pages per wall-clock second | 2026-09-19 | | Large-document layout peak allocation | maximum 64 MiB, observed 29.03 MiB | rdocx 0.14.0 | macOS 26.6.2, Apple M5 Max, arm64 | release, one test thread | 1,000 one-page paragraphs with deterministic fonts | `cargo test -p rdocx --test regression_test --release a_thousand_page_document_paginates_and_renders_within_the_declared_limits -- --ignored --exact --nocapture --test-threads=1` | peak live allocation | 2026-09-19 | | Large-document PDF throughput | minimum 1,000 pages/s, observed 60,058.0 pages/s | rdocx 0.14.0 | macOS 26.6.2, Apple M5 Max, arm64 | release, one test thread | 1,000 deterministic layout pages | `cargo test -p rdocx --test regression_test --release a_thousand_page_document_paginates_and_renders_within_the_declared_limits -- --ignored --exact --nocapture --test-threads=1` | pages per wall-clock second | 2026-09-19 | diff --git a/crates/rdocx-oxml/README.md b/crates/rdocx-oxml/README.md index a170fe67b..6f8e6eece 100644 --- a/crates/rdocx-oxml/README.md +++ b/crates/rdocx-oxml/README.md @@ -17,7 +17,7 @@ schema order, and retains unmodelled XML alongside typed edits. | Measurement | Value | Version | Platform | Build mode | Input | Command | Statistic | Measured on | |---|---|---|---|---|---|---|---|---| -| Crates.io archive: rdocx-oxml | 565,559 compressed bytes, 3,484,893 member bytes, 32 members | 0.16.4 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo publish --workspace --dry-run --allow-dirty --locked` | Tracked `rdocx-oxml` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-10-28 | +| Crates.io archive: rdocx-oxml | 565,548 compressed bytes, 3,484,892 member bytes, 32 members | 0.16.4 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo publish --workspace --dry-run --allow-dirty --locked` | Tracked `rdocx-oxml` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-10-28 | ## Use it when From 2d897dd0d4fea6403ad233e24a5d57e3e87446a1 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Sat, 31 Oct 2026 22:10:27 +0100 Subject: [PATCH 10/11] fix(table): let a grid span absorb a cell that holds only paragraph properties set_cell_grid_span, and the row omissions that share its check, took a cell as empty only when its paragraph equalled a bare CT_P, so an empty cell Word leaves in a right-aligned column, , was refused with "horizontal merge cannot consume a nonempty cell". The check now uses the emptiness merge_cells applies since case 4: one paragraph without content, whatever its paragraph properties and its mark's run properties. The first cell's paragraph stays. A cell holding text is still refused. Part of #432, case 4. --- crates/rdocx-py/tests/test_core.py | 33 ++++++++++++ crates/rdocx/src/table.rs | 7 ++- crates/rdocx/tests/regression_test.rs | 76 +++++++++++++++++++++++++++ 3 files changed, 112 insertions(+), 4 deletions(-) diff --git a/crates/rdocx-py/tests/test_core.py b/crates/rdocx-py/tests/test_core.py index dc2e74706..06c1206e3 100644 --- a/crates/rdocx-py/tests/test_core.py +++ b/crates/rdocx-py/tests/test_core.py @@ -15284,3 +15284,36 @@ def link_runs(document): document = rdocx.Document() document.add_paragraph("plain").add_run(" text") assert "Hyperlink" not in document.part_xml("word/document.xml") + + +def test_issue432_a_cell_with_only_paragraph_properties_merges_as_empty(): + import rdocx + + def build(): + document = rdocx.Document() + table = document.add_table(1, 3, style="Table Grid") + table.cell(0, 0).text = "Total" + table.cell(0, 1).paragraphs[0].alignment = rdocx.WD_ALIGN_PARAGRAPH.RIGHT + table.cell(0, 2).text = "Kept" + return document + + document = build() + document.tables[0].set_cell_grid_span(0, 0, 2) + assert [p.text for p in document.tables[0].cell(0, 0).paragraphs] == ["Total"] + assert [c.text for c in document.tables[0].rows[0].cells] == ["Total", "Kept"] + + document = build() + merged = document.tables[0].cell(0, 0).merge(document.tables[0].cell(0, 1)) + assert [p.text for p in merged.paragraphs] == ["Total"] + + document = rdocx.Document() + table = document.add_table(2, 1) + table.cell(0, 0).text = "Total" + table.cell(1, 0).paragraphs[0].alignment = rdocx.WD_ALIGN_PARAGRAPH.RIGHT + merged = document.tables[0].cell(0, 0).merge(document.tables[0].cell(1, 0)) + assert [p.text for p in merged.paragraphs] == ["Total"] + + # A cell that holds text is still refused. + document = build() + with pytest.raises(Exception, match="nonempty cell"): + document.tables[0].set_cell_grid_span(0, 1, 2) diff --git a/crates/rdocx/src/table.rs b/crates/rdocx/src/table.rs index 2dbcde3dc..7c372ddd3 100644 --- a/crates/rdocx/src/table.rs +++ b/crates/rdocx/src/table.rs @@ -675,10 +675,9 @@ pub(crate) fn validate_table_topology(table: &CT_Tbl) -> Result<()> { } fn cell_is_discardable_for_grid_edit(cell: &CT_Tc) -> bool { - let empty_content = matches!( - cell.content.as_slice(), - [CellContent::Paragraph(paragraph)] if paragraph == &CT_P::new() - ); + // An empty cell Word leaves in a formatted column keeps its paragraph + // properties, which say nothing about content. + let empty_content = holds_one_empty_paragraph(cell); let width_only = cell.properties.as_ref().is_none_or(|properties| { properties.grid_span.is_none() && properties.h_merge.is_none() diff --git a/crates/rdocx/tests/regression_test.rs b/crates/rdocx/tests/regression_test.rs index e80dd1b7e..4601def2b 100644 --- a/crates/rdocx/tests/regression_test.rs +++ b/crates/rdocx/tests/regression_test.rs @@ -408801,3 +408801,79 @@ fn issue432_literal_replacement_leaves_chart_labels_to_their_workbook() { assert_eq!(document.part_xml(&name).unwrap(), before, "{name}"); } } + +#[test] +fn issue432_a_cell_holding_only_paragraph_properties_merges_as_an_empty_cell() { + // Word leaves this paragraph in an empty cell of a right-aligned column, + // its mark formatted as the column's text. + let empty = r#""#; + let total = r#"Total"#; + let text = r#"Kept"#; + let grid = r#""#; + let table = |rows: &str, columns: usize| { + let grid = if columns == 3 { + grid.to_owned() + } else { + r#""#.to_owned() + }; + wrap_word_body(&format!( + r#"{grid}{rows}"# + )) + }; + let cell_texts = |document: &Document| { + let table = document.table(0).unwrap(); + let cell = table.cell(0, 0).unwrap(); + cell.paragraphs().map(|p| p.text()).collect::>() + }; + + // A grid span absorbs the empty cell and keeps the first cell's paragraph. + let mut document = document_with_field_parts( + &table(&format!("{total}{empty}{text}"), 3), + None, + None, + ); + document + .table_mut(0) + .unwrap() + .set_cell_grid_span_checked(0, 0, Some(2)) + .unwrap(); + assert_eq!(cell_texts(&document), ["Total"]); + assert_eq!(document.table(0).unwrap().row(0).unwrap().cell_count(), 2); + + // A cell holding text is still refused. + let mut document = document_with_field_parts( + &table(&format!("{total}{text}{empty}"), 3), + None, + None, + ); + let error = document + .table_mut(0) + .unwrap() + .set_cell_grid_span_checked(0, 0, Some(2)) + .unwrap_err(); + assert!(error.to_string().contains("nonempty cell"), "{error}"); + + // merge_cells drops it too, horizontally and vertically. + for (label, rows, columns, other) in [ + ( + "horizontal", + format!("{total}{empty}{text}"), + 3, + (0, 1), + ), + ( + "vertical", + format!("{total}{empty}"), + 1, + (1, 0), + ), + ] { + let mut document = document_with_field_parts(&table(&rows, columns), None, None); + document + .table_mut(0) + .unwrap() + .merge_cells((0, 0), other) + .unwrap(); + assert_eq!(cell_texts(&document), ["Total"], "{label}"); + } +} From aca195c4412f65cfc497a955b34a3e52efd3e2e7 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Sat, 31 Oct 2026 22:10:52 +0100 Subject: [PATCH 11/11] record the archive measurements The rdocx archive changes with the grid span fix. The other crates keep their rows. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8d250aef0..2a9f7fbc0 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ rows are the enforced release-mode bounds plus one dated observation. | Measurement | Value | Version | Platform | Build mode | Input | Command | Statistic | Measured on | |---|---|---|---|---|---|---|---|---| -| Crates.io archive: rdocx | 4,112,132 compressed bytes, 54,140,737 member bytes, 37 members | 0.16.4 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo publish --workspace --dry-run --allow-dirty --locked` | Tracked `rdocx` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-10-28 | +| Crates.io archive: rdocx | 4,112,736 compressed bytes, 54,143,654 member bytes, 37 members | 0.16.4 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo publish --workspace --dry-run --allow-dirty --locked` | Tracked `rdocx` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-10-28 | | Large-document layout throughput | minimum 250 pages/s, observed 31,019.1 pages/s | rdocx 0.14.0 | macOS 26.6.2, Apple M5 Max, arm64 | release, one test thread | 1,000 one-page paragraphs with deterministic fonts | `cargo test -p rdocx --test regression_test --release a_thousand_page_document_paginates_and_renders_within_the_declared_limits -- --ignored --exact --nocapture --test-threads=1` | pages per wall-clock second | 2026-09-19 | | Large-document layout peak allocation | maximum 64 MiB, observed 29.03 MiB | rdocx 0.14.0 | macOS 26.6.2, Apple M5 Max, arm64 | release, one test thread | 1,000 one-page paragraphs with deterministic fonts | `cargo test -p rdocx --test regression_test --release a_thousand_page_document_paginates_and_renders_within_the_declared_limits -- --ignored --exact --nocapture --test-threads=1` | peak live allocation | 2026-09-19 | | Large-document PDF throughput | minimum 1,000 pages/s, observed 60,058.0 pages/s | rdocx 0.14.0 | macOS 26.6.2, Apple M5 Max, arm64 | release, one test thread | 1,000 deterministic layout pages | `cargo test -p rdocx --test regression_test --release a_thousand_page_document_paginates_and_renders_within_the_declared_limits -- --ignored --exact --nocapture --test-threads=1` | pages per wall-clock second | 2026-09-19 |