diff --git a/README.md b/README.md
index 0f39a02a2..b79e97f7e 100644
--- a/README.md
+++ b/README.md
@@ -41,7 +41,7 @@ The archive row uses `cargo package --locked --allow-dirty --no-verify` with all
| Measurement | Value | Version | Platform | Build mode | Input | Command | Statistic | Measured on |
|---|---|---|---|---|---|---|---|---|
-| Crates.io archive: rdocx | 4,501,789 compressed bytes, 56,396,845 member bytes, 37 members | 0.17.0 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo package --locked --allow-dirty --no-verify` | Tracked `rdocx` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-11-09 |
+| Crates.io archive: rdocx | 4,531,634 compressed bytes, 56,539,892 member bytes, 37 members | 0.17.0 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo package --locked --allow-dirty --no-verify` | Tracked `rdocx` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-11-16 |
| 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-py/tests/test_core.py b/crates/rdocx-py/tests/test_core.py
index d180c0174..f64729b82 100644
--- a/crates/rdocx-py/tests/test_core.py
+++ b/crates/rdocx-py/tests/test_core.py
@@ -16927,6 +16927,161 @@ def renumber(match):
assert "word/footnotes.xml" not in archive.namelist()
+
+# F-X287 Word-save fixtures: the body content and footnote owners of rdocx
+# comparisons that Microsoft Word for Mac 16.115 (26110837) opened and saved
+# with "save as". rsid and w14 paragraph identities are removed, the rest is
+# what Word wrote, including its renumbering and merged insertions.
+ISSUE430_W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
+ISSUE430_DATE = 'w:date="2026-10-30T12:00:00Z"'
+ISSUE430_DELIVERY = (
+ ''
+ ' Delivery note, p.1.'
+)
+
+
+def _issue430_word_saved(body, notes):
+ import rdocx
+
+ base = rdocx.Document()
+ base.add_footnote(base.add_paragraph("seed"), "seed")
+ output = io.BytesIO()
+ with zipfile.ZipFile(io.BytesIO(base.to_bytes())) as source:
+ with zipfile.ZipFile(output, "w") as destination:
+ for info in source.infolist():
+ payload = source.read(info.filename)
+ if info.filename == "word/document.xml":
+ payload = (f'{body}'
+ "").encode()
+ elif info.filename == "word/footnotes.xml":
+ payload = f'{notes}'.encode()
+ destination.writestr(info, payload)
+ return output.getvalue()
+
+
+def _issue430_markers(document):
+ with zipfile.ZipFile(io.BytesIO(document.to_bytes())) as archive:
+ return sorted(set(match.decode() for name in archive.namelist()
+ for match in re.findall(rb"_rdocxCmpNoteF\w+", archive.read(name))))
+
+
+def _issue430_note_ids(document):
+ with zipfile.ZipFile(io.BytesIO(document.to_bytes())) as archive:
+ if "word/footnotes.xml" not in archive.namelist():
+ return None
+ notes = archive.read("word/footnotes.xml")
+ return [int(value) for value in re.findall(rb'The buyer took delivery on 12 June.'
+ f''
+ f'The seller wrote twice to ask for payment.'
+ ''
+ ''
+ 'Payment was due in thirty days.'
+ )
+ added_notes = (
+ f'{ISSUE430_DELIVERY}'
+ f''
+ ''
+ ' Letter of 1 July, p.2.'
+ )
+ pending = _issue430_word_saved(added, added_notes)
+ for accept, notes, texts in (
+ (True, [1, 2], ["The buyer took delivery on 12 June.",
+ "The seller wrote twice to ask for payment.",
+ "Payment was due in thirty days."]),
+ (False, [1], ["The buyer took delivery on 12 June.", "Payment was due in thirty days."]),
+ ):
+ document = rdocx.Document.from_bytes(pending)
+ count = (document.accept_revisions_by_author("A") if accept
+ else document.reject_revisions_by_author("A"))
+ assert count > 0
+ document = rdocx.Document.from_bytes(document.to_bytes())
+ assert [paragraph.text for paragraph in document.paragraphs] == texts
+ assert _issue430_note_ids(document) == notes
+ assert document.revisions == ()
+ assert _issue430_markers(document) == []
+ # A footnote added to an existing paragraph, saved by Word, which dropped
+ # the note pair. Accepting settles the note part and its leftover pair.
+ note_only = (
+ 'Payment was due in thirty days.'
+ ''
+ f''
+ )
+ note_only_notes = (
+ f'{ISSUE430_DELIVERY}'
+ f''
+ ' Contract, clause 7.'
+ )
+ document = rdocx.Document.from_bytes(_issue430_word_saved(note_only, note_only_notes))
+ assert _issue430_markers(document) == ["_rdocxCmpNoteF4P11B"]
+ document.accept_all()
+ assert _issue430_note_ids(document) == [1, 2]
+ assert _issue430_markers(document) == []
+
+
+def test_issue430_word_saved_lost_note_pairs_resolve_in_both_author_orders():
+ import rdocx
+
+ # Author A added a footnote with a body change, author B compared on top
+ # of it and added another, and Word saved the result, dropping both note
+ # pairs. Each note is still wholly tracked with its one reference.
+ body = (
+ 'The buyer took delivery on 12 June.'
+ f'Payment was due in thirty days'
+ f'The seller wrote twice to ask for payment'
+ '.'
+ f''
+ 'The parties met in '
+ 'September'
+ 'October'
+ '.'
+ ''
+ )
+ notes = (
+ f'{ISSUE430_DELIVERY}'
+ f''
+ ' Letter of 1 July, p.2.'
+ ''
+ ''
+ ' Minutes of the meeting, p.4.'
+ )
+ pending = _issue430_word_saved(body, notes)
+ pairs = ["_rdocxCmpNoteF18P11B", "_rdocxCmpNoteF8P11B"]
+ for first, second in (("A", "B"), ("B", "A")):
+ for accept_first in (False, True):
+ for accept_second in (False, True):
+ document = rdocx.Document.from_bytes(pending)
+ for author, accept in ((first, accept_first), (second, accept_second)):
+ if accept:
+ document.accept_revisions_by_author(author)
+ else:
+ document.reject_revisions_by_author(author)
+ document = rdocx.Document.from_bytes(document.to_bytes())
+ if author == first:
+ assert _issue430_markers(document) == pairs
+ assert {revision.author for revision in document.revisions} == {second}
+ keep_a = accept_first if first == "A" else accept_second
+ keep_b = accept_first if first == "B" else accept_second
+ expected = [1] + [2] * keep_a + [3] * keep_b
+ assert _issue430_note_ids(document) == expected
+ texts = [paragraph.text for paragraph in document.paragraphs]
+ assert texts[1] == ("The seller wrote twice to ask for payment." if keep_a
+ else "Payment was due in thirty days.")
+ assert texts[-1] == ("The parties met in October." if keep_b
+ else "The parties met in September.")
+ assert document.revisions == ()
+ assert _issue430_markers(document) == []
+
+
@pytest.mark.parametrize("family", ("footnote", "endnote"))
@pytest.mark.parametrize("text", ("", "Source note", " text"))
def test_issue432_note_defaults_and_space(family, text):
@@ -17328,6 +17483,40 @@ def test_issue434_compare_equal_split_and_one_word_public(granularity):
assert [(r.kind, r.text) for r in original.revisions] == [("deletion", "thirty"), ("insertion", "sixty")]
+@pytest.mark.parametrize("granularity", ["word", "character"])
+def test_issue446_compare_keeps_unchanged_text_in_whole_runs(granularity):
+ import rdocx
+
+ def document(word):
+ document = rdocx.Document()
+ for index in range(12):
+ document.add_paragraph(f"Paragraph {index}: the bearing moved about {word} millimetres since the survey.")
+ return rdocx.Document.from_bytes(document.to_bytes())
+
+ original = document("twelve")
+ assert original.compare(document("fifteen"), "R", "2026-11-09T00:00:00Z", granularity=granularity) == ()
+ xml = _document_xml(original)
+ # One text element a run: a revision is never cut into its compared units.
+ assert b"" not in xml
+ revisions = original.revisions
+ for index, paragraph in enumerate(original.paragraphs):
+ runs = [run.text for run in paragraph.runs]
+ assert runs[0] == f"Paragraph {index}: the bearing moved about "
+ assert runs[-1].endswith(" millimetres since the survey.")
+ assert "".join(runs) == f"Paragraph {index}: the bearing moved about fifteen millimetres since the survey."
+ # One run a revision, and one for the text before, between and after them.
+ assert xml.count(b"") <= 12 + 2 * len(revisions)
+ if granularity == "word":
+ assert [(r.kind, r.text) for r in revisions] == [("deletion", "twelve"), ("insertion", "fifteen")] * 12
+ assert [run.text for run in original.paragraphs[3].runs] == [
+ "Paragraph 3: the bearing moved about ",
+ "fifteen",
+ " millimetres since the survey.",
+ ]
+ assert xml.count(b"") == 12 * 4
+
@pytest.mark.parametrize("normal", [False, True, "distinct"])
def test_issue434_insert_effective_font_and_saved_body(normal):
import rdocx
diff --git a/crates/rdocx/src/comparison.rs b/crates/rdocx/src/comparison.rs
index 71ddfc698..62aa9c326 100644
--- a/crates/rdocx/src/comparison.rs
+++ b/crates/rdocx/src/comparison.rs
@@ -615,6 +615,10 @@ pub(crate) fn apply_comment_snapshot(
#[cfg(test)]
thread_local! {
static FAIL_AFTER_COMPARISON_STAGING: std::cell::Cell = const { std::cell::Cell::new(false) };
+ /// The bytes of the parents [`RunSource::capture_all`],
+ /// [`publication_parents_at`] and [`source_children`] have read, which the
+ /// tests of the cost of a comparison count instead of timing it.
+ static SOURCE_READ_BYTES: std::cell::Cell = const { std::cell::Cell::new(0) };
}
type ControlPropertySignature<'a> = Option<(
@@ -1611,14 +1615,13 @@ impl Document {
&new_ids,
)?;
}
- let mut accepted_body = resolved_package(
+ let accepted = resolved_candidate(
&candidate,
|document| document.accept_revision_ids(&new_ids),
- &original_stories,
- options,
- &text_box_markers,
Some(&new_ids),
)?;
+ let mut accepted_body =
+ normalized_package(&accepted, &original_stories, options, &text_box_markers)?;
let mut edited_package =
normalized_package(&edited, &edited_stories, options, &text_box_markers)?;
let main_ignored = story_ignored(options, ComparisonStoryKind::Main);
@@ -1688,7 +1691,7 @@ impl Document {
1,
&new_ids,
)?;
- verify_footnote_destination(&candidate, &edited, &new_ids, true, options)?;
+ verify_footnote_destination(&accepted, &edited, true, options)?;
if accepted_body != edited_package {
return Err(comparison_postcondition_error(
"acceptance",
@@ -1706,14 +1709,13 @@ impl Document {
));
}
}
- let mut rejected_package = resolved_package(
+ let rejected = resolved_candidate(
&candidate,
|document| document.reject_revision_ids(&new_ids),
- &original_stories,
- options,
- &text_box_markers,
Some(&new_ids),
)?;
+ let mut rejected_package =
+ normalized_package(&rejected, &original_stories, options, &text_box_markers)?;
let mut original_package =
normalized_package(&original, &original_stories, options, &text_box_markers)?;
if main_ignored {
@@ -1728,7 +1730,7 @@ impl Document {
0,
&new_ids,
)?;
- verify_footnote_destination(&candidate, &original, &new_ids, false, options)?;
+ verify_footnote_destination(&rejected, &original, false, options)?;
if rejected_package != original_package {
return Err(comparison_postcondition_error(
"rejection",
@@ -3726,79 +3728,217 @@ fn source_fragment(xml: &str, bindings: &[(String, String)]) -> Result {
}
fn publication_parent_at(parent: &str, at: usize) -> Result {
+ publication_parents_at(parent, &[at])
+ .pop()
+ .expect("one result per position")
+}
+
+/// The scope of the element that holds each position of `parent`, as
+/// [`publication_parent_at`] gives it for that position alone.
+///
+/// One read of `parent` answers every position, so a parent of many children
+/// is read once, not once per child. Each result, an error included, is the
+/// one a read for that position alone gives, and is only met when a caller
+/// takes it.
+fn publication_parents_at(parent: &str, positions: &[usize]) -> Vec> {
+ if positions.is_empty() {
+ return Vec::new();
+ }
+ #[cfg(test)]
+ SOURCE_READ_BYTES.with(|bytes| bytes.set(bytes.get() + parent.len()));
let opening = format!(r#""#);
let wrapped = format!("{opening}{parent}");
let mut reader = NsReader::from_str(&wrapped);
- let mut scopes = Vec::new();
- loop {
+ let mut scopes = Vec::::new();
+ let mut results = positions.iter().map(|_| None).collect::>();
+ // The positions still to reach, the nearest last.
+ let mut pending = (0..positions.len()).collect::>();
+ pending.sort_by_key(|index| std::cmp::Reverse(positions[*index]));
+ // A position the read passed holds no event. Its read goes on to the end.
+ let mut passed = Vec::new();
+ let failure = loop {
+ if pending.is_empty() && passed.is_empty() {
+ break None;
+ }
let before = reader.buffer_position() as usize;
- let (_, event) = reader
- .read_resolved_event()
- .map_err(|error| Error::Other(error.to_string()))?;
- if before == opening.len() + at {
- return scopes
- .last()
- .cloned()
- .ok_or_else(|| Error::Other("publication boundary has no actual parent".into()));
+ let event = match reader.read_resolved_event() {
+ Ok((_, event)) => event,
+ Err(error) => break Some(error.to_string()),
+ };
+ while let Some(&index) = pending.last()
+ && opening.len() + positions[index] <= before
+ {
+ pending.pop();
+ if opening.len() + positions[index] == before {
+ results[index] = Some(scopes.last().cloned().ok_or_else(|| {
+ Error::Other("publication boundary has no actual parent".into())
+ }));
+ } else {
+ passed.push(index);
+ }
}
match event {
- Event::Start(_) => scopes.push(resolved_source_bindings(&reader)?),
+ Event::Start(_) => match resolved_source_bindings(&reader) {
+ Ok(bindings) => scopes.push(bindings),
+ Err(error) => break Some(error.to_string()),
+ },
Event::End(_) => {
scopes.pop();
}
Event::Eof => {
- return Err(Error::Other(
- "publication boundary is absent from its actual shell".into(),
- ));
+ break Some("publication boundary is absent from its actual shell".into());
}
_ => {}
}
+ };
+ if let Some(message) = failure {
+ for index in pending.into_iter().chain(passed) {
+ results[index] = Some(Err(Error::Other(message.clone())));
+ }
+ }
+ results
+ .into_iter()
+ .map(|result| result.expect("every position is answered"))
+ .collect()
+}
+
+/// The scopes [`publication_parent_at`] gives for the positions of one
+/// parent that a caller may ask, read in one pass on the first question.
+/// A position outside that set is read alone.
+struct ParentScopes<'a> {
+ parent: &'a str,
+ positions: Vec,
+ scopes: std::cell::OnceCell>>,
+}
+
+impl<'a> ParentScopes<'a> {
+ fn new(parent: &'a str, positions: Vec) -> Self {
+ Self {
+ parent,
+ positions,
+ scopes: std::cell::OnceCell::new(),
+ }
+ }
+
+ fn at(&self, position: usize) -> Result {
+ let scopes = self.scopes.get_or_init(|| {
+ self.positions
+ .iter()
+ .copied()
+ .zip(publication_parents_at(self.parent, &self.positions))
+ .collect()
+ });
+ match scopes.get(&position) {
+ Some(Ok(scope)) => Ok(scope.clone()),
+ // Every error of that read is `Error::Other`, so this is that error.
+ Some(Err(error)) => Err(Error::Other(error.to_string())),
+ None => publication_parent_at(self.parent, position),
+ }
}
}
fn source_child(parent: &str, span: Range) -> Result {
+ source_children(parent, &[span])
+ .pop()
+ .expect("one result per span")
+}
+
+/// The child of `parent` at each span with the namespaces in scope declared
+/// on its root, as [`source_child`] gives it for that span alone.
+///
+/// One read of `parent` answers every span. Each result, an error included,
+/// is the one a read for that span alone gives.
+fn source_children(parent: &str, spans: &[Range]) -> Vec> {
+ if spans.is_empty() {
+ return Vec::new();
+ }
+ #[cfg(test)]
+ SOURCE_READ_BYTES.with(|bytes| bytes.set(bytes.get() + parent.len()));
let opening = format!(r#""#);
let wrapped = format!("{opening}{parent}");
let mut reader = NsReader::from_str(&wrapped);
- loop {
+ let mut results = spans.iter().map(|_| None).collect::>();
+ // The spans still to reach, the nearest last.
+ let mut pending = (0..spans.len()).collect::>();
+ pending.sort_by_key(|index| std::cmp::Reverse(spans[*index].start));
+ // A span the read passed opens no element. Its read goes on to the end.
+ let mut passed = Vec::new();
+ let failure = loop {
+ if pending.is_empty() && passed.is_empty() {
+ break None;
+ }
let before = reader.buffer_position() as usize;
- let (_, event) = reader
- .read_resolved_event()
- .map_err(|error| Error::Other(format!("source namespace scan failed: {error}")))?;
- if before == opening.len() + span.start
- && matches!(event, Event::Start(_) | Event::Empty(_))
- {
- let bindings = reader
- .resolver()
- .bindings()
- .map(|(prefix, uri)| {
- let prefix = match prefix {
- quick_xml::name::PrefixDeclaration::Default => String::new(),
- quick_xml::name::PrefixDeclaration::Named(prefix) => {
- String::from_utf8(prefix.to_vec()).map_err(utf8_error)?
- }
- };
- let uri = std::str::from_utf8(uri.as_ref()).map_err(utf8_error)?;
- Ok((
- if prefix.is_empty() {
- "xmlns".to_owned()
- } else {
- format!("xmlns:{prefix}")
- },
- quick_xml::escape::unescape(uri)
- .map_err(|error| Error::Other(error.to_string()))?
- .into_owned(),
- ))
- })
- .collect::>>()?;
- return source_fragment(&parent[span], &bindings);
+ let event = match reader.read_resolved_event() {
+ Ok((_, event)) => event,
+ Err(error) => break Some(format!("source namespace scan failed: {error}")),
+ };
+ let opens = matches!(event, Event::Start(_) | Event::Empty(_));
+ while let Some(&index) = pending.last() {
+ let start = opening.len() + spans[index].start;
+ if start < before {
+ pending.pop();
+ passed.push(index);
+ } else if start == before && opens {
+ pending.pop();
+ results[index] = Some(source_child_at(&reader, parent, spans[index].clone()));
+ } else {
+ break;
+ }
}
if matches!(event, Event::Eof) {
- return Err(Error::Other(
- "source child has no opening at its span".into(),
- ));
+ break Some("source child has no opening at its span".into());
+ }
+ };
+ if let Some(message) = failure {
+ for index in pending.into_iter().chain(passed) {
+ results[index] = Some(Err(Error::Other(message.clone())));
}
}
+ results
+ .into_iter()
+ .map(|result| result.expect("every span is answered"))
+ .collect()
+}
+
+/// The parent scope and the scoped source of the child of `parent` at each
+/// span, from one read of `parent` for each, in the order of `spans`.
+fn child_scopes(
+ parent: &str,
+ spans: &[Range],
+) -> std::iter::Zip>, std::vec::IntoIter>>
+{
+ let starts = spans.iter().map(|span| span.start).collect::>();
+ publication_parents_at(parent, &starts)
+ .into_iter()
+ .zip(source_children(parent, spans))
+}
+
+/// The child at `span` with the bindings `reader` holds at its opening.
+fn source_child_at(reader: &NsReader<&[u8]>, parent: &str, span: Range) -> Result {
+ let bindings = reader
+ .resolver()
+ .bindings()
+ .map(|(prefix, uri)| {
+ let prefix = match prefix {
+ quick_xml::name::PrefixDeclaration::Default => String::new(),
+ quick_xml::name::PrefixDeclaration::Named(prefix) => {
+ String::from_utf8(prefix.to_vec()).map_err(utf8_error)?
+ }
+ };
+ let uri = std::str::from_utf8(uri.as_ref()).map_err(utf8_error)?;
+ Ok((
+ if prefix.is_empty() {
+ "xmlns".to_owned()
+ } else {
+ format!("xmlns:{prefix}")
+ },
+ quick_xml::escape::unescape(uri)
+ .map_err(|error| Error::Other(error.to_string()))?
+ .into_owned(),
+ ))
+ })
+ .collect::>>()?;
+ source_fragment(&parent[span], &bindings)
}
fn root_namespace_bindings(
@@ -4054,6 +4194,23 @@ struct FootnotePart {
impl FootnotePart {
fn of(document: &Document) -> Result"),
+ "{owner_xml}"
+ );
+ let open = owner_xml[..pair].rfind(&format!("<{wrapper} ")).unwrap();
+ assert!(!owner_xml[open..pair].contains(&format!("{wrapper}>")));
+ } else if addition {
+ let open = owner_xml[..pair].rfind(""),
+ "{owner_xml}"
+ );
+ } else {
+ assert!(owner_xml[..pair].ends_with(""), "{owner_xml}");
+ }
+ let mut saved = issue430_roundtrip(&mut original);
+ for accept in [true, false] {
+ let mut resolved = Document::from_bytes(&saved.to_bytes().unwrap()).unwrap();
+ if accept {
+ resolved.accept_all().unwrap();
+ } else {
+ resolved.reject_all().unwrap();
+ }
+ let retained = if accept == addition {
+ vec![1, 2]
+ } else {
+ vec![1]
+ };
+ issue430_assert_settled(&mut resolved, &retained, true);
+ }
+ }
+ }
+}
+
+#[test]
+fn issue430_word_saved_note_pair_after_the_reference_mark_resolves_and_compares() {
+ // rdocx compared a three-paragraph original with an edit that adds a
+ // second footnote to its second paragraph, the note pair placed after the
+ // reference mark, and Word saved it. Word kept both pairs.
+ let body = r#"The buyer took delivery on 12 June.Payment was due in thirty days.The parties met in September."#;
+ let added = r#" Contract, clause 7."#;
+ let notes = format!(
+ "{}{}{added}",
+ issue430_word_separators(),
+ issue430_word_delivery_note()
+ );
+ let texts = [
+ "The buyer took delivery on 12 June.",
+ "Payment was due in thirty days.",
+ "The parties met in September.",
+ ];
+ issue430_word_save_destinations(body, ¬es, (&[1, 2], &texts), (&[1], &texts));
+ issue430_word_save_unrelated_comparison(
+ body,
+ ¬es,
+ ("met in September", "met in October"),
+ &[1, 2],
+ &[1],
+ );
+}
+
+fn issue430_word_added_paragraph(pair_in_body: &str) -> String {
+ format!(
+ r#"The buyer took delivery on 12 June.{pair_in_body}Payment was due in thirty days."#
+ )
+}
+fn issue430_word_added_paragraph_notes() -> String {
+ format!(
+ r#"{}{} Letter of 1 July, p.2."#,
+ issue430_word_separators(),
+ issue430_word_delivery_note()
+ )
+}
+const ISSUE430_WORD_PAIR: &str =
+ r#""#;
+const ISSUE430_WORD_REFERENCE: &str = r#""#;
+
+#[test]
+fn issue430_word_saved_body_pair_in_its_reference_insertion_resolves_and_compares() {
+ // The issue's "a footnote added" result: a new middle paragraph with a new
+ // note, the note pair placed after the reference mark. Word merged the
+ // paragraph's text insertion with the reference insertion (same author
+ // and date), which moved the body pair inside the merged insertion, right
+ // before the reference run. Word kept the note pair.
+ let merged = format!(
+ r#"The seller wrote twice to ask for payment.{ISSUE430_WORD_PAIR}{ISSUE430_WORD_REFERENCE}"#
+ );
+ let body = issue430_word_added_paragraph(&merged);
+ let notes = issue430_word_added_paragraph_notes();
+ let accepted = [
+ "The buyer took delivery on 12 June.",
+ "The seller wrote twice to ask for payment.",
+ "Payment was due in thirty days.",
+ ];
+ let rejected = [
+ "The buyer took delivery on 12 June.",
+ "Payment was due in thirty days.",
+ ];
+ issue430_word_save_destinations(&body, ¬es, (&[1, 2], &accepted), (&[1], &rejected));
+ issue430_word_save_unrelated_comparison(
+ &body,
+ ¬es,
+ ("due in thirty days", "due in forty days"),
+ &[1, 2],
+ &[1],
+ );
+ // A selector that covers only the merged wrapper is still a partial unit.
+ let mut document = issue430_fixture(&body, Some(¬es));
+ let before = document.to_bytes().unwrap();
+ assert!(
+ document
+ .reject_revision_id(1)
+ .unwrap_err()
+ .to_string()
+ .contains("partial footnote custody")
+ );
+ assert_eq!(document.to_bytes().unwrap(), before);
+}
+
+#[test]
+fn issue430_body_pair_in_any_other_revision_position_still_refuses() {
+ let text = r#"The seller wrote twice to ask for payment."#;
+ let deleted = r#"The seller wrote twice to ask for payment."#;
+ let open = r#""#;
+ let other = r#""#;
+ let inside = "body custody pair is inside a revision";
+ let notes = issue430_word_added_paragraph_notes();
+ let variants = [
+ // folded into the preceding text insertion, with no reference after it
+ format!("{open}{text}{ISSUE430_WORD_PAIR}{other}{ISSUE430_WORD_REFERENCE}"),
+ // inside the reference's insertion, but before a text run
+ format!("{open}{ISSUE430_WORD_PAIR}{text}{ISSUE430_WORD_REFERENCE}"),
+ // a move destination is not an insertion
+ format!(
+ r#"{open}{text}{ISSUE430_WORD_PAIR}{ISSUE430_WORD_REFERENCE}"#
+ ),
+ // a deletion: Word was never observed to put a pair there
+ format!(
+ r#"{deleted}{ISSUE430_WORD_PAIR}{ISSUE430_WORD_REFERENCE}"#
+ ),
+ ]
+ .map(|variant| (issue430_word_added_paragraph(&variant), notes.clone(), inside));
+ // nested one level deeper, inside a hyperlink of the reference's insertion
+ let nested = (
+ issue430_word_added_paragraph(&format!(
+ r#"{open}{text}{ISSUE430_WORD_PAIR}{ISSUE430_WORD_REFERENCE}"#
+ )),
+ notes.clone(),
+ "custody pair has no direct paragraph owner",
+ );
+ // An unmatched pair (no note pair) inside another author's insertion,
+ // before the re-inserted reference of an existing untracked note.
+ let unmatched = (
+ format!(
+ r#"Text more"#
+ ),
+ format!(
+ "{}{}",
+ issue430_word_separators(),
+ issue430_word_delivery_note()
+ ),
+ inside,
+ );
+ for (body, notes, message) in variants.into_iter().chain([nested, unmatched]) {
+ for action in 0..3 {
+ let mut document = issue430_fixture(&body, Some(¬es));
+ let before = document.to_bytes().unwrap();
+ let error = match action {
+ 0 => document.accept_all().unwrap_err(),
+ 1 => document.reject_revisions_by_author("A").unwrap_err(),
+ _ => {
+ let mut edited = issue430_fixture(&body, Some(¬es));
+ let edited = issue430_roundtrip(&mut edited);
+ document.compare(&edited, "C", ISSUE430_DATE).unwrap_err()
+ }
+ };
+ assert!(error.to_string().contains(message), "{error}");
+ assert_eq!(document.to_bytes().unwrap(), before);
+ }
+ }
+}
+
+#[test]
+fn issue430_comparison_refuses_a_note_reference_that_moves_to_another_site() {
+ // Review A's "a new note before an existing one". The edited input adds a
+ // note to the first paragraph, which takes id 2, and the existing note
+ // moves to id 3. Pairing by id would leave the deleted original reference
+ // and the inserted edited reference both naming note 2, a shared pending
+ // reference that Word for Mac 16.115 cannot open, with note 2's text
+ // change pairing two different notes. The comparison refuses atomically.
+ let note = |id: i32, text: &str| {
+ format!(
+ r#" {text}"#
+ )
+ };
+ let mut original = issue430_fixture(
+ &format!(
+ "{}{}",
+ issue430_p("The buyer took delivery.", None),
+ issue430_p("Payment was due.", Some(2))
+ ),
+ Some(¬e(2, "Contract, clause 7.")),
+ );
+ let edited = issue430_fixture(
+ &format!(
+ "{}{}",
+ issue430_p("The buyer took delivery.", Some(2)),
+ issue430_p("Payment was due.", Some(3))
+ ),
+ Some(&format!(
+ "{}{}",
+ note(2, "Delivery note, p.1."),
+ note(3, "Contract, clause 7.")
+ )),
+ );
+ let before = original.to_bytes().unwrap();
+ let error = original
+ .compare(&edited, "A", ISSUE430_DATE)
+ .unwrap_err()
+ .to_string();
+ assert!(
+ error.contains("footnote 2") && error.contains("moved to another site"),
+ "{error}"
+ );
+ assert_eq!(original.to_bytes().unwrap(), before);
+ // The same edit with the new note after the existing one keeps the ids
+ // apart and still compares, both destinations exact.
+ let mut original = issue430_fixture(
+ &format!(
+ "{}{}",
+ issue430_p("Payment was due.", Some(2)),
+ issue430_p("The buyer took delivery.", None)
+ ),
+ Some(¬e(2, "Contract, clause 7.")),
+ );
+ let edited = issue430_fixture(
+ &format!(
+ "{}{}",
+ issue430_p("Payment was due.", Some(2)),
+ issue430_p("The buyer took delivery.", Some(3))
+ ),
+ Some(&format!(
+ "{}{}",
+ note(2, "Contract, clause 7."),
+ note(3, "Delivery note, p.1.")
+ )),
+ );
+ original.compare(&edited, "A", ISSUE430_DATE).unwrap();
+ let mut rejected = issue430_roundtrip(&mut original);
+ rejected.reject_all().unwrap();
+ issue430_assert_settled(&mut rejected, &[2], true);
+ original.accept_all().unwrap();
+ issue430_assert_settled(&mut original, &[2, 3], true);
+}
+
+#[test]
+fn issue430_body_pair_lifted_out_of_a_rejected_insertion_keeps_its_vote() {
+ // Hand-built, not a Word save: it combines two observed Word shapes so that
+ // the only creation bits sit on a merged pair. Note 1 was created with the
+ // part (bits 01) and its body pair sits inside the inserted paragraph's
+ // insertion, as Word 16.115 writes it after merging that insertion with
+ // the reference insertion. Note 2 came from a later comparison (bits 11).
+ // Rejecting note 1 removes the insertion around its pair: the pair stays as
+ // a direct child of the merged paragraph, so its creation bits still vote
+ // and rejecting note 2 then removes the part.
+ let date = ISSUE430_DATE;
+ let body = format!(
+ r#"Added paragraph.Kept paragraph."#
+ );
+ let note = |id: i32, author: &str, ids: (i32, i32), pair: &str, text: &str| {
+ format!(
+ r#"{pair} {text}"#,
+ ids.0, ids.1
+ )
+ };
+ let notes = format!(
+ "{}{}{}",
+ issue430_word_separators(),
+ note(
+ 1,
+ "A",
+ (3, 4),
+ r#""#,
+ "First."
+ ),
+ note(
+ 2,
+ "Y",
+ (6, 7),
+ r#""#,
+ "Second."
+ )
+ );
+ let mut source = issue430_fixture(&body, Some(¬es));
+ for (first, second) in [("A", "Y"), ("Y", "A")] {
+ for accept_first in [false, true] {
+ for accept_second in [false, true] {
+ let mut document = Document::from_bytes(&source.to_bytes().unwrap()).unwrap();
+ for (author, accept) in [(first, accept_first), (second, accept_second)] {
+ if accept {
+ document.accept_revisions_by_author(author).unwrap();
+ } else {
+ document.reject_revisions_by_author(author).unwrap();
+ }
+ document = issue430_roundtrip(&mut document);
+ if author == first {
+ // The other unit is pending: every pair is still present,
+ // except the note pair of a rejected (removed) note.
+ let markers = issue430_markers(&mut document);
+ assert!(markers.contains(&"_rdocxCmpNoteF7P01B".to_owned()));
+ assert!(markers.contains(&"_rdocxCmpNoteF8P11B".to_owned()));
+ if author == "A" && !accept {
+ let body = String::from_utf8(
+ issue430_package(&mut document)
+ .get_part("/word/document.xml")
+ .unwrap()
+ .to_vec(),
+ )
+ .unwrap();
+ let pair = body.find("_rdocxCmpNoteF7P01B").unwrap();
+ assert!(body[pair..].starts_with(
+ r#"_rdocxCmpNoteF7P01B"/>Kept paragraph."#
+ ), "{body}");
+ assert!(!body.contains(">();
+ issue430_assert_settled(&mut document, &retained, !retained.is_empty());
+ }
+ }
+ }
+}
+
+fn issue430_word_note_only_body() -> &'static str {
+ r#"The buyer took delivery on 12 June.Payment was due in thirty days.The parties met in September."#
+}
+fn issue430_word_note_only_notes() -> String {
+ format!(
+ r#"{}{} Contract, clause 7."#,
+ issue430_word_separators(),
+ issue430_word_delivery_note()
+ )
+}
+fn issue430_word_mixed_body() -> &'static str {
+ r#"The buyer took delivery on 12 June.Payment was due in thirty daysThe seller wrote twice to ask for payment.Payment was due in sixty days.The parties met in SeptemberOctober."#
+}
+fn issue430_word_mixed_notes() -> String {
+ format!(
+ r#"{}{} Letter of 1 July, p.2. Minutes of the meeting, p.4."#,
+ issue430_word_separators(),
+ issue430_word_delivery_note()
+ )
+}
+
+#[test]
+fn issue430_word_saved_unmatched_body_pair_retires_when_its_part_settles() {
+ // rdocx compared the three-paragraph original with an edit that adds a
+ // second footnote to its second paragraph (the pair before the reference
+ // mark, as v0.17.0 wrote it), and Word saved it. Word dropped the note
+ // pair, so the body pair has no note counterpart. Accepting settles every
+ // note revision, and settlement retires the leftover pair.
+ let accepted = [
+ "The buyer took delivery on 12 June.",
+ "Payment was due in thirty days.",
+ "The parties met in September.",
+ ];
+ let mut source = issue430_fixture(
+ issue430_word_note_only_body(),
+ Some(&issue430_word_note_only_notes()),
+ );
+ for all in [true, false] {
+ let mut document = Document::from_bytes(&source.to_bytes().unwrap()).unwrap();
+ if all {
+ document.accept_all().unwrap();
+ } else {
+ document.accept_revisions_by_author("A").unwrap();
+ }
+ let mut document = issue430_roundtrip(&mut document);
+ assert_eq!(issue430_texts(&document), accepted);
+ issue430_assert_settled(&mut document, &[1, 2], true);
+ }
+ // Word's own Accept All of that file (Word 16.115, AppleScript `accept all
+ // revisions` then `save as`) keeps the body pair in a settled part. It stays
+ // while a resolution leaves the note part untouched, and retires once a
+ // resolution edits the part and leaves no note revision pending.
+ let settled_body = r#"The buyer took delivery on 12 June.Payment was due in thirty days.The parties met in September."#;
+ // The control adds one unrelated tracked paragraph to Word's bytes, and in
+ // the second case one tracked run to the second note.
+ let unrelated = format!(
+ r#"{settled_body}Unrelated."#
+ );
+ let settled_notes = format!(
+ r#"{}{} Contract, clause 7.{{extra}}"#,
+ issue430_word_separators(),
+ issue430_word_delivery_note()
+ );
+ let pair = vec!["_rdocxCmpNoteF4P11B".to_owned()];
+ let mut untouched = issue430_fixture(&unrelated, Some(&settled_notes.replace("{extra}", "")));
+ assert_eq!(untouched.accept_revision_id(100).unwrap(), 1);
+ assert_eq!(issue430_markers(&mut untouched), pair);
+ let edited_note = settled_notes.replace(
+ "{extra}",
+ &format!(
+ r#" Also clause 8."#
+ ),
+ );
+ for both in [false, true] {
+ let mut document = issue430_fixture(&unrelated, Some(&edited_note));
+ if both {
+ assert_eq!(document.accept_all().unwrap(), 2);
+ assert!(issue430_markers(&mut document).is_empty());
+ } else {
+ assert_eq!(document.accept_revision_id(100).unwrap(), 1);
+ assert_eq!(issue430_markers(&mut document), pair);
+ assert_eq!(document.reject_revision_id(101).unwrap(), 1);
+ assert!(issue430_markers(&mut document).is_empty());
+ }
+ }
+}
+
+#[test]
+fn issue430_settling_only_the_reference_retires_the_leftover_body_pair() {
+ // The Word-saved result whose note pair Word dropped. Accepting the note's
+ // own two elements first leaves only the reference pending, and the pair
+ // stays. Accepting the reference then settles the part, and its leftover
+ // pair retires, whichever side settles last.
+ let pair = vec!["_rdocxCmpNoteF4P11B".to_owned()];
+ let mut document = issue430_fixture(
+ issue430_word_note_only_body(),
+ Some(&issue430_word_note_only_notes()),
+ );
+ for id in [2, 3] {
+ document.accept_revision_id(id).unwrap();
+ document = issue430_roundtrip(&mut document);
+ assert_eq!(issue430_markers(&mut document), pair);
+ }
+ assert_eq!(document.story_revisions().unwrap().len(), 1);
+ assert_eq!(document.accept_revision_id(1).unwrap(), 1);
+ let mut document = issue430_roundtrip(&mut document);
+ issue430_assert_settled(&mut document, &[1, 2], true);
+ // The same state as Word leaves it after accepting only the note side:
+ // the note is settled and only the reference insertion is pending.
+ let settled_note = issue430_word_note_only_notes()
+ .replace(
+ r#""#,
+ "",
+ )
+ .replace(
+ r#""#,
+ "",
+ )
+ .replace("", "");
+ assert!(!settled_note.contains("The buyer took delivery on 12 June.Payment was due in thirty daysThe seller wrote twice to ask for payment.Payment was due in sixty days.The parties met in September."#;
+ let middle_notes = format!(
+ r#"{}{} Letter of 1 July, p.2."#,
+ issue430_word_separators(),
+ issue430_word_delivery_note()
+ );
+ issue430_word_save_destinations(
+ middle,
+ &middle_notes,
+ (
+ &[1, 2],
+ &[
+ buyer,
+ "The seller wrote twice to ask for payment.",
+ "Payment was due in sixty days.",
+ "The parties met in September.",
+ ],
+ ),
+ (
+ &[1],
+ &[
+ buyer,
+ "Payment was due in thirty days.",
+ "The parties met in September.",
+ ],
+ ),
+ );
+ issue430_word_save_unrelated_comparison(
+ middle,
+ &middle_notes,
+ ("met in September", "met in October"),
+ &[1, 2],
+ &[1],
+ );
+ // The issue's "a footnote added" result: Word also merged the body pair
+ // into the inserted paragraph's insertion.
+ let merged = format!(
+ r#"The seller wrote twice to ask for payment.{ISSUE430_WORD_PAIR}{ISSUE430_WORD_REFERENCE}"#
+ );
+ let added = issue430_word_added_paragraph(&merged);
+ let added_notes = issue430_word_added_paragraph_notes().replace(
+ r#""#,
+ "",
+ );
+ issue430_word_save_destinations(
+ &added,
+ &added_notes,
+ (
+ &[1, 2],
+ &[
+ buyer,
+ "The seller wrote twice to ask for payment.",
+ "Payment was due in thirty days.",
+ ],
+ ),
+ (&[1], &[buyer, "Payment was due in thirty days."]),
+ );
+ issue430_word_save_unrelated_comparison(
+ &added,
+ &added_notes,
+ ("due in thirty days", "due in forty days"),
+ &[1, 2],
+ &[1],
+ );
+ // A second footnote removed while the last paragraph changed: the deletion
+ // direction, where accepting removes the note.
+ let removed = r#"The buyer took delivery on 12 June.Payment was due in thirty days.The parties met in SeptemberOctober."#;
+ let removed_notes = format!(
+ r#"{}{} Contract, clause 7."#,
+ issue430_word_separators(),
+ issue430_word_delivery_note()
+ );
+ issue430_word_save_destinations(
+ removed,
+ &removed_notes,
+ (
+ &[1],
+ &[
+ buyer,
+ "Payment was due in thirty days.",
+ "The parties met in October.",
+ ],
+ ),
+ (
+ &[1, 2],
+ &[
+ buyer,
+ "Payment was due in thirty days.",
+ "The parties met in September.",
+ ],
+ ),
+ );
+}
+
+fn issue430_word_mixed_choices(body: &str, notes: &str) {
+ let buyer = "The buyer took delivery on 12 June.";
+ let mut source = issue430_fixture(body, Some(notes));
+ for (first, second) in [("A", "B"), ("B", "A")] {
+ for accept_first in [false, true] {
+ for accept_second in [false, true] {
+ let mut document = Document::from_bytes(&source.to_bytes().unwrap()).unwrap();
+ for (step, (author, accept)) in [(first, accept_first), (second, accept_second)]
+ .into_iter()
+ .enumerate()
+ {
+ let before = document.to_bytes().unwrap();
+ let result = if accept {
+ document.accept_revisions_by_author(author)
+ } else {
+ document.reject_revisions_by_author(author)
+ };
+ assert!(
+ result.is_ok(),
+ "{first}{accept_first}{second}{accept_second} {result:?}"
+ );
+ assert_ne!(document.to_bytes().unwrap(), before);
+ document = issue430_roundtrip(&mut document);
+ if step == 0 {
+ // The other author is still pending, so both body
+ // pairs are retained tombstones or open custody.
+ let markers = issue430_markers(&mut document);
+ for pair in ["_rdocxCmpNoteF8P11B", "_rdocxCmpNoteF18P11B"] {
+ assert!(markers.contains(&pair.to_owned()), "{markers:?}");
+ }
+ let revisions = document.story_revisions().unwrap();
+ assert!(!revisions.is_empty());
+ assert!(revisions.iter().all(|revision| revision.author() == second));
+ }
+ }
+ let keep_a = if first == "A" {
+ accept_first
+ } else {
+ accept_second
+ };
+ let keep_b = if first == "B" {
+ accept_first
+ } else {
+ accept_second
+ };
+ let mut texts = vec![buyer];
+ if keep_a {
+ texts.extend([
+ "The seller wrote twice to ask for payment.",
+ "Payment was due in sixty days.",
+ ]);
+ } else {
+ texts.push("Payment was due in thirty days.");
+ }
+ texts.push(if keep_b {
+ "The parties met in October."
+ } else {
+ "The parties met in September."
+ });
+ let ids = [(1, true), (2, keep_a), (3, keep_b)]
+ .into_iter()
+ .filter_map(|(id, keep)| keep.then_some(id))
+ .collect::>();
+ assert_eq!(issue430_texts(&document), texts);
+ issue430_assert_settled(&mut document, &ids, true);
+ }
+ }
+ }
+}
+
+#[test]
+fn issue430_word_saved_mixed_authors_resolve_in_both_orders_and_choices() {
+ // Author A's result (a footnote added with a body text change), then
+ // author B compared on top of it (a footnote and a text change in the
+ // last paragraph), then Word saved it and dropped both note pairs.
+ issue430_word_mixed_choices(issue430_word_mixed_body(), &issue430_word_mixed_notes());
+ // The same result with A's note pair moved after its reference mark before
+ // the save (the placement of the first commit), then saved by Word 16.115:
+ // Word kept A's note pair and dropped B's. A is a marked unit and B a
+ // tracked note, so resolving A first must not retire B's body pair.
+ let keep_a_body = r#"The buyer took delivery on 12 June.Payment was due in thirty daysThe seller wrote twice to ask for payment.Payment was due in sixty days.The parties met in SeptemberOctober."#;
+ let keep_a_notes = format!(
+ r#"{}{} Letter of 1 July, p.2. Minutes of the meeting, p.4."#,
+ issue430_word_separators(),
+ issue430_word_delivery_note()
+ );
+ issue430_word_mixed_choices(keep_a_body, &keep_a_notes);
+}
+
+#[test]
+fn issue430_word_saved_mixed_note_outside_the_grammar_keeps_both_pairs() {
+ // From review B. The mixed Word save with both note pairs lost, where one
+ // author's note also holds an internal hyperlink, so it is not a tracked
+ // note. Resolving the other author's tracked note, either way, keeps both
+ // body pairs while that note's revisions are pending, as v0.17.0 does.
+ let link = |author: &str, date: &str| {
+ format!(
+ r#"minutes"#
+ )
+ };
+ let both = [
+ "_rdocxCmpNoteF18P11B".to_owned(),
+ "_rdocxCmpNoteF8P11B".to_owned(),
+ ];
+ let b_linked = issue430_word_mixed_notes().replace(
+ " Minutes of the meeting, p.4.",
+ &format!(
+ " Minutes of the meeting, p.4.{}",
+ link("B", "2026-10-31T12:00:00Z")
+ ),
+ );
+ let a_linked = issue430_word_mixed_notes().replace(
+ " Letter of 1 July, p.2.",
+ &format!(
+ " Letter of 1 July, p.2.{}",
+ link("A", "2026-10-30T12:00:00Z")
+ ),
+ );
+ for (notes, first) in [(&b_linked, "A"), (&a_linked, "B")] {
+ assert_ne!(notes, &issue430_word_mixed_notes());
+ for accept in [true, false] {
+ let mut document = issue430_fixture(issue430_word_mixed_body(), Some(notes));
+ if accept {
+ document.accept_revisions_by_author(first).unwrap();
+ } else {
+ document.reject_revisions_by_author(first).unwrap();
+ }
+ let mut document = issue430_roundtrip(&mut document);
+ assert!(!document.story_revisions().unwrap().is_empty());
+ assert_eq!(
+ issue430_markers(&mut document),
+ both,
+ "first {first} accept {accept}"
+ );
+ }
+ }
+}
+
+#[test]
+fn issue430_comparison_over_a_word_saved_tracked_note_keeps_both_lifetimes() {
+ // Author B compares on top of A's Word-saved result whose note pair Word
+ // dropped (A's note is a pending tracked note), adding a referenced note to
+ // the last paragraph. The comparison keeps A's unmatched body pair and
+ // emits B's custody. Every order and choice reaches its destination and
+ // keeps every pair until the last note settles.
+ let mut original = issue430_fixture(
+ issue430_word_note_only_body(),
+ Some(&issue430_word_note_only_notes()),
+ );
+ let package = issue430_package(&mut original);
+ let body = String::from_utf8(package.get_part("/word/document.xml").unwrap().to_vec()).unwrap();
+ let notes =
+ String::from_utf8(package.get_part("/word/footnotes.xml").unwrap().to_vec()).unwrap();
+ let edited = issue430_replace_parts(
+ &mut original,
+ Some(body.replace(
+ "The parties met in September.",
+ r#"The parties met in September."#,
+ )),
+ Some(notes.replace(
+ "",
+ r#" Minutes."#,
+ )),
+ );
+ original.compare(&edited, "B", ISSUE430_DATE).unwrap();
+ let mut pending = issue430_roundtrip(&mut original);
+ let markers = issue430_markers(&mut pending);
+ assert!(
+ markers.contains(&"_rdocxCmpNoteF4P11B".to_owned()),
+ "{markers:?}"
+ );
+ assert_eq!(markers.iter().filter(|name| name.ends_with('B')).count(), 2);
+ for (first, second) in [("A", "B"), ("B", "A")] {
+ for accept_first in [false, true] {
+ for accept_second in [false, true] {
+ let mut document = issue430_roundtrip(&mut pending);
+ for (author, accept) in [(first, accept_first), (second, accept_second)] {
+ if accept {
+ document.accept_revisions_by_author(author).unwrap();
+ } else {
+ document.reject_revisions_by_author(author).unwrap();
+ }
+ document = issue430_roundtrip(&mut document);
+ if author == first {
+ let left = issue430_markers(&mut document);
+ assert!(left.contains(&"_rdocxCmpNoteF4P11B".to_owned()), "{left:?}");
+ assert_eq!(left.iter().filter(|name| name.ends_with('B')).count(), 2);
+ }
+ }
+ let keep_a = if first == "A" {
+ accept_first
+ } else {
+ accept_second
+ };
+ let keep_b = if first == "B" {
+ accept_first
+ } else {
+ accept_second
+ };
+ let retained = [(1, true), (2, keep_a), (3, keep_b)]
+ .into_iter()
+ .filter_map(|(id, keep)| keep.then_some(id))
+ .collect::>();
+ issue430_assert_settled(&mut document, &retained, true);
+ }
+ }
+ }
+}
+
+#[test]
+fn issue430_word_saved_created_part_with_a_lost_note_pair_settles_to_its_destination() {
+ // One comparison created the footnotes part (bits 01) with two notes, the
+ // second re-authored Y, and Word saved it. Word kept the first note's pair
+ // and dropped the second's. Every path must end at its input's part
+ // presence: absent when both notes are rejected, whatever the order.
+ let body = r#"The buyer took delivery on 12 June.Payment was due in thirtysixty days.The parties met in September."#;
+ let notes = format!(
+ r#"{} Delivery note, p.1. Contract, clause 7."#,
+ issue430_word_separators()
+ );
+ let mut source = issue430_fixture(body, Some(¬es));
+ let pairs = ["_rdocxCmpNoteF15P01B", "_rdocxCmpNoteF7P01B"];
+ for (steps, retained) in [
+ (vec![(false, "A"), (false, "Y")], vec![]),
+ (vec![(false, "Y"), (false, "A")], vec![]),
+ (vec![(true, "A"), (false, "Y")], vec![1]),
+ (vec![(false, "A"), (true, "Y")], vec![2]),
+ (vec![(true, "Y"), (true, "A")], vec![1, 2]),
+ ] {
+ let mut document = Document::from_bytes(&source.to_bytes().unwrap()).unwrap();
+ for (step, (accept, author)) in steps.iter().enumerate() {
+ if *accept {
+ document.accept_revisions_by_author(author).unwrap();
+ } else {
+ document.reject_revisions_by_author(author).unwrap();
+ }
+ document = issue430_roundtrip(&mut document);
+ if step == 0 {
+ let markers = issue430_markers(&mut document);
+ for pair in pairs {
+ assert!(markers.contains(&pair.to_owned()), "{steps:?} {markers:?}");
+ }
+ }
+ }
+ issue430_assert_settled(&mut document, &retained, !retained.is_empty());
+ }
+ let mut rejected = Document::from_bytes(&source.to_bytes().unwrap()).unwrap();
+ rejected.reject_all().unwrap();
+ issue430_assert_settled(&mut rejected, &[], false);
+ // Without any custody pair, nothing records that the part was created:
+ // rejecting both tracked notes keeps the separator-only part, as Word does.
+ let mut plain_body = body.to_owned();
+ let mut plain_notes = notes.clone();
+ for (id, name) in [
+ (0, "_rdocxCmpNoteF7P01B"),
+ (7, "_rdocxCmpNoteF15P01B"),
+ (3, "_rdocxCmpNoteF7P01N"),
+ ] {
+ let pair = format!(
+ r#""#
+ );
+ plain_body = plain_body.replace(&pair, "");
+ plain_notes = plain_notes.replace(&pair, "");
+ }
+ let mut native = issue430_fixture(&plain_body, Some(&plain_notes));
+ native.reject_all().unwrap();
+ issue430_assert_settled(&mut native, &[], true);
+}
+
+#[test]
+fn issue430_tracked_note_needs_its_whole_owner_and_its_only_reference_tracked_one_way() {
+ let body = issue430_word_note_only_body();
+ let notes = issue430_word_note_only_notes();
+ let reference_ins = r#""#;
+ let note_end = "";
+ assert_eq!(notes.matches(note_end).count(), 1);
+ let variants = [
+ // an untracked run in the owner
+ (
+ body.to_owned(),
+ notes.replace(note_end, "plain"),
+ ),
+ // the reference is not tracked
+ (body.replace(reference_ins, "").replace("", ""), notes.clone()),
+ // the content is deleted while the paragraph mark is inserted
+ (
+ body.to_owned(),
+ notes
+ .replace(
+ r#""#,
+ r#""#,
+ )
+ .replace(" Contract, clause 7.", " Contract, clause 7.")
+ .replace(r#" Contract"#, r#" Contract"#)
+ .replace(note_end, ""),
+ ),
+ // two tracked references to the note stay with the shared-reference rules
+ (
+ body.replace(
+ "The parties met in September.",
+ r#"The parties met in September."#,
+ ),
+ notes.clone(),
+ ),
+ ];
+ for (body, notes) in variants {
+ assert!(body != issue430_word_note_only_body() || notes != issue430_word_note_only_notes());
+ let mut document = issue430_fixture(&body, Some(¬es));
+ let before = document.to_bytes().unwrap();
+ let error = document.reject_all().unwrap_err();
+ assert!(
+ error.to_string().contains("final paragraph mark"),
+ "{error}"
+ );
+ assert_eq!(document.to_bytes().unwrap(), before);
+ }
+ // A partial selection keeps the ordinary element rules. Rejecting only the
+ // reference leaves an unreferenced tracked note, which a later whole
+ // selection removes. Rejecting only the note's own elements still refuses.
+ let mut document = issue430_fixture(body, Some(¬es));
+ assert_eq!(document.reject_revision_id(1).unwrap(), 1);
+ let mut document = issue430_roundtrip(&mut document);
+ assert_eq!(
+ document
+ .footnotes()
+ .iter()
+ .map(|(id, _)| *id)
+ .collect::>(),
+ [1, 2]
+ );
+ assert_eq!(document.story_revisions().unwrap().len(), 2);
+ document.reject_all().unwrap();
+ issue430_assert_settled(&mut document, &[1], true);
+ let referenced = body.replace(
+ reference_ins,
+ r#""#,
+ );
+ let mut document = issue430_fixture(&referenced, Some(¬es));
+ let before = document.to_bytes().unwrap();
+ let error = document.reject_revisions_by_author("A").unwrap_err();
+ assert!(
+ error.to_string().contains("final paragraph mark"),
+ "{error}"
+ );
+ assert_eq!(document.to_bytes().unwrap(), before);
+ document.reject_revisions_by_author("Ref").unwrap();
+ let mut document = issue430_roundtrip(&mut document);
+ document.reject_revisions_by_author("A").unwrap();
+ issue430_assert_settled(&mut document, &[1], true);
+}
+
#[test]
fn issue432_note_mark_order_separators_and_space() {
let mut doc = Document::new();
diff --git a/crates/rdocx/tests/regression_test.rs b/crates/rdocx/tests/regression_test.rs
index 52ba847e8..1d576b84d 100644
--- a/crates/rdocx/tests/regression_test.rs
+++ b/crates/rdocx/tests/regression_test.rs
@@ -41448,14 +41448,15 @@ mod compare_producer_noise {
}
}
- // A space split out of a text keeps reading as a space in the redline.
- for granularity in [
- ComparisonGranularity::Word,
- ComparisonGranularity::Character,
+ // A space that a split leaves at the edge of a text keeps reading as
+ // a space in the redline.
+ for (granularity, edited) in [
+ (ComparisonGranularity::Word, "two wordy"),
+ (ComparisonGranularity::Character, "two xords"),
] {
let (kinds, tracked) = compared_kinds_with(
¶graph("two words"),
- ¶graph("two wordy"),
+ ¶graph(&format!("{edited}")),
&ComparisonOptions {
granularity,
..Default::default()
@@ -41463,9 +41464,9 @@ mod compare_producer_noise {
);
let tracked = comparison_structure_xml(&tracked);
assert_eq!(kinds, changed, "{granularity:?}");
- assert!(!tracked.contains(""), "{tracked}");
+ assert!(!tracked.contains("two "), "{tracked}");
assert!(
- tracked.contains(r#""#),
+ tracked.contains(r#"two "#),
"{tracked}"
);
}
@@ -412775,6 +412776,535 @@ fn issue434_compare_one_word_beside_split_invoice() {
}
}
+/// One `w:r` of a story part: the element that holds it, the text of each of
+/// its text elements, and whether it directly follows a sibling run that has
+/// the same `w:rPr`.
+struct Issue446Run {
+ parent: String,
+ texts: Vec,
+ repeats_sibling: bool,
+}
+
+fn issue446_runs(xml: &str) -> Vec {
+ #[derive(Default)]
+ struct Open {
+ name: String,
+ start: usize,
+ // The `w:rPr` of the run that is the last child read so far.
+ last_run: Option,
+ // For a run, the `w:rPr` of the run it directly follows, then its own.
+ follows: Option,
+ properties: String,
+ texts: Vec,
+ }
+ let mut reader = XmlReader::from_str(xml);
+ let mut open = vec![Open::default()];
+ let mut runs = Vec::new();
+ loop {
+ let start = reader.buffer_position() as usize;
+ let event = reader.read_event().unwrap();
+ let end = reader.buffer_position() as usize;
+ if let XmlEvent::Start(element) | XmlEvent::Empty(element) = &event {
+ let name = String::from_utf8(element.name().as_ref().to_vec()).unwrap();
+ let parent = open.last_mut().unwrap();
+ let follows = parent.last_run.take().filter(|_| name == "w:r");
+ if parent.name == "w:r" && matches!(name.as_str(), "w:t" | "w:delText") {
+ parent.texts.push(String::new());
+ }
+ open.push(Open {
+ name,
+ start,
+ follows,
+ ..Default::default()
+ });
+ }
+ match event {
+ XmlEvent::Text(text) => {
+ if let [.., run, leaf] = open.as_mut_slice()
+ && run.name == "w:r"
+ && matches!(leaf.name.as_str(), "w:t" | "w:delText")
+ {
+ run.texts
+ .last_mut()
+ .unwrap()
+ .push_str(&text.decode().unwrap());
+ }
+ }
+ XmlEvent::End(_) | XmlEvent::Empty(_) => {
+ let closed = open.pop().unwrap();
+ let parent = open.last_mut().unwrap();
+ if closed.name == "w:rPr" && parent.name == "w:r" {
+ parent.properties = xml[closed.start..end].to_owned();
+ }
+ if closed.name == "w:r" {
+ runs.push(Issue446Run {
+ parent: parent.name.clone(),
+ repeats_sibling: closed.follows.as_ref() == Some(&closed.properties),
+ texts: closed.texts,
+ });
+ parent.last_run = Some(closed.properties);
+ }
+ }
+ XmlEvent::Eof => break,
+ _ => {}
+ }
+ }
+ runs
+}
+
+/// A story a comparison revises: its name, its part and the document that
+/// holds a text in it as one run.
+type Issue446Story = (&'static str, &'static str, fn(&str) -> Document);
+
+fn issue446_stories() -> Vec {
+ fn body(content: &str) -> Document {
+ document_with_content_controls(&wrap_word_body(content))
+ }
+ fn run(text: &str) -> String {
+ format!("{text}")
+ }
+ vec![
+ ("body", "/word/document.xml", |text| {
+ body(&format!("{}", run(text)))
+ }),
+ ("table cell", "/word/document.xml", |text| {
+ body(&format!(
+ r#"{}"#,
+ run(text)
+ ))
+ }),
+ ("inline control", "/word/document.xml", |text| {
+ body(&format!(
+ "{}",
+ run(text)
+ ))
+ }),
+ ("hyperlink", "/word/document.xml", |text| {
+ body(&format!(
+ r#"{}"#,
+ run(text)
+ ))
+ }),
+ ("header", "/word/header1.xml", |text| {
+ document_with_comparison_header(&format!("{}", run(text)))
+ }),
+ ("footnote", "/word/footnotes.xml", |text| {
+ let mut document = Document::new();
+ document.add_paragraph("The survey is on file.");
+ let location = document.paragraph_story_location(0).unwrap().unwrap();
+ document.create_footnote(&location, text).unwrap();
+ Document::from_bytes(&document.to_bytes().unwrap()).unwrap()
+ }),
+ ]
+}
+
+#[test]
+fn issue446_comparison_writes_one_run_per_stretch_in_every_story() {
+ // The granularity sets what is compared, not how the result is cut: the
+ // text between two revisions stays one run with one text element, and a
+ // revision holds its text in one `w:delText` or `w:t`.
+ let original_text = "The bearing at pier 4 moved about twelve millimetres since the survey.";
+ let edited_text = "The bearing at pier 4 moved about fifteen millimetres since the survey.";
+ for (story, part, document) in issue446_stories() {
+ for granularity in [
+ rdocx::ComparisonGranularity::Word,
+ rdocx::ComparisonGranularity::Character,
+ ] {
+ let context = format!("{story} {granularity:?}");
+ let options = rdocx::ComparisonOptions {
+ granularity,
+ ..Default::default()
+ };
+ let mut tracked = document(original_text);
+ let before = issue446_runs(&comparison_part_xml(&mut tracked, part));
+ tracked
+ .compare_with_options(
+ &document(edited_text),
+ "Ada",
+ "2026-11-15T09:00:00Z",
+ &options,
+ )
+ .unwrap_or_else(|error| panic!("{context}: {error}"));
+ let revisions = tracked.story_revisions().unwrap();
+ if granularity == rdocx::ComparisonGranularity::Word {
+ assert_eq!(
+ revisions
+ .iter()
+ .map(|revision| revision.text().to_owned())
+ .collect::>(),
+ ["twelve", "fifteen"],
+ "{context}"
+ );
+ }
+ let xml = comparison_part_xml(&mut tracked, part);
+ let runs = issue446_runs(&xml);
+ for run in &runs {
+ assert!(run.texts.len() <= 1, "{context}: {:?} in {xml}", run.texts);
+ }
+ // The redline adds no run that repeats the properties of the
+ // sibling run it follows.
+ let repeats =
+ |runs: &[Issue446Run]| runs.iter().filter(|run| run.repeats_sibling).count();
+ assert_eq!(repeats(&runs), repeats(&before), "{context}: {xml}");
+ // One run a revision, and one for the text before, between and
+ // after them.
+ assert!(
+ runs.len() <= before.len() + 2 * revisions.len(),
+ "{context}: {} runs for {} revisions in {xml}",
+ runs.len(),
+ revisions.len()
+ );
+ let pieces = |parent: &str| {
+ runs.iter()
+ .filter(|run| run.parent == parent)
+ .flat_map(|run| run.texts.iter().map(String::as_str))
+ .collect::>()
+ };
+ for (parent, kind) in [
+ ("w:del", RevisionKind::Deletion),
+ ("w:ins", RevisionKind::Insertion),
+ ] {
+ // Each revision is one run holding its whole text.
+ assert_eq!(
+ pieces(parent),
+ revisions
+ .iter()
+ .filter(|revision| revision.kind() == kind)
+ .map(|revision| revision.text())
+ .collect::>(),
+ "{context}: {xml}"
+ );
+ }
+ if granularity == rdocx::ComparisonGranularity::Word {
+ assert_eq!(pieces("w:del"), ["twelve"], "{context}");
+ assert_eq!(pieces("w:ins"), ["fifteen"], "{context}");
+ assert!(
+ runs.iter()
+ .any(|run| run.texts == ["The bearing at pier 4 moved about "])
+ && runs
+ .iter()
+ .any(|run| run.texts == [" millimetres since the survey."]),
+ "{context}: {xml}"
+ );
+ }
+ let story_text = |document: &mut Document| {
+ issue446_runs(&comparison_part_xml(document, part))
+ .into_iter()
+ .flat_map(|run| run.texts)
+ .collect::()
+ };
+ let bytes = tracked.to_bytes().unwrap();
+ for (resolve, wanted) in [
+ (Document::accept_all as fn(&mut Document) -> _, edited_text),
+ (Document::reject_all, original_text),
+ ] {
+ let mut resolved = Document::from_bytes(&bytes).unwrap();
+ resolve(&mut resolved).unwrap();
+ assert_eq!(
+ story_text(&mut resolved),
+ story_text(&mut document(wanted)),
+ "{context}"
+ );
+ }
+ }
+ }
+}
+
+#[test]
+fn issue446_comparison_keeps_the_runs_a_change_does_not_reach() {
+ let document = |last: &str| {
+ document_with_content_controls(&wrap_word_body(&format!(
+ r#"Plain bold and a tail of {last} days"#
+ )))
+ };
+ for granularity in [
+ rdocx::ComparisonGranularity::Word,
+ rdocx::ComparisonGranularity::Character,
+ ] {
+ let mut tracked = document("thirty");
+ tracked
+ .compare_with_options(
+ &document("ninety"),
+ "Ada",
+ "2026-11-15T09:00:00Z",
+ &rdocx::ComparisonOptions {
+ granularity,
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ let xml = document_xml(&mut tracked);
+ let pieces = issue446_runs(&xml)
+ .into_iter()
+ .map(|run| (run.parent, run.texts.concat()))
+ .collect::>();
+ let pieces = pieces
+ .iter()
+ .map(|(parent, text)| (parent.as_str(), text.as_str()))
+ .collect::>();
+ // The two runs before the edited one are whole, and the edited run
+ // is cut only where a revision starts or ends.
+ assert_eq!(
+ pieces[..3],
+ [
+ ("w:p", "Plain "),
+ ("w:p", "bold"),
+ ("w:p", " and a tail of ")
+ ],
+ "{granularity:?}: {xml}"
+ );
+ assert!(
+ matches!(pieces.last(), Some(("w:p", text)) if text.ends_with(" days")),
+ "{granularity:?}: {xml}"
+ );
+ if granularity == rdocx::ComparisonGranularity::Word {
+ assert_eq!(
+ pieces[3..],
+ [("w:del", "thirty"), ("w:ins", "ninety"), ("w:p", " days")],
+ "{xml}"
+ );
+ }
+ }
+}
+
+#[test]
+fn issue446_comparison_cost_follows_the_changes_not_the_unchanged_text() {
+ // Every later stage reads the redline run by run, so its run count and
+ // its size over the original are the structural cost of a comparison.
+ // Both depend on the edit alone, whatever the length of the text around
+ // it and whatever the unit the granularity compares.
+ for granularity in [
+ rdocx::ComparisonGranularity::Word,
+ rdocx::ComparisonGranularity::Character,
+ ] {
+ let cost = |words: usize| {
+ let document = |last: &str| {
+ let mut document = Document::new();
+ for _ in 0..3 {
+ document.add_paragraph(&format!("{}{last} days.", "kept ".repeat(words)));
+ }
+ Document::from_bytes(&document.to_bytes().unwrap()).unwrap()
+ };
+ let mut tracked = document("thirty");
+ let original = document_xml(&mut tracked);
+ tracked
+ .compare_with_options(
+ &document("sixty"),
+ "Ada",
+ "2026-11-15T09:00:00Z",
+ &rdocx::ComparisonOptions {
+ granularity,
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ let xml = document_xml(&mut tracked);
+ (
+ issue446_runs(&xml).len(),
+ tracked.story_revisions().unwrap().len(),
+ xml.len() - original.len(),
+ )
+ };
+ assert_eq!(cost(4), cost(400), "{granularity:?}");
+ if granularity == rdocx::ComparisonGranularity::Word {
+ // Three paragraphs, each with the text before, the deletion, the
+ // insertion and the text after.
+ assert_eq!((cost(4).0, cost(4).1), (12, 6));
+ }
+ }
+}
+
+#[test]
+fn issue446_comparison_keeps_refusing_a_drawing_in_a_field_begin_run() {
+ // The source guard reads the cleaned clone of each story again, as
+ // v0.17.0 does. That read refuses a drawing that shares its run with
+ // the begin mark of a complex field, whatever else changes. Speeding the
+ // comparison up must not change which inputs it refuses.
+ let png: &[u8] = &[
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44,
+ 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00, 0x00, 0x90,
+ 0x77, 0x53, 0xde, 0x00, 0x00, 0x00, 0x0c, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8,
+ 0xcf, 0xc0, 0x00, 0x00, 0x03, 0x01, 0x01, 0x00, 0xc9, 0xfe, 0x92, 0xef, 0x00, 0x00, 0x00,
+ 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
+ ];
+ let mut seed = Document::new();
+ seed.add_picture(png, "a.png", Length::emu(914400), Length::emu(914400));
+ let seed = seed.to_bytes().unwrap();
+ let package = oxml_opc::OpcPackage::from_reader(std::io::Cursor::new(&seed)).unwrap();
+ let xml = String::from_utf8(package.get_part("/word/document.xml").unwrap().to_vec()).unwrap();
+ let drawing = &xml[xml.find("").unwrap()
+ ..xml.find("").unwrap() + "".len()];
+ let head = &xml[..xml.find("").unwrap() + "".len()];
+ let tail = &xml[xml.find("{text}"#,
+ r#"{drawing}"#,
+ r#" PAGE "#,
+ r#"1"#,
+ r#""#,
+ ),
+ text = text,
+ drawing = drawing,
+ );
+ let mut package = oxml_opc::OpcPackage::from_reader(std::io::Cursor::new(&seed)).unwrap();
+ package.set_part(
+ "/word/document.xml",
+ format!("{head}{body}{tail}").into_bytes(),
+ );
+ let mut bytes = std::io::Cursor::new(Vec::new());
+ package.write_to(&mut bytes).unwrap();
+ Document::from_bytes(bytes.get_ref()).unwrap()
+ };
+ for granularity in [
+ rdocx::ComparisonGranularity::Run,
+ rdocx::ComparisonGranularity::Word,
+ rdocx::ComparisonGranularity::Character,
+ ] {
+ let mut original = document("alpha beta");
+ let before = original.to_bytes().unwrap();
+ let error = original
+ .compare_with_options(
+ &document("alpha gamma"),
+ "Ada",
+ "2026-11-16T09:00:00Z",
+ &rdocx::ComparisonOptions {
+ granularity,
+ ..Default::default()
+ },
+ )
+ .unwrap_err();
+ assert_eq!(
+ error.to_string(),
+ "comparison could not correlate split field run 2",
+ "{granularity:?}"
+ );
+ assert_eq!(original.to_bytes().unwrap(), before, "{granularity:?}");
+ }
+}
+
+#[test]
+fn issue446_comparison_splits_text_that_holds_references() {
+ // The reader reports `&`, `"` and numeric references as events
+ // of their own between pieces of text. A word or character comparison
+ // that splits such a text refused it ("split text has opaque mixed
+ // events"), including text rdocx writes itself.
+ let original = r#"Smith&Sons pay "now", café 😀."#;
+ let edited = r#"Smith+Sons pay "later", café 😀."#;
+ let body: fn(&str) -> Document =
+ |paragraph| document_with_content_controls(&wrap_word_body(paragraph));
+ let header: fn(&str) -> Document = document_with_comparison_header;
+ for (story, document) in [("body", body), ("header", header)] {
+ for granularity in [
+ rdocx::ComparisonGranularity::Word,
+ rdocx::ComparisonGranularity::Character,
+ ] {
+ let context = format!("{story} {granularity:?}");
+ let mut tracked = document(original);
+ tracked
+ .compare_with_options(
+ &document(edited),
+ "Ada",
+ "2026-11-16T09:00:00Z",
+ &rdocx::ComparisonOptions {
+ granularity,
+ ..Default::default()
+ },
+ )
+ .unwrap_or_else(|error| panic!("{context}: {error}"));
+ let revisions = tracked
+ .story_revisions()
+ .unwrap()
+ .iter()
+ .map(|revision| (revision.kind(), revision.text().to_owned()))
+ .collect::>();
+ assert!(
+ revisions.contains(&(RevisionKind::Deletion, "&".to_owned())),
+ "{context}: {revisions:?}"
+ );
+ if granularity == rdocx::ComparisonGranularity::Word {
+ assert_eq!(
+ revisions,
+ [
+ (RevisionKind::Deletion, "&".to_owned()),
+ (RevisionKind::Insertion, "+".to_owned()),
+ (RevisionKind::Deletion, "now".to_owned()),
+ (RevisionKind::Insertion, "later".to_owned()),
+ ],
+ "{context}"
+ );
+ }
+ let bytes = tracked.to_bytes().unwrap();
+ for (resolve, wanted) in [
+ (Document::accept_all as fn(&mut Document) -> _, edited),
+ (Document::reject_all, original),
+ ] {
+ let mut resolved = Document::from_bytes(&bytes).unwrap();
+ resolve(&mut resolved).unwrap();
+ resolved
+ .compare(&document(wanted), "Ada", "2026-11-16T09:01:00Z")
+ .unwrap();
+ assert!(
+ resolved.story_revisions().unwrap().is_empty(),
+ "{context}: {wanted}"
+ );
+ }
+ }
+ }
+}
+
+#[test]
+fn issue446_comparison_reads_a_resplit_inline_control_as_equal() {
+ // Runs that only split the same text differently read as equal inside an
+ // inline control as they do in a paragraph, so accepting a granular
+ // redline there and comparing again gives no revision.
+ let control = |runs: &str| {
+ issue434_paragraph_document(&format!(
+ r#"Before {runs}"#
+ ))
+ };
+ let run = |text: &str| {
+ format!(r#"{text}"#)
+ };
+ let one = run("alpha beta gamma delta");
+ let three = [run("alpha beta "), run("gamma"), run(" delta")].concat();
+ for granularity in [
+ rdocx::ComparisonGranularity::Run,
+ rdocx::ComparisonGranularity::Word,
+ rdocx::ComparisonGranularity::Character,
+ ] {
+ let options = rdocx::ComparisonOptions {
+ granularity,
+ ..Default::default()
+ };
+ let mut original = control(&one);
+ let before = document_xml(&mut original);
+ original
+ .compare_with_options(&control(&three), "Ada", "2026-11-16T09:00:00Z", &options)
+ .unwrap();
+ assert!(
+ original.story_revisions().unwrap().is_empty(),
+ "{granularity:?}"
+ );
+ assert_eq!(document_xml(&mut original), before, "{granularity:?}");
+ // A real change inside the control is still revised.
+ let mut original = control(&one);
+ original
+ .compare_with_options(
+ &control(&[run("alpha beta "), run("gamma"), run(" epsilon")].concat()),
+ "Ada",
+ "2026-11-16T09:00:00Z",
+ &options,
+ )
+ .unwrap();
+ assert!(
+ !original.story_revisions().unwrap().is_empty(),
+ "{granularity:?}"
+ );
+ }
+}
+
#[test]
fn issue434_comparison_crossing_reply_composition() {
let mut original = Document::new();
diff --git a/docs/hld/03-architecture.md b/docs/hld/03-architecture.md
index 491226411..f74e1e4cd 100644
--- a/docs/hld/03-architecture.md
+++ b/docs/hld/03-architecture.md
@@ -1513,7 +1513,31 @@ Fields, drawings, ignored units, opaque children, bookmark and comment markers,
hyperlinks, controls and formatting transitions stop grouping. Formatting-only
changes and replacements using ignored formatting also stop it. Different runs
retain their own formatting and coalescing ownership. Run granularity retains
-its existing alignment and revision output. Supported inline controls retain raw
+its existing alignment and revision output. The granularity sets the compared
+unit, never the written run. Unchanged units that continue one original and one
+edited text element are written as one run, and the fragments of one text
+element inside a written run rejoin as one text element with one source
+selection, whole again when every fragment is there. A redline therefore holds
+one run for each revision and for each stretch of text between two of them,
+whatever the unit, in every story, with two exceptions. Under
+`ignore_whitespace` an ignored whitespace unit ends a stretch, so unchanged text
+is written one run per word and per space. A tab, a break or other run content
+ends a stretch as it ends a text element. Text that holds a character or entity
+reference, such as `&`, splits like any other text. An inline control whose
+runs only split the same text differently keeps its original source, as an
+equal paragraph does.
+
+The cost of a comparison follows its changes, not its units or the size of the
+parents that hold them, with one exception. A comparison reads the source of a
+paragraph, table, row, cell or control a fixed number of times whatever
+children it holds: one read answers all its children, every answer, an error
+included, being the one a read for that child alone gives. A
+character-granularity signature holds one token per stretch of plain text, and
+each postcondition direction resolves the candidate once for both the package
+guard and the footnote destination check. The package guard still reads each
+cleaned story a second time, which keeps its refusals. The exception is the
+alignment of one shell segment, a full longest-common-subsequence table,
+quadratic in the units it compares. Supported inline controls retain raw
child run cuts before extraction, align Word and Character units within those
shell segments and copy each shell before its first inserted unit.
Non-text content remains atomic. Unmatched identical owners become move pairs
@@ -1571,18 +1595,33 @@ with differing story shells are rejected unless their story category is
ignored or the change is a supported normal-footnote topology change.
Footnote comparison binds physical reference occurrences to their actual note
ids. It aligns the body owners and run boundaries, preserves repeated references
-without synthesizing another site, and preserves original unused definitions.
-A new unreferenced definition is refused. Omitted type and explicit `normal`
-identify normal notes at every signed id. The three explicit separator types
-remain special. Empty and unknown types keep their legacy read projection, but
-their owner bytes and reference identity must remain unchanged. Classification
-uses each attribute's effective Word namespace, including local prefix shadows.
+without synthesizing another site, and preserves original unused definitions. A
+footnote that both inputs reference refuses atomically when its pending result
+would hold more physical references than either input gives it, which happens
+when its reference moves to another site, for example when a new note inserted
+before it takes its id. Such a pending result would name one owner from a
+deleted and an inserted reference. A new unreferenced definition is refused.
+Omitted type and explicit `normal` identify normal notes at every signed id. The
+three explicit separator types remain special. Empty and unknown types keep
+their legacy read projection, but their owner bytes and reference identity must
+remain unchanged. Classification uses each attribute's effective Word namespace,
+including local prefix shadows.
Added and removed definitions use paired hidden standard bookmarks in the body
and first note paragraph. Names carry a persistent token and the emitting
transaction's original and edited part-presence bits. The body pair precedes the
-first actual reference outside its revision wrapper. An added note's pair is
-inside its content insertion. A deleted note's pair stays outside the deletion.
+first actual reference outside its revision wrapper. Word for Mac 16.115 merges
+adjacent insertions of one author and date, which can move the pair inside the
+reference's own insertion. A body pair is admitted there only in the main story,
+only with its note pair, and only as a direct child of the one insertion whose
+next child is the reference run, the same next-sibling proof as outside it.
+Resolving that insertion keeps the pair in its place, so its lifetime and
+part-presence vote do not depend on Word's merging. Any other position inside a
+revision refuses, as does an unmatched pair inside one. The note pair follows
+the note's reference-mark run inside its content insertion or deletion, because
+Word 16.115 drops a pair that precedes the reference mark of a note that is not
+the first of its part. A note without a reference-mark run keeps the pair at the
+start of its insertion, or outside its deletion.
Tokens and bookmark ids are reserved before allocating new comparison ids.
A token is identity, independent of every current revision id and token order.
Listing and id, author and date scopes still operate on revision elements.
@@ -1593,6 +1632,22 @@ Within the positively admitted custody grammar, resolved units retain zero-width
A valid body pair without a note pair has no surviving note-owner identity.
It stays a tombstone in an open part or completed imported metadata in a settled
part. A following reference or revision wrapper cannot identify its former owner.
+A normal owner that no pair binds is still a unit, a tracked note, when its own
+bytes prove that the whole definition is tracked as one insertion or one
+deletion: every paragraph carries a paragraph-mark revision of that kind, every
+other paragraph child is a wrapper of that kind or a zero-width range marker,
+and its reference, when it has one, bound by footnote id, is wrapped the same
+way. A tracked note left without a reference is removed by a whole selection of
+its own elements. The proof reads no marker, so an unmatched body pair stays
+unassociated. An unmatched body pair inside its reference's insertion is
+admitted only when that reference's note is a tracked note, and only keeps its
+place there. A tracked note has no token or bits and does not vote on part
+presence, but it is pending for the open lifetime, so pairs stay while it is
+pending. When a tracked note settles while a note owner outside every unit still
+holds a revision, the pairs also stay. Selecting all its elements resolves it as
+one and removes the owner when the resolution removes its content. A partial
+selection keeps the ordinary element rules. An owner with two or more references
+keeps the shared-reference rules.
Collision reconciliation preserves a completed body pair when its token, bits,
pair id, part and exact source paragraph boundary agree between inputs. This
does not reconstruct a missing note owner. An unrelated paragraph edit keeps
@@ -1613,11 +1668,14 @@ Creating a part carries the actual edited special inventory, including none.
Accept restores the edited identities and inventory, and reject restores the
original. Settlement physically retires library custody pairs. A marker left
by Word in an already completed part is preserved when untouched and retired
-before editing its owner or part or emitting new custody there. Ignored notes
+before editing its owner or part or emitting new custody there. A resolution
+that edits the note part or resolves a note reference, and leaves no note owner
+or reference revision pending, also settles the part when no unit is recognized,
+for example after Word dropped a note pair, and retires the pairs left in it. Ignored notes
retain original bytes and cannot supply a dangling new body reference. Endnote
topology retains its existing refusal while ordinary text edits remain supported.
-Word-save interoperability is qualified only for actual admitted marker layouts. A note-plus-body-text Word save can move the body custody pair inside a revision and drop its note counterpart. Such a package can open, list and no-op serialize while Accept All, Reject All and an unrelated comparison refuse atomically. Some mixed-author Word saves refuse rejection of a remaining author's revisions. On a fully pending mixed input, an earlier successful selective action can retire all custody markers while another author's revisions remain pending. A failing action preserves its immediate pre-action state, not the state before earlier successful calls. Successful return or reopen therefore does not prove the unresolved-marker lifetime for these two native families. These are current Word-save limitations carried to pending F-X287, not a blanket restriction on ordinary note authoring, reading or otherwise admitted comparison. Issue430 remains open and Q-A430-28 remains independently unproved.
+Word-save interoperability is qualified on reconstructed Word for Mac 16.115 saves, not on the retained RC3 packets. Word 16.115 can drop a note pair placed before the reference mark of a note that is not the first of its part, merge the body pair into its reference's insertion, and renumber notes, bookmarks and revisions. The note pair follows the reference mark, a body pair inside its own reference's insertion is admitted with its note pair, or without it before a tracked note's reference, and a note whose pair Word dropped resolves as a tracked note. A note outside the tracked-note grammar, for example one that holds a hyperlink, keeps the earlier limits once Word drops its pair: rejecting it refuses atomically, and when Word kept the other author's pair, resolving that author first retires the outside note's body pair while its revisions remain pending, as on v0.17.0. A footnote inserted in Word 16.115 with Track Changes on is not a tracked note, because Word tracks its reference and content but not its paragraph mark, so rejecting it keeps an empty unreferenced footnote where Word's own Reject All removes the note, as on v0.17.0. A completed body pair that an earlier Word resolution left in a part still votes when a later tracked note settles that part, so such a stale creation bit can remove a part that held only special records. A failing action preserves its immediate pre-action state, not the state before earlier successful calls. Native qualification of these families on the RC3 packets remains with F-X287. Issue430 remains open and Q-A430-28 remains independently unproved.
Inputs may hold existing modeled revisions, such as the redline of an
earlier comparison. A story owner that holds one, a paragraph, table, or
diff --git a/docs/hld/10-bindings-spec.md b/docs/hld/10-bindings-spec.md
index c5493ba53..5ea9edabb 100644
--- a/docs/hld/10-bindings-spec.md
+++ b/docs/hld/10-bindings-spec.md
@@ -3042,32 +3042,42 @@ refuses atomically, including when a token happens to equal an unrelated id.
No selector treats the token as a request to select the unit.
For positively admitted custody states, accept restores edited note identities,
-reference inventory, special records and part presence. Reject restores the original destination. Creating a part
-carries the actual edited special inventory, including none. An open creation
-unwinds to absence after its final owned note is rejected unless retained
-unowned content requires the part. Resolved units keep tombstones while another
-unit is pending, and settlement physically retires library markers. An unmatched
-body pair has no surviving note-owner identity and cannot group or select an
-adjacent reference, even inside a revision wrapper. Its ordinary revisions keep
-their ordinary selectors. Exact note-present owner, reference, token, bits and
-pair checks remain mandatory, and a note pair without its body pair refuses.
-Missing note-pair corruption cannot always be distinguished from identical valid
+reference inventory, special records and part presence. Reject restores the
+original destination. Creating a part carries the actual edited special
+inventory, including none. An open creation unwinds to absence after its final
+owned note is rejected unless retained unowned content requires the part.
+Resolved units keep tombstones while another unit is pending, and settlement
+physically retires library markers. A resolution that edits the note part or
+resolves a note reference, and leaves no note revision pending, settles it even
+when no unit is recognized, and retires its remaining pairs. An unmatched body
+pair has no surviving note-owner identity and cannot group or select an adjacent
+reference, even inside a revision wrapper. Its ordinary revisions keep their
+ordinary selectors. A normal note whose whole definition and only reference, if
+any, are tracked one way, proved from its own bytes and the reference's footnote id,
+resolves as one tracked note under a selection of all its elements, and keeps
+the ordinary selectors otherwise. An unmatched body pair inside a revision is
+admitted only before such a note's reference. Exact note-present owner,
+reference, token, bits and pair
+checks remain mandatory, and a note pair without its body pair refuses. Missing
+note-pair corruption cannot always be distinguished from identical valid
removed-note histories. Opaque revision-shaped payload does not add listing or
resolution counts. Genuine admitted textbox and structural revisions still do.
-Reopen
-reads the same persisted units and part-presence votes without chronology or
-process-local history. Imported Word-completed markers stay exact when untouched
-through an unrelated scoped paragraph replacement and comparison, including a
-terminal body pair with no surviving note counterpart. Complete removal of a
-comparison-owned footnotes part also retires its settings references while
-preserving other note policy. Completed markers retire before an affected
-comparison edits their owner or part or adds
-custody. Ignored footnote stories retain original parts and refuse body changes
-that would leave a missing note target. Endnote text comparison remains
-supported, while new endnote topology remains refused. These operations use
-existing held-handle invalidation and leave all live state unchanged on refusal.
-
-Word-save interoperability is qualified only for actual admitted marker layouts. A note-plus-body-text Word save can move the body custody pair inside a revision and drop its note counterpart. Such a package can open, list and no-op serialize while Accept All, Reject All and an unrelated comparison refuse atomically. Some mixed-author Word saves refuse rejection of a remaining author's revisions. On a fully pending mixed input, an earlier successful selective action can retire all custody markers while another author's revisions remain pending. A failing action preserves its immediate pre-action state, not the state before earlier successful calls. Successful return or reopen therefore does not prove the unresolved-marker lifetime for these two native families. These are current Word-save limitations carried to pending F-X287, not a blanket restriction on ordinary note authoring, reading or otherwise admitted comparison. Issue430 remains open and Q-A430-28 remains independently unproved.
+Reopen reads the same persisted units and part-presence votes without chronology
+or process-local history. Imported Word-completed markers stay exact when
+untouched through an unrelated scoped paragraph replacement and comparison,
+including a terminal body pair with no surviving note counterpart. Complete
+removal of a comparison-owned footnotes part also retires its settings
+references while preserving other note policy. Completed markers retire before
+an affected comparison edits their owner or part or adds custody. Ignored
+footnote stories retain original parts and refuse body changes that would leave
+a missing note target. A comparison whose pending result would give a
+referenced footnote more physical references than either input, because its
+reference moved to another site, refuses atomically. Endnote text comparison
+remains supported, while new
+endnote topology remains refused. These operations use existing held-handle
+invalidation and leave all live state unchanged on refusal.
+
+Word-save interoperability is qualified on reconstructed Word for Mac 16.115 saves, not on the retained RC3 packets. Word 16.115 can drop a note pair placed before the reference mark of a note that is not the first of its part, merge the body pair into its reference's insertion, and renumber notes, bookmarks and revisions. The note pair follows the reference mark, a body pair inside its own reference's insertion is admitted with its note pair, or without it before a tracked note's reference, and a note whose pair Word dropped resolves as a tracked note. A note outside the tracked-note grammar, for example one that holds a hyperlink, keeps the earlier limits once Word drops its pair: rejecting it refuses atomically, and when Word kept the other author's pair, resolving that author first retires the outside note's body pair while its revisions remain pending, as on v0.17.0. A footnote inserted in Word 16.115 with Track Changes on is not a tracked note, because Word tracks its reference and content but not its paragraph mark, so rejecting it keeps an empty unreferenced footnote where Word's own Reject All removes the note, as on v0.17.0. A completed body pair that an earlier Word resolution left in a part still votes when a later tracked note settles that part, so such a stale creation bit can remove a part that held only special records. A failing action preserves its immediate pre-action state, not the state before earlier successful calls. Native qualification of these families on the RC3 packets remains with F-X287. Issue430 remains open and Q-A430-28 remains independently unproved.
Word and character revisions group changed stretches as deletions followed by
insertions. Whitespace between changes folds, while a non-whitespace anchor
@@ -3075,7 +3085,14 @@ folds only when its joined word count is strictly shorter than both changed
sides before and after it. Character units count joined words rather than
letters. Structural, opaque and formatting boundaries, fields, drawings and
ignored units remain barriers. Default and explicit run granularity retain their
-existing output. Inside supported inline controls, retained raw children keep
+existing output. Word and character redlines keep the text between two revisions
+as one run with one text element, and each revision holds its text in one text
+element, so the run count follows the revisions and not the compared units. Two
+exceptions remain. With `ignore_whitespace` unchanged text is written one run
+per word and per space, and a tab or a break between two texts ends a run. Word
+and character comparisons split text that holds a character or entity
+reference, such as `&`. An inline control whose runs only split the same
+text differently compares equal. Inside supported inline controls, retained raw children keep
their physical text ownership on both sides through accept, reject and reopen.
No comparison option or existing public signature changes. The additive doc-hidden
lower native `properties::protected_source_residual(xml, inherited_bindings)`
diff --git a/docs/hld/12-testing-strategy.md b/docs/hld/12-testing-strategy.md
index 8c0ca6f86..d946d25ad 100644
--- a/docs/hld/12-testing-strategy.md
+++ b/docs/hld/12-testing-strategy.md
@@ -1296,6 +1296,24 @@ reconstruction controls remain active.
A bounded unit matrix checks coverage, deterministic output and retained segment
identity without timing thresholds or an additional alignment algorithm.
+The Issue446 regressions state the written shape as invariants at word and
+character granularity in the body, a table cell, an inline control, a hyperlink,
+a header and a footnote. No run holds two text elements, no run repeats the
+properties of the sibling run it follows, each revision is one run with its
+whole text, and the run count is bounded by the revision count. The run count
+and the size a redline adds over its original do not depend on the length of
+the unchanged text. Unit controls check that merged fragments rejoin one text
+element with one source selection, that a character-granularity signature holds
+one token per stretch and reads the same for every run split, and that run
+sources and parent scopes read together equal those read alone, errors
+included. A count of the source bytes a comparison reads shows that it reads a
+paragraph, a hyperlink, a table and an inserted paragraph or table a fixed
+number of times whatever their children, at every granularity. Further
+regressions pin the v0.17.0 refusal of a drawing that shares its run with a
+field begin mark, compare text holding references in the body and a header,
+and compare a resplit inline control as equal. None of these uses a timing
+threshold.
+
Chart comparison regressions cover chart-only Word and Run granularity, adjacent
text edits and an unchanged-chart control. Saved and reopened resolutions follow
the surviving drawing relationships and independently check exact ChartML,
diff --git a/scripts/readme_doctests.py b/scripts/readme_doctests.py
index bf17a18d9..9dd0495fe 100644
--- a/scripts/readme_doctests.py
+++ b/scripts/readme_doctests.py
@@ -376,7 +376,7 @@ class ReadmeCase:
"oxml-opc": "2026-11-06",
"oxml-pdf": "2026-11-06",
"oxml-sml": "2026-11-06",
- "rdocx": "2026-11-09",
+ "rdocx": "2026-11-16",
"rdocx-cli": "2026-11-07",
"rdocx-html": "2026-11-06",
"rdocx-layout": "2026-11-09",
@@ -402,7 +402,7 @@ class ReadmeCase:
"oxml-opc": (119_252, 486_417, 12),
"oxml-pdf": (102_219, 478_926, 14),
"oxml-sml": (24_956, 115_575, 6),
- "rdocx": (4_501_789, 56_396_845, 37),
+ "rdocx": (4_531_634, 56_539_892, 37),
"rdocx-cli": (126_182, 593_817, 8),
"rdocx-html": (29_407, 118_370, 11),
"rdocx-layout": (463_844, 2_543_127, 15),