diff --git a/README.md b/README.md index 0f39a02a2..89e13bede 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,517,067 compressed bytes, 56,462,895 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..7c6c6ada7 100644 --- a/crates/rdocx-py/tests/test_core.py +++ b/crates/rdocx-py/tests/test_core.py @@ -17328,6 +17328,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..da520dba5 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( @@ -5987,25 +6127,18 @@ fn bind_note_reference_revisions( Ok(()) } +/// Check the footnote part of `actual`, a [`resolved_candidate`], against the +/// input that resolution must reproduce. fn verify_footnote_destination( - candidate: &Document, + actual: &Document, wanted: &Document, - ids: &HashSet, accept: bool, options: &ComparisonOptions, ) -> Result<()> { if story_ignored(options, ComparisonStoryKind::Footnote) { return Ok(()); } - let mut actual = candidate.clone_for_staging(); - if accept { - actual.accept_revision_ids(ids)?; - } else { - actual.reject_revision_ids(ids)?; - } - let units = validate_footnote_custody(candidate, &crate::revision::RevisionScope::Ids(ids))?; - project_resolved_note_tombstones(candidate, &mut actual, &units)?; - let left = FootnotePart::of(&actual)?; + let left = FootnotePart::of(actual)?; let right = FootnotePart::of(wanted)?; match (&left, &right) { (None, None) => Ok(()), @@ -6269,6 +6402,7 @@ fn refuse_changed_existing_revisions( Ok(()) } +#[cfg(test)] fn resolved_package( candidate: &Document, resolve: impl FnOnce(&mut Document) -> Result, @@ -6277,6 +6411,18 @@ fn resolved_package( text_box_markers: &TextBoxMarkers, custody_ids: Option<&HashSet>, ) -> Result { + let resolved = resolved_candidate(candidate, resolve, custody_ids)?; + normalized_package(&resolved, stories, options, text_box_markers) +} + +/// The candidate with its revisions resolved one way and the transient note +/// pairs of fully resolved units projected out. Every postcondition of that +/// resolution reads this one document, so the package is resolved once. +fn resolved_candidate( + candidate: &Document, + resolve: impl FnOnce(&mut Document) -> Result, + custody_ids: Option<&HashSet>, +) -> Result { let mut resolved = candidate.clone_for_staging(); let units = custody_ids .map(|ids| validate_footnote_custody(candidate, &crate::revision::RevisionScope::Ids(ids))) @@ -6285,7 +6431,7 @@ fn resolved_package( if let Some(units) = units { project_resolved_note_tombstones(candidate, &mut resolved, &units)?; } - normalized_package(&resolved, stories, options, text_box_markers) + Ok(resolved) } /// Comparison guards may omit only the current fully resolved units' transient @@ -8626,42 +8772,82 @@ struct RunSource { } impl RunSource { - fn capture(run: Option<&CT_R>, parent: &str, span: Range) -> Result { + /// The source of the run at each span of `parent`, in the order given. + /// + /// One read of `parent` serves every run. A read per run reads the parent + /// again up to that run, which is quadratic in the runs it holds. Each + /// result, an error included, is the one a read for that run alone gives. + fn capture_all(runs: &[(Option<&CT_R>, Range)], parent: &str) -> Vec> { + if runs.is_empty() { + return Vec::new(); + } #[cfg(test)] if destination_diagnostic_enabled() { - policy_diagnostic( - "destination_actual_parent", - serde_json::json!({"parent_source":parent,"run_span":[span.start,span.end]}), - ); + for (_, span) in runs { + policy_diagnostic( + "destination_actual_parent", + serde_json::json!({"parent_source":parent,"run_span":[span.start,span.end]}), + ); + } } + #[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 = runs.iter().map(|_| None).collect::>(); + // The runs still to reach, the nearest last. + let mut pending = (0..runs.len()).collect::>(); + pending.sort_by_key(|index| std::cmp::Reverse(runs[*index].1.start)); + // A run the read passed opens no element. Its read goes on to the end. + let mut passed = Vec::new(); + let capture = |(run, span): &(Option<&CT_R>, Range), + bindings: &NamespaceBindings, + parent_scope: Option<&NamespaceBindings>| + -> Result { + let raw = parent[span.clone()].to_owned(); + let mut source = Self { + owner: run.map_or(0, |run| run as *const CT_R as usize), + scoped: source_fragment(&raw, bindings)?, + raw, + parent: parent_scope.cloned().unwrap_or_default(), + raw_slots: Vec::new(), + typed_slots: Vec::new(), + projected_raw_slots: HashSet::new(), + projected_typed_slots: HashSet::new(), + }; + if let Some(run) = run { + source.capture_children(run)?; + } + Ok(source) + }; + 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()))?; + 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() + runs[index].1.start < before + { + pending.pop(); + passed.push(index); + } match event { Event::Start(_) | Event::Empty(_) => { - let bindings = resolved_source_bindings(&reader)?; - if before == opening.len() + span.start { - let raw = parent[span].to_owned(); - let mut source = Self { - owner: run.map_or(0, |run| run as *const CT_R as usize), - scoped: source_fragment(&raw, &bindings)?, - raw, - parent: scopes.last().cloned().unwrap_or_default(), - raw_slots: Vec::new(), - typed_slots: Vec::new(), - projected_raw_slots: HashSet::new(), - projected_typed_slots: HashSet::new(), - }; - if let Some(run) = run { - source.capture_children(run)?; - } - return Ok(source); + let bindings = match resolved_source_bindings(&reader) { + Ok(bindings) => bindings, + Err(error) => break Some(error.to_string()), + }; + while let Some(&index) = pending.last() + && opening.len() + runs[index].1.start == before + { + pending.pop(); + results[index] = Some(capture(&runs[index], &bindings, scopes.last())); } if matches!(event, Event::Start(_)) { scopes.push(bindings); @@ -8670,10 +8856,19 @@ impl RunSource { Event::End(_) => { scopes.pop(); } - Event::Eof => return Err(Error::Other("run source has no actual opening".into())), + Event::Eof => break Some("run source has no actual opening".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 run is answered")) + .collect() } } @@ -9798,7 +9993,8 @@ impl SourceSnapshots { let mut parent_writer = Writer::new(Vec::new()); parent_writer.write_event(Event::Start(root))?; let opening = String::from_utf8(parent_writer.into_inner()).map_err(utf8_error)?; - let mut field_spans = modeled_paragraph_run_spans(paragraph, xml)?; + let spans = modeled_paragraph_run_spans(paragraph, xml)?; + let mut field_spans = spans.clone(); // Legacy rendering keeps zero-length continuation placeholders. A source // witness instead retains the proven whole physical span at every actual // logical slot of that same shared group. @@ -9843,6 +10039,20 @@ impl SourceSnapshots { .ok_or_else(|| { Error::Other("field owner namespace closure changed its source boundary".into()) })?; + // One read of the paragraph answers the scope of every field. + let field_starts = paragraph + .runs + .iter() + .enumerate() + .flat_map(|(run_index, run)| { + run.content + .iter() + .filter(|content| matches!(content, RunContent::Field(_))) + .map(move |_| run_index) + }) + .map_while(|run_index| field_spans.get(run_index).map(|span| span.start)) + .collect::>(); + let mut field_parents = publication_parents_at(xml, &field_starts).into_iter(); let mut field_slot = 0usize; for (run_index, run) in paragraph.runs.iter().enumerate() { for content in &run.content { @@ -9861,7 +10071,7 @@ impl SourceSnapshots { let actual_field_source = &physical_owner[physical_span.clone()]; let actual_scope = actual_root_bindings( actual_field_source, - &publication_parent_at(xml, span.start)?, + &field_parents.next().expect("one scope per field")?, )?; self.capture_field_occurrence( std::ptr::from_ref(paragraph) as usize, @@ -9900,28 +10110,42 @@ impl SourceSnapshots { } if !self.properties_only { - let spans = modeled_paragraph_run_spans(paragraph, xml)?; let (opening, closing) = paragraph_shell(Some(xml))?; + // The runs the paragraph source holds as they are are captured in + // one read after this walk. Each was read in turn before, so an + // error capturing one still comes before any later error. + let mut plain = Vec::new(); + let mut failure = None; let mut index = 0; - while index < paragraph.runs.len() { - if let Some((coverage, fragments)) = - paragraph.field_source_run_fragments_at(index)? - { + 'runs: while index < paragraph.runs.len() { + let fragments = match paragraph.field_source_run_fragments_at(index) { + Ok(fragments) => fragments, + Err(error) => { + failure = Some(Error::from(error)); + break; + } + }; + if let Some((coverage, fragments)) = fragments { for (run, fragment) in paragraph.runs[index..index + coverage] .iter() .zip(fragments) { if let Some(raw) = fragment { - let raw = String::from_utf8(raw).map_err(utf8_error)?; - let wrapped = format!("{opening}{raw}{closing}"); - self.runs.insert( - run as *const CT_R as usize, - RunSource::capture( - Some(run), - &wrapped, - opening.len()..opening.len() + raw.len(), - )?, - ); + let source = + String::from_utf8(raw).map_err(utf8_error).and_then(|raw| { + let wrapped = format!("{opening}{raw}{closing}"); + let span = opening.len()..opening.len() + raw.len(); + RunSource::capture_all(&[(Some(run), span)], &wrapped).remove(0) + }); + match source { + Ok(source) => { + self.runs.insert(run as *const CT_R as usize, source); + } + Err(error) => { + failure = Some(error); + break 'runs; + } + } } } index += coverage; @@ -9929,18 +10153,25 @@ impl SourceSnapshots { } let run = ¶graph.runs[index]; if !run_is_field(run) { - self.runs.insert( - run as *const CT_R as usize, - RunSource::capture(Some(run), xml, spans[index].clone())?, - ); + plain.push((Some(run), spans[index].clone())); } index += 1; } + for ((run, _), source) in plain.iter().zip(RunSource::capture_all(&plain, xml)) { + if let Some(run) = run { + self.runs.insert(*run as *const CT_R as usize, source?); + } + } + if let Some(error) = failure { + return Err(error); + } } let controls = direct_word_element_spans(xml, "sdt")?; + let mut scopes = child_scopes(xml, &controls); for (index, ((_, _, _, control), span)) in paragraph.content_controls.iter().zip(controls).enumerate() { + let (parent, source) = scopes.next().expect("one scope per control span"); self.inherit_owner_path( std::ptr::from_ref(paragraph) as usize, std::ptr::from_ref(control) as usize, @@ -9966,6 +10197,7 @@ impl SourceSnapshots { .ok_or_else(|| { Error::Other("control budget interval precedes physical owner".into()) })?; + let parent = parent?; self.budget_holes .entry(std::ptr::from_ref(paragraph) as usize) .or_default() @@ -9973,19 +10205,13 @@ impl SourceSnapshots { path, 1, hole, - actual_root_bindings( - &xml[span.clone()], - &publication_parent_at(xml, span.start)?, - )?, + actual_root_bindings(&xml[span.clone()], &parent)?, )); self.roots.insert( control as *const CT_Sdt as usize, - ( - xml[span.clone()].to_owned(), - publication_parent_at(xml, span.start)?, - ), + (xml[span.clone()].to_owned(), parent), ); - self.control(control, &source_child(xml, span)?)?; + self.control(control, &source?)?; } for (ordinal, (at, raw_before, revision)) in paragraph.revisions.iter().enumerate() { let raw = paragraph @@ -10018,12 +10244,10 @@ impl SourceSnapshots { } self.tables .insert(table as *const CT_Tbl as usize, xml.to_owned()); - for (index, (row, span)) in table - .rows - .iter() - .zip(direct_word_element_spans(xml, "tr")?) - .enumerate() - { + let rows = direct_word_element_spans(xml, "tr")?; + let mut scopes = child_scopes(xml, &rows); + for (index, (row, span)) in table.rows.iter().zip(rows).enumerate() { + let (parent, source) = scopes.next().expect("one scope per row span"); self.inherit_owner_path( std::ptr::from_ref(table) as usize, std::ptr::from_ref(row) as usize, @@ -10038,19 +10262,16 @@ impl SourceSnapshots { )?; self.roots.insert( row as *const CT_Row as usize, - ( - xml[span.clone()].to_owned(), - publication_parent_at(xml, span.start)?, - ), + (xml[span].to_owned(), parent?), ); - self.row(row, &source_child(xml, span)?)?; + self.row(row, &source?)?; } - for (index, ((_, _, control), span)) in table - .content_controls - .iter() - .zip(direct_word_element_spans(xml, "sdt")?) - .enumerate() + let controls = direct_word_element_spans(xml, "sdt")?; + let mut scopes = child_scopes(xml, &controls); + for (index, ((_, _, control), span)) in + table.content_controls.iter().zip(controls).enumerate() { + let (parent, source) = scopes.next().expect("one scope per control span"); self.inherit_owner_path( std::ptr::from_ref(table) as usize, std::ptr::from_ref(control) as usize, @@ -10065,12 +10286,9 @@ impl SourceSnapshots { )?; self.roots.insert( control as *const CT_Sdt as usize, - ( - xml[span.clone()].to_owned(), - publication_parent_at(xml, span.start)?, - ), + (xml[span].to_owned(), parent?), ); - self.control(control, &source_child(xml, span)?)?; + self.control(control, &source?)?; } Ok(()) } @@ -10085,12 +10303,10 @@ impl SourceSnapshots { } self.rows .insert(row as *const CT_Row as usize, xml.to_owned()); - for (index, (cell, span)) in row - .cells - .iter() - .zip(direct_word_element_spans(xml, "tc")?) - .enumerate() - { + let cells = direct_word_element_spans(xml, "tc")?; + let mut scopes = child_scopes(xml, &cells); + for (index, (cell, span)) in row.cells.iter().zip(cells).enumerate() { + let (parent, source) = scopes.next().expect("one scope per cell span"); self.inherit_owner_path( std::ptr::from_ref(row) as usize, std::ptr::from_ref(cell) as usize, @@ -10105,19 +10321,16 @@ impl SourceSnapshots { )?; self.roots.insert( cell as *const CT_Tc as usize, - ( - xml[span.clone()].to_owned(), - publication_parent_at(xml, span.start)?, - ), + (xml[span].to_owned(), parent?), ); - self.cell(cell, &source_child(xml, span)?)?; + self.cell(cell, &source?)?; } - for (index, ((_, _, control), span)) in row - .content_controls - .iter() - .zip(direct_word_element_spans(xml, "sdt")?) - .enumerate() + let controls = direct_word_element_spans(xml, "sdt")?; + let mut scopes = child_scopes(xml, &controls); + for (index, ((_, _, control), span)) in + row.content_controls.iter().zip(controls).enumerate() { + let (parent, source) = scopes.next().expect("one scope per control span"); self.inherit_owner_path( std::ptr::from_ref(row) as usize, std::ptr::from_ref(control) as usize, @@ -10132,12 +10345,9 @@ impl SourceSnapshots { )?; self.roots.insert( control as *const CT_Sdt as usize, - ( - xml[span.clone()].to_owned(), - publication_parent_at(xml, span.start)?, - ), + (xml[span].to_owned(), parent?), ); - self.control(control, &source_child(xml, span)?)?; + self.control(control, &source?)?; } Ok(()) } @@ -10152,12 +10362,13 @@ impl SourceSnapshots { } self.cells .insert(cell as *const CT_Tc as usize, xml.to_owned()); - for (index, (child, (_, span))) in cell - .content - .iter() - .zip(cell_child_spans(cell, xml, "source snapshot")?) - .enumerate() - { + let children = cell_child_spans(cell, xml, "source snapshot")? + .into_iter() + .map(|(_, span)| span) + .collect::>(); + let mut scopes = child_scopes(xml, &children); + for (index, (child, span)) in cell.content.iter().zip(children).enumerate() { + let (parent, source) = scopes.next().expect("one scope per cell child span"); let child_key = match child { CellContent::Paragraph(p) => std::ptr::from_ref(p) as usize, CellContent::Table(t) => std::ptr::from_ref(t) as usize, @@ -10170,36 +10381,21 @@ impl SourceSnapshots { xml, span.start, )?; - let source = source_child(xml, span.clone())?; + let source = source?; match child { CellContent::Paragraph(p) => { - self.roots.insert( - p as *const CT_P as usize, - ( - xml[span.clone()].to_owned(), - publication_parent_at(xml, span.start)?, - ), - ); + self.roots + .insert(p as *const CT_P as usize, (xml[span].to_owned(), parent?)); self.paragraph(p, &source)? } CellContent::Table(t) => { - self.roots.insert( - t as *const CT_Tbl as usize, - ( - xml[span.clone()].to_owned(), - publication_parent_at(xml, span.start)?, - ), - ); + self.roots + .insert(t as *const CT_Tbl as usize, (xml[span].to_owned(), parent?)); self.table(t, &source)? } CellContent::ContentControl(c) => { - self.roots.insert( - c as *const CT_Sdt as usize, - ( - xml[span.clone()].to_owned(), - publication_parent_at(xml, span.start)?, - ), - ); + self.roots + .insert(c as *const CT_Sdt as usize, (xml[span].to_owned(), parent?)); self.control(c, &source)? } } @@ -10265,6 +10461,56 @@ impl SourceSnapshots { )); } let spans = modeled_control_source_spans(&content, &payload)?; + // One read of the content answers every child. Each answer, an error + // included, is met where a read for that child alone was made. + let elements = content + .iter() + .zip(&spans) + .enumerate() + .filter(|(_, (child, _))| !matches!(child, SdtContent::RawXml(_))) + .map(|(index, (_, span))| (index, span.clone())) + .collect::>(); + let element_spans = elements + .iter() + .map(|(_, span)| span.clone()) + .collect::>(); + let element_starts = element_spans + .iter() + .map(|span| span.start) + .collect::>(); + let mut child_sources = content.iter().map(|_| None).collect::>(); + let mut child_parents = content.iter().map(|_| None).collect::>(); + for (((index, _), source), parent) in elements + .iter() + .zip(source_children(&payload, &element_spans)) + .zip(publication_parents_at(&payload, &element_starts)) + { + child_sources[*index] = Some(source); + child_parents[*index] = Some(parent); + } + let mut captured = content.iter().map(|_| None).collect::>(); + if !self.properties_only { + let plain = content + .iter() + .zip(&spans) + .enumerate() + .filter_map(|(index, (child, span))| match child { + SdtContent::Run(run) + if !run + .content + .iter() + .any(|content| matches!(content, RunContent::Field(_))) => + { + Some((index, (Some(run), span.clone()))) + } + _ => None, + }) + .collect::>(); + let runs = plain.iter().map(|(_, run)| run.clone()).collect::>(); + for ((index, _), source) in plain.iter().zip(RunSource::capture_all(&runs, &payload)) { + captured[*index] = Some(source); + } + } let mut field_slot = 0usize; for (index, (child, span)) in content.into_iter().zip(spans).enumerate() { let child_key = match child { @@ -10296,45 +10542,40 @@ impl SourceSnapshots { if matches!(child, SdtContent::RawXml(_)) { continue; } - let source = source_child(&payload, span.clone())?; + let source = child_sources[index] + .take() + .expect("an element child has its source")?; + let mut parent = || { + child_parents[index] + .take() + .expect("an element child has its parent scope") + }; match child { SdtContent::Paragraph(p) => { self.roots.insert( p as *const CT_P as usize, - ( - payload[span.clone()].to_owned(), - publication_parent_at(&payload, span.start)?, - ), + (payload[span.clone()].to_owned(), parent()?), ); self.paragraph(p, &source)?; } SdtContent::Table(t) => { self.roots.insert( t as *const CT_Tbl as usize, - ( - payload[span.clone()].to_owned(), - publication_parent_at(&payload, span.start)?, - ), + (payload[span.clone()].to_owned(), parent()?), ); self.table(t, &source)?; } SdtContent::Row(r) => { self.roots.insert( r as *const CT_Row as usize, - ( - payload[span.clone()].to_owned(), - publication_parent_at(&payload, span.start)?, - ), + (payload[span.clone()].to_owned(), parent()?), ); self.row(r, &source)?; } SdtContent::Cell(c) => { self.roots.insert( c as *const CT_Tc as usize, - ( - payload[span.clone()].to_owned(), - publication_parent_at(&payload, span.start)?, - ), + (payload[span.clone()].to_owned(), parent()?), ); self.cell(c, &source)?; } @@ -10358,24 +10599,14 @@ impl SourceSnapshots { .ok_or_else(|| { Error::Other("nested control source-budget interval overflow".into()) })?; + let scope = parent()?; self.budget_holes .entry(std::ptr::from_ref(control) as usize) .or_default() - .push(( - path, - 6, - hole, - actual_root_bindings( - &source, - &publication_parent_at(&payload, span.start)?, - )?, - )); + .push((path, 6, hole, actual_root_bindings(&source, &scope)?)); self.roots.insert( c as *const CT_Sdt as usize, - ( - payload[span.clone()].to_owned(), - publication_parent_at(&payload, span.start)?, - ), + (payload[span.clone()].to_owned(), scope), ); self.control(c, &source)?; } @@ -10388,44 +10619,46 @@ impl SourceSnapshots { _ => None, }) .collect::>(); - if fields.is_empty() { - if !self.properties_only { - self.runs.insert( - r as *const CT_R as usize, - RunSource::capture(Some(r), &payload, span)?, - ); - } - } else { - for field in fields { - let scope = actual_root_bindings( - &source, - &actual_root_bindings(&payload, &Vec::new())?, - )?; - self.capture_field_occurrence( - std::ptr::from_ref(control) as usize, - field, - field_slot, - raw_payload, - span.start.checked_sub(closure_growth) - .zip(span.end.checked_sub(closure_growth)) - .map(|(start, end)| start..end) - .ok_or_else(|| Error::Other("control field source precedes its actual content owner".into()))?, - scope.clone(), - )?; - field_slot += 1; - self.field_scopes - .insert(std::ptr::from_ref(field) as usize, scope.clone()); - self.fields.insert( - std::ptr::from_ref(field) as usize, - field_source_metadata( - &source_without_text_properties( - &field_result_source_paragraph(&source, &scope)?, - &Vec::new(), - )?, - field.is_complex(), + if fields.is_empty() + && let Some(source) = captured[index].take() + { + self.runs.insert(r as *const CT_R as usize, source?); + } + for field in fields { + let scope = actual_root_bindings( + &source, + &actual_root_bindings(&payload, &Vec::new())?, + )?; + self.capture_field_occurrence( + std::ptr::from_ref(control) as usize, + field, + field_slot, + raw_payload, + span.start + .checked_sub(closure_growth) + .zip(span.end.checked_sub(closure_growth)) + .map(|(start, end)| start..end) + .ok_or_else(|| { + Error::Other( + "control field source precedes its actual content owner" + .into(), + ) + })?, + scope.clone(), + )?; + field_slot += 1; + self.field_scopes + .insert(std::ptr::from_ref(field) as usize, scope.clone()); + self.fields.insert( + std::ptr::from_ref(field) as usize, + field_source_metadata( + &source_without_text_properties( + &field_result_source_paragraph(&source, &scope)?, + &Vec::new(), )?, - ); - } + field.is_complex(), + )?, + ); } } SdtContent::RawXml(_) => {} @@ -12615,7 +12848,6 @@ fn source_text_fragment( )); }; let mut reader = Reader::from_str(xml); - let mut texts = 0; let mut depth = 0; loop { match reader @@ -12632,9 +12864,9 @@ fn source_text_fragment( Event::End(_) => { depth -= 1; } - Event::Text(_) if depth == 1 && texts == 0 => { - texts += 1; - } + // The reader splits text around each character or entity + // reference, such as `&`. The value comes from the model. + Event::Text(_) | Event::GeneralRef(_) if depth == 1 => {} Event::Eof => break, _ => return Err(Error::Other("split text has opaque mixed events".into())), } @@ -13963,11 +14195,21 @@ fn compare_granular_paragraph( .map(str::to_owned) .map_or_else(|| paragraph_xml(original), Ok)?; let actual_spans = modeled_paragraph_run_spans(original, &actual_source)?; + // One read of the paragraph answers the scope of every run, on first use. + // Reading it again for each written piece is quadratic in its runs. + let run_parents = ParentScopes::new( + &actual_source, + actual_spans + .iter() + .map(|span| span.start) + .chain(element_opening(&actual_source).ok().map(|(end, ..)| end)) + .collect(), + ); let parent_for = |owner: usize| { let at = actual_spans .get(owner) .map_or(element_opening(&actual_source)?.0, |span| span.start); - publication_parent_at(&actual_source, at) + run_parents.at(at) }; let boundary_error = || { Error::Other(format!( @@ -14373,12 +14615,14 @@ fn compare_granular_paragraph( let mut right_raw = Vec::new(); let mut right_typed = Vec::new(); let left = merge_unit_runs( + &original.runs, &original_units, &left_indices, &mut left_raw, &mut left_typed, )?; let right = merge_unit_runs( + &edited.runs, &edited_units, &right_indices, &mut right_raw, @@ -15554,6 +15798,13 @@ fn retain_projection_separators( Ok(()) } +/// The aligned pairs grouped into the pieces the redline writes as one run. +/// +/// The granularity sets what the diff compares, never how many runs carry the +/// result. A change takes every consecutive pair of its kind that the same +/// physical runs own. Unchanged text takes every consecutive pair that +/// continues the same original and edited text element, so it stays one run +/// between two revisions whether the units are words or characters. fn coalesced_granular_alignment( aligned: &[(Option, Option)], original_units: &[AttributedRunUnit], @@ -15561,6 +15812,23 @@ fn coalesced_granular_alignment( original_signatures: &[String], edited_signatures: &[String], ) -> Vec<(GranularAction, Range)> { + let owners = |at: usize| { + ( + aligned[at].0.map(|index| original_units[index].owner), + aligned[at].1.map(|index| edited_units[index].owner), + ) + }; + // The text element each side of an unchanged pair is a fragment of. + let elements = |at: usize| { + aligned[at] + .0 + .and_then(|index| unit_text_element(&original_units[index])) + .zip( + aligned[at] + .1 + .and_then(|index| unit_text_element(&edited_units[index])), + ) + }; let mut groups = Vec::new(); let mut start = 0usize; while start < aligned.len() { @@ -15571,30 +15839,24 @@ fn coalesced_granular_alignment( original_signatures, edited_signatures, ); - let owners = ( - aligned[start].0.map(|index| original_units[index].owner), - aligned[start].1.map(|index| edited_units[index].owner), - ); + let continues = |at: usize| match action { + GranularAction::Replace | GranularAction::Delete | GranularAction::Insert => true, + GranularAction::Equal => elements(start).is_some() && elements(at) == elements(start), + GranularAction::Preserve | GranularAction::Drop => false, + }; let mut end = start + 1; - if matches!( - action, - GranularAction::Replace | GranularAction::Delete | GranularAction::Insert - ) { - while end < aligned.len() - && granular_action( - aligned[end], - original_units, - edited_units, - original_signatures, - edited_signatures, - ) == action - && ( - aligned[end].0.map(|index| original_units[index].owner), - aligned[end].1.map(|index| edited_units[index].owner), - ) == owners - { - end += 1; - } + while end < aligned.len() + && continues(end) + && granular_action( + aligned[end], + original_units, + edited_units, + original_signatures, + edited_signatures, + ) == action + && owners(end) == owners(start) + { + end += 1; } groups.push((action, start..end)); start = end; @@ -15602,6 +15864,15 @@ fn coalesced_granular_alignment( groups } +/// The content ordinal of the text element a plain unit is a fragment of. +fn unit_text_element(unit: &AttributedRunUnit) -> Option { + unit_plain_text(unit)?; + match unit.typed_sources.as_slice() { + [Some(selected)] => Some(selected.ordinal), + _ => None, + } +} + /// The text of a unit that holds nothing but text, which grouping may move /// into a deletion or an insertion. fn unit_plain_text(unit: &AttributedRunUnit) -> Option<&str> { @@ -15814,7 +16085,13 @@ fn grouped_text_alignment( (grouped, grouped_segments) } +/// The units at `indices`, all fragments of one run of `runs`, as one run. +/// +/// Consecutive fragments of one text element are written back as one text +/// with one source selection, so a merged run holds one `w:t` or `w:delText` +/// per stretch of its source text, never one per compared unit. fn merge_unit_runs( + runs: &[CT_R], units: &[AttributedRunUnit], indices: &[usize], raw_sources: &mut Vec<(usize, usize, usize)>, @@ -15827,6 +16104,7 @@ fn merge_unit_runs( raw_sources.extend_from_slice(&first.raw_sources); typed_sources.extend_from_slice(&first.typed_sources); let property_boundary = usize::from(merged.properties.is_some()); + let mut joined = false; for &index in &indices[1..] { let unit = &units[index]; if unit.owner != first.owner { @@ -15835,9 +16113,14 @@ fn merge_unit_runs( )); } let next = &unit.run; - let content_offset = merged.content.len(); - merged.content.extend(next.content.iter().cloned()); - typed_sources.extend_from_slice(&unit.typed_sources); + let continued = join_text_fragment(&mut merged, typed_sources, unit, property_boundary); + joined |= continued; + // The raw children of a joined fragment follow the text it extends. + let content_offset = merged.content.len() - usize::from(continued); + if !continued { + merged.content.extend(next.content.iter().cloned()); + typed_sources.extend_from_slice(&unit.typed_sources); + } merged .alt_drawings .extend(next.alt_drawings.iter().cloned()); @@ -15870,9 +16153,98 @@ fn merge_unit_runs( "fragment raw source order or multiplicity is invalid".into(), )); } + if joined { + // A joined text reads its space flag as a unit of its own would, and + // one that is its whole source element again selects it whole. + let source = runs + .get(first.owner) + .ok_or_else(|| Error::Other("merged run owner is absent".into()))?; + for (content, selected) in merged.content.iter_mut().zip(typed_sources.iter_mut()) { + let ( + RunContent::Text(text) | RunContent::DeletedText(text), + Some(TypedSourceSelection { + ordinal, + scalars: scalars @ Some(_), + }), + ) = (content, selected) + else { + continue; + }; + let Some(RunContent::Text(actual) | RunContent::DeletedText(actual)) = + source.content.get(*ordinal) + else { + return Err(Error::Other( + "joined text has no actual source element".into(), + )); + }; + text.preserve_space = actual.preserve_space || has_edge_whitespace(&text.text); + if *scalars == Some((0, actual.text.chars().count())) { + *scalars = None; + } + } + } Ok(Some(merged)) } +/// Append `unit` to the text that ends `merged` when it holds the next scalars +/// of the same source text element with no raw child between the two, and +/// report whether it did. `typed` holds one selection per content of `merged`. +fn join_text_fragment( + merged: &mut CT_R, + typed: &mut [Option], + unit: &AttributedRunUnit, + property_boundary: usize, +) -> bool { + let content_end = property_boundary + merged.content.len(); + let raw_positions = |run: &CT_R| { + run.extra_xml_positions + .iter() + .filter(|encoded| !CT_R::raw_child_is_root_attributes(**encoded)) + .map(|encoded| CT_R::raw_child_position(*encoded)) + .collect::>() + }; + if !unit.run.alt_drawings.is_empty() + || raw_positions(merged) + .iter() + .any(|position| *position >= content_end) + || raw_positions(&unit.run) + .iter() + .any(|position| *position <= property_boundary) + { + return false; + } + let ( + Some(TypedSourceSelection { + ordinal: previous, + scalars: Some((_, previous_end)), + }), + [ + Some(TypedSourceSelection { + ordinal, + scalars: Some((start, end)), + }), + ], + ) = ( + typed.last_mut().and_then(Option::as_mut), + unit.typed_sources.as_slice(), + ) + else { + return false; + }; + if *previous != *ordinal || *previous_end != *start { + return false; + } + match (merged.content.last_mut(), unit.run.content.as_slice()) { + (Some(RunContent::Text(text)), [RunContent::Text(fragment)]) + | (Some(RunContent::DeletedText(text)), [RunContent::DeletedText(fragment)]) => { + text.text.push_str(&fragment.text); + *previous_end = *end; + true + } + _ => false, + } +} + /// The paragraph source with `properties` in place of its own `w:pPr`. A /// self-closing paragraph, such as an empty one, is opened first, so the /// properties and runs go inside it. @@ -16021,6 +16393,7 @@ fn compare_granular_controls( } let mut child_leaves = Vec::new(); let mut control_replacements = Vec::with_capacity(control_spans.len()); + let mut sources = source_children(output, &control_spans).into_iter(); for (index, ((_, _, _, left), (_, _, _, right))) in original .content_controls .iter() @@ -16028,13 +16401,14 @@ fn compare_granular_controls( .enumerate() { let child_mark = metadata.leaf_publications.len(); + let source = sources.next().expect("one source per control span"); control_replacements.push(compare_control_from_xml( left, right, &format!("{location}/content-control[{index}]"), metadata, diagnostics, - &source_child(output, control_spans[index].clone())?, + &source?, )?); child_leaves.push(metadata.leaf_publications.split_off(child_mark)); } @@ -16623,11 +16997,18 @@ fn compare_complex_paragraph( location, )?; } + // One read of the paragraph answers the scope at every run edge. + let parents = ParentScopes::new( + &source, + std::iter::once(0) + .chain(run_spans.iter().flat_map(|span| [span.start, span.end])) + .collect(), + ); let mut output = String::new(); let mut cursor = 0usize; for (left, right) in aligned { let at = left.map_or(cursor, |index| run_spans[index].start); - let destination_parent = publication_parent_at(&source, at)?; + let destination_parent = parents.at(at)?; let revision_parent = metadata.ids.revision_parent_scope(&destination_parent); if let Some(index) = left { let span = &run_spans[index]; @@ -16716,19 +17097,21 @@ fn compare_complex_paragraph( ))); } let mut replacements = Vec::with_capacity(spans.len()); + let mut sources = source_children(&output, &spans).into_iter(); for (index, ((_, _, _, left), (_, _, _, right))) in original .content_controls .iter() .zip(&edited.content_controls) .enumerate() { + let source = sources.next().expect("one source per control span"); replacements.push(compare_control_from_xml( left, right, &format!("{location}/content-control[{index}]"), metadata, diagnostics, - &source_child(&output, spans[index].clone())?, + &source?, )?); } replace_direct_word_elements(&output, "sdt", &replacements) @@ -17240,6 +17623,8 @@ fn paragraph_children_xml( } let mut xml = paragraph_xml(&children)?; let spans = modeled_paragraph_run_spans(&children, &xml)?; + // One read of the paragraph answers the scope of every run. + let parents = ParentScopes::new(&xml, spans.iter().map(|span| span.start).collect()); let mut replacements = Vec::new(); let mut index = 0; while index < children.runs.len() { @@ -17259,9 +17644,7 @@ fn paragraph_children_xml( &children.runs[index], &raw, &typed, - &metadata - .ids - .revision_parent_scope(&publication_parent_at(&xml, span.start)?), + &metadata.ids.revision_parent_scope(&parents.at(span.start)?), &metadata.ids, ) }?)); @@ -17391,6 +17774,11 @@ fn compare_table( ))); } let aligned = align(&original_signatures, &edited_signatures); + // One read of the table answers the source of every row. + let mut row_sources = source_children(&source, &row_spans) + .into_iter() + .map(Some) + .collect::>(); let mut output = String::new(); let mut cursor = 0usize; for (alignment_index, &(left, right)) in aligned.iter().enumerate() { @@ -17413,7 +17801,7 @@ fn compare_table( output.push_str(&compare_row( &original.rows[i], &edited.rows[j], - Some(&source_child(&source, row_spans[i].clone())?), + Some(&row_sources[i].take().expect("a row is compared once")?), &format!("{location}/row[{j}]"), metadata, diagnostics, @@ -17439,6 +17827,7 @@ fn compare_table( } let mut child_leaves = Vec::new(); let mut replacements = Vec::with_capacity(spans.len()); + let mut sources = source_children(&output, &spans).into_iter(); for (index, ((_, _, left), (_, _, right))) in original .content_controls .iter() @@ -17446,13 +17835,14 @@ fn compare_table( .enumerate() { let child_mark = metadata.leaf_publications.len(); + let source = sources.next().expect("one source per control span"); replacements.push(compare_control_from_xml( left, right, &format!("{location}/content-control[{index}]"), metadata, diagnostics, - &source_child(&output, spans[index].clone())?, + &source?, )?); child_leaves.push(metadata.leaf_publications.split_off(child_mark)); } @@ -17665,9 +18055,10 @@ fn marked_row_xml(row: &str, kind: &str, metadata: &mut Metadata<'_>) -> Result< xml = insert_first_child(&xml, &properties)?; } } - let cells = direct_word_element_spans(&xml, "tc")? + let cell_spans = direct_word_element_spans(&xml, "tc")?; + let cells = source_children(&xml, &cell_spans) .into_iter() - .map(|span| marked_cell_xml(&source_child(&xml, span)?, kind, metadata)) + .map(|source| marked_cell_xml(&source?, kind, metadata)) .collect::>>()?; metadata .ids @@ -17678,19 +18069,23 @@ fn marked_cell_xml(cell: &str, kind: &str, metadata: &mut Metadata<'_>) -> Resul #[cfg(test)] let _destination_diagnostic_scope = PolicyDiagnosticScope::enter("destination:marked_cell_xml", cell); - let paragraphs = direct_word_element_spans(cell, "p")? + let paragraph_spans = direct_word_element_spans(cell, "p")?; + let paragraphs = source_children(cell, ¶graph_spans) .into_iter() - .map(|span| { + .map(|source| { let marker = metadata .ids .marker(kind, metadata.author, metadata.timestamp)?; - let source = source_child(cell, span)?; + let source = source?; let paragraph = marked_paragraph_xml(&source, &marker, &metadata.ids)?; let paragraph = marked_direct_runs_xml(¶graph, kind, metadata)?; - let hyperlinks = direct_word_element_spans(¶graph, "hyperlink")? - .into_iter() - .map(|span| { - let scoped = source_child(¶graph, span.clone())?; + let hyperlink_spans = direct_word_element_spans(¶graph, "hyperlink")?; + let hyperlinks = hyperlink_spans + .iter() + .cloned() + .zip(source_children(¶graph, &hyperlink_spans)) + .map(|(span, scoped)| { + let scoped = scoped?; let marked = marked_direct_runs_xml(&scoped, kind, metadata)?; let destination = root_namespace_bindings(¶graph, "p", &[])?; retain_source_root_namespaces(&marked, ¶graph[span], &destination) @@ -17700,14 +18095,16 @@ fn marked_cell_xml(cell: &str, kind: &str, metadata: &mut Metadata<'_>) -> Resul }) .collect::>>()?; let cell = replace_direct_word_elements(cell, "p", ¶graphs)?; - let tables = direct_word_element_spans(&cell, "tbl")? + let table_spans = direct_word_element_spans(&cell, "tbl")?; + let tables = source_children(&cell, &table_spans) .into_iter() - .map(|span| { - let scoped_table = source_child(&cell, span)?; + .map(|scoped_table| { + let scoped_table = scoped_table?; let table = scoped_table.as_str(); - let rows = direct_word_element_spans(table, "tr")? + let row_spans = direct_word_element_spans(table, "tr")?; + let rows = source_children(table, &row_spans) .into_iter() - .map(|span| marked_row_xml(&source_child(table, span)?, kind, metadata)) + .map(|source| marked_row_xml(&source?, kind, metadata)) .collect::>>()?; replace_direct_word_elements(table, "tr", &rows) }) @@ -17723,10 +18120,14 @@ fn marked_direct_runs_xml(owner: &str, kind: &str, metadata: &mut Metadata<'_>) #[cfg(test)] let _destination_diagnostic_scope = PolicyDiagnosticScope::enter("destination:marked_direct_runs_xml", owner); - let runs = direct_word_element_spans(owner, "r")? + let spans = direct_word_element_spans(owner, "r")? .into_iter() - .map(|span| { - let source = RunSource::capture(None, owner, span)?; + .map(|span| (None, span)) + .collect::>(); + let runs = RunSource::capture_all(&spans, owner) + .into_iter() + .map(|source| { + let source = source?; let mut run = source.scoped.clone(); if kind == "del" { for (local, deleted_local) in [("t", "delText"), ("instrText", "delInstrText")] { @@ -17796,15 +18197,17 @@ fn compare_row( } let mut child_leaves = Vec::new(); let mut cell_replacements = Vec::with_capacity(cell_spans.len()); + let mut sources = source_children(&output, &cell_spans).into_iter(); for (index, (left, right)) in original.cells.iter().zip(&edited.cells).enumerate() { let child_mark = metadata.leaf_publications.len(); + let source = sources.next().expect("one source per cell span"); cell_replacements.push(compare_cell_from_xml( left, right, &format!("{location}/cell[{index}]"), metadata, diagnostics, - &source_child(&output, cell_spans[index].clone())?, + &source?, )?); child_leaves.push(metadata.leaf_publications.split_off(child_mark)); } @@ -17825,6 +18228,7 @@ fn compare_row( } let mut child_leaves = Vec::new(); let mut control_replacements = Vec::with_capacity(control_spans.len()); + let mut sources = source_children(&output, &control_spans).into_iter(); for (index, ((_, _, left), (_, _, right))) in original .content_controls .iter() @@ -17832,13 +18236,14 @@ fn compare_row( .enumerate() { let child_mark = metadata.leaf_publications.len(); + let source = sources.next().expect("one source per control span"); control_replacements.push(compare_control_from_xml( left, right, &format!("{location}/content-control[{index}]"), metadata, diagnostics, - &source_child(&output, control_spans[index].clone())?, + &source?, )?); child_leaves.push(metadata.leaf_publications.split_off(child_mark)); } @@ -17898,7 +18303,12 @@ fn compare_cell_from_xml( let children = cell_child_spans(original, original_xml, location)?; let mut child_leaves = Vec::new(); let mut replacements = Vec::with_capacity(children.len()); - for (index, ((left, right), (_, span))) in original + let child_spans = children + .iter() + .map(|(_, span)| span.clone()) + .collect::>(); + let mut sources = source_children(original_xml, &child_spans).into_iter(); + for (index, ((left, right), _)) in original .content .iter() .zip(&edited.content) @@ -17906,7 +18316,7 @@ fn compare_cell_from_xml( .enumerate() { let child_location = format!("{location}/content[{index}]"); - let source = source_child(original_xml, span.clone())?; + let source = sources.next().expect("one source per cell child span")?; let source = source.as_str(); let child_mark = metadata.leaf_publications.len(); replacements.push(match (left, right) { @@ -18008,6 +18418,40 @@ fn compare_control_from_xml( control_metadata_diagnostics(original, edited, location, diagnostics)?; let original_content = modeled_control_content(original); let edited_content = modeled_control_content(edited); + // Runs that only split the same text differently read as equal, as + // they do in a paragraph, and keep the original source. Equal runs + // keep the path below. + let only_runs = |content: &[&SdtContent]| { + !content.is_empty() + && content + .iter() + .all(|child| matches!(child, SdtContent::Run(_))) + }; + if !metadata.leaf_capture + && only_runs(&original_content) + && only_runs(&edited_content) + && original_content != edited_content + { + let runs_of = |content: &[&SdtContent]| { + let mut paragraph = CT_P::new(); + paragraph.runs = content + .iter() + .filter_map(|child| match child { + SdtContent::Run(run) => Some(run.clone()), + _ => None, + }) + .collect(); + paragraph + }; + if coalesced_paragraphs_equal( + &runs_of(&original_content), + &runs_of(&edited_content), + metadata.options, + metadata, + ) { + return Ok(original_xml.to_owned()); + } + } let direct_run_or_raw = |content: &&SdtContent| matches!(content, SdtContent::Run(_) | SdtContent::RawXml(_)); if uses_attributed_run_path(metadata.options) @@ -18720,12 +19164,14 @@ fn compare_control_runs_with_options( let mut right_raw = Vec::new(); let mut right_typed = Vec::new(); let left = merge_unit_runs( + original, &original_units, &left_indices, &mut left_raw, &mut left_typed, )?; let right = merge_unit_runs( + edited, &edited_units, &right_indices, &mut right_raw, @@ -21585,6 +22031,10 @@ fn paragraph_signature_with_options(paragraph: &CT_P, options: &ComparisonOption enum ParagraphToken { /// A compared unit, or a whole run on the whole-run path. Unit(String), + /// Consecutive plain characters at character granularity. One token + /// holds the whole stretch, so the signature costs one token per stretch + /// of text and still reads the same however the runs split it. + Scalars(String), /// A unit the options ignore, such as whitespace, a field or a comment /// reference. Ignored(String), @@ -21602,12 +22052,6 @@ enum ParagraphToken { /// marker on either side of ignored content still differs. fn paragraph_tokens(paragraph: &CT_P, options: &ComparisonOptions) -> Vec { let attributed = uses_attributed_run_path(options); - let units = if attributed { - attributed_run_units(¶graph.runs, options) - } else { - Vec::new() - }; - let mut next_unit = 0; let mut tokens = Vec::new(); let mut open_hyperlink = None; for boundary in 0..=paragraph.runs.len() { @@ -21645,13 +22089,20 @@ fn paragraph_tokens(paragraph: &CT_P, options: &ComparisonOptions) -> Vec Vec::new(); + for (token, _) in tokens.into_iter().zip(keep).filter(|(_, keep)| *keep) { + // A stretch continues over ignored units that left no token. + if let (ParagraphToken::Scalars(text), Some(ParagraphToken::Scalars(stretch))) = + (&token, kept.last_mut()) + { + stretch.push_str(text); + } else { + kept.push(token); + } + } + kept.into_iter() + .map(|token| match token { ParagraphToken::Unit(signature) => format!("unit:{signature}"), + ParagraphToken::Scalars(text) => format!("scalars:{text:?}"), ParagraphToken::Ignored(signature) | ParagraphToken::Boundary(signature) => signature, }) .collect() } +/// The units a signature reads `run` as. +/// +/// At character granularity a run of plain content is read one stretch at a +/// time, which gives the tokens its characters would give once +/// [`signature_scalars`] joins them. A raw child and deleted text belong to +/// single characters, so a run that holds one is read character by character. +fn signature_run_units(run: &CT_R, options: &ComparisonOptions) -> Vec { + let stretches = options.granularity == ComparisonGranularity::Character + && run.extra_xml.is_empty() + && run.alt_drawings.is_empty() + && !run + .content + .iter() + .any(|content| matches!(content, RunContent::DeletedText(_))); + if stretches { + attributed_run_units( + std::slice::from_ref(run), + &ComparisonOptions { + granularity: ComparisonGranularity::Run, + ..options.clone() + }, + ) + } else { + attributed_run_units(std::slice::from_ref(run), options) + } +} + +/// The plain characters of a unit, which a character-granularity signature +/// holds with those before and after them as one token. +fn signature_scalars<'a>( + unit: &'a AttributedRunUnit, + options: &ComparisonOptions, +) -> Option<&'a str> { + (options.granularity == ComparisonGranularity::Character) + .then(|| unit_plain_text(unit)) + .flatten() + .filter(|text| !text.is_empty()) +} + /// Push the raw children, comment markers and inline controls at one run /// boundary in the order `CT_P` serialization writes them. fn push_boundary_tokens( @@ -21853,20 +22352,36 @@ fn cell_signature_with_options(cell: &CT_Tc, options: &ComparisonOptions) -> Str fn control_signature_with_options(control: &CT_Sdt, options: &ComparisonOptions) -> String { let mut content = Vec::new(); + // The plain characters since the last token, written as one token. + let mut scalars = String::new(); + let close = |scalars: &mut String, content: &mut Vec| { + if !scalars.is_empty() { + content.push(format!("u:scalars:{:?}", std::mem::take(scalars))); + } + }; for child in &control.content { match child { SdtContent::RawXml(raw) if raw.iter().all(u8::is_ascii_whitespace) => {} SdtContent::Run(run) if uses_attributed_run_path(options) => { - content.extend( - attributed_run_units(std::slice::from_ref(run), options) - .into_iter() - .filter(|unit| !unit_is_ignorable(unit) && !unit_is_empty(unit)) - .map(|unit| format!("u:{}", attributed_unit_signature(&unit))), - ); + for unit in signature_run_units(run, options) + .into_iter() + .filter(|unit| !unit_is_ignorable(unit) && !unit_is_empty(unit)) + { + if let Some(text) = signature_scalars(&unit, options) { + scalars.push_str(text); + } else { + close(&mut scalars, &mut content); + content.push(format!("u:{}", attributed_unit_signature(&unit))); + } + } + } + child => { + close(&mut scalars, &mut content); + content.push(control_content_signature_with_options(child, options)); } - child => content.push(control_content_signature_with_options(child, options)), } } + close(&mut scalars, &mut content); format!("{:?}:{:?}", control_property_signature(control), content) } @@ -23689,6 +24204,542 @@ mod tests { } } + /// One side of a written piece: its merged run and source selections. + type WrittenSide = Option<(CT_R, Vec>)>; + + /// The alignment of two single-run paragraphs grouped into the pieces + /// the redline writes, each as its original and edited merged run. + fn written_pieces(texts: [&str; 2], options: &ComparisonOptions) -> Vec<[WrittenSide; 2]> { + let runs = texts.map(|text| [CT_R::new(text)]); + let units = [ + attributed_run_units(&runs[0], options), + attributed_run_units(&runs[1], options), + ]; + let signatures = [0, 1].map(|side| { + units[side] + .iter() + .map(attributed_unit_signature) + .collect::>() + }); + let aligned = align(&signatures[0], &signatures[1]); + let (aligned, _) = grouped_text_alignment( + &aligned, + &vec![0; aligned.len()], + &units[0], + &units[1], + &signatures[0], + &signatures[1], + options, + ); + super::coalesced_granular_alignment( + &aligned, + &units[0], + &units[1], + &signatures[0], + &signatures[1], + ) + .into_iter() + .map(|(_, members)| { + [0, 1].map(|side| { + let indices = members + .clone() + .filter_map(|at| [aligned[at].0, aligned[at].1][side]) + .collect::>(); + let (mut raw, mut typed) = (Vec::new(), Vec::new()); + super::merge_unit_runs(&runs[side], &units[side], &indices, &mut raw, &mut typed) + .unwrap() + .map(|run| (run, typed)) + }) + }) + .collect() + } + + #[test] + fn granular_pieces_follow_the_changes_not_the_compared_units() { + for granularity in [ + ComparisonGranularity::Word, + ComparisonGranularity::Character, + ] { + let options = ComparisonOptions { + granularity, + ..Default::default() + }; + let pieces = [2, 200].map(|words| { + let kept = "kept ".repeat(words); + written_pieces( + [&format!("{kept}thirty days"), &format!("{kept}sixty days")], + &options, + ) + }); + // The unchanged text before the edit is one piece however many + // units it holds, so both lengths give the same pieces. + assert_eq!(pieces[0].len(), pieces[1].len(), "{granularity:?}"); + if granularity == ComparisonGranularity::Word { + // The text before, the replaced word and the text after. + assert_eq!(pieces[0].len(), 3); + } + for (run, typed) in pieces.iter().flatten().flatten().flatten() { + // One piece is one text with one source selection. + assert_eq!(run.content.len(), 1, "{granularity:?}: {run:?}"); + assert_eq!(typed.len(), 1, "{granularity:?}: {typed:?}"); + } + let kept = "kept ".repeat(200); + assert!(matches!( + &pieces[1][0], + [Some((left, _)), Some((right, _))] + if matches!(left.content.as_slice(), [RunContent::Text(text)] if text.text == kept) + && left.content == right.content + )); + } + } + + #[test] + fn merged_units_rejoin_the_fragments_of_one_text_element() { + let options = ComparisonOptions { + granularity: ComparisonGranularity::Word, + ..Default::default() + }; + let mut run = CT_R::new("alpha beta"); + run.content.push(RunContent::Tab); + run.content.push(RunContent::Text(CT_Text { + text: "gamma".to_owned(), + preserve_space: false, + })); + let runs = [run]; + // alpha, space, beta, the tab, gamma. + let units = attributed_run_units(&runs, &options); + assert_eq!(units.len(), 5); + let merge = |indices: &[usize]| { + let (mut raw, mut typed) = (Vec::new(), Vec::new()); + let run = super::merge_unit_runs(&runs, &units, indices, &mut raw, &mut typed) + .unwrap() + .unwrap(); + let texts = run + .content + .iter() + .map(|content| match content { + RunContent::Text(text) => Some((text.text.clone(), text.preserve_space)), + _ => None, + }) + .collect::>(); + let scalars = typed + .iter() + .map(|selected| selected.unwrap().scalars) + .collect::>(); + (texts, scalars) + }; + // Every fragment of an element is that element again, selected whole. + let whole = runs[0].content[0].clone(); + let RunContent::Text(whole) = whole else { + unreachable!() + }; + assert_eq!( + merge(&[0, 1, 2]), + ( + vec![Some(("alpha beta".to_owned(), whole.preserve_space))], + vec![None] + ) + ); + // Some of its fragments are one text over their scalars, which keeps + // the space a new edge exposes. + assert_eq!( + merge(&[0, 1]), + (vec![Some(("alpha ".to_owned(), true))], vec![Some((0, 6))]) + ); + assert_eq!( + merge(&[1, 2]), + (vec![Some((" beta".to_owned(), true))], vec![Some((5, 10))]) + ); + // Fragments that do not follow each other stay apart, and so does + // text on either side of other content. + assert_eq!(merge(&[0, 2]).0.len(), 2); + assert_eq!( + merge(&[0, 1, 2, 3, 4]), + ( + vec![ + Some(("alpha beta".to_owned(), whole.preserve_space)), + None, + Some(("gamma".to_owned(), false)) + ], + vec![None, None, None] + ) + ); + } + + #[test] + fn character_signatures_hold_one_token_per_text_stretch() { + let scalar = ComparisonOptions { + granularity: ComparisonGranularity::Character, + ..Default::default() + }; + let bindings = vec![("xmlns:w".to_owned(), W_NS.to_owned())]; + let tokens = |runs: &str, options: &ComparisonOptions| { + let model = story_document(&format!("{runs}"), &bindings).unwrap(); + let BodyContent::Paragraph(paragraph) = &model.body.content[0] else { + unreachable!() + }; + super::paragraph_tokens(paragraph, options) + }; + let run = |text: &str| format!(r#"{text}"#); + // The cost of a signature follows its stretches, not its characters. + assert_eq!(tokens(&run("word"), &scalar).len(), 1); + assert_eq!(tokens(&run(&"word ".repeat(2000)), &scalar).len(), 1); + // The reading is the same however runs split the text. + let whole = tokens(&run("invoice thirty days"), &scalar); + assert_eq!( + whole, + tokens( + &[run("invoi"), run("ce thi"), run("rty days")].concat(), + &scalar + ) + ); + assert_ne!(whole, tokens(&run("invoice sixty days"), &scalar)); + // A run read one character at a time, because it holds a raw child, + // continues the stretch of a run read whole. + let raw = r#""#; + let with_raw = |text: &str| format!(r#"{text}{raw}"#); + assert_eq!( + tokens(&[run("ab"), with_raw("cd")].concat(), &scalar), + tokens(&[run("abc"), with_raw("d")].concat(), &scalar) + ); + assert_ne!( + tokens(&[run("ab"), with_raw("cd")].concat(), &scalar), + tokens(&[run("abcd"), with_raw("")].concat(), &scalar) + ); + // Deleted text reads one character at a time, whatever holds it. + let deleted = |texts: &[&str]| { + texts + .iter() + .map(|text| format!("{text}")) + .collect::() + }; + assert_eq!( + tokens(&deleted(&["abc"]), &scalar), + tokens(&deleted(&["a", "bc"]), &scalar) + ); + assert_ne!( + tokens(&deleted(&["abc"]), &scalar), + tokens(&run("abc"), &scalar) + ); + // Other content and empty text still stand between two stretches. + assert_eq!( + tokens("ab", &scalar).len(), + 3 + ); + assert_ne!( + tokens(&run("ab"), &scalar), + tokens("ab", &scalar) + ); + // The direct runs of an inline control follow the same rule. + let control = |runs: &str| { + let model = story_document( + &format!("{runs}"), + &bindings, + ) + .unwrap(); + let BodyContent::Paragraph(paragraph) = &model.body.content[0] else { + unreachable!() + }; + super::control_signature_with_options(¶graph.content_controls[0].3, &scalar) + }; + assert_eq!( + control(&run("invoice thirty days")), + control(&[run("invoi"), run("ce thi"), run("rty days")].concat()) + ); + assert_ne!( + control(&run("invoice thirty days")), + control(&run("invoice sixty days")) + ); + assert_eq!( + control(&[run("ab"), with_raw("cd")].concat()), + control(&[run("abc"), with_raw("d")].concat()) + ); + // Ignored whitespace leaves no token and does not end a stretch. + let ignoring = ComparisonOptions { + ignore_whitespace: true, + ..scalar.clone() + }; + assert_eq!(tokens(&run("a b c"), &ignoring).len(), 1); + assert_eq!( + tokens(&run("a b c"), &ignoring), + tokens(&[run("ab "), run(" c")].concat(), &ignoring) + ); + assert_ne!( + tokens(&run("a b c"), &scalar), + tokens(&[run("ab "), run(" c")].concat(), &scalar) + ); + } + + #[test] + fn run_sources_of_one_parent_are_captured_in_one_pass() { + let xml = format!( + r#"abcde"# + ); + let paragraph = rdocx_oxml::text::CT_P::from_xml_fragment(xml.as_bytes()).unwrap(); + let spans = super::modeled_paragraph_run_spans(¶graph, &xml).unwrap(); + assert_eq!(spans.len(), 5); + let runs = paragraph + .runs + .iter() + .map(Some) + .zip(spans) + .collect::>(); + // A span inside a run opens no element. It is answered among the + // others as it is alone, and leaves the other answers as they are. + let mut asked = runs.clone(); + asked.insert(2, (None, runs[1].1.start + 3..runs[1].1.end)); + super::SOURCE_READ_BYTES.set(0); + let together = super::RunSource::capture_all(&asked, &xml); + assert_eq!(super::SOURCE_READ_BYTES.get(), xml.len()); + let facts = |source: &super::Result| { + source.as_ref().map_err(ToString::to_string).map(|source| { + ( + source.owner, + source.scoped.clone(), + source.raw.clone(), + source.parent.clone(), + source.raw_slots.clone(), + source.typed_slots.clone(), + ) + }) + }; + for (run, source) in asked.iter().zip(&together) { + let alone = super::RunSource::capture_all(std::slice::from_ref(run), &xml); + assert_eq!(facts(source), facts(&alone[0])); + } + assert_eq!( + facts(&together[2]), + Err("run source has no actual opening".to_owned()) + ); + let together = together + .into_iter() + .filter_map(Result::ok) + .collect::>(); + assert_eq!(together.len(), 5); + // The scope of each run is the one its own ancestors declare. + let link = ("xmlns:x".to_owned(), "urn:link".to_owned()); + assert_eq!( + together + .iter() + .map(|source| source.parent.contains(&link)) + .collect::>(), + [false, true, true, false, false] + ); + assert!( + together + .iter() + .all(|source| !source.parent.iter().any(|(_, uri)| uri == "urn:run")) + ); + } + + #[test] + fn parent_scopes_of_many_children_are_read_in_one_pass() { + let xml = format!( + r#""# + ); + let rows = super::direct_word_element_spans(&xml, "tr").unwrap(); + let control = super::direct_word_element_spans(&xml, "sdt").unwrap()[0].clone(); + // Rows, a control between them, a span inside a tag, the end of the + // table and a span past it. + let mut spans = rows.clone(); + spans.insert(1, control.clone()); + spans.push(control.start + 2..control.end); + spans.push(xml.len() - "".len()..xml.len()); + spans.push(xml.len() + 5..xml.len() + 9); + let starts = spans.iter().map(|span| span.start).collect::>(); + fn text(result: &super::Result) -> Result { + result.as_ref().map_err(ToString::to_string).cloned() + } + super::SOURCE_READ_BYTES.set(0); + let parents = super::publication_parents_at(&xml, &starts); + let children = super::source_children(&xml, &spans); + assert_eq!(super::SOURCE_READ_BYTES.get(), 2 * xml.len()); + // Each answer, an error included, is the one a read for that + // position alone gives. + for ((start, span), (parent, child)) in + starts.iter().zip(&spans).zip(parents.iter().zip(&children)) + { + assert_eq!( + text(parent), + text(&super::publication_parents_at(&xml, &[*start])[0]) + ); + assert_eq!( + text(child), + text(&super::source_children(&xml, std::slice::from_ref(span))[0]) + ); + } + // The rows and the control open elements, and the end of the table + // is the start of an event, so all have a scope. The others are + // refused. + let absent = Err("publication boundary is absent from its actual shell".to_owned()); + assert!(parents[..3].iter().all(Result::is_ok) && parents[4].is_ok()); + assert_eq!( + [text(&parents[3]), text(&parents[5])], + [absent.clone(), absent] + ); + assert!(children[..3].iter().all(Result::is_ok)); + assert!(children[3..].iter().all(|child| { + text(child) == Err("source child has no opening at its span".to_owned()) + })); + // A row declares its own namespace for its source, not its scope. + assert!( + children[0] + .as_ref() + .unwrap() + .contains(r#"xmlns:x="urn:row""#) + && !parents[0] + .as_ref() + .unwrap() + .iter() + .any(|(_, uri)| uri == "urn:row") + ); + // The same request in another order gets the same answers. + let reversed = starts.iter().rev().copied().collect::>(); + assert_eq!( + super::publication_parents_at(&xml, &reversed) + .iter() + .rev() + .map(text) + .collect::>(), + parents.iter().map(text).collect::>() + ); + } + + /// The source bytes one comparison of the documents `body` makes for the + /// original and the edited text reads. + fn comparison_reads(body: &dyn Fn(&str) -> String, options: &ComparisonOptions) -> usize { + let document = |text: &str| { + let xml = format!( + r#"{}"#, + body(text) + ); + let mut document = Document::new(); + document + .package + .set_part(&document.doc_part_name, xml.into_bytes()); + Document::from_package(document.package).unwrap() + }; + let mut original = document("thirty days"); + let edited = document("sixty days"); + super::SOURCE_READ_BYTES.set(0); + original + .compare_with_options(&edited, "Ada", "2026-11-15T09:00:00Z", options) + .unwrap(); + assert!(!original.story_revisions().unwrap().is_empty()); + super::SOURCE_READ_BYTES.get() + } + + #[test] + fn comparison_reads_a_parent_once_per_snapshot_whatever_its_children() { + // Reading a paragraph or a table again for each run, row or cell made + // the cost quadratic in its children. The count of reads is the same + // for few and for many children. + let runs = |count: usize| { + (0..count) + .map(|index| { + format!( + r#"{}word{index} "#, + if index % 2 == 0 { + "" + } else { + "" + } + ) + }) + .collect::() + }; + let paragraph = |count: usize| { + move |text: &str| format!("{}{text}", runs(count)) + }; + let linked = |count: usize| { + move |text: &str| { + format!( + r#"{}{text}"#, + runs(count) + ) + } + }; + let added = |count: usize| { + move |text: &str| { + let extra = if text.starts_with("sixty") { + format!("{}", runs(count)) + } else { + String::new() + }; + format!("{text}{extra}") + } + }; + let table = |count: usize| { + move |text: &str| { + let rows = (0..count) + .map(|index| { + format!( + r#"row {index}{}"#, + if index == count / 2 { text } else { "kept" } + ) + }) + .collect::(); + format!( + r#"{rows}"# + ) + } + }; + let added_table = |count: usize| { + move |text: &str| { + let paragraph = format!("{text}"); + if text.starts_with("sixty") { + format!("{paragraph}{}", table(count)("kept")) + } else { + paragraph + } + } + }; + for granularity in [ + ComparisonGranularity::Run, + ComparisonGranularity::Word, + ComparisonGranularity::Character, + ] { + let options = ComparisonOptions { + granularity, + ..Default::default() + }; + // 16 times the children read at most 32 times the bytes, where a + // read of the parent for each child reads about 256 times more. + for (name, few, many) in [ + ( + "paragraph", + comparison_reads(¶graph(3), &options), + comparison_reads(¶graph(48), &options), + ), + ( + "hyperlink", + comparison_reads(&linked(3), &options), + comparison_reads(&linked(48), &options), + ), + ( + "added paragraph", + comparison_reads(&added(3), &options), + comparison_reads(&added(48), &options), + ), + ( + "table", + comparison_reads(&table(3), &options), + comparison_reads(&table(48), &options), + ), + ( + "added table", + comparison_reads(&added_table(3), &options), + comparison_reads(&added_table(48), &options), + ), + ] { + assert!( + many <= 32 * few, + "{name} {granularity:?}: {few} then {many} bytes" + ); + } + } + } + #[test] fn mixed_owner_gap_pairing_is_deterministic_and_preserves_every_owner() { let original = (0..48) @@ -25206,7 +26257,9 @@ mod tests { let spans = story_content_spans(body, &bindings).unwrap(); let xml = &body[spans[0].clone()]; let spans = modeled_paragraph_run_spans(p, xml).unwrap(); - RunSource::capture(Some(&p.runs[0]), xml, spans[0].clone()).unwrap() + RunSource::capture_all(&[(Some(&p.runs[0]), spans[0].clone())], xml) + .remove(0) + .unwrap() }; let left_source = source(original_body, &left); let right_source = source(edited_body, &right); @@ -26120,7 +27173,8 @@ mod tests { let pspan = story_content_spans(body, bindings)?[0].clone(); let closed = source_fragment(&body[pspan], bindings)?; let spans = modeled_paragraph_run_spans(p, &closed)?; - RunSource::capture(Some(&p.runs[0]), &closed, spans[0].clone()) + RunSource::capture_all(&[(Some(&p.runs[0]), spans[0].clone())], &closed) + .remove(0) }; let left_source = capture(left_body, left, &bindings_left)?; let right_source = capture(right_body, right, &bindings_right)?; 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..8dbce047a 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 diff --git a/docs/hld/10-bindings-spec.md b/docs/hld/10-bindings-spec.md index c5493ba53..fea349d43 100644 --- a/docs/hld/10-bindings-spec.md +++ b/docs/hld/10-bindings-spec.md @@ -3075,7 +3075,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..dde0d01d4 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_517_067, 56_462_895, 37), "rdocx-cli": (126_182, 593_817, 8), "rdocx-html": (29_407, 118_370, 11), "rdocx-layout": (463_844, 2_543_127, 15),