Skip to main content

jubarte_redlines/document_comparer/
mod.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2// SPDX-FileCopyrightText: Microsoft Corporation
3// SPDX-FileCopyrightText: 2025-2026 John Scrudato IV
4//
5// SPDX-License-Identifier: Apache-2.0 AND LicenseRef-Docxodus-MIT
6
7//! DocumentComparer façade (M5). Port of `DocumentComparer.ts` (compare path).
8//!
9//! `compare_documents(original, modified, author) -> Vec<u8>` opens both
10//! packages, diffs their main-document bodies, and writes a redline `.docx` (the
11//! original package with `word/document.xml` replaced by the tracked-revision
12//! result).
13//!
14//! NOTE: this is the text-level compare path. Full DocumentComparer additionally
15//! runs PreProcessMarkup/accept/hash and relocates footnotes/comments/related
16//! parts (the M4.5–M4.6 refinements) for exact golden parity on complex docs.
17
18use crate::comparer::{WmlComparerSettings, compare_bodies_faithful};
19use crate::namespaces::{R, W, W14};
20use crate::opc::{OpcError, PartFs};
21use crate::xmllinq::{Dom, NodeId, XName};
22
23mod pre_process;
24mod stories;
25mod styles;
26use pre_process::*;
27use stories::*;
28use styles::*;
29
30/// A header/footer comparison that cannot produce a faithful redline.
31/// Carried inside [`OpcError::Io`]; callers can downcast its `get_ref()`.
32#[derive(Debug)]
33pub struct StoryDiffError {
34    /// Package part whose comparison failed.
35    pub part: String,
36    /// The failed operation or output invariant.
37    pub reason: &'static str,
38}
39
40impl std::fmt::Display for StoryDiffError {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        write!(f, "STORY_DIFF_FAILED: {}: {}", self.part, self.reason)
43    }
44}
45
46impl std::error::Error for StoryDiffError {}
47
48pub use crate::limits::UnsupportedContentError;
49
50/// Each section of the redline `root` in order, as (its break is deleted,
51/// the header/footer parts it references). A paragraph's `w:sectPr` whose
52/// mark is deleted is a deleted break; any other paragraph's, and the
53/// body's own, is a live section.
54#[doc(hidden)]
55pub fn section_story_parts(
56    dom: &Dom,
57    root: NodeId,
58    pkg: &PartFs,
59    main: &str,
60) -> Vec<(bool, Vec<String>)> {
61    let Some(rels) = pkg.read_rels_for(main) else {
62        return Vec::new();
63    };
64    let targets: std::collections::HashMap<&str, &str> = rels
65        .items
66        .iter()
67        .map(|r| (r.id.as_str(), r.target.as_str()))
68        .collect();
69    section_props(dom, root)
70        .into_iter()
71        .map(|sect| {
72            let deleted = dom
73                .parent(sect)
74                .filter(|&p| dom.name_is(p, &W::p_pr()))
75                .and_then(|p| dom.element(p, &W::r_pr()))
76                .is_some_and(|r| dom.element(r, &W::del()).is_some());
77            let parts = dom
78                .elements(sect, None)
79                .into_iter()
80                .filter(|&r| {
81                    dom.name_is(r, &W::header_reference()) || dom.name_is(r, &W::footer_reference())
82                })
83                .filter_map(|r| targets.get(dom.attribute(r, &R::id())?))
84                .map(|target| referenced_part(pkg, main, target))
85                .collect();
86            (deleted, parts)
87        })
88        .collect()
89}
90
91/// Default pinned revision date when the caller doesn't specify one.
92pub const DEFAULT_DATE: &str = "1970-01-01T00:00:00Z";
93
94/// C.1/C.2 — `WmlComparer.PreProcessMarkup` (:434) at package level:
95/// `ChangeFootnoteEndnoteReferencesToUniqueRange` (:1627) then
96/// `AddFootnotesEndnotesParts` (:1604). C.3–C.5 extend it with
97/// FillInEmptyFootnotesEndnotes, DetachExternalData and
98/// AddUnidsToMarkupInContentParts in the C# order. Returns the names of the
99/// parts it rewrote or created (empty = pure no-op, bytes untouched). An
100/// orphaned footnote/endnote reference is an `invalid_content` error — C#
101/// throws DocxodusException when no ComparisonLog is wired (:1676), and the
102/// compare path wires none.
103///
104/// # Errors
105///
106/// [`OpcError`] when an orphan footnote/endnote reference has no matching
107/// definition, or the OPC layer cannot parse / serialise a referenced part.
108pub fn pre_process_markup(
109    pkg: &mut PartFs,
110    starting_id_for_footnotes_endnotes: i32,
111) -> Result<Vec<String>, OpcError> {
112    pre_process(pkg, starting_id_for_footnotes_endnotes, false)
113}
114
115/// A.11 — `RevisionProcessor.AcceptRevisions` byte facade: accept every
116/// tracked revision across main + headers/footers + notes + comments +
117/// styles parts and return the result as a `.docx` byte vector. The input
118/// is admitted under [`crate::admission::InputLimits::compare`] first.
119///
120/// # Errors
121///
122/// [`OpcError`] when admission refuses the input or the OPC layer cannot
123/// parse / serialise the package.
124pub fn accept_revisions(docx: &[u8]) -> Result<Vec<u8>, OpcError> {
125    crate::admission::admit_package(docx)?;
126    let mut pkg = PartFs::open(docx)?;
127    crate::revision_processor::accept_revisions_package(&mut pkg);
128    repair_resolved_package_validity(&mut pkg);
129    pkg.to_zip()
130}
131
132/// A.11 — `RevisionProcessor.RejectRevisions` byte facade: reject every
133/// tracked revision across main + headers/footers + notes + comments +
134/// styles parts.
135pub fn reject_revisions(docx: &[u8]) -> Result<Vec<u8>, OpcError> {
136    crate::admission::admit_package(docx)?;
137    let mut pkg = PartFs::open(docx)?;
138    crate::revision_processor::reject_revisions_package(&mut pkg);
139    repair_resolved_package_validity(&mut pkg);
140    pkg.to_zip()
141}
142
143/// M481 — Word-repair: wire core parts the package carries but the main
144/// document never references. superdoc_hyperlink_cases ships styles.xml
145/// WITHOUT a styles relationship in document.xml.rels; a spec-following
146/// consumer (LO included) then never loads the stylesheet and the whole
147/// document renders in fallback fonts. Word repairs the relationship on
148/// open (oracle rels: rId1 -> styles.xml), so match it at compare time —
149/// same family as the dangling-numbering repair.
150const CUSTOM_PROPS_REL: &str =
151    "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties";
152
153/// The part the package's custom-properties relationship reaches.
154fn custom_props_part(pkg: &PartFs) -> Option<String> {
155    pkg.package_relationships()
156        .items
157        .iter()
158        .find(|r| r.rel_type == CUSTOM_PROPS_REL)
159        .map(|r| r.target.trim_start_matches('/').to_string())
160        .filter(|p| pkg.part_bytes(p).is_some())
161}
162
163/// Word's redline keeps the custom document properties of both sides: the
164/// revision's alone when the original has none (83 of the 96 Word redlines
165/// where only the revision has them), else the union, the original's value
166/// winning where both name a property (every conflict among the 47 with
167/// both). Without them a `DOCPROPERTY` field of the accepted text reads
168/// "Error! Unknown document property name." (f8c1ce3e92).
169fn merge_custom_properties(out: &mut PartFs, pkg2: &PartFs) {
170    let Some(b_part) = custom_props_part(pkg2) else {
171        return;
172    };
173    let Some(b_xml) = pkg2.part_string(&b_part) else {
174        return;
175    };
176    let Some(a_part) = custom_props_part(out) else {
177        if out.part_bytes(&b_part).is_some() {
178            return;
179        }
180        out.set_part(&b_part, b_xml.into_bytes());
181        out.add_content_type_override(
182            &format!("/{b_part}"),
183            "application/vnd.openxmlformats-officedocument.custom-properties+xml",
184        );
185        out.add_package_relationship(CUSTOM_PROPS_REL, &b_part);
186        return;
187    };
188    let Some(a_xml) = out.part_string(&a_part) else {
189        return;
190    };
191    let mut dom = Dom::new();
192    let a_doc = dom.parse_xdocument(&a_xml);
193    let b_doc = dom.parse_xdocument(&b_xml);
194    let (Some(a_root), Some(b_root)) = (dom.root(a_doc), dom.root(b_doc)) else {
195        return;
196    };
197    let name = XName::get("name", "");
198    let pid = XName::get("pid", "");
199    let a_props = dom.elements(a_root, None);
200    let mut next_pid = a_props
201        .iter()
202        .filter_map(|&p| dom.attribute(p, &pid)?.parse::<u32>().ok())
203        .max()
204        .unwrap_or(1);
205    // Property names match without regard to case: the original's
206    // "Actno" and the revision's "ActNo" are one property, and two of them
207    // make Word refuse the package (19eb128df9 vs 9666fa13fb).
208    let mut a_names: std::collections::HashSet<String> = a_props
209        .iter()
210        .filter_map(|&p| dom.attribute(p, &name).map(str::to_lowercase))
211        .collect();
212    let mut added = false;
213    for bp in dom.elements(b_root, None) {
214        let Some(n) = dom.attribute(bp, &name) else {
215            continue;
216        };
217        if !a_names.insert(n.to_lowercase()) {
218            continue;
219        }
220        let clone = dom.clone_subtree(bp);
221        next_pid += 1;
222        dom.set_attribute_value(clone, &pid, Some(&next_pid.to_string()));
223        dom.add(a_root, clone);
224        added = true;
225    }
226    if added {
227        out.set_part(&a_part, dom.serialize_document(a_doc).into_bytes());
228    }
229}
230
231fn repair_missing_core_relationships(out: &mut PartFs, out_main: &str) {
232    const CORE: [(&str, &str); 5] = [
233        ("word/styles.xml", "styles"),
234        ("word/settings.xml", "settings"),
235        ("word/webSettings.xml", "webSettings"),
236        ("word/fontTable.xml", "fontTable"),
237        ("word/theme/theme1.xml", "theme"),
238    ];
239    for (part, rel_suffix) in CORE {
240        if out.part_bytes(part).is_none() {
241            continue;
242        }
243        let has_rel = out.read_rels_for(out_main).is_some_and(|r| {
244            r.items
245                .iter()
246                .any(|i| i.rel_type.ends_with(&format!("/{rel_suffix}")))
247        });
248        if !has_rel {
249            let target = crate::opc::relative_rel_target(out_main, part);
250            out.add_document_relationship(
251                out_main,
252                &format!(
253                    "http://schemas.openxmlformats.org/officeDocument/2006/relationships/{rel_suffix}"
254                ),
255                &target,
256            );
257        }
258    }
259}
260
261/// D.6 — `WmlComparer.GetRevisions` (:3940) byte facade: list every tracked
262/// revision in a redline `.docx` — main-part groups, footnote/endnote
263/// definition groups, `w:rPrChange` format changes, then (settings-gated)
264/// move detection. `TestForInvalidContent` failures are an `invalid_content`
265/// error where C# throws.
266pub fn get_revisions(
267    docx: &[u8],
268    settings: &crate::comparer::WmlComparerSettings,
269) -> Result<Vec<crate::comparer::WmlComparerRevision>, OpcError> {
270    use crate::comparer::{preprocess, revisions};
271
272    crate::admission::admit_input("input", docx, settings.input_limits)?;
273    let pkg = PartFs::open_within(docx, settings.input_limits)?;
274    let main = pkg
275        .main_document_part()
276        .unwrap_or_else(|| "word/document.xml".to_string());
277    let xml = pkg
278        .part_string(&main)
279        .ok_or_else(|| OpcError::PartNotFound(main.clone()))?;
280    let mut dom = Dom::new();
281    let d = dom.parse_xdocument(&xml);
282    let root = dom
283        .root(d)
284        .ok_or_else(|| OpcError::PartNotFound(format!("{main}: no root element")))?;
285
286    // C# :3948–:3949 — TestForInvalidContent (throws) +
287    // RemoveExistingPowerToolsMarkup on main and both notes parts.
288    refuse_unatomizable(&dom, root, "input document")?;
289    preprocess::remove_existing_powertools_markup(&mut dom, root);
290    let mut note_roots: Vec<(NodeId, &str, crate::xmllinq::XName)> = Vec::new();
291    let (fn_part, en_part) = notes_part_names(&pkg);
292    for (part, def) in [
293        (fn_part.as_str(), W::footnote()),
294        (en_part.as_str(), W::endnote()),
295    ] {
296        if let Some(x) = pkg.part_string(part) {
297            let nd = dom.parse_xdocument(&x);
298            if let Some(r) = dom.root(nd) {
299                refuse_unatomizable(&dom, r, part)?;
300                preprocess::remove_existing_powertools_markup(&mut dom, r);
301                note_roots.push((r, part, def));
302            }
303        }
304    }
305    let units = note_roots
306        .iter()
307        .fold(story_units(&dom, root), |sum, (r, _, _)| {
308            sum.saturating_add(story_units(&dom, *r))
309        });
310    refuse_past_story_budget(units, "input document", settings.input_limits)?;
311
312    let body = dom
313        .element(root, &W::body())
314        .ok_or_else(|| OpcError::PartNotFound(format!("{main}: no w:body")))?;
315    let mut revs = revisions::get_revisions_from_body(&mut dom, body, &main, settings);
316    for (r, part, def) in &note_roots {
317        revs.extend(revisions::get_revisions_from_note_definitions(
318            &mut dom, *r, def, part, settings,
319        ));
320    }
321    let mut fc_parts: Vec<(NodeId, &str)> = vec![(root, main.as_str())];
322    for (r, part, _) in &note_roots {
323        fc_parts.push((*r, part));
324    }
325    revs.extend(revisions::get_format_change_revisions(&mut dom, &fc_parts));
326    revisions::detect_moves(&mut revs, settings);
327    Ok(revs)
328}
329
330/// Serialize one revision to the stable JSON object shape of the wasm
331/// `getRevisions` and Python `get_revisions` bindings. Strings escape
332/// backslash, quote and every control character below U+0020, so document
333/// text can carry `\t`, `\r`, vertical tabs, etc.; U+007F passes as is.
334pub fn revision_to_json(r: &crate::comparer::WmlComparerRevision) -> String {
335    fn esc(s: &str) -> String {
336        let mut o = String::with_capacity(s.len());
337        for c in s.chars() {
338            match c {
339                '\\' => o.push_str("\\\\"),
340                '"' => o.push_str("\\\""),
341                '\n' => o.push_str("\\n"),
342                '\r' => o.push_str("\\r"),
343                '\t' => o.push_str("\\t"),
344                c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)),
345                c => o.push(c),
346            }
347        }
348        o
349    }
350    let format_change = r.format_change.as_ref().map_or("null".to_string(), |fc| {
351        let props: Vec<String> = fc
352            .changed_properties
353            .iter()
354            .map(|p| format!("\"{}\"", esc(p)))
355            .collect();
356        format!("{{\"changedProperties\":[{}]}}", props.join(","))
357    });
358    format!(
359        "{{\"type\":\"{:?}\",\"author\":\"{}\",\"date\":\"{}\",\"part\":\"{}\",\"moveGroupId\":{},\"isMoveSource\":{},\"formatChange\":{},\"text\":\"{}\"}}",
360        r.revision_type,
361        esc(r.author.as_deref().unwrap_or("")),
362        esc(r.date.as_deref().unwrap_or("")),
363        esc(&r.part_name),
364        r.move_group_id
365            .map_or("null".to_string(), |v| v.to_string()),
366        r.is_move_source
367            .map_or("null".to_string(), |v| v.to_string()),
368        format_change,
369        esc(r.text.as_deref().unwrap_or("")),
370    )
371}
372
373/// Serialize a revision list to a single JSON array string — the wasm
374/// `getRevisions` binding shape. The CLI prints one object per line
375/// instead.
376pub fn revisions_to_json(revs: &[crate::comparer::WmlComparerRevision]) -> String {
377    let items: Vec<String> = revs.iter().map(revision_to_json).collect();
378    format!("[{}]", items.join(","))
379}
380
381/// `DocumentComparer.CompareDocuments(original, modified, author)`.
382pub fn compare_documents(
383    original: &[u8],
384    modified: &[u8],
385    author: &str,
386) -> Result<Vec<u8>, OpcError> {
387    compare_documents_with_options(original, modified, author, DEFAULT_DATE)
388}
389
390/// Compare with an explicit revision timestamp (for reproducible output).
391pub fn compare_documents_with_options(
392    original: &[u8],
393    modified: &[u8],
394    author: &str,
395    date: &str,
396) -> Result<Vec<u8>, OpcError> {
397    compare_documents_internal(original, modified, author, date, true)
398}
399
400/// Compare with caller-supplied [`WmlComparerSettings`] (author/date/detail
401/// threshold/…). The other entry points delegate here with defaults.
402pub fn compare_documents_with_settings(
403    original: &[u8],
404    modified: &[u8],
405    settings: &WmlComparerSettings,
406) -> Result<Vec<u8>, OpcError> {
407    compare_documents_impl(original, modified, settings, true, true)
408}
409
410/// Edit restores permissions under its own revised-by-id policy (#1176).
411#[doc(hidden)]
412pub fn compare_documents_for_edit(
413    original: &[u8],
414    modified: &[u8],
415    settings: &WmlComparerSettings,
416) -> Result<Vec<u8>, OpcError> {
417    compare_documents_impl(original, modified, settings, true, false)
418}
419
420/// `WmlComparer.CompareInternal` (:152). `pre_process_original` mirrors C#'s
421/// `preProcessMarkupInOriginal` — true for Compare; Consolidate passes false
422/// because its original is already preprocessed (`CompareInternal(..., false)`).
423pub fn compare_documents_internal(
424    original: &[u8],
425    modified: &[u8],
426    author: &str,
427    date: &str,
428    pre_process_original: bool,
429) -> Result<Vec<u8>, OpcError> {
430    let settings = WmlComparerSettings {
431        author_for_revisions: author.to_string(),
432        date_time_for_revisions: date.to_string(),
433        ..WmlComparerSettings::default()
434    };
435    compare_documents_impl(original, modified, &settings, pre_process_original, true)
436}
437
438/// Resolve the footnotes/endnotes part names via the main-document rels,
439/// falling back to the standard names. OPC makes the rels authoritative —
440/// producers legally use nonstandard part names, and hardcoding
441/// `word/footnotes.xml` silently skipped their notes (PR #51 review).
442fn notes_part_names(pkg: &PartFs) -> (String, String) {
443    let main = pkg
444        .main_document_part()
445        .unwrap_or_else(|| "word/document.xml".to_string());
446    let mut fn_p = "word/footnotes.xml".to_string();
447    let mut en_p = "word/endnotes.xml".to_string();
448    if let Some(rels) = pkg.read_rels_for(&main) {
449        for r in &rels.items {
450            if r.target_mode.as_deref() == Some("External") {
451                continue;
452            }
453            match r.rel_type.rsplit('/').next().unwrap_or("") {
454                "footnotes" => fn_p = pkg.resolve_rel_target(&main, &r.target),
455                "endnotes" => en_p = pkg.resolve_rel_target(&main, &r.target),
456                _ => {}
457            }
458        }
459    }
460    (fn_p, en_p)
461}
462
463/// True when any package part's XML carries tracked-change markup that Word
464/// Compare would fold into the final view before diffing. Opened under the
465/// same budget the caller admitted the input with, so a settings budget
466/// looser than the constructor's still governs (#645).
467fn main_part_xml(docx: &[u8], limits: crate::admission::InputLimits) -> Option<String> {
468    let pkg = PartFs::open_within(docx, limits).ok()?;
469    let main = pkg
470        .main_document_part()
471        .unwrap_or_else(|| "word/document.xml".to_string());
472    let xml = pkg.part_string(&main)?;
473    Some(normalize_strict_namespaces(&xml).into_owned())
474}
475
476fn docx_has_tracked_changes(docx: &[u8], limits: crate::admission::InputLimits) -> bool {
477    let Ok(pkg) = PartFs::open_within(docx, limits) else {
478        return false;
479    };
480    for name in pkg.parts() {
481        if !name.ends_with(".xml") {
482            continue;
483        }
484        let Some(xml) = pkg.part_string(&name) else {
485            continue;
486        };
487        // Whole element names: `<w:instrText>` and `<w:insideH>` are not
488        // revisions, and tidying a document with none rewrites it (#1870).
489        if crate::revision_processor::xml_has_tracked_revisions(&xml) {
490            return true;
491        }
492    }
493    false
494}
495
496fn compare_documents_impl(
497    original: &[u8],
498    modified: &[u8],
499    settings: &WmlComparerSettings,
500    pre_process_original: bool,
501    union_permissions: bool,
502) -> Result<Vec<u8>, OpcError> {
503    // Admit both packages before anything inflates them: the central
504    // directory's sizes are untrusted, and an unbounded inflate aborts the
505    // Python and WASM hosts rather than failing the call.
506    crate::admission::admit_input("original", original, settings.input_limits)?;
507    // IDENTICAL-INPUT-01: same input bytes → empty redline is the (accepted)
508    // original package. Avoids dual package prep, Dom parse, LCS, and produce.
509    // Critical for self-compare fixtures (e.g. redline × self).
510    if original == modified {
511        let mut owned = crate::strict_translation::strict_to_transitional_docx_within(
512            original,
513            settings.input_limits,
514        )
515        .map_err(crate::opc::refused)?;
516        if settings.merge_replaced_paragraphs
517            && !settings.preserve_untouched
518            && docx_has_tracked_changes(&owned, settings.input_limits)
519        {
520            owned = accept_source_revisions(&owned, settings.input_limits)?;
521        }
522        return finalize_identical_compare(&owned, settings);
523    }
524
525    // M8: normalize ISO/IEC 29500 "Strict" inputs to "Transitional" before any
526    // PartFs::open sees them (mirrors the OpenXML SDK's pre-compare step).
527    // Transitional packages round-trip byte-identical (zero-churn), so the
528    // golden/parity paths are unaffected; only Strict inputs are rewritten.
529    crate::admission::admit_input("modified", modified, settings.input_limits)?;
530    let mut original_owned = crate::strict_translation::strict_to_transitional_docx_within(
531        original,
532        settings.input_limits,
533    )
534    .map_err(crate::opc::refused)?;
535    let mut modified_owned = crate::strict_translation::strict_to_transitional_docx_within(
536        modified,
537        settings.input_limits,
538    )
539    .map_err(crate::opc::refused)?;
540
541    // Accept-before-diff flattens a revised insertion into live text, so a late
542    // pass can no longer see where that insertion ended. Keep both main parts
543    // from this moment. Faithful mode never reads them, nor does an edit:
544    // the ladder matches Word Compare's shapes, not the plan's.
545    let ladder_sources = if settings.merge_replaced_paragraphs && !settings.preserve_untouched {
546        match (
547            main_part_xml(&original_owned, settings.input_limits),
548            main_part_xml(&modified_owned, settings.input_limits),
549        ) {
550            (Some(original_xml), Some(revised_xml)) => Some((original_xml, revised_xml)),
551            _ => None,
552        }
553    } else {
554        None
555    };
556
557    // Word-visual mode + either side already carries track changes: accept both
558    // packages first (Word Compare of *finals*). Without this, stamp/re-emit of
559    // pre-existing TC drowns real moves and inflates ins/del (broken_ones_two
560    // file_8_file_9 37→56, file_27_file_28 38→61 with accept-then). PowerTools
561    // faithful leaves inputs as-is. So does an edit (`preserve_untouched`):
562    // its plan settled the revisions it resolves, and those left (a style's
563    // record) are the source's to keep, untidied (#1885).
564    if settings.merge_replaced_paragraphs
565        && !settings.preserve_untouched
566        && (docx_has_tracked_changes(&original_owned, settings.input_limits)
567            || docx_has_tracked_changes(&modified_owned, settings.input_limits))
568    {
569        original_owned = accept_source_revisions(&original_owned, settings.input_limits)?;
570        modified_owned = accept_source_revisions(&modified_owned, settings.input_limits)?;
571    }
572
573    // After prep, packages may still be byte-identical (rare non-self paths).
574    if original_owned == modified_owned {
575        return finalize_identical_compare(&original_owned, settings);
576    }
577
578    let original: &[u8] = &original_owned;
579    let modified: &[u8] = &modified_owned;
580
581    let mut pkg1 = PartFs::open_within(original, settings.input_limits)?;
582    let mut pkg2 = PartFs::open_within(modified, settings.input_limits)?;
583
584    // The notes parts the original has before preprocessing adds empty ones.
585    let original_notes = {
586        let (footnotes, endnotes) = notes_part_names(&pkg1);
587        (
588            pkg1.part_bytes(&footnotes).is_some(),
589            pkg1.part_bytes(&endnotes).is_some(),
590        )
591    };
592
593    // CompareInternal :154–:155 — disjoint footnote/endnote id spaces: doc A
594    // gets starting_id+1000, doc B +2000 (block hashing ignores ref ids, so
595    // correlation is unaffected; the disjoint spaces make reference-driven
596    // note pairing sound).
597    let changed1 = if pre_process_original {
598        pre_process(
599            &mut pkg1,
600            settings.starting_id_for_footnotes_endnotes + 1000,
601            settings.preserve_untouched,
602        )?
603    } else {
604        Vec::new()
605    };
606    pre_process(
607        &mut pkg2,
608        settings.starting_id_for_footnotes_endnotes + 2000,
609        settings.preserve_untouched,
610    )?;
611
612    let main1 = pkg1
613        .main_document_part()
614        .unwrap_or_else(|| "word/document.xml".to_string());
615    let main2 = pkg2
616        .main_document_part()
617        .unwrap_or_else(|| "word/document.xml".to_string());
618
619    let xml1 = pkg1.part_string(&main1).ok_or_else(|| {
620        OpcError::PartNotFound(format!("original main document missing: {main1}"))
621    })?;
622    let xml2 = pkg2.part_string(&main2).ok_or_else(|| {
623        OpcError::PartNotFound(format!("modified main document missing: {main2}"))
624    })?;
625    // Strict/ISO OOXML uses purl.oclc.org namespace URIs; normalize to Transitional
626    // (the only variant our XName tables model) so the body/markup is recognized.
627    let xml1 = normalize_strict_namespaces(&xml1);
628    let xml2 = normalize_strict_namespaces(&xml2);
629
630    // Parse both into one arena so the comparer can work across them.
631    let mut dom = Dom::new();
632    let d1 = dom.parse_xdocument(&xml1);
633    let d2 = dom.parse_xdocument(&xml2);
634    let root1 = dom
635        .root(d1)
636        .ok_or_else(|| OpcError::PartNotFound("original has no root element".into()))?;
637    let root2 = dom
638        .root(d2)
639        .ok_or_else(|| OpcError::PartNotFound("modified has no root element".into()))?;
640    let body1 = merged_body(&mut dom, root1)
641        .ok_or_else(|| OpcError::PartNotFound("original has no w:body".into()))?;
642    let body2 = merged_body(&mut dom, root2)
643        .ok_or_else(|| OpcError::PartNotFound("modified has no w:body".into()))?;
644    refuse_unatomizable(&dom, root1, "original document")?;
645    refuse_unatomizable(&dom, root2, "modified document")?;
646
647    // #531: canonicalize measure spellings on BOTH inputs before the diff —
648    // here, where Strict is translated. The diff's property signatures
649    // compare raw attribute strings, so "2in" vs "2880" recorded a
650    // formatting revision whose old and new sides serialized identically
651    // (the output sweep alone normalized only what the record showed).
652    // Plain integers — every Transitional spelling — are untouched.
653    for root in [root1, root2] {
654        crate::comparer::finalize::normalize_universal_measures(&mut dom, root);
655    }
656
657    // B.4 — reference-driven notes processing: parse both documents' notes
658    // parts AND an independent copy of the original's parts (the withRevisions
659    // parts — C# gets them from the wmlResult clone of preprocessed source1)
660    // into the same Dom as the bodies. The pipeline (B.2/B.3) diffs each
661    // definition by its reference's correlation status and rebuilds the
662    // withRevisions parts renumbered 1..n.
663    fn parse_part_root(dom: &mut Dom, pkg: &PartFs, name: &str) -> Option<NodeId> {
664        let xml = pkg.part_string(name)?;
665        let d = dom.parse_xdocument(&xml);
666        dom.root(d)
667    }
668    let (fn1, en1) = notes_part_names(&pkg1);
669    let (fn2, en2) = notes_part_names(&pkg2);
670    let mut notes_ctx = crate::comparer::NotesContext {
671        fn_before: parse_part_root(&mut dom, &pkg1, &fn1),
672        fn_after: parse_part_root(&mut dom, &pkg2, &fn2),
673        en_before: parse_part_root(&mut dom, &pkg1, &en1),
674        en_after: parse_part_root(&mut dom, &pkg2, &en2),
675        fn_with_revisions: parse_part_root(&mut dom, &pkg1, &fn1),
676        en_with_revisions: parse_part_root(&mut dom, &pkg1, &en1),
677    };
678    // Same canonicalization for the notes parts the pipeline diffs: a
679    // spelling-only footnote geometry pair is not a formatting change.
680    for root in [
681        notes_ctx.fn_before,
682        notes_ctx.fn_after,
683        notes_ctx.en_before,
684        notes_ctx.en_after,
685        notes_ctx.fn_with_revisions,
686        notes_ctx.en_with_revisions,
687    ]
688    .into_iter()
689    .flatten()
690    {
691        crate::comparer::finalize::normalize_universal_measures(&mut dom, root);
692    }
693    for (root, part) in [
694        (notes_ctx.fn_before, &fn1),
695        (notes_ctx.fn_after, &fn2),
696        (notes_ctx.en_before, &en1),
697        (notes_ctx.en_after, &en2),
698    ] {
699        if let Some(root) = root {
700            refuse_unatomizable(&dom, root, part)?;
701        }
702    }
703    for (side, main, notes) in [
704        (
705            "original document",
706            root1,
707            [notes_ctx.fn_before, notes_ctx.en_before],
708        ),
709        (
710            "modified document",
711            root2,
712            [notes_ctx.fn_after, notes_ctx.en_after],
713        ),
714    ] {
715        let units = notes
716            .into_iter()
717            .flatten()
718            .fold(story_units(&dom, main), |sum, root| {
719                sum.saturating_add(story_units(&dom, root))
720            });
721        refuse_past_story_budget(units, side, settings.input_limits)?;
722    }
723
724    // Word mode: each side's unstyled-paragraph line pitch, for the
725    // demo-default spacing strip.
726    if settings.merge_replaced_paragraphs {
727        for (pkg, root) in [(&pkg1, root1), (&pkg2, root2)] {
728            let line = pkg
729                .part_string("word/styles.xml")
730                .map_or_else(|| "240".to_string(), |x| default_paragraph_line(&x));
731            dom.set_attribute_value(root, &crate::namespaces::PT::default_line(), Some(&line));
732            if pkg
733                .part_string("word/styles.xml")
734                .is_some_and(|x| has_default_table_style(&x))
735            {
736                dom.set_attribute_value(
737                    root,
738                    &crate::namespaces::PT::has_default_table_style(),
739                    Some("1"),
740                );
741            }
742        }
743    }
744    let result_root = crate::comparer::try_compare_bodies_faithful_with_notes(
745        &mut dom,
746        root1,
747        root2,
748        body1,
749        body2,
750        settings,
751        Some(&mut notes_ctx),
752    )
753    .map_err(crate::opc::refused)?;
754    // A break the revision adds is an inserted paragraph mark. The body
755    // comparison still leaves that break live, so Reject All would keep it.
756    track_added_section_breaks(&mut dom, result_root, body1, body2, settings);
757    for root in [root1, root2] {
758        dom.set_attribute_value(root, &crate::namespaces::PT::default_line(), None);
759        dom.set_attribute_value(
760            root,
761            &crate::namespaces::PT::has_default_table_style(),
762            None,
763        );
764    }
765
766    // Base the output on the original package, replacing the main document
767    // part. When PreProcessMarkup rewrote parts (notes renumbering), base it
768    // on the PREPROCESSED original instead — C# builds wmlResult from the
769    // preprocessed source1 (:197 comment: the renumbered/unid'd markup must be
770    // the one appearing in the result). Note-free inputs keep the raw bytes.
771    let mut out = if changed1.is_empty() {
772        PartFs::open_within(original, settings.input_limits)?
773    } else {
774        PartFs::open_within(&pkg1.to_zip()?, settings.input_limits)?
775    };
776    // M4.H.3: carry over / drop dangling relationship references from inserted
777    // content so the output has no dangling rId (Word-repair preventer).
778    crate::comparer::parts::reconcile_dangling_relationships(
779        &mut dom,
780        result_root,
781        &mut out,
782        &[&pkg1, &pkg2],
783    );
784    // Word-alignment mode: adopt the revised document's headers/footers when
785    // the original supplied none (must run BEFORE the result serialization —
786    // it adds references to the final sectPr).
787    if settings.merge_replaced_paragraphs {
788        adopt_revised_header_footer(&mut dom, result_root, &pkg2, &mut out, &main1, settings);
789        // Word inheritance: drop body-final HF slots already set on an earlier
790        // mid-section break (dual chrome otherwise). Mid multi-section copies stay.
791        strip_final_sectpr_inherited_header_footer(
792            &mut dom,
793            result_root,
794            &final_header_footer_slots(&pkg2),
795        );
796    }
797    if needs_unmerged_section_story_cleanup(settings) {
798        strip_final_a_only_deleted_break_stories(&mut dom, result_root, &out, &pkg2, &main1);
799    }
800    // A-only stories on deleted breaks or solely on the final section must
801    // disappear on Accept All, including when paragraph merging is disabled.
802    let mut dead_only = parts_only_deleted_breaks_reference(&dom, result_root, &out, &main1);
803    if needs_unmerged_section_story_cleanup(settings) {
804        let a_only = a_only_header_footer_parts(&pkg1, &pkg2);
805        dead_only.retain(|part| a_only.contains(part));
806    }
807    mark_a_only_hf_content_as_deleted(&mut out, &pkg1, &pkg2, &dead_only, settings);
808    move_page_story_to_final_section(&mut dom, result_root, &out, &main1, &dead_only);
809
810    // M35: comments carryover is a package-validity invariant, not a
811    // Word-visual formatting pass. Both supported comparer presets must union
812    // comment parts and re-inject their anchors; otherwise PowerTools-faithful
813    // output can retain an original comment definition after its source
814    // paragraph becomes a deletion while silently losing the anchor triplet.
815    let has_comments = pkg1.part_string("word/comments.xml").is_some()
816        || pkg2.part_string("word/comments.xml").is_some();
817    crate::comparer::comments::carry_comments(
818        &mut dom,
819        result_root,
820        (&pkg1, &main1),
821        (&pkg2, &main2),
822        (&mut out, &main1),
823        &settings.author_for_revisions,
824    );
825    if has_comments {
826        // Comment anchors keep source ids (aligned with comments.xml). Re-run
827        // revision renumber with those ids reserved so move/tblPrChange never
828        // share an id with commentRange* (Word "unreadable content").
829        crate::comparer::finalize::fix_up_revision_ids(&mut dom, &[result_root]);
830    }
831
832    // M472 — re-assert Word's ins-before-del replacement order after the
833    // comment-carry rebuilds run blocks (diff_before10 × diff_before11: the
834    // early reorder's work was undone by comment anchoring, leaving
835    // [ins][del][ins] where Word emits ins…ins del). Idempotent and
836    // text-preserving.
837    crate::comparer::finalize::reorder_replacements_ins_before_del(&mut dom, result_root);
838
839    // Word mode: the deleted rows of a paired table whose style or layout
840    // changed become tables of their own, as in Word's redlines (#1817).
841    // Before the pass below, which reads the deleted tables.
842    if settings.merge_replaced_paragraphs {
843        use crate::comparer::table_split::{TableStyleNames, split_rows_by_table_identity};
844        split_rows_by_table_identity(
845            &mut dom,
846            result_root,
847            &TableStyleNames::original(pkg1.part_string("word/styles.xml").as_deref()),
848            &TableStyleNames::revision(pkg2.part_string("word/styles.xml").as_deref()),
849        );
850    }
851
852    // Inserted words a deleted paragraph mark joins across a deleted table
853    // start the paragraph they join (#1851): Word 16.115 crashes opening
854    // some such redlines. After the comment carry and M472, which rebuild
855    // runs; the bookmarks below are carried around the moved runs.
856    crate::comparer::deleted_tables::move_inserted_text_past_deleted_tables(&mut dom, result_root);
857
858    // M463 — rewrite outer-wrapped math revisions into Word's internal form.
859    // Must run after every mesh/finalize pass (they reason about the outer
860    // wrap) and before serialize.
861    crate::comparer::produce::convert_outer_math_wraps_to_internal(&mut dom, result_root, settings);
862
863    // Word keeps both documents' body bookmarks (union by name); without
864    // them every updated TOC/REF field prints "Error! Bookmark not defined."
865    // Runs on the finished body so no later pass moves the markers.
866    crate::comparer::bookmarks::carry_bookmarks(
867        &mut dom,
868        result_root,
869        (&pkg1, &main1),
870        (&pkg2, &main2),
871        &settings.author_for_revisions,
872    );
873    if union_permissions {
874        crate::comparer::bookmarks::carry_permission_union(
875            &mut dom,
876            result_root,
877            (&pkg1, &main1),
878            (&pkg2, &main2),
879            &settings.author_for_revisions,
880        );
881    }
882
883    // Final drawing/shape id renumber immediately before serialize — package
884    // post-steps (reconcile, header/footer adopt, comments) can clone/graft
885    // drawings after the mid-produce FixUpDocPrIds pass (S-dup-docpr-id).
886    crate::comparer::fixups::fix_up_drawing_ids(&mut dom, result_root, settings.preserve_untouched);
887
888    let result_xml = dom.serialize_element(result_root);
889    out.set_part(&main1, result_xml.into_bytes());
890
891    // M4.H.8/H.9: copy styles/numbering referenced by inserted (modified) content
892    // into the output so it stays Word-valid.
893    // Word-mode also: adopt missing docDefaults/latentStyles from B, then
894    // canonicalize styleIds (numeric/`styleN` → Heading1/…) and remap refs.
895    let mut style_renames: std::collections::HashMap<String, String> =
896        std::collections::HashMap::new();
897    // POSTSTEP-STYLES-CACHE-01: the style-validity passes each re-parse the
898    // (often large) output stylesheet — 3-4× per compare dominates medium-doc
899    // poststeps. Capture the defined style-id set here, after styles-copy has
900    // finished mutating `word/styles.xml` (copy-missing + canonicalize), so the
901    // pStyle/rStyle strip below reuses it instead of re-parsing. Nothing between
902    // here and that strip changes the style-id SET (the main-doc / spacing
903    // passes touch the body, not styles.xml), so the cached set is exact.
904    let mut cached_defined_styles: Option<std::collections::HashSet<String>> = None;
905    // POSTSTEP-STYLES-CACHE-02: keep the parsed styles arena (out stylesheet
906    // `tr`, revised stylesheet `fr`) alive so the M-PAG Normal-merge below can
907    // reuse it instead of re-parsing both stylesheets. styles-copy still
908    // serializes the stylesheet (so a compare that skips M-PAG is unaffected);
909    // M-PAG then mutates the same in-memory `tr` and re-serializes. serialize→
910    // parse is a lossless structural round-trip, so `tr` is identical to what
911    // M-PAG would have re-parsed.
912    let mut styles_arena: Option<(Dom, NodeId, NodeId)> = None;
913    for (part, is_styles) in [("word/styles.xml", true), ("word/numbering.xml", false)] {
914        match (out.part_string(part), pkg2.part_string(part)) {
915            (Some(to_xml), Some(from_xml)) => {
916                let mut sd = Dom::new();
917                let td = sd.parse_xdocument(&to_xml);
918                let fd = sd.parse_xdocument(&from_xml);
919                if let (Some(tr), Some(fr)) = (sd.root(td), sd.root(fd)) {
920                    if is_styles {
921                        // An edit's revised stylesheet is the source's plus
922                        // what the plan added, under the same ids: copy the
923                        // additions, rename nothing.
924                        if settings.merge_replaced_paragraphs && !settings.preserve_untouched {
925                            let a_ids = crate::comparer::footnotes::defined_style_ids(&sd, tr);
926                            materialize_builtin_paragraph_defaults(&mut sd, tr);
927                            materialize_builtin_paragraph_defaults(&mut sd, fr);
928                            let b_to_out = copy_missing_styles_by_name(&mut sd, tr, fr);
929                            let _ = adopt_missing_styles_structure(&mut sd, tr, fr);
930                            style_renames = canonicalize_style_ids(&mut sd, tr);
931                            // B's content names paired styles by B's ids; send
932                            // them to the output style's final id. An id A
933                            // also declares names A's own style: leave it. The
934                            // copied B styles link to them by B's ids too.
935                            let mut b_renames = std::collections::HashMap::new();
936                            for (b_id, out_id) in b_to_out {
937                                let target = style_renames.get(&out_id).cloned().unwrap_or(out_id);
938                                if b_id != target && !a_ids.contains(&b_id) {
939                                    b_renames.insert(b_id, target);
940                                }
941                            }
942                            for local in ["basedOn", "next", "link"] {
943                                for e in sd.descendants(tr, Some(&W::name(local))) {
944                                    if let Some(to) =
945                                        sd.attribute(e, &W::val()).and_then(|v| b_renames.get(v))
946                                    {
947                                        let to = to.clone();
948                                        sd.set_attribute_value(e, &W::val(), Some(&to));
949                                    }
950                                }
951                            }
952                            style_renames.extend(b_renames);
953                        } else {
954                            crate::comparer::footnotes::copy_missing_styles(&mut sd, tr, fr);
955                        }
956                    } else {
957                        let (num_remap, copied_bullets) =
958                            crate::comparer::footnotes::copy_missing_numbering(&mut sd, tr, fr);
959                        // B's picture bullets draw through B's numbering rels;
960                        // give each its own relationships, since the same ids
961                        // may already name A's images here.
962                        for bullet in copied_bullets {
963                            for el in sd.descendants_and_self(bullet, None) {
964                                for (an, rid) in sd.attributes(el) {
965                                    if an.namespace_name() != crate::namespaces::R::URI {
966                                        continue;
967                                    }
968                                    let carried = crate::comparer::parts::carry_relationship(
969                                        &mut out,
970                                        part,
971                                        &pkg2,
972                                        part,
973                                        &rid,
974                                        |_| true,
975                                    );
976                                    sd.set_attribute_value(el, &an, carried.as_deref());
977                                }
978                            }
979                        }
980                        // M482: colliding B numIds were renumbered in the
981                        // merged numbering part — rewrite the refs inside
982                        // B-INSERTED paragraphs (mark rPr carries w:ins) or
983                        // they resolve against A's same-id definitions
984                        // (bullets where B's decimals should render).
985                        // Word mode also moves unchanged paragraphs to B's
986                        // list and records A's numId in a pPrChange: the
987                        // circle bullet struck, the disc inserted (native
988                        // bullet circle × disc).
989                        if !num_remap.is_empty()
990                            && let Some(doc_xml) = out.part_string(&main1)
991                        {
992                            let mut pd = Dom::new();
993                            let dd = pd.parse_xdocument(&doc_xml);
994                            if let Some(droot) = pd.root(dd) {
995                                let mut changed = false;
996                                // Comment anchors and carried bookmarks keep their
997                                // ids; stay clear of both (Word never shares one).
998                                let mut next_id = [
999                                    "commentRangeStart",
1000                                    "commentRangeEnd",
1001                                    "commentReference",
1002                                    "bookmarkStart",
1003                                    "bookmarkEnd",
1004                                ]
1005                                .into_iter()
1006                                .flat_map(|n| pd.descendants(droot, Some(&W::name(n))))
1007                                .filter_map(|c| pd.attribute(c, &W::id())?.parse::<u32>().ok())
1008                                .map(|n| n + 1)
1009                                .fold(next_free_revision_id(&pd, droot), u32::max);
1010                                for p in pd.descendants(droot, Some(&W::p())) {
1011                                    let Some(ppr) = pd.element(p, &W::p_pr()) else {
1012                                        continue;
1013                                    };
1014                                    let mark = pd.element(ppr, &W::r_pr());
1015                                    let mark_has = |n: &str| {
1016                                        mark.is_some_and(|r| pd.element(r, &W::name(n)).is_some())
1017                                    };
1018                                    let mark_inserted = mark_has("ins");
1019                                    let unchanged = settings.merge_replaced_paragraphs
1020                                        && !mark_inserted
1021                                        && !mark_has("del");
1022                                    if !mark_inserted && !unchanged {
1023                                        continue;
1024                                    }
1025                                    let Some(nid) = pd
1026                                        .element(ppr, &W::num_pr())
1027                                        .and_then(|np| pd.element(np, &W::name("numId")))
1028                                    else {
1029                                        continue;
1030                                    };
1031                                    let cur = pd.attribute(nid, &W::val()).map(str::to_string);
1032                                    let Some(new_id) =
1033                                        cur.as_deref().and_then(|c| num_remap.get(c)).cloned()
1034                                    else {
1035                                        continue;
1036                                    };
1037                                    if unchanged && pd.element(ppr, &W::p_pr_change()).is_none() {
1038                                        let old_ppr = pd.new_element(W::p_pr());
1039                                        for c in pd.elements(ppr, None) {
1040                                            if pd.name(c).is_some_and(|n| {
1041                                                n == W::r_pr() || n == W::sect_pr()
1042                                            }) {
1043                                                continue;
1044                                            }
1045                                            let clone = pd.clone_subtree(c);
1046                                            pd.add(old_ppr, clone);
1047                                        }
1048                                        let chg = pd.new_element(W::p_pr_change());
1049                                        pd.set_attribute_value(
1050                                            chg,
1051                                            &W::id(),
1052                                            Some(&next_id.to_string()),
1053                                        );
1054                                        next_id += 1;
1055                                        pd.set_attribute_value(
1056                                            chg,
1057                                            &W::author(),
1058                                            Some(&settings.author_for_revisions),
1059                                        );
1060                                        pd.set_attribute_value(
1061                                            chg,
1062                                            &W::date(),
1063                                            Some(&settings.date_time_for_revisions),
1064                                        );
1065                                        pd.add(chg, old_ppr);
1066                                        pd.add(ppr, chg);
1067                                    }
1068                                    pd.set_attribute_value(nid, &W::val(), Some(&new_id));
1069                                    changed = true;
1070                                }
1071                                if changed {
1072                                    out.set_part(&main1, pd.serialize_element(droot).into_bytes());
1073                                }
1074                            }
1075                        }
1076                    }
1077                    if is_styles {
1078                        cached_defined_styles =
1079                            Some(crate::comparer::footnotes::defined_style_ids(&sd, tr));
1080                    }
1081                    out.set_part(part, sd.serialize_element(tr).into_bytes());
1082                    if is_styles {
1083                        // Hand the parsed arena (out `tr`, revised `fr`) to M-PAG.
1084                        styles_arena = Some((sd, tr, fr));
1085                    }
1086                }
1087            }
1088            // A has no numbering part, B does (file_21×file_22): copy B's
1089            // numbering wholesale + document rel. Prior match required both
1090            // sides present → insert-heavy next with lists lost numbering.
1091            // An edit takes the stylesheet its plan created the same way.
1092            (None, Some(from_xml)) if !is_styles || settings.preserve_untouched => {
1093                let (ct_type, rel_type, rel_suffix, target) = if is_styles {
1094                    (
1095                        "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml",
1096                        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
1097                        "/styles",
1098                        "styles.xml",
1099                    )
1100                } else {
1101                    (
1102                        "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml",
1103                        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",
1104                        "/numbering",
1105                        "numbering.xml",
1106                    )
1107                };
1108                out.set_part(part, from_xml.into_bytes());
1109                out.add_content_type_override(&format!("/{part}"), ct_type);
1110                let has_rel = out
1111                    .read_rels_for(&main1)
1112                    .is_some_and(|r| r.items.iter().any(|i| i.rel_type.ends_with(rel_suffix)));
1113                if !has_rel {
1114                    out.add_document_relationship(&main1, rel_type, target);
1115                }
1116            }
1117            // A has no styles part, B does: copy B, canonicalize, then M462 —
1118            // swap in Word's FACTORY docDefaults and bake B-effective metrics
1119            // into each style (Word scaffolds from its blank document, not
1120            // from B: tiff_image × two_column oracle). A's referenced theme
1121            // stays; only a missing one becomes Word's default, in
1122            // ensure_factory_package_chrome.
1123            (None, Some(from_xml)) if is_styles && settings.merge_replaced_paragraphs => {
1124                let mut sd = Dom::new();
1125                let fd = sd.parse_xdocument(&from_xml);
1126                if let Some(fr) = sd.root(fd) {
1127                    style_renames = canonicalize_style_ids(&mut sd, fr);
1128                    factory_scaffold_bake_b_styles(&mut sd, fr, settings);
1129                    out.set_part(part, sd.serialize_element(fr).into_bytes());
1130                    out.add_content_type_override(
1131                        "/word/styles.xml",
1132                        "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml",
1133                    );
1134                    let has_rel = out
1135                        .read_rels_for(&main1)
1136                        .is_some_and(|r| r.items.iter().any(|i| i.rel_type.ends_with("/styles")));
1137                    if !has_rel {
1138                        out.add_document_relationship(
1139                            &main1,
1140                            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
1141                            "styles.xml",
1142                        );
1143                    }
1144                }
1145            }
1146            // A has styles, B has none: still canonicalize A's ids (Word does).
1147            (Some(to_xml), None)
1148                if is_styles
1149                    && settings.merge_replaced_paragraphs
1150                    && !settings.preserve_untouched =>
1151            {
1152                let mut sd = Dom::new();
1153                let td = sd.parse_xdocument(&to_xml);
1154                if let Some(tr) = sd.root(td) {
1155                    style_renames = canonicalize_style_ids(&mut sd, tr);
1156                    out.set_part(part, sd.serialize_element(tr).into_bytes());
1157                }
1158            }
1159            _ => {}
1160        }
1161    }
1162    // Remap pStyle/rStyle/tblStyle in every XML part that can carry them.
1163    if settings.merge_replaced_paragraphs && !style_renames.is_empty() {
1164        let part_names: Vec<String> = out
1165            .parts()
1166            .into_iter()
1167            .filter(|p| {
1168                p.ends_with(".xml")
1169                    && (p.starts_with("word/document")
1170                        || p.starts_with("word/header")
1171                        || p.starts_with("word/footer")
1172                        || p.starts_with("word/footnotes")
1173                        || p.starts_with("word/endnotes")
1174                        || p.starts_with("word/comments")
1175                        || p == "word/styles.xml")
1176            })
1177            .collect();
1178        for part in part_names {
1179            let Some(xml) = out.part_string(&part) else {
1180                continue;
1181            };
1182            let mut pd = Dom::new();
1183            let doc = pd.parse_xdocument(&xml);
1184            let Some(root) = pd.root(doc) else {
1185                continue;
1186            };
1187            // styles.xml basedOn/next/link already remapped inside canonicalize.
1188            if part == "word/styles.xml" {
1189                continue;
1190            }
1191            if remap_style_refs(&mut pd, root, &style_renames) > 0 {
1192                out.set_part(&part, pd.serialize_element(root).into_bytes());
1193            }
1194        }
1195    }
1196
1197    // The revised text brings its fonts: their table entries come too.
1198    if let (Some(out_fonts), Some(b_fonts)) = (
1199        out.part_string("word/fontTable.xml"),
1200        pkg2.part_string("word/fontTable.xml"),
1201    ) && let Some(merged) = merge_revised_font_table(&out_fonts, &b_fonts)
1202    {
1203        out.set_part("word/fontTable.xml", merged.into_bytes());
1204    }
1205    // Word-mode: adopt B's package chrome (settings/fontTable/theme) when A is
1206    // thin. When BOTH sides are bare demos (C5 formatting one-pagers), Word
1207    // still saves factory settings/theme/fontTable — inject if still missing.
1208    if settings.merge_replaced_paragraphs {
1209        // An edit's source keeps the parts it has: no chrome comes from
1210        // Word's blank document.
1211        if !settings.preserve_untouched {
1212            adopt_revised_styles_chrome(&mut out, &pkg2, &main1);
1213            ensure_factory_package_chrome(&mut out, &main1);
1214        }
1215        repair_missing_core_relationships(&mut out, &main1);
1216        merge_custom_properties(&mut out, &pkg2);
1217        // M492: deleted paragraphs keep their A-ORIGINAL direct spacing.
1218        if let (Some(a_xml), Some(out_xml)) = (
1219            pkg1.part_string("word/document.xml"),
1220            out.part_string(&main1),
1221        ) && let Some(restored) = restore_deleted_paragraph_spacing(&a_xml, &out_xml)
1222        {
1223            out.set_part(&main1, restored.into_bytes());
1224        }
1225        // M491: B's DOCUMENT-FINAL paragraph mark never materializes as a
1226        // mid-document insertion — Word EQ-pairs the two documents' final
1227        // marks. Our windowed diff can splice B's terminal empty ¶ into the
1228        // body as an ins-para; the extra rendered line cascades every page
1229        // break below it (h_f_normal × sd_1495: paraId 5352EB15, 46.66 with
1230        // its content-ceiling at 97.13; 16-pair census). Remove the
1231        // ins-marked EMPTY paragraph carrying B's final paraId unless it is
1232        // itself the output's final paragraph.
1233        if let (Some(b_xml), Some(out_xml)) = (
1234            pkg2.part_string("word/document.xml"),
1235            out.part_string(&main1),
1236        ) {
1237            let b_final_pid = {
1238                let mut bd = Dom::new();
1239                let d = bd.parse_xdocument(&b_xml);
1240                bd.root(d)
1241                    .and_then(|r| bd.element(r, &W::body()))
1242                    .and_then(|body| {
1243                        let bdom = bd;
1244                        let paras: Vec<NodeId> = bdom
1245                            .elements(body, None)
1246                            .into_iter()
1247                            .filter(|&k| bdom.name_is(k, &W::p()))
1248                            .collect();
1249                        paras.last().and_then(|&p| {
1250                            bdom.attribute(p, &crate::namespaces::W14::name("paraId"))
1251                                .map(str::to_string)
1252                        })
1253                    })
1254            };
1255            if let Some(bf) = b_final_pid {
1256                let mut pd = Dom::new();
1257                let d = pd.parse_xdocument(&out_xml);
1258                if let Some(root) = pd.root(d)
1259                    && let Some(body) = pd.element(root, &W::body())
1260                {
1261                    let paras: Vec<NodeId> = pd
1262                        .elements(body, None)
1263                        .into_iter()
1264                        .filter(|&k| pd.name_is(k, &W::p()))
1265                        .collect();
1266                    let w14_pid = crate::namespaces::W14::name("paraId");
1267                    let target = paras.iter().enumerate().find(|&(i, &p)| {
1268                        i + 1 != paras.len() && pd.attribute(p, &w14_pid) == Some(bf.as_str())
1269                    });
1270                    if let Some((idx, &p)) = target {
1271                        let is_ins_empty = |pd: &Dom, q: NodeId| {
1272                            let mark_ins = pd
1273                                .element(q, &W::p_pr())
1274                                .and_then(|pr| pd.element(pr, &W::r_pr()))
1275                                .is_some_and(|r| pd.element(r, &W::ins()).is_some());
1276                            // A paragraph whose only content is a real embedded
1277                            // object (DrawingML image/shape, OLE object, a VML
1278                            // picture, a text box, or an AlternateContent shape)
1279                            // carries no w:t, but it is NOT empty — removing it
1280                            // drops the graphic (vrect_node × wmf_emf: B's final ¶
1281                            // is a full-page WMF, misjudged empty → whole page lost,
1282                            // 18.21). A BARE w:pict horizontal rule (o:hr `v:rect`,
1283                            // no imagedata/textbox) is decorative, not content, and
1284                            // must stay droppable — checking for the real content
1285                            // markers (not the w:pict wrapper) avoids regressing the
1286                            // trailing-hr-spacer pairs (sd_2517 hr rules).
1287                            let has_embedded = [
1288                                W::drawing(),
1289                                W::object(),
1290                                crate::namespaces::MC::name("AlternateContent"),
1291                                crate::namespaces::VML::name("imagedata"),
1292                                W::txbx_content(),
1293                                crate::namespaces::WNE::name("txbxContent"),
1294                            ]
1295                            .iter()
1296                            .any(|nm| !pd.descendants(q, Some(nm)).is_empty());
1297                            mark_ins
1298                                && !has_embedded
1299                                && !pd
1300                                    .descendants(q, Some(&W::t()))
1301                                    .iter()
1302                                    .any(|&t| !pd.value_str(t).trim().is_empty())
1303                                && pd.descendants(q, Some(&W::del_text())).is_empty()
1304                        };
1305                        // Run gate: Word trims B's final ¶ out of a RUN of
1306                        // inserted empties (h_f: three in a row, two kept);
1307                        // a LONE inserted empty spacer stays — Word keeps it
1308                        // under another identity (file_82 × file_83, M389:
1309                        // stripping it cost −18.9).
1310                        let prev_also_empty = idx > 0 && is_ins_empty(&pd, paras[idx - 1]);
1311                        if is_ins_empty(&pd, p) && prev_also_empty {
1312                            pd.remove(p);
1313                            out.set_part(&main1, pd.serialize_element(root).into_bytes());
1314                        }
1315                    }
1316                }
1317            }
1318        }
1319        // #1678: a table that replaced the body's last paragraph keeps the
1320        // revised document's empty close. After M491, which only removes a
1321        // misplaced copy of that paragraph.
1322        if let (Some(revised_xml), Some(produced_xml)) =
1323            (pkg2.part_string(&main2), out.part_string(&main1))
1324            && let Some(kept) =
1325                crate::comparer::finalize::keep_revised_empty_close(&produced_xml, &revised_xml)
1326        {
1327            out.set_part(&main1, kept.into_bytes());
1328        }
1329    }
1330
1331    // Word-parity: strip pStyle/rStyle that styles.xml does not define. LO maps
1332    // built-in names (Heading1, Title, …) even when the style entry is absent;
1333    // Word's redline omits the attribute entirely (heading_1_bold×heading_1_style).
1334    // An edit keeps the source's references as they are.
1335    if settings.merge_replaced_paragraphs && !settings.preserve_untouched {
1336        // POSTSTEP-STYLES-CACHE-01: reuse the defined-style-id set captured after
1337        // styles-copy instead of re-parsing word/styles.xml. Fall back to a fresh
1338        // parse only when styles-copy did not run (no output stylesheet).
1339        let defined = cached_defined_styles.clone().or_else(|| {
1340            out.part_string("word/styles.xml").map(|sx| {
1341                let mut sd = Dom::new();
1342                let doc = sd.parse_xdocument(&sx);
1343                sd.root(doc)
1344                    .map(|r| crate::comparer::footnotes::defined_style_ids(&sd, r))
1345                    .unwrap_or_default()
1346            })
1347        });
1348        if let Some(defined) = defined {
1349            // Main document + common related parts that can carry pStyle/rStyle.
1350            let mut part_names: Vec<String> = vec![main1.clone()];
1351            for p in out.parts() {
1352                let is_style_carrier = p.starts_with("word/header")
1353                    || p.starts_with("word/footer")
1354                    || p == "word/footnotes.xml"
1355                    || p == "word/endnotes.xml"
1356                    || p == "word/comments.xml"
1357                    || p.starts_with("word/comments");
1358                if is_style_carrier {
1359                    part_names.push(p);
1360                }
1361            }
1362            part_names.sort();
1363            part_names.dedup();
1364            for part in part_names {
1365                let Some(xml) = out.part_string(&part) else {
1366                    continue;
1367                };
1368                let mut pd = Dom::new();
1369                let doc = pd.parse_xdocument(&xml);
1370                let Some(root) = pd.root(doc) else {
1371                    continue;
1372                };
1373                let n = crate::comparer::footnotes::strip_unresolved_style_refs(
1374                    &mut pd, root, &defined,
1375                );
1376                if n > 0 {
1377                    out.set_part(&part, pd.serialize_element(root).into_bytes());
1378                }
1379            }
1380        }
1381    }
1382
1383    // M-PAG mechanism 2 (word mode): merged Normal style. Word's redline
1384    // stylesheet carries the REVISED document's effective Normal spacing with
1385    // a w:pPrChange recording the old value; ours (A-based) kept A's Normal
1386    // verbatim, diffusing ~1 page of drift per ~20 (sd-2517_sectpr-headerref:
1387    // 111 → 117 pages with this patch, GT 116). Provenance: when B's Normal
1388    // pPr is empty/absent, Word resolves it to FACTORY defaults
1389    // (after=160 line=278 lineRule=auto — matches neither side's docDefaults).
1390    // An edit's Normal is the source's.
1391    if settings.merge_replaced_paragraphs && !settings.preserve_untouched {
1392        // POSTSTEP-STYLES-CACHE-02: reuse the arena styles-copy already parsed;
1393        // fall back to a fresh parse of both stylesheets only when it did not run.
1394        let arena = styles_arena.take().or_else(|| {
1395            match (
1396                out.part_string("word/styles.xml"),
1397                pkg2.part_string("word/styles.xml"),
1398            ) {
1399                (Some(out_xml), Some(b_xml)) => {
1400                    let mut sd = Dom::new();
1401                    let od = sd.parse_xdocument(&out_xml);
1402                    let bd = sd.parse_xdocument(&b_xml);
1403                    match (sd.root(od), sd.root(bd)) {
1404                        (Some(or), Some(br)) => Some((sd, or, br)),
1405                        _ => None,
1406                    }
1407                }
1408                _ => None,
1409            }
1410        });
1411        if let Some((mut sd, or, br)) = arena {
1412            // Workstream S runs FIRST, while the output stylesheet still holds
1413            // A's definitions: `merge_normal_style_*` below rewrites Normal to
1414            // B's values, and every style based on Normal would then resolve its
1415            // "original" chain against the already-revised Normal.
1416            // S2: the styles A actually declared, by (type, name) — styles in
1417            // `or` beyond this set were copied from B and take the phase-2
1418            // docDefaults bake.
1419            let a_declared_keys: std::collections::HashSet<(String, String)> = pkg1
1420                .part_string("word/styles.xml")
1421                .map(|xml| {
1422                    let mut ad = Dom::new();
1423                    let doc = ad.parse_xdocument(&xml);
1424                    ad.root(doc)
1425                        .map(|r| {
1426                            ad.elements(r, Some(&W::name("style")))
1427                                .into_iter()
1428                                .filter_map(|s| style_match_key(&ad, s))
1429                                .collect()
1430                        })
1431                        .unwrap_or_default()
1432                })
1433                .unwrap_or_default();
1434            // Word leaves a style the revision's stylesheet lacks as the
1435            // original defines it, without a change record (51 of 51 accept
1436            // pairs), whatever Normal and the docDefaults become under it:
1437            // the passes below only see it to be put back.
1438            let a_styles = pkg1.part_string("word/styles.xml").and_then(|xml| {
1439                let doc = sd.parse_xdocument(&xml);
1440                sd.root(doc)
1441            });
1442            let inherited_only = a_styles.map_or_else(std::collections::HashSet::new, |a_root| {
1443                inherited_only_style_changes(&sd, or, a_root, br)
1444            });
1445            let only_a = styles_the_revision_lacks(&mut sd, or, br);
1446            let mut changed = merge_revised_style_definitions(
1447                &mut sd,
1448                or,
1449                br,
1450                settings,
1451                &a_declared_keys,
1452                &inherited_only,
1453            );
1454            changed |= merge_normal_style_spacing(&mut sd, or, br, settings);
1455            // M-PAG mechanism 2b / M71: rewrite Normal rPr to B's effective
1456            // metrics when they differ. Formerly gated on header/footer→Normal
1457            // (footer knife-edge). That skipped file_197 (no HF): Word writes
1458            // B's Calibri dd onto Normal + rPrChange(A Ubuntu); we kept A.
1459            // M65 still skips both-bare (file_170). HF-linked cases unchanged.
1460            changed |= merge_normal_style_rpr(&mut sd, or, br, settings);
1461            // M467: Word keeps only per-attr DELTAS vs the output docDefaults
1462            // on the merged Normal (tab_test × table_autofit: kern/szCs/
1463            // eastAsiaTheme/ligatures dropped as redundant, Arial+sz=20 kept).
1464            changed |= prune_normal_rpr_context_equal_attrs(&mut sd, or);
1465            // M480b: dd-delta disabling neutralizers on both-sides merged
1466            // styles — after the Normal merges (so a stamped Normal reads as
1467            // a provider), before M111 adds cascade records.
1468            changed |= bake_bothsides_dd_disabling_neutralizers(&mut sd, or, br);
1469            // M111: cascade Normal pPrChange/rPrChange onto basedOn=Normal styles
1470            // (ListParagraph/BodyText/Header/… — file_130 Word has ~30).
1471            changed |= cascade_normal_change_to_based_styles(&mut sd, or, settings);
1472            // M79: Word single-line on Heading/Title/ListParagraph (file_33 3→2pp).
1473            changed |= normalize_word_paragraph_style_line(&mut sd, or);
1474            // M80: Title/ListParagraph/Highlighted Arial + Heading Latin inherit.
1475            changed |= align_paragraph_style_fonts_with_normal(&mut sd, or);
1476            // Redefined styles take B's effective metrics as a delta against
1477            // the output context (Word's rule, mined over 4,924 styles). Runs
1478            // last so it settles what the heuristic passes above wrote.
1479            changed |= resolve_redefined_style_metrics(&mut sd, or, br);
1480            // Root styles record their old properties in full against the
1481            // docDefaults, the way Word's Reject All needs them.
1482            changed |= complete_root_style_change_records(&mut sd, or, settings);
1483            // Below the roots, the record carries what the original's chain
1484            // gave the style, which Reject All would otherwise read as built-in.
1485            if let Some(a_root) = a_styles {
1486                changed |= complete_based_style_change_records(&mut sd, or, a_root);
1487            }
1488            changed |= remove_inherited_only_style_records(&mut sd, &inherited_only);
1489            changed |= restore_styles(&mut sd, or, only_a);
1490            // M483: re-cache themed color hexes against the shipped theme —
1491            // must run AFTER the merge writes B's blocks (their w:val hexes
1492            // were cached under B's theme). The shipped theme is the one the
1493            // main part references, wherever it lives.
1494            if let Some(theme_xml) =
1495                referenced_theme_part(&out, &main1).and_then(|p| out.part_string(&p))
1496            {
1497                changed |= reresolve_theme_color_hexes(&mut sd, or, &theme_xml);
1498            }
1499            if changed {
1500                out.set_part("word/styles.xml", sd.serialize_element(or).into_bytes());
1501            }
1502            // M487 — bake B-effective paragraph spacing onto B-INSERTED
1503            // paragraphs. The output ships A's docDefaults, so an inserted
1504            // paragraph styled by B renders with the wrong spacing unless its
1505            // pPr carries B's effective values directly. Word synthesizes
1506            // exactly this (rstyle_combos × pre_separated_list oracle: every
1507            // inserted ListParagraph gains `w:spacing w:after="0" w:line=
1508            // "240" w:lineRule="auto"` that B's source never declared;
1509            // content-ceiling for the pair 44.83 → 100.00). The M480
1510            // neutralizer principle at the document.xml level.
1511            {
1512                let index = |dom: &Dom,
1513                             root: NodeId|
1514                 -> std::collections::HashMap<String, NodeId> {
1515                    dom.elements(root, Some(&W::name("style")))
1516                        .into_iter()
1517                        .filter_map(|s| Some((dom.attribute(s, &W::style_id())?.to_string(), s)))
1518                        .collect()
1519                };
1520                let out_idx = index(&sd, or);
1521                let b_idx = index(&sd, br);
1522                // B's counterpart of an output style id: the style of the same
1523                // (type, name), as Word pairs them — ids name nothing across
1524                // documents (b4cd671041's revision calls List Paragraph
1525                // `Listaszerbekezds` and Table Grid `Rcsostblzat`).
1526                let mut b_by_key: std::collections::HashMap<(String, String), String> =
1527                    std::collections::HashMap::new();
1528                for s in sd.elements(br, Some(&W::name("style"))) {
1529                    if let (Some(k), Some(id)) =
1530                        (style_match_key(&sd, s), sd.attribute(s, &W::style_id()))
1531                    {
1532                        b_by_key.entry(k).or_insert_with(|| id.to_string());
1533                    }
1534                }
1535                let b_id_for = |out_id: &str| -> Option<String> {
1536                    out_idx
1537                        .get(out_id)
1538                        .and_then(|&s| style_match_key(&sd, s))
1539                        .and_then(|k| b_by_key.get(&k).cloned())
1540                        .or_else(|| b_idx.contains_key(out_id).then(|| out_id.to_string()))
1541                };
1542                let (b_default, out_default) = {
1543                    let dp = |dom: &Dom, root: NodeId| -> Option<String> {
1544                        dom.elements(root, Some(&W::name("style")))
1545                            .into_iter()
1546                            .find(|&s| {
1547                                dom.attribute(s, &W::type_()) == Some("paragraph")
1548                                    && matches!(
1549                                        dom.attribute(s, &W::name("default")),
1550                                        Some("1") | Some("true")
1551                                    )
1552                            })
1553                            .and_then(|s| dom.attribute(s, &W::style_id()).map(str::to_string))
1554                    };
1555                    (dp(&sd, br), dp(&sd, or))
1556                };
1557                if let Some(doc_xml) = out.part_string(&main1) {
1558                    let mut pd = Dom::new();
1559                    let dd = pd.parse_xdocument(&doc_xml);
1560                    if let Some(droot) = pd.root(dd) {
1561                        let mut doc_changed = false;
1562                        for p in pd.descendants(droot, Some(&W::p())) {
1563                            let Some(ppr) = pd.element(p, &W::p_pr()) else {
1564                                continue;
1565                            };
1566                            let mark_inserted = pd
1567                                .element(ppr, &W::r_pr())
1568                                .is_some_and(|r| pd.element(r, &W::ins()).is_some());
1569                            // A container's last paragraph keeps its mark when
1570                            // a paragraph is added after it, so the new words
1571                            // end on the old mark, under a record of its old
1572                            // properties (#1669): every word inserted, that
1573                            // paragraph is B's as much as an inserted one, and
1574                            // Reject All restores the record whatever is baked.
1575                            let words_inserted = || {
1576                                let words = pd.descendants(p, Some(&W::t()));
1577                                !words.is_empty()
1578                                    && pd.element(ppr, &W::p_pr_change()).is_some()
1579                                    && words.iter().all(|&t| {
1580                                        pd.ancestors(t, Some(&W::ins())).first().is_some_and(
1581                                            |&ins| {
1582                                                pd.ancestors(ins, Some(&W::p())).first() == Some(&p)
1583                                            },
1584                                        )
1585                                    })
1586                            };
1587                            if !mark_inserted && !words_inserted() {
1588                                continue;
1589                            }
1590                            // EMPTY inserted paragraphs keep their bare pPr —
1591                            // the oracle never bakes spacing onto them, and the
1592                            // empty line's default height decides the page
1593                            // break (rstyle_combos: baking onto the one empty
1594                            // separator para cost the whole second page,
1595                            // 98.18 → 44.70).
1596                            let has_text = pd
1597                                .descendants(p, Some(&W::t()))
1598                                .iter()
1599                                .any(|&t| !pd.value_str(t).trim().is_empty());
1600                            if !has_text {
1601                                continue;
1602                            }
1603                            // STYLED OR NUMBERED paragraphs only: the oracle
1604                            // bakes pStyle'd paras and pStyle-less LIST paras
1605                            // (numPr present — rstyle "List item 2"/"Back"),
1606                            // never truly-bare ones (m370 title;
1607                            // tiff×h_f_normal regressed −56 when its 52 bare
1608                            // inserted paras took the bake).
1609                            let pstyle = pd
1610                                .element(ppr, &W::p_style())
1611                                .and_then(|ps| pd.attribute(ps, &W::val()))
1612                                .map(str::to_string);
1613                            let has_numpr = pd.element(ppr, &W::num_pr()).is_some();
1614                            if pstyle.is_none() && !has_numpr {
1615                                continue;
1616                            }
1617                            let (Some(out_style), Some(b_style)) = (match pstyle {
1618                                Some(id) => (Some(id.clone()), b_id_for(&id)),
1619                                None => (out_default.clone(), b_default.clone()),
1620                            }) else {
1621                                continue; // style not from B — no B-effective target
1622                            };
1623                            // The innermost table's style, on each side.
1624                            let out_table = pd
1625                                .ancestors(p, Some(&W::tbl()))
1626                                .first()
1627                                .and_then(|&t| pd.element(t, &W::tbl_pr()))
1628                                .and_then(|t| pd.element(t, &W::name("tblStyle")))
1629                                .and_then(|t| pd.attribute(t, &W::val()))
1630                                .map(str::to_string);
1631                            let b_table = out_table.as_deref().and_then(b_id_for);
1632                            let (b_eff, b_declared, _) = effective_para_spacing(
1633                                &sd,
1634                                br,
1635                                &b_idx,
1636                                &b_style,
1637                                b_table.as_deref(),
1638                            );
1639                            let (o_eff, _, _) = effective_para_spacing(
1640                                &sd,
1641                                or,
1642                                &out_idx,
1643                                &out_style,
1644                                out_table.as_deref(),
1645                            );
1646                            if b_eff == o_eff {
1647                                continue;
1648                            }
1649                            let sp = pd.element(ppr, &W::spacing_el());
1650                            let attr_names = ["after", "before", "line", "lineRule"];
1651                            let mut to_write: Vec<(usize, String)> = Vec::new();
1652                            for i in 0..4 {
1653                                if b_eff[i] == o_eff[i] || b_declared[i] {
1654                                    continue;
1655                                }
1656                                let declared = sp.is_some_and(|s| {
1657                                    pd.attribute(s, &W::name(attr_names[i])).is_some()
1658                                });
1659                                if !declared {
1660                                    to_write.push((i, b_eff[i].clone()));
1661                                }
1662                            }
1663                            // line without lineRule renders as exact twips —
1664                            // carry the rule whenever line is written.
1665                            if to_write.iter().any(|(i, _)| *i == 2)
1666                                && !to_write.iter().any(|(i, _)| *i == 3)
1667                                && !sp.is_some_and(|s| {
1668                                    pd.attribute(s, &W::name("lineRule")).is_some()
1669                                })
1670                            {
1671                                to_write.push((3, b_eff[3].clone()));
1672                            }
1673                            if to_write.is_empty() {
1674                                continue;
1675                            }
1676                            let sp = match sp {
1677                                Some(s) => s,
1678                                None => {
1679                                    let s = pd.new_element(W::spacing_el());
1680                                    insert_child_by_rank(
1681                                        &mut pd,
1682                                        ppr,
1683                                        s,
1684                                        "spacing",
1685                                        &ppr_child_rank,
1686                                    );
1687                                    s
1688                                }
1689                            };
1690                            for (i, v) in to_write {
1691                                pd.set_attribute_value(sp, &W::name(attr_names[i]), Some(&v));
1692                                doc_changed = true;
1693                            }
1694                        }
1695                        if doc_changed {
1696                            out.set_part(&main1, pd.serialize_element(droot).into_bytes());
1697                        }
1698                    }
1699                }
1700            }
1701        }
1702    }
1703
1704    // Word-mode repair: Word synthesizes a default numbering definition when
1705    // the document references a numId no w:num defines — dangling numbering
1706    // silently renders lists as plain paragraphs; Word repairs it on open, so
1707    // match it at compare time (evidence: nested-table-rowspan_numbered-list).
1708    // An edit leaves the source's numbering as Word opens it.
1709    if settings.merge_replaced_paragraphs && !settings.preserve_untouched {
1710        let num_id = W::name("numId");
1711        let mut referenced: Vec<String> = Vec::new();
1712        let mut seen = std::collections::HashSet::new();
1713        for np in dom.descendants(result_root, Some(&W::num_pr())) {
1714            // numeric guard: ST_DecimalNumber ids only — also keeps the
1715            // synthesized w:num XML injection-proof (ids are interpolated
1716            // into a template downstream)
1717            if let Some(nid) = dom.element(np, &num_id)
1718                && let Some(v) = dom.attribute(nid, &W::val())
1719                && v != "0"
1720                && v.parse::<u32>().is_ok()
1721                && seen.insert(v.to_string())
1722            {
1723                referenced.push(v.to_string());
1724            }
1725        }
1726        if !referenced.is_empty() {
1727            let existing = out.part_string("word/numbering.xml");
1728            let mut nd = Dom::new();
1729            let (nroot, part_was_missing) = match &existing {
1730                Some(xml) => {
1731                    let d = nd.parse_xdocument(xml);
1732                    (nd.root(d), false)
1733                }
1734                None => {
1735                    let d = nd.parse_xdocument(&format!(
1736                        "<w:numbering xmlns:w=\"{}\"></w:numbering>",
1737                        W::URI
1738                    ));
1739                    (nd.root(d), true)
1740                }
1741            };
1742            if let Some(nroot) = nroot {
1743                let defined: std::collections::HashSet<String> = nd
1744                    .elements(nroot, Some(&W::name("num")))
1745                    .into_iter()
1746                    .filter_map(|e| nd.attribute(e, &num_id).map(|s| s.to_string()))
1747                    .collect();
1748                let dangling: Vec<String> = referenced
1749                    .into_iter()
1750                    .filter(|r| !defined.contains(r))
1751                    .collect();
1752                if !dangling.is_empty() {
1753                    crate::comparer::footnotes::synthesize_dangling_numbering(
1754                        &mut nd, nroot, &dangling,
1755                    );
1756                    out.set_part(
1757                        "word/numbering.xml",
1758                        nd.serialize_element(nroot).into_bytes(),
1759                    );
1760                    if part_was_missing {
1761                        out.add_content_type_override(
1762                            "/word/numbering.xml",
1763                            "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml",
1764                        );
1765                        let has_rel = out.read_rels_for(&main1).is_some_and(|r| {
1766                            r.items.iter().any(|i| i.rel_type.ends_with("/numbering"))
1767                        });
1768                        if !has_rel {
1769                            out.add_document_relationship(
1770                                &main1,
1771                                "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",
1772                                "numbering.xml",
1773                            );
1774                        }
1775                    }
1776                }
1777            }
1778        }
1779    }
1780
1781    // B.4 — write the rectified withRevisions notes parts (separators +
1782    // referenced definitions renumbered 1..n with real revision markup) into
1783    // the output package. Replaces the old by-id `compare_note_parts` model,
1784    // whose pairing broke whenever Word renumbered notes.
1785    //
1786    // Remap style refs on notes_ctx *before* serialize/writeback so B.4 does
1787    // not clobber an earlier styles pass with un-remapped note content.
1788    if settings.merge_replaced_paragraphs && !style_renames.is_empty() {
1789        for note_root in [notes_ctx.fn_with_revisions, notes_ctx.en_with_revisions]
1790            .into_iter()
1791            .flatten()
1792        {
1793            remap_style_refs(&mut dom, note_root, &style_renames);
1794        }
1795    }
1796    let mut footnote_ids: std::collections::HashSet<String> = std::collections::HashSet::new();
1797    let mut endnote_ids: std::collections::HashSet<String> = std::collections::HashSet::new();
1798    for (part, root, is_fn) in [
1799        (fn1.as_str(), notes_ctx.fn_with_revisions, true),
1800        (en1.as_str(), notes_ctx.en_with_revisions, false),
1801    ] {
1802        if let Some(r) = root {
1803            if union_permissions {
1804                crate::comparer::bookmarks::carry_permission_union(
1805                    &mut dom,
1806                    r,
1807                    (&pkg1, part),
1808                    (&pkg2, if is_fn { &fn2 } else { &en2 }),
1809                    &settings.author_for_revisions,
1810                );
1811            }
1812            let def = if is_fn { W::footnote() } else { W::endnote() };
1813            let ids: std::collections::HashSet<String> = dom
1814                .elements(r, Some(&def))
1815                .into_iter()
1816                .filter_map(|n| dom.attribute(n, &W::id()).map(str::to_string))
1817                .collect();
1818            if is_fn {
1819                footnote_ids = ids;
1820            } else {
1821                endnote_ids = ids;
1822            }
1823            out.set_part(part, dom.serialize_element(r).into_bytes());
1824        }
1825    }
1826    // M379: after B.4 notes writeback — if A had no separators, B.4 left empty
1827    // shells or skipped; copy B's separator/continuationSeparator notes.
1828    if settings.merge_replaced_paragraphs {
1829        adopt_b_notes_when_a_lacks_separators(&mut out, &pkg1, &pkg2, &main1);
1830    }
1831    // An edit leaves no empty notes part the source did not have: the one
1832    // preprocessing added held nothing the plan wrote.
1833    if settings.preserve_untouched {
1834        for (had, ids, kind) in [
1835            (original_notes.0, &footnote_ids, "footnotes"),
1836            (original_notes.1, &endnote_ids, "endnotes"),
1837        ] {
1838            if had || !ids.is_empty() {
1839                continue;
1840            }
1841            let rel_type = format!(
1842                "http://schemas.openxmlformats.org/officeDocument/2006/relationships/{kind}"
1843            );
1844            let rel_ids: Vec<String> = out
1845                .read_rels_for(&main1)
1846                .map(|rels| {
1847                    rels.items
1848                        .iter()
1849                        .filter(|r| r.rel_type == rel_type)
1850                        .map(|r| r.id.clone())
1851                        .collect()
1852                })
1853                .unwrap_or_default();
1854            for id in rel_ids {
1855                out.remove_related_part(&main1, &id);
1856            }
1857        }
1858    }
1859    // settings.xml may still list special footnote/endnote ids (e.g. id=1
1860    // continuationNotice) that rectify dropped. Dangling settings refs make
1861    // Word show "unreadable content" (OpenXmlValidator Semantic).
1862    if let Some(sx) = out.part_string("word/settings.xml") {
1863        let mut sd = Dom::new();
1864        let sdoc = sd.parse_xdocument(&sx);
1865        if let Some(sroot) = sd.root(sdoc) {
1866            crate::comparer::footnotes::sync_settings_special_note_ids(
1867                &mut sd,
1868                sroot,
1869                &footnote_ids,
1870                &endnote_ids,
1871            );
1872            out.set_part(
1873                "word/settings.xml",
1874                sd.serialize_element(sroot).into_bytes(),
1875            );
1876        }
1877    }
1878    // M4.H.x: header/footer CONTENT diff (Word redlines header/footer changes; we
1879    // previously only copied the original's). Match A's parts to B's by reference
1880    // (kind,type), diff the content and write the redline into the output's
1881    // (original's) part. Neutralize dangling references on both sides and
1882    // carry B's valid references into A's rels before diffing. A failed story
1883    // comparison must refuse the package, never silently retain A (#1709).
1884    {
1885        let (sections_a, refs_a) = header_footer_refs_by_section(&pkg1);
1886        let (sections_b, refs_b) = header_footer_refs_by_section(&pkg2);
1887        let pairing = out
1888            .part_string(&main1)
1889            .and_then(|x| section_pairing(&x, sections_a, sections_b));
1890        let own_slots: std::collections::HashSet<(usize, String, String)> = refs_a
1891            .iter()
1892            .map(|(s, k, t, _)| (*s, k.clone(), t.clone()))
1893            .collect();
1894        let mut ordinals: std::collections::HashMap<(String, String), usize> =
1895            std::collections::HashMap::new();
1896        let mut diffed = std::collections::HashSet::new();
1897        for (section_a, kind, ty, part_a) in refs_a {
1898            let ordinal = ordinals.entry((kind.clone(), ty.clone())).or_default();
1899            let at = *ordinal;
1900            *ordinal += 1;
1901            if !diffed.insert(part_a.clone()) {
1902                continue;
1903            }
1904            // The part also shows in the later sections that inherit it:
1905            // the first whose break survives says what it became (Word
1906            // probe hs5 diffs a deleted section's header that the last
1907            // section inherits).
1908            let section = pairing.as_ref().map(|p| {
1909                (section_a..p.len())
1910                    .take_while(|&s| {
1911                        s == section_a || !own_slots.contains(&(s, kind.clone(), ty.clone()))
1912                    })
1913                    .find_map(|s| p[s])
1914            });
1915            let Some(part_b) =
1916                pair_header_footer(&pkg1, &pkg2, &refs_b, (&kind, &ty, &part_a), at, section)
1917            else {
1918                continue;
1919            };
1920            let part_b = &part_b;
1921            {
1922                let xa = pkg1.part_string(&part_a).ok_or_else(|| {
1923                    story_diff_error(&part_a, "original story XML is unavailable")
1924                })?;
1925                let xb = pkg2
1926                    .part_string(part_b)
1927                    .ok_or_else(|| story_diff_error(part_b, "revised story XML is unavailable"))?;
1928                let xa = neutralize_story_relationships(&pkg1, &part_a, &xa)?;
1929                let xb = neutralize_story_relationships(&pkg2, part_b, &xb)?;
1930                // B's references that mean something else in A's part (both
1931                // headers picture their own logo as rId1) move to fresh ids.
1932                let xb = if part_rels_agree((&pkg1, &part_a), (&pkg2, part_b), &xb) {
1933                    xb
1934                } else {
1935                    carry_revised_part_relationships(&mut out, &part_a, (&pkg2, part_b), &xb)
1936                        .ok_or_else(|| {
1937                            story_diff_error(part_b, "cannot carry revised story relationships")
1938                        })?
1939                };
1940                let mut hd = Dom::new();
1941                let da = hd.parse_xdocument(&xa);
1942                let db = hd.parse_xdocument(&xb);
1943                let ra = hd.root(da).ok_or_else(|| {
1944                    story_diff_error(&part_a, "original story has no root element")
1945                })?;
1946                let rb = hd
1947                    .root(db)
1948                    .ok_or_else(|| story_diff_error(part_b, "revised story has no root element"))?;
1949                let container_name = if kind == "header" { W::hdr() } else { W::ftr() };
1950                for (root, part) in [(ra, part_a.as_str()), (rb, part_b.as_str())] {
1951                    if !hd.name_is(root, &container_name) {
1952                        return Err(story_diff_error(part, "unexpected story root element"));
1953                    }
1954                    refuse_unatomizable(&hd, root, part)?;
1955                    refuse_past_story_budget(story_units(&hd, root), part, settings.input_limits)?;
1956                }
1957                {
1958                    let text_of = |d: &Dom, n: crate::xmllinq::NodeId| -> String {
1959                        d.descendants(n, Some(&W::t()))
1960                            .into_iter()
1961                            .map(|t| d.value(t))
1962                            .collect()
1963                    };
1964                    // capture BEFORE the compare mutates the arena
1965                    let a_text = text_of(&hd, ra);
1966                    let b_text = text_of(&hd, rb);
1967                    let b_ends_with_table = hd
1968                        .elements(rb, None)
1969                        .last()
1970                        .is_some_and(|&e| hd.name_is(e, &W::tbl()));
1971                    let res = compare_bodies_faithful(&mut hd, ra, rb, ra, rb, settings);
1972                    // compare_bodies_faithful always rebuilds into
1973                    // <w:document><w:body>…</w:body></w:document>, even when the
1974                    // source roots are w:hdr / w:ftr. Looking for a nested
1975                    // hdr/ftr under that wrapper is dead (PR #81 / kilo): re-wrap
1976                    // the body children as the original container type so the
1977                    // redlined part stays a valid header/footer part.
1978                    let out_body = hd.element(res, &W::body()).ok_or_else(|| {
1979                        story_diff_error(&part_a, "story comparison produced no body")
1980                    })?;
1981                    let container = hd.new_element(container_name);
1982                    // Preserve source-root namespace decls (w already on body
1983                    // children; copy any extras from A's original root).
1984                    let xmlns_ns = crate::xmllinq::XNamespace::xmlns();
1985                    for (an, av) in hd.attributes(ra) {
1986                        if an.namespace_name() == xmlns_ns.namespace_name()
1987                            || an.local_name() == "Ignorable"
1988                        {
1989                            hd.set_attribute_value(container, &an, Some(&av));
1990                        }
1991                    }
1992                    // Body-level sectPr is document geometry from the
1993                    // compare_bodies_faithful wrap — not valid inside hdr/ftr.
1994                    for c in hd.elements(out_body, None) {
1995                        if hd.name(c) == Some(W::sect_pr()) {
1996                            continue;
1997                        }
1998                        hd.remove(c);
1999                        hd.add(container, c);
2000                    }
2001                    if b_ends_with_table {
2002                        delete_story_closing_mark(&mut hd, container, settings);
2003                    }
2004                    if union_permissions {
2005                        crate::comparer::bookmarks::carry_permission_union(
2006                            &mut hd,
2007                            container,
2008                            (&pkg1, &part_a),
2009                            (&pkg2, part_b),
2010                            &settings.author_for_revisions,
2011                        );
2012                    }
2013                    // A changed story with no revision marks is not a redline.
2014                    // The old M-PAG guard silently kept A when this failed;
2015                    // refuse instead, including when the diff lost B's text.
2016                    let redlined = hd.serialize_element(container);
2017                    let has_revisions =
2018                        crate::revision_processor::xml_has_tracked_revisions(&redlined);
2019                    ensure_story_text_tracked(
2020                        &part_a,
2021                        &a_text,
2022                        &b_text,
2023                        &text_of(&hd, container),
2024                        has_revisions,
2025                    )?;
2026                    out.set_part(&part_a, redlined.into_bytes());
2027                }
2028            }
2029        }
2030    }
2031
2032    // Every other part resolves its own r:* references too (B's comments, notes,
2033    // headers/footers and picture bullets arrive without B's per-part rels).
2034    crate::comparer::parts::reconcile_part_relationships(&mut out, &main1, &pkg1, &pkg2);
2035    // …and every copied part keeps the content type its source declared (a B
2036    // header's `.wdp` HD Photo arrived without B's `wdp` Default).
2037    out.adopt_missing_content_types(&[&pkg2, &pkg1]);
2038
2039    // Strict/ISO OOXML: when the original is Strict, the output package would mix
2040    // a Transitional comparison-result document.xml with Strict styles/numbering/
2041    // rels (and copied-in Transitional styles) — an invalid mixed package. Make
2042    // the whole package consistently Transitional. No-op for Transitional packages.
2043    for part in out.parts() {
2044        if !(part.ends_with(".xml") || part.ends_with(".rels")) {
2045            continue;
2046        }
2047        if let Some(s) = out.part_string(&part)
2048            && s.contains("purl.oclc.org/ooxml/")
2049        {
2050            let n = normalize_strict_namespaces(&s).into_owned();
2051            out.set_part(&part, n.into_bytes());
2052        }
2053    }
2054    sweep_part_validity(
2055        &mut out,
2056        &main1,
2057        Some(&ComparisonSweep {
2058            original: &pkg1,
2059            settings,
2060            ladder_sources: ladder_sources.as_ref(),
2061        }),
2062    );
2063    // Final package-level notes↔settings coherence (after the validity sweep
2064    // re-serialized those parts). Dangling special-note ids in settings are a
2065    // package bug, not a document.xml bug.
2066    {
2067        let collect_ids = |part: &str, local: &str| -> std::collections::HashSet<String> {
2068            let mut set = std::collections::HashSet::new();
2069            let Some(x) = out.part_string(part) else {
2070                return set;
2071            };
2072            let mut d = Dom::new();
2073            let doc = d.parse_xdocument(&x);
2074            let Some(root) = d.root(doc) else {
2075                return set;
2076            };
2077            let name = W::name(local);
2078            for n in d.elements(root, Some(&name)) {
2079                if let Some(id) = d.attribute(n, &W::id()) {
2080                    set.insert(id.to_string());
2081                }
2082            }
2083            set
2084        };
2085        let fn_ids = collect_ids("word/footnotes.xml", "footnote");
2086        let en_ids = collect_ids("word/endnotes.xml", "endnote");
2087        if let Some(sx) = out.part_string("word/settings.xml") {
2088            let mut sd = Dom::new();
2089            let sdoc = sd.parse_xdocument(&sx);
2090            if let Some(sroot) = sd.root(sdoc) {
2091                crate::comparer::footnotes::sync_settings_special_note_ids(
2092                    &mut sd, sroot, &fn_ids, &en_ids,
2093                );
2094                out.set_part(
2095                    "word/settings.xml",
2096                    sd.serialize_element(sroot).into_bytes(),
2097                );
2098            }
2099        }
2100    }
2101    // A header or footer of the original whose slots the revised section
2102    // breaks took over (redlineB_* parts) is left with no reference: Word's
2103    // own redlines carry none, and its half-matched fields read as broken.
2104    crate::revision_processor::drop_unreferenced_headers_footers(&mut out);
2105    isolate_shared_drawing_stories(&mut out, &main1);
2106    number_doc_prs_in_package(&mut out, &main1, settings.preserve_untouched);
2107    out.to_zip()
2108}
2109
2110/// The relationship types whose parts are WordprocessingML stories that can
2111/// hold drawings beside the main document.
2112#[doc(hidden)]
2113pub const DRAWING_STORY_REL_SUFFIXES: [&str; 5] =
2114    ["/header", "/footer", "/footnotes", "/endnotes", "/comments"];
2115
2116/// The package-wide drawing-id repair compare ends with, for `validate
2117/// --repair`: a shared header or footer with drawings gets one copy per
2118/// further section, then every story's `wp:docPr` ids are numbered in one
2119/// space. `preserve_untouched` keeps first holders' ids.
2120#[doc(hidden)]
2121pub fn fix_up_drawing_ids_across_package(pkg: &mut PartFs, preserve_untouched: bool) {
2122    let main = pkg
2123        .main_document_part()
2124        .unwrap_or_else(|| "word/document.xml".to_string());
2125    isolate_shared_drawing_stories(pkg, &main);
2126    number_doc_prs_in_package(pkg, &main, preserve_untouched);
2127}
2128
2129/// The main document's header, footer, notes and comments parts, sorted.
2130#[doc(hidden)]
2131pub fn drawing_story_parts(pkg: &PartFs, main: &str) -> Vec<String> {
2132    let Some(rels) = pkg.read_rels_for(main) else {
2133        return Vec::new();
2134    };
2135    let mut related: Vec<String> = rels
2136        .items
2137        .iter()
2138        .filter(|r| r.target_mode.as_deref() != Some("External"))
2139        .filter(|r| {
2140            DRAWING_STORY_REL_SUFFIXES
2141                .iter()
2142                .any(|s| r.rel_type.ends_with(s))
2143        })
2144        .map(|r| referenced_part(pkg, main, &r.target))
2145        .filter(|n| n != main)
2146        .collect();
2147    related.sort();
2148    related.dedup();
2149    related
2150}
2151
2152/// Word loads a header or footer once for every section that references it,
2153/// so a part with drawings that two sections share repeats its drawings'
2154/// `wp:docPr` ids, and Word refuses the package (7c98e8f2b6 and c04ae787d4,
2155/// remote Word 2024, 2026-11-23; a copy with fresh ids opens). Word itself
2156/// never writes such a share. Give each further section its own copy of a
2157/// shared part that has drawings; [`number_doc_prs_in_package`] then
2158/// numbers the copy's drawings apart from the original's.
2159fn isolate_shared_drawing_stories(out: &mut PartFs, main: &str) {
2160    let Some(xml) = out.part_string(main) else {
2161        return;
2162    };
2163    let Some(rels) = out.read_rels_for(main) else {
2164        return;
2165    };
2166    let rels: std::collections::HashMap<String, (String, String)> = rels
2167        .items
2168        .iter()
2169        .map(|r| (r.id.clone(), (r.rel_type.clone(), r.target.clone())))
2170        .collect();
2171    let mut dom = Dom::new();
2172    let doc = dom.parse_xdocument(&xml);
2173    let Some(root) = dom.root(doc) else {
2174        return;
2175    };
2176    let mut seen = std::collections::HashSet::new();
2177    let mut changed = false;
2178    for sect in section_props(&dom, root) {
2179        let references: Vec<NodeId> = dom
2180            .elements(sect, None)
2181            .into_iter()
2182            .filter(|&r| {
2183                dom.name_is(r, &W::header_reference()) || dom.name_is(r, &W::footer_reference())
2184            })
2185            .collect();
2186        for reference in references {
2187            let Some(rid) = dom.attribute(reference, &R::id()).map(str::to_string) else {
2188                continue;
2189            };
2190            if seen.insert(rid.clone()) {
2191                continue;
2192            }
2193            let Some((rel_type, target)) = rels.get(&rid) else {
2194                continue;
2195            };
2196            let part = referenced_part(out, main, target);
2197            let Some(bytes) = out.part_bytes(&part).map(<[u8]>::to_vec) else {
2198                continue;
2199            };
2200            if !bytes.windows(6).any(|w| w == b":docPr") {
2201                continue;
2202            }
2203            let copy = unused_sibling_part_name(out, &part);
2204            out.set_part(&copy, bytes);
2205            if let Some(part_rels) = out.read_rels_for(&part)
2206                && let Ok(rels_xml) = part_rels.to_xml()
2207            {
2208                out.set_part(&rels_part_name(&copy), rels_xml);
2209            }
2210            if let Some(content_type) = out.content_type_for(&part) {
2211                out.add_content_type_override(&copy, &content_type);
2212            }
2213            let copy_target = crate::opc::relative_rel_target(main, &copy);
2214            let copy_rid = out.add_document_relationship(main, rel_type, &copy_target);
2215            dom.set_attribute_value(reference, &R::id(), Some(&copy_rid));
2216            changed = true;
2217        }
2218    }
2219    if changed {
2220        out.set_part(main, dom.serialize_element(root).into_bytes());
2221    }
2222}
2223
2224/// `word/header3.xml` → the first `word/header3_N.xml` no part has.
2225fn unused_sibling_part_name(out: &PartFs, part: &str) -> String {
2226    let stem = part.strip_suffix(".xml").unwrap_or(part);
2227    (1u32..)
2228        .map(|n| format!("{stem}_{n}.xml"))
2229        .find(|name| out.part_bytes(name).is_none())
2230        .unwrap_or_else(|| format!("{stem}_copy.xml"))
2231}
2232
2233/// `word/header3.xml` → `word/_rels/header3.xml.rels`.
2234fn rels_part_name(part: &str) -> String {
2235    match part.rsplit_once('/') {
2236        Some((dir, file)) => format!("{dir}/_rels/{file}.rels"),
2237        None => format!("_rels/{part}.rels"),
2238    }
2239}
2240
2241/// Number the drawings of the main document and of every header, footer,
2242/// footnotes, endnotes and comments part it relates in one id space: each
2243/// part was numbered from 1 on its own, and Word refuses a package whose
2244/// header drawing repeats a body drawing's `wp:docPr` id (14 jubarte 0.19.0
2245/// redlines, remote Word 2024, 2026-11-23).
2246fn number_doc_prs_in_package(out: &mut PartFs, main: &str, preserve_untouched: bool) {
2247    let mut names = vec![main.to_string()];
2248    names.extend(drawing_story_parts(out, main));
2249    let mut parts = Vec::new();
2250    let mut kept = Vec::new();
2251    for name in names {
2252        let Some(xml) = out.part_string(&name) else {
2253            continue;
2254        };
2255        let mut dom = Dom::new();
2256        let doc = dom.parse_xdocument(&xml);
2257        if let Some(root) = dom.root(doc) {
2258            parts.push((dom, root));
2259            kept.push(name);
2260        }
2261    }
2262    let changed =
2263        crate::comparer::fixups::number_doc_prs_across_parts(&mut parts, preserve_untouched);
2264    for ((name, (dom, root)), changed) in kept.iter().zip(&parts).zip(changed) {
2265        if changed {
2266            out.set_part(name, dom.serialize_element(*root).into_bytes());
2267        }
2268    }
2269}
2270
2271/// The inherited-shape repairs and schema-order pass every package we build
2272/// gets (#1712, #1796): an identical compare's output and, since #1717, a
2273/// standalone accept's or reject's.
2274fn repair_resolved_package_validity(pkg: &mut PartFs) {
2275    let main = pkg
2276        .main_document_part()
2277        .unwrap_or_else(|| "word/document.xml".to_string());
2278    sweep_part_validity(pkg, &main, None);
2279}
2280
2281/// Identical inputs need repairs, not the chrome of a newly produced redline.
2282/// Work on the admitted package directly: serializing drawing repairs and then
2283/// reopening them would incorrectly apply input limits to our expanded output.
2284fn finalize_identical_compare(
2285    bytes: &[u8],
2286    settings: &WmlComparerSettings,
2287) -> Result<Vec<u8>, OpcError> {
2288    let mut out = PartFs::open_within(bytes, settings.input_limits)?;
2289    let main = out
2290        .main_document_part()
2291        .unwrap_or_else(|| "word/document.xml".to_string());
2292    let xml = out
2293        .part_string(&main)
2294        .ok_or_else(|| OpcError::PartNotFound(format!("main document missing: {main}")))?;
2295    let mut dom = Dom::new();
2296    let doc = dom.parse_xdocument(&xml);
2297    if dom.root(doc).is_none() {
2298        return Err(OpcError::PartNotFound(format!(
2299            "main document has no root element: {main}"
2300        )));
2301    }
2302    repair_resolved_package_validity(&mut out);
2303    out.to_zip()
2304}
2305
2306/// Context available only when comparison has actually produced a redline.
2307struct ComparisonSweep<'a> {
2308    original: &'a PartFs,
2309    settings: &'a WmlComparerSettings,
2310    ladder_sources: Option<&'a (String, String)>,
2311}
2312
2313/// Repairs run at every successful exit. Comparison cleanup is interleaved
2314/// only on the full path, in exactly its original order (#1796).
2315fn sweep_part_validity(out: &mut PartFs, main: &str, comparison: Option<&ComparisonSweep<'_>>) {
2316    // Word-validity normalization on every validity-swept content part — NOT
2317    // document.xml alone. Word opens the package (headers/footers/notes/
2318    // settings/styles/rels/content-types); a clean body with a corrupt notes
2319    // or settings part still raises "unreadable content".
2320    //
2321    // (validator sweep: 146/166 outputs carried schema errors Word's own
2322    // redlines don't): canonicalize universal measures / fractional ints,
2323    // fix Strict artifacts (cnfStyle bitmask, wp14 percents, out-of-range
2324    // paraIds), and strip pt:* scratch so headers/notes don't ship Unids.
2325    // Scope notes: `word/charts/` (DrawingML) and `word/theme/` are included
2326    // ON PURPOSE — the Strict percent→per-thousand rewrite covers drawingml
2327    // namespaces; `word/media/*.xml` is vacuous for binary payloads.
2328    // Custom XML data holds the application's own XML whatever its name
2329    // (`word/headerData.xml`), so no sweep below touches it (#1680).
2330    let custom_data = {
2331        let parts = out.parts();
2332        crate::opc::custom_xml_data(std::iter::once(("", out.package_relationships())).chain(
2333            parts.iter().filter_map(|source| {
2334                out.read_rels_for(source)
2335                    .map(|rels| (source.as_str(), rels))
2336            }),
2337        ))
2338    };
2339    // Comment bodies are a story the comparison writes, and can hold a table
2340    // (#1712). The glossary is no story and stays as it came (#1680).
2341    for part in out.parts() {
2342        if custom_data
2343            .iter()
2344            .any(|data| data.eq_ignore_ascii_case(&part))
2345        {
2346            continue;
2347        }
2348        let is_swept = part == main
2349            || part == "word/styles.xml"
2350            || part == "word/numbering.xml"
2351            || part == "word/footnotes.xml"
2352            || part == "word/endnotes.xml"
2353            || part == "word/comments.xml"
2354            || part == "word/settings.xml"
2355            || (part.starts_with("word/header") && part.ends_with(".xml"))
2356            || (part.starts_with("word/footer") && part.ends_with(".xml"))
2357            || (part.starts_with("word/diagrams/") && part.ends_with(".xml"))
2358            || (part.starts_with("word/charts/") && part.ends_with(".xml"))
2359            || (part.starts_with("word/theme/") && part.ends_with(".xml"))
2360            || (part.starts_with("word/media/") && part.ends_with(".xml"));
2361        if !is_swept {
2362            continue;
2363        }
2364        if let Some(x) = out.part_string(&part) {
2365            let mut vd = Dom::new();
2366            let doc = vd.parse_xdocument(&x);
2367            if let Some(vr) = vd.root(doc) {
2368                // Preserve every untouched part byte-for-byte on an identical
2369                // exit; the full path historically does this for comments only.
2370                let carried = (comparison.is_none() || part == "word/comments.xml")
2371                    .then(|| vd.serialize_element(vr));
2372                if comparison.is_none() && part == main {
2373                    // Unique DrawingML ids are valid; VML duplicates are too.
2374                    // Only missing/invalid or duplicate docPr ids need repair.
2375                    crate::comparer::fixups::rename_repeated_doc_pr_ids(&mut vd, vr);
2376                }
2377                repair_part_validity(&mut vd, vr, comparison.is_some());
2378                if let Some(context) = comparison {
2379                    sweep_comparison_chrome(out, &part, main, &mut vd, vr, context);
2380                }
2381                // Last: every pass above may append properties out of order.
2382                if comparison.is_some() {
2383                    crate::comparer::finalize::enforce_part_schema_order(&mut vd, vr);
2384                    crate::comparer::finalize::declare_extension_namespaces_ignorable(&mut vd, vr);
2385                } else {
2386                    crate::comparer::finalize::repair_part_schema_order(&mut vd, vr);
2387                }
2388                crate::comparer::finalize::bind_compatibility_prefixes(&mut vd, vr);
2389                let swept = vd.serialize_element(vr);
2390                if carried.as_deref() == Some(swept.as_str()) {
2391                    continue;
2392                }
2393                out.set_part(&part, swept.into_bytes());
2394            }
2395        }
2396    }
2397    // The glossary is not swept above: it is not a story. Repair the three
2398    // inherited shapes in it anyway, and leave the part untouched when that
2399    // repair changes nothing.
2400    repair_glossary_shapes(out);
2401    // Settling final marks is comparison chrome, including renamed stories.
2402    if comparison.is_none() {
2403        return;
2404    }
2405    // A story part under a name of its own (a header at `word/chrome.xml`)
2406    // is not swept above, but its cells' final marks settle too
2407    // (#1680, round 10). Stories are known by the main document's
2408    // relationships to them: a custom XML data item or the glossary holds
2409    // cells too, but the comparison wrote neither and they stay as they
2410    // were (#1680, round 11).
2411    let stories: Vec<String> = out
2412        .read_rels_for(main)
2413        .map(|rels| {
2414            rels.items
2415                .iter()
2416                .filter(|r| {
2417                    r.target_mode.as_deref() != Some("External")
2418                        && ["/header", "/footer", "/footnotes", "/endnotes", "/comments"]
2419                            .iter()
2420                            .any(|kind| r.rel_type.ends_with(kind))
2421                })
2422                .map(|r| out.resolve_rel_target(main, &r.target))
2423                .collect()
2424        })
2425        .unwrap_or_default();
2426    for part in stories {
2427        // Settled above already. One predicate for both sweeps, so a story
2428        // part cannot fall between them (`word/headerA.dat`,
2429        // #1680, round 12).
2430        if sweeps_final_marks(&part, main) {
2431            continue;
2432        }
2433        let Some(x) = out.part_string(&part).filter(|x| x.contains("tc")) else {
2434            continue;
2435        };
2436        let mut vd = Dom::new();
2437        let doc = vd.parse_xdocument(&x);
2438        let Some(vr) = vd.root(doc) else {
2439            continue;
2440        };
2441        let unsettled = vd.name(vr).is_some_and(|n| n.namespace_name() == W::URI)
2442            && vd
2443                .descendants(vr, Some(&W::tc()))
2444                .into_iter()
2445                .any(|cell| !crate::validate_dom::uncovered_final_marks(&vd, cell).is_empty());
2446        if unsettled {
2447            crate::comparer::final_marks::settle_cell_final_marks(&mut vd, vr);
2448            // The finalizers the sweep above runs, so a renamed story keeps
2449            // its extension namespaces declared and ignorable
2450            // (#1680).
2451            crate::comparer::finalize::enforce_part_schema_order(&mut vd, vr);
2452            crate::comparer::finalize::declare_extension_namespaces_ignorable(&mut vd, vr);
2453            crate::comparer::finalize::bind_compatibility_prefixes(&mut vd, vr);
2454            out.set_part(&part, vd.serialize_element(vr).into_bytes());
2455        }
2456    }
2457}
2458
2459/// Schema/structural validity repairs shared by the two sweep modes.
2460fn repair_part_validity(dom: &mut Dom, root: NodeId, comparison: bool) {
2461    if comparison {
2462        crate::comparer::finalize::normalize_universal_measures(dom, root);
2463        crate::comparer::finalize::fix_strict_validity_artifacts(dom, root);
2464    } else {
2465        crate::comparer::finalize::repair_invalid_measures(dom, root);
2466        crate::comparer::finalize::repair_strict_validity_artifacts(dom, root);
2467    }
2468    crate::comparer::finalize::repair_inherited_invalidity(dom, root);
2469    // CT_RunTrackChange excludes hyperlink and fldSimple wrappers. Hoist
2470    // only those illegal immediate children, preserving revision ownership.
2471    crate::comparer::finalize::hoist_hyperlinks_out_of_revisions(dom, root);
2472    if comparison {
2473        crate::comparer::finalize::enforce_deleted_text_kinds(dom, root);
2474    }
2475}
2476
2477/// Formatting/default removal belongs to a comparison, never an identical exit.
2478fn sweep_comparison_chrome(
2479    out: &PartFs,
2480    part: &str,
2481    main: &str,
2482    vd: &mut Dom,
2483    root: NodeId,
2484    context: &ComparisonSweep<'_>,
2485) {
2486    let ComparisonSweep {
2487        original,
2488        settings,
2489        ladder_sources,
2490    } = context;
2491    crate::comparer::finalize::remove_powertools_scratch_markup(vd, root);
2492    // Produce strips an empty pPr shell, then later package steps
2493    // (style cascade, spacing restore) can take the live children
2494    // back off and leave the shell. Word's redline of the short
2495    // title mixes has neither the shell nor the children.
2496    if part == main {
2497        crate::comparer::finalize::strip_propertyless_ppr(vd, root);
2498        // Word-visual chrome. Faithful mode runs none of these;
2499        // the body path already gates them the same way, and an
2500        // edit keeps the source's markup and the plan's links.
2501        if settings.merge_replaced_paragraphs && !settings.preserve_untouched {
2502            // Package steps can put a default nextPage back into the
2503            // recorded sectPr, or leave line=276 on a deleted mark.
2504            let original_line = original
2505                .part_string("word/styles.xml")
2506                .map(|x| default_paragraph_line(&x));
2507            crate::comparer::finalize::strip_unrecorded_word_defaults(
2508                vd,
2509                root,
2510                original_line.as_deref(),
2511            );
2512            let id_to_target: std::collections::HashMap<String, String> = out
2513                .read_rels_for(main)
2514                .map(|rels| {
2515                    rels.items
2516                        .iter()
2517                        .filter(|r| r.rel_type.ends_with("/hyperlink"))
2518                        .map(|r| (r.id.clone(), r.target.clone()))
2519                        .collect()
2520                })
2521                .unwrap_or_default();
2522            let base_targets: std::collections::HashSet<String> = original
2523                .read_rels_for(main)
2524                .map(|rels| {
2525                    rels.items
2526                        .iter()
2527                        .filter(|r| r.rel_type.ends_with("/hyperlink"))
2528                        .map(|r| r.target.clone())
2529                        .collect()
2530                })
2531                .unwrap_or_default();
2532            crate::comparer::finalize::rewrite_inserted_external_hyperlinks(
2533                vd,
2534                root,
2535                &id_to_target,
2536                &base_targets,
2537            );
2538            crate::comparer::finalize::align_word_table_and_comment_chrome(vd, root);
2539        }
2540        if let Some((original_xml, revised_xml)) = ladder_sources {
2541            crate::comparer::finalize::align_remaining_ladder_rungs(
2542                vd,
2543                root,
2544                &crate::comparer::finalize::LadderSources {
2545                    original_xml,
2546                    revised_xml,
2547                    settings,
2548                },
2549            );
2550            // After every mark-writing pass and before the cells settle:
2551            // the inserted paragraph and the deleted table are both
2552            // finished here (#1683, case 2).
2553            if let Some(body) = vd.element(root, &W::body()) {
2554                crate::comparer::finalize::pair_closing_insert_across_deleted_table(
2555                    vd,
2556                    body,
2557                    revised_xml,
2558                );
2559            }
2560        }
2561    }
2562    // A cell's final mark carries no revision its row does not
2563    // (#1669, #1684), in every story: the body (its text boxes
2564    // too), the notes, the headers and footers. After every pass
2565    // that writes marks.
2566    if sweeps_final_marks(part, main) {
2567        crate::comparer::final_marks::settle_cell_final_marks(vd, root);
2568    }
2569}
2570
2571/// The parts the validity sweep settles cells' final marks in, by name: the
2572/// main part, the notes, and `word/header*.xml` / `word/footer*.xml`. The
2573/// story sweep after it settles every other story part.
2574fn sweeps_final_marks(part: &str, main: &str) -> bool {
2575    part == main
2576        || part == "word/footnotes.xml"
2577        || part == "word/endnotes.xml"
2578        || ((part.starts_with("word/header") || part.starts_with("word/footer"))
2579            && part.ends_with(".xml"))
2580}
2581
2582/// Glossary parts: the canonical building-block part, and any part a
2583/// `glossaryDocument` relationship reaches. Not a story, so cell marks are
2584/// left alone; only the inherited schema shapes are repaired.
2585fn glossary_parts(out: &PartFs) -> Vec<String> {
2586    let mut found: Vec<String> = Vec::new();
2587    let mut push = |name: String| {
2588        if name.is_empty()
2589            || found
2590                .iter()
2591                .any(|have: &String| have.eq_ignore_ascii_case(&name))
2592        {
2593            return;
2594        }
2595        found.push(name);
2596    };
2597    for part in out.parts() {
2598        if part.eq_ignore_ascii_case("word/glossary/document.xml") {
2599            push(part);
2600        }
2601    }
2602    for (source, rels) in out.relationship_parts() {
2603        for rel in &rels.items {
2604            if rel.target_mode.as_deref() == Some("External")
2605                || !rel.rel_type.ends_with("/glossaryDocument")
2606            {
2607                continue;
2608            }
2609            push(out.resolve_rel_target(source, &rel.target));
2610        }
2611    }
2612    found
2613}
2614
2615/// Drop an empty shading fill, a grid-column type, and out-of-order cell
2616/// margins in a glossary. Write the part back only when that changes it.
2617/// The glossary is carried, not compared, so compare repairs it as accept
2618/// and reject do: the comparison's canonicalizer would drop comments and
2619/// whitespace in a valid part's properties and rewrite it (#2117 review).
2620fn repair_glossary_shapes(out: &mut PartFs) {
2621    for part in glossary_parts(out) {
2622        let Some(xml) = out.part_string(&part) else {
2623            continue;
2624        };
2625        let mut dom = Dom::new();
2626        let doc = dom.parse_xdocument(&xml);
2627        let Some(root) = dom.root(doc) else {
2628            continue;
2629        };
2630        let before = dom.serialize_element(root);
2631        crate::comparer::finalize::repair_inherited_invalidity(&mut dom, root);
2632        crate::comparer::finalize::repair_part_schema_order(&mut dom, root);
2633        let after = dom.serialize_element(root);
2634        if before != after {
2635            out.set_part(&part, after.into_bytes());
2636        }
2637    }
2638}
2639
2640#[cfg(test)]
2641#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2642#[path = "tests/based_style_record_tests.rs"]
2643mod based_style_record_tests;
2644
2645#[cfg(test)]
2646#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2647#[path = "tests/tests.rs"]
2648mod tests;
2649
2650#[cfg(test)]
2651#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2652#[path = "tests/coverage_boundary_tests.rs"]
2653mod coverage_boundary_tests;
2654
2655#[cfg(test)]
2656#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2657#[path = "tests/comparer_relationship_contract_tests.rs"]
2658mod comparer_relationship_contract_tests;
2659#[cfg(test)]
2660#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2661#[path = "tests/coverage_package_source_matrix_tests.rs"]
2662mod coverage_package_source_matrix_tests;
2663
2664#[cfg(test)]
2665#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2666#[path = "tests/authored_style_chain_boundary_tests.rs"]
2667mod authored_style_chain_boundary_tests;
2668
2669#[cfg(test)]
2670#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2671#[path = "tests/isolated_header_container_revision_boundary_tests.rs"]
2672mod isolated_header_container_revision_boundary_tests;
2673
2674#[cfg(test)]
2675#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2676#[path = "tests/redefined_style_chain_source_owner_tests.rs"]
2677mod redefined_style_chain_source_owner_tests;
2678
2679#[cfg(test)]
2680#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2681#[path = "tests/namespace_declared_default_property_owner_tests.rs"]
2682mod namespace_declared_default_property_owner_tests;
2683
2684#[cfg(test)]
2685#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2686#[path = "tests/adopted_story_relationship_owner_tests.rs"]
2687mod adopted_story_relationship_owner_tests;
2688
2689#[cfg(test)]
2690#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2691#[path = "tests/word_style_line_owned_boundary_tests.rs"]
2692mod word_style_line_owned_boundary_tests;
2693
2694#[cfg(test)]
2695#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2696#[path = "tests/public_numbering_definition_source_owner_tests.rs"]
2697mod public_numbering_definition_source_owner_tests;
2698
2699#[cfg(test)]
2700#[path = "tests/story_diff_failure_tests.rs"]
2701mod story_diff_failure_tests;
2702
2703/// A section break the revised paragraph carries and the original paragraph
2704/// does not. The final body section, hoisted into the last paragraph before
2705/// the diff, is not one: it wears the hoist stamp.
2706fn authored_section_break(dom: &Dom, paragraph: NodeId) -> bool {
2707    let hoist = crate::namespaces::PT::name("BodySectPrHoist");
2708    dom.element(paragraph, &W::p_pr()).is_some_and(|ppr| {
2709        dom.elements(ppr, Some(&W::sect_pr()))
2710            .into_iter()
2711            .any(|section| dom.attribute(section, &hoist) != Some("1"))
2712    })
2713}
2714
2715fn paragraph_plain_text(dom: &Dom, paragraph: NodeId) -> String {
2716    dom.descendants(paragraph, Some(&W::t()))
2717        .into_iter()
2718        .map(|text| dom.value(text))
2719        .collect()
2720}
2721
2722struct SectionRow {
2723    text: String,
2724    authored: bool,
2725    /// A paragraph, table or block wrapper follows it in its body. A
2726    /// break added there takes Word's middle model, even when what follows
2727    /// is a blank paragraph or a table (#2126 review).
2728    followed: bool,
2729}
2730
2731fn followed_by_block(dom: &Dom, paragraph: NodeId) -> bool {
2732    let mut next = dom.next_element(paragraph);
2733    while let Some(node) = next {
2734        if dom
2735            .name(node)
2736            .is_some_and(|name| matches!(name.local_name(), "p" | "tbl" | "sdt" | "customXml"))
2737        {
2738            return true;
2739        }
2740        next = dom.next_element(node);
2741    }
2742    false
2743}
2744
2745fn section_rows(dom: &Dom, body: NodeId) -> Vec<SectionRow> {
2746    dom.elements(body, Some(&W::p()))
2747        .into_iter()
2748        .filter_map(|paragraph| {
2749            let text = paragraph_plain_text(dom, paragraph);
2750            if text.is_empty() {
2751                None
2752            } else {
2753                Some(SectionRow {
2754                    authored: authored_section_break(dom, paragraph),
2755                    followed: followed_by_block(dom, paragraph),
2756                    text,
2757                })
2758            }
2759        })
2760        .collect()
2761}
2762
2763fn has_paragraph_mark(dom: &Dom, paragraph: NodeId) -> bool {
2764    dom.element(paragraph, &W::p_pr())
2765        .and_then(|ppr| dom.element(ppr, &W::r_pr()))
2766        .is_some_and(|rpr| {
2767            dom.elements(rpr, None).into_iter().any(|child| {
2768                dom.name(child).is_some_and(|name| {
2769                    matches!(name.local_name(), "ins" | "del" | "moveFrom" | "moveTo")
2770                })
2771            })
2772        })
2773}
2774
2775fn next_revision_id(dom: &Dom, root: NodeId) -> u32 {
2776    let mut next = 0u32;
2777    for node in dom.descendants_and_self(root, None) {
2778        let Some(raw) = dom.attribute(node, &W::id()) else {
2779            continue;
2780        };
2781        let Ok(id) = raw.parse::<u32>() else {
2782            continue;
2783        };
2784        next = next.max(id.saturating_add(1));
2785    }
2786    next
2787}
2788
2789fn paragraph_properties(dom: &mut Dom, paragraph: NodeId) -> NodeId {
2790    if let Some(ppr) = dom.element(paragraph, &W::p_pr()) {
2791        return ppr;
2792    }
2793    let ppr = dom.new_element(W::p_pr());
2794    dom.add_first(paragraph, ppr);
2795    ppr
2796}
2797
2798fn run_properties_before_section(dom: &mut Dom, ppr: NodeId) -> NodeId {
2799    if let Some(rpr) = dom.element(ppr, &W::r_pr()) {
2800        return rpr;
2801    }
2802    let rpr = dom.new_element(W::r_pr());
2803    let anchor = dom
2804        .elements(ppr, None)
2805        .into_iter()
2806        .find(|&child| dom.name_is(child, &W::sect_pr()) || dom.name_is(child, &W::p_pr_change()));
2807    if let Some(anchor) = anchor {
2808        dom.add_before_self(anchor, rpr);
2809    } else {
2810        dom.add(ppr, rpr);
2811    }
2812    rpr
2813}
2814
2815fn drop_empty_paragraph_change(dom: &mut Dom, ppr: NodeId) {
2816    let Some(change) = dom.element(ppr, &W::p_pr_change()) else {
2817        return;
2818    };
2819    let records_layout = dom.element(change, &W::p_pr()).is_some_and(|inner| {
2820        dom.elements(inner, None)
2821            .into_iter()
2822            .any(|child| !dom.name_is(child, &W::r_pr()))
2823    });
2824    if !records_layout {
2825        dom.remove(change);
2826    }
2827}
2828
2829fn push_paragraph_mark(
2830    dom: &mut Dom,
2831    rpr: NodeId,
2832    inserted: bool,
2833    id: u32,
2834    author: &str,
2835    date: &str,
2836) {
2837    let marked = dom.elements(rpr, None).into_iter().any(|child| {
2838        dom.name(child)
2839            .is_some_and(|name| matches!(name.local_name(), "ins" | "del" | "moveFrom" | "moveTo"))
2840    });
2841    if marked {
2842        return;
2843    }
2844    let mark = dom.new_element(if inserted { W::ins() } else { W::del() });
2845    let id_text = id.to_string();
2846    dom.set_attribute_value(mark, &W::id(), Some(&id_text));
2847    dom.set_attribute_value(mark, &W::author(), Some(author));
2848    dom.set_attribute_value(mark, &W::date(), Some(date));
2849    dom.add_first(rpr, mark);
2850}
2851
2852fn following_paragraph(dom: &Dom, paragraph: NodeId) -> Option<NodeId> {
2853    let parent = dom.parent(paragraph)?;
2854    let siblings = dom.elements(parent, Some(&W::p()));
2855    let index = siblings.iter().position(|&sibling| sibling == paragraph)?;
2856    siblings.get(index + 1).copied()
2857}
2858
2859fn paragraph_is_blank(dom: &Dom, paragraph: NodeId) -> bool {
2860    paragraph_plain_text(dom, paragraph).is_empty()
2861        && dom
2862            .element(paragraph, &W::p_pr())
2863            .is_none_or(|ppr| dom.element(ppr, &W::sect_pr()).is_none())
2864}
2865
2866fn track_closing_added_break(dom: &mut Dom, paragraph: NodeId, id: u32, author: &str, date: &str) {
2867    let ppr = paragraph_properties(dom, paragraph);
2868    if dom.element(ppr, &W::sect_pr()).is_none() {
2869        return;
2870    }
2871    drop_empty_paragraph_change(dom, ppr);
2872    let rpr = run_properties_before_section(dom, ppr);
2873    push_paragraph_mark(dom, rpr, true, id, author, date);
2874    let followed_by_blank =
2875        following_paragraph(dom, paragraph).is_some_and(|next| paragraph_is_blank(dom, next));
2876    if !followed_by_blank {
2877        let blank = dom.new_element(W::p());
2878        dom.add_after_self(paragraph, blank);
2879    }
2880}
2881
2882fn track_middle_added_break(
2883    dom: &mut Dom,
2884    paragraph: NodeId,
2885    deleted_id: u32,
2886    inserted_id: u32,
2887    author: &str,
2888    date: &str,
2889) {
2890    let ppr = paragraph_properties(dom, paragraph);
2891    let Some(section) = dom.element(ppr, &W::sect_pr()) else {
2892        return;
2893    };
2894    drop_empty_paragraph_change(dom, ppr);
2895    let rpr = run_properties_before_section(dom, ppr);
2896    push_paragraph_mark(dom, rpr, false, deleted_id, author, date);
2897    let blank = dom.new_element(W::p());
2898    let blank_ppr = dom.new_element(W::p_pr());
2899    dom.add(blank, blank_ppr);
2900    // Accept All merges this paragraph into the carrier and keeps the
2901    // carrier's properties, so it carries the paragraph's own (#2126
2902    // review). Its mark, break and recorded change stay apart.
2903    for child in dom.elements(ppr, None) {
2904        if dom.name_is(child, &W::r_pr())
2905            || dom.name_is(child, &W::sect_pr())
2906            || dom.name_is(child, &W::p_pr_change())
2907        {
2908            continue;
2909        }
2910        let copy = dom.clone_subtree(child);
2911        dom.add(blank_ppr, copy);
2912    }
2913    let blank_rpr = dom.new_element(W::r_pr());
2914    dom.add(blank_ppr, blank_rpr);
2915    push_paragraph_mark(dom, blank_rpr, true, inserted_id, author, date);
2916    dom.remove(section);
2917    dom.add(blank_ppr, section);
2918    dom.add_after_self(paragraph, blank);
2919}
2920
2921/// Track a section break the revision adds, when the same paragraphs are
2922/// still in order on both sides. The closing paragraph keeps the break
2923/// under an inserted mark and an empty paragraph follows it. A break
2924/// before a later paragraph deletes this mark and the break moves onto
2925/// that new empty paragraph.
2926fn track_added_section_breaks(
2927    dom: &mut Dom,
2928    result_root: NodeId,
2929    original_body: NodeId,
2930    revised_body: NodeId,
2931    settings: &WmlComparerSettings,
2932) {
2933    if !settings.merge_replaced_paragraphs {
2934        return;
2935    }
2936    let Some(result_body) = dom.element(result_root, &W::body()) else {
2937        return;
2938    };
2939    let original = section_rows(dom, original_body);
2940    let revised = section_rows(dom, revised_body);
2941    let result: Vec<NodeId> = dom
2942        .elements(result_body, Some(&W::p()))
2943        .into_iter()
2944        .filter(|&paragraph| !paragraph_plain_text(dom, paragraph).is_empty())
2945        .collect();
2946    if original.len() != revised.len() || original.len() != result.len() {
2947        return;
2948    }
2949    let mut next_id = next_revision_id(dom, result_root);
2950    for index in (0..result.len()).rev() {
2951        if original[index].text != revised[index].text
2952            || original[index].text != paragraph_plain_text(dom, result[index])
2953        {
2954            continue;
2955        }
2956        if !revised[index].authored || original[index].authored {
2957            continue;
2958        }
2959        if has_paragraph_mark(dom, result[index]) {
2960            continue;
2961        }
2962        let author = settings.author_for_revisions.as_str();
2963        let date = settings.date_time_for_revisions.as_str();
2964        if !original[index].followed {
2965            track_closing_added_break(dom, result[index], next_id, author, date);
2966            next_id = next_id.saturating_add(1);
2967        } else {
2968            let inserted_id = next_id.saturating_add(1);
2969            track_middle_added_break(dom, result[index], next_id, inserted_id, author, date);
2970            next_id = inserted_id.saturating_add(1);
2971        }
2972    }
2973}
2974
2975#[cfg(test)]
2976#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2977#[path = "tests/cross_shape_roundtrip_tests.rs"]
2978mod cross_shape_roundtrip_tests;