Skip to main content

jubarte_redlines/
revision_processor.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//! Revision accept / reject pipeline (M3).
8//!
9//! Port of `RevisionProcessor.ts` — the byte-level accept / reject facade
10//! (`accept_revisions_package`, `reject_revisions_package`) and the
11//! A.0–A.11 transforms that compose
12//! them: paragraph / block-content iteration, paragraph-mark and
13//! content-control re-wrap, moveFrom / moveTo, deleted-cell merging,
14//! adjacent-table merging, and the reject path (revert → reverse →
15//! remove rsid → accept).
16//!
17//! The element-scope helpers (`accept_revisions_document`,
18//! `reject_revisions_document`, `accept_revisions_for_element`) are
19//! the per-subtree entry the M4 compare pipeline calls to hash the
20//! accepted / rejected projections before correlating them.
21
22mod bookmarks;
23pub(crate) mod comments;
24mod notes;
25mod sections;
26pub(crate) mod style_records;
27mod word_save;
28
29// The doc and edit layers above reach these through the facade's
30// revision_processor re-export (changes, edit, scrub).
31#[doc(hidden)]
32pub use comments::{prune_orphan_comments, renumber_rescued_comments};
33#[doc(hidden)]
34pub use sections::Resolution;
35pub(crate) use word_save::drop_unreferenced_headers_footers;
36
37use std::collections::{HashMap, HashSet};
38use std::sync::LazyLock;
39
40use crate::markup_simplifier::remove_rsid_transform;
41use crate::namespaces::{M, PT, W, W14};
42use crate::xmllinq::{Dom, NodeId, XName, XNamespace};
43
44/// Local names of `RevisionProcessor.TrackedRevisionsElements` (W namespace).
45const TRACKED_REVISION_LOCALS: &[&str] = &[
46    "cellDel",
47    "cellIns",
48    "cellMerge",
49    "customXmlDelRangeEnd",
50    "customXmlDelRangeStart",
51    "customXmlInsRangeEnd",
52    "customXmlInsRangeStart",
53    "customXmlMoveFromRangeEnd",
54    "customXmlMoveFromRangeStart",
55    "customXmlMoveToRangeEnd",
56    "customXmlMoveToRangeStart",
57    "del",
58    "delInstrText",
59    "delText",
60    "ins",
61    "moveFrom",
62    "moveFromRangeEnd",
63    "moveFromRangeStart",
64    "moveTo",
65    "moveToRangeEnd",
66    "moveToRangeStart",
67    "numberingChange",
68    "pPrChange",
69    "rPrChange",
70    "sectPrChange",
71    "tblGridChange",
72    "tblPrChange",
73    "tblPrExChange",
74    "tcPrChange",
75    "trPrChange",
76];
77
78static TRACKED_REVISION_LOCAL_SET: LazyLock<HashSet<&'static str>> =
79    LazyLock::new(|| TRACKED_REVISION_LOCALS.iter().copied().collect());
80
81/// The element names whose presence indicates the document carries
82/// tracked revisions (one per local name in the `w:` namespace). The
83/// `has_tracked_revisions` check below is the constant-time local-name
84/// lookup the byte-level pipeline uses.
85pub fn tracked_revisions_elements() -> Vec<XName> {
86    TRACKED_REVISION_LOCALS.iter().map(|l| W::name(l)).collect()
87}
88
89/// True if `root` (or any descendant) is a tracked-revision element. The
90/// element-scope equivalent of `RevisionProcessor.PartHasTrackedRevisions`.
91///
92/// The check is a non-allocating DFS against the static local-name set
93/// (ACCEPT-SCAN-01): no `Vec<XName>` / `descendants_and_self` allocation,
94/// so the byte-level pipeline can call it on every part without GC churn.
95pub fn element_has_tracked_revisions(dom: &Dom, root: NodeId) -> bool {
96    fn walk(dom: &Dom, id: NodeId) -> bool {
97        if let Some(name) = dom.name(id)
98            && name.namespace_name() == W::URI
99            && TRACKED_REVISION_LOCAL_SET.contains(name.local_name())
100        {
101            return true;
102        }
103        for i in 0..dom.child_count(id) {
104            if walk(dom, dom.child_at(id, i)) {
105                return true;
106            }
107        }
108        false
109    }
110    walk(dom, root)
111}
112
113/// True if `xml` opens a `w:` element named in `TRACKED_REVISION_LOCALS`:
114/// the byte-level twin of [`element_has_tracked_revisions`]. It matches
115/// whole names, so a field's `<w:instrText>` and a table's `<w:insideH>`
116/// are not a `<w:ins>` (#1870).
117pub(crate) fn xml_has_tracked_revisions(xml: &str) -> bool {
118    xml.match_indices("<w:").any(|(at, open)| {
119        let rest = &xml[at + open.len()..];
120        let end = rest
121            .find(|c: char| c.is_ascii_whitespace() || c == '>' || c == '/')
122            .unwrap_or(rest.len());
123        TRACKED_REVISION_LOCAL_SET.contains(&rest[..end])
124    })
125}
126
127/// Does `el` have a child element named `local` (in the W namespace)?
128fn has_child(dom: &Dom, el: NodeId, name: &XName) -> bool {
129    dom.element(el, name).is_some()
130}
131
132/// Path check `el / a / b` exists (a, b are direct-child element names).
133fn has_path(dom: &Dom, el: NodeId, a: &XName, b: &XName) -> bool {
134    dom.elements(el, Some(a))
135        .into_iter()
136        .any(|ae| has_child(dom, ae, b))
137}
138
139/// Port of `AcceptMoveFromMoveToTransform` — unwrap `w:moveTo`, drop
140/// `w:moveFrom`. A moved-from paragraph mark (`pPr/rPr/moveFrom`) is kept
141/// (A.5a joins that paragraph with the next, so the join the witness
142/// expects needs to be visible). Otherwise the whole `w:moveFrom` is hoisted
143/// into range markers.
144///
145/// Subtrees with no moveFrom / moveTo (and no other tracked revision
146/// markers) are detached and returned as-is — `Dom::add` reuses them
147/// without `clone_subtree`.
148pub fn accept_move_from_move_to_transform(dom: &mut Dom, node: NodeId) -> Vec<NodeId> {
149    // No move/revision markers in this subtree → transfer ownership.
150    if !element_has_tracked_revisions(dom, node) {
151        return take_subtree(dom, node);
152    }
153    if !dom.is_element(node) {
154        return take_subtree(dom, node);
155    }
156    let name = dom.name(node).unwrap();
157    if name == W::move_to() {
158        let mut out = Vec::new();
159        for c in dom.nodes(node) {
160            out.extend(accept_move_from_move_to_transform(dom, c));
161        }
162        return out;
163    }
164    if name == W::move_from() {
165        // A moved-from paragraph mark (`pPr/rPr/moveFrom`) stays for A.5a,
166        // which joins that paragraph with the next as Word does; dropping it
167        // here left an empty paragraph behind.
168        let is_mark = dom.parent(node).is_some_and(|rpr| {
169            dom.name(rpr) == Some(W::r_pr())
170                && dom.parent(rpr).and_then(|ppr| dom.name(ppr)) == Some(W::p_pr())
171        });
172        return if is_mark {
173            take_subtree(dom, node)
174        } else {
175            // The bookmark range pass already removed wholly moved-away
176            // spans. Preserve empty or partially surviving anchors exactly
177            // as the ordinary deletion transform does.
178            hoist_range_markers_from(dom, node)
179        };
180    }
181    let ne = dom.new_element(name);
182    dom.copy_attributes(node, ne);
183    for c in dom.nodes(node) {
184        for tn in accept_move_from_move_to_transform(dom, c) {
185            dom.add(ne, tn);
186        }
187    }
188    vec![ne]
189}
190
191/// Detach `node` from its parent (if any) and return it for reparenting.
192/// Unparented nodes are reused by [`Dom::add`] without cloning.
193fn take_subtree(dom: &mut Dom, node: NodeId) -> Vec<NodeId> {
194    if dom.parent(node).is_some() {
195        dom.remove(node);
196    }
197    vec![node]
198}
199
200/// Non-allocating presence of `name` on `root` or any descendant element.
201fn element_or_desc_has_name(dom: &Dom, root: NodeId, name: &XName) -> bool {
202    fn walk(dom: &Dom, id: NodeId, name: &XName) -> bool {
203        if dom.name(id).as_ref() == Some(name) {
204            return true;
205        }
206        let n = dom.child_count(id);
207        for i in 0..n {
208            if walk(dom, dom.child_at(id, i), name) {
209                return true;
210            }
211        }
212        false
213    }
214    walk(dom, root, name)
215}
216
217/// True iff a transformed element still carries run/inline content (port of
218/// `HasRunContent`) — used to decide whether an emptied `w:hyperlink` survives.
219fn has_run_content(dom: &Dom, element: NodeId) -> bool {
220    let content_names = [
221        W::r(),
222        W::smart_tag(),
223        W::ins(),
224        W::del(),
225        W::hyperlink(),
226        W::fld_simple(),
227        W::sdt(),
228    ];
229    dom.elements(element, None)
230        .into_iter()
231        .any(|e| dom.name(e).is_some_and(|n| content_names.contains(&n)))
232}
233
234fn try_accept_wholly_revised_equation(
235    dom: &mut Dom,
236    node: NodeId,
237    name: &XName,
238) -> Option<Vec<NodeId>> {
239    if name == &M::name("oMath") || name == &M::name("oMathPara") {
240        let owners: Vec<_> = dom
241            .descendants(node, None)
242            .into_iter()
243            .filter(|&n| dom.name_is(n, &M::name("r")) || dom.name_is(n, &M::name("ctrlPr")))
244            .collect();
245        let has_authored_empty_equation = dom
246            .descendants(node, Some(&M::name("oMath")))
247            .into_iter()
248            .any(|equation| {
249                !dom.descendants(equation, None)
250                    .into_iter()
251                    .any(|n| dom.name_is(n, &M::name("r")) || dom.name_is(n, &M::name("ctrlPr")))
252            });
253        let has_unowned_content = dom.descendants(node, None).into_iter().any(|child| {
254            let ancestors = dom.ancestors(child, None);
255            if dom.name_is(child, &W::del())
256                || ancestors
257                    .iter()
258                    .any(|&ancestor| dom.name_is(ancestor, &W::del()))
259            {
260                return false;
261            }
262            let Some(child_name) = dom.name(child) else {
263                return !dom
264                    .text_value(child)
265                    .is_some_and(|text| text.trim().is_empty());
266            };
267            // oMath admits ordinary WML runs, anchors and transparent controls.
268            // They are independent owners even when all m:r owners are deleted.
269            if child_name.namespace_name() != M::URI {
270                return true;
271            }
272            if child_name.local_name() == "r" || child_name.local_name() == "ctrlPr" {
273                return false;
274            }
275            // Math property leaves describe the removed equation; an empty
276            // expression/container outside properties is an authored sibling.
277            let in_math_properties = child_name.local_name().ends_with("Pr")
278                || ancestors.iter().any(|&ancestor| {
279                    dom.name(ancestor).is_some_and(|name| {
280                        name.namespace_name() == M::URI && name.local_name().ends_with("Pr")
281                    })
282                });
283            !in_math_properties && dom.elements(child, None).is_empty()
284        });
285        if !has_authored_empty_equation
286            && !has_unowned_content
287            && !owners.is_empty()
288            && owners.iter().all(|&owner| {
289                let children = dom.elements(owner, None);
290                !children.is_empty()
291                    && children.iter().all(|&child| dom.name_is(child, &W::del()))
292                    && dom.nodes(owner).into_iter().all(|child| {
293                        dom.is_element(child)
294                            || dom
295                                .text_value(child)
296                                .is_some_and(|text| text.trim().is_empty())
297                    })
298            })
299        {
300            return Some(hoist_range_markers_from(dom, node));
301        }
302    }
303    None
304}
305
306fn try_accept_math_fraction(dom: &mut Dom, node: NodeId, name: &XName) -> Option<Vec<NodeId>> {
307    if name == &M::name("f") {
308        let removed = dom
309            .elements(node, Some(&M::name("fPr")))
310            .into_iter()
311            .any(|fpr| has_path(dom, fpr, &M::name("ctrlPr"), &W::del()));
312        if removed {
313            return Some(vec![]);
314        }
315    }
316    None
317}
318
319fn try_accept_deleted_row(dom: &mut Dom, node: NodeId, name: &XName) -> Option<Vec<NodeId>> {
320    if name == &W::tr() && has_path(dom, node, &W::tr_pr(), &W::del()) {
321        return Some(vec![]);
322    }
323    None
324}
325
326fn try_accept_deleted_table(dom: &mut Dom, node: NodeId, name: &XName) -> Option<Vec<NodeId>> {
327    if name == &W::tbl() && table_rows_all_deleted(dom, node) {
328        return Some(vec![]);
329    }
330    None
331}
332
333fn try_accept_deleted_text(dom: &mut Dom, node: NodeId, name: &XName) -> Option<Vec<NodeId>> {
334    if name == &W::del() {
335        return Some(hoist_range_markers_from(dom, node));
336    }
337    None
338}
339
340fn try_accept_cell_merge(dom: &mut Dom, node: NodeId, name: &XName) -> Option<Vec<NodeId>> {
341    if name == &W::cell_merge() {
342        let parent_is_tcpr = dom
343            .parent(node)
344            .and_then(|p| dom.name(p))
345            .is_some_and(|pn| pn == W::tc_pr());
346        if parent_is_tcpr {
347            let vmerge = dom.attribute(node, &W::v_merge()).map(|s| s.to_string());
348            if vmerge.as_deref() == Some("rest") {
349                let v = dom.new_element(W::v_merge());
350                dom.set_attribute_value(v, &W::val(), Some("restart"));
351                return Some(vec![v]);
352            }
353            if vmerge.as_deref() == Some("cont") {
354                let v = dom.new_element(W::v_merge());
355                dom.set_attribute_value(v, &W::val(), Some("continue"));
356                return Some(vec![v]);
357            }
358        }
359    }
360    None
361}
362
363fn try_accept_hyperlink(dom: &mut Dom, node: NodeId, name: &XName) -> Option<Vec<NodeId>> {
364    if name == &W::hyperlink() {
365        let ne = dom.new_element(name.clone());
366        dom.copy_attributes(node, ne);
367        for c in dom.nodes(node) {
368            for tn in accept_all_other_revisions_transform(dom, c) {
369                dom.add(ne, tn);
370            }
371        }
372        return Some(if has_run_content(dom, ne) {
373            vec![ne]
374        } else {
375            hoist_range_markers_from(dom, ne)
376        });
377    }
378    None
379}
380
381/// Port of `AcceptAllOtherRevisionsTransform` — accept inserts (unwrap
382/// `w:ins`), drop deletions and revision-range markers, accept formatting-
383/// change markers, handle deleted rows/tables, cell merges, and empty
384/// hyperlink shells.
385///
386/// A wholly-revised equation (every `m:r` / `m:ctrlPr` deleted) is
387/// removed entirely; a wholly-revised oMath inside a surviving paragraph
388/// goes with it (so the paragraph never carries an empty math shell).
389///
390/// Subtrees with no tracked-revision elements are detached and returned
391/// as-is (ACCEPT-REUSE-CLEAN); callers reparent via `Dom::add`, which
392/// reuses unparented nodes.
393pub fn accept_all_other_revisions_transform(dom: &mut Dom, node: NodeId) -> Vec<NodeId> {
394    // Clean subtree (incl. plain text leaves): transfer, do not rebuild.
395    if !element_has_tracked_revisions(dom, node) {
396        return take_subtree(dom, node);
397    }
398    if !dom.is_element(node) {
399        return take_subtree(dom, node);
400    }
401    let name = dom.name(node).unwrap();
402
403    // Accept inserted content: collapse w:ins.
404    // #1155: resolve even the final paragraph mark, unlike Word's Accept/Reject All.
405    if name == W::ins() {
406        let mut out = Vec::new();
407        for c in dom.nodes(node) {
408            out.extend(accept_all_other_revisions_transform(dom, c));
409        }
410        return out;
411    }
412
413    // Drop revision-range markers (handled by the range transforms).
414    let drop_markers = [
415        "customXmlDelRangeStart",
416        "customXmlDelRangeEnd",
417        "customXmlInsRangeStart",
418        "customXmlInsRangeEnd",
419        "customXmlMoveFromRangeStart",
420        "customXmlMoveFromRangeEnd",
421        "customXmlMoveToRangeStart",
422        "customXmlMoveToRangeEnd",
423        "moveFromRangeStart",
424        "moveFromRangeEnd",
425        "moveToRangeStart",
426        "moveToRangeEnd",
427    ];
428    if name.namespace_name() == W::URI && drop_markers.contains(&name.local_name()) {
429        return vec![];
430    }
431
432    // Accept formatting-change / deleted-content markers by removing them.
433    let drop_format = [
434        "pPrChange",
435        "rPrChange",
436        "tblPrChange",
437        "tblGridChange",
438        "tcPrChange",
439        "trPrChange",
440        "tblPrExChange",
441        "sectPrChange",
442        "numberingChange",
443        "delInstrText",
444        "delText",
445        "cellIns",
446    ];
447    if name.namespace_name() == W::URI && drop_format.contains(&name.local_name()) {
448        return vec![];
449    }
450
451    if let Some(res) = try_accept_wholly_revised_equation(dom, node, &name) {
452        return res;
453    }
454    if let Some(res) = try_accept_math_fraction(dom, node, &name) {
455        return res;
456    }
457    if let Some(res) = try_accept_deleted_row(dom, node, &name) {
458        return res;
459    }
460    if let Some(res) = try_accept_deleted_table(dom, node, &name) {
461        return res;
462    }
463    if let Some(res) = try_accept_deleted_text(dom, node, &name) {
464        return res;
465    }
466    if let Some(res) = try_accept_cell_merge(dom, node, &name) {
467        return res;
468    }
469    if let Some(res) = try_accept_hyperlink(dom, node, &name) {
470        return res;
471    }
472
473    // Identity clone with transformed children.
474    let ne = dom.new_element(name.clone());
475    dom.copy_attributes(node, ne);
476    for c in dom.nodes(node) {
477        for tn in accept_all_other_revisions_transform(dom, c) {
478            dom.add(ne, tn);
479        }
480    }
481    vec![ne]
482}
483
484/// Port of `AcceptRevisionsForElement` (the documented simple-revision entry
485/// point, RevisionProcessor.ts:1004): RemoveRsid → AcceptMoveFromMoveTo →
486/// AcceptAllOtherRevisions → strip PT.UniqueId/RunIds → drop empty w:numPr.
487///
488/// NOTE: this is the element-level accept (handles the common ins/del/format
489/// cases). The fuller part-level pipeline (`AcceptRevisionsForPart`) adds
490/// deleted-paragraph-mark merging, move-from ranges, field codes, content
491/// controls, table merges, and OrderTcPr — see the module status note.
492///
493/// ACCEPT-SKIP-01: when the subtree has no tracked-revision elements, skip
494/// the two identity full-tree rebuilds (move + all-other) after RemoveRsid.
495pub fn accept_revisions_for_element(dom: &mut Dom, element: NodeId) -> NodeId {
496    let has_rev = element_has_tracked_revisions(dom, element);
497    let e = remove_rsid_transform(dom, element).expect("root not dropped by rsid removal");
498    let e = if has_rev {
499        let v = accept_move_from_move_to_transform(dom, e);
500        debug_assert_eq!(v.len(), 1);
501        let e = v[0];
502        let v = accept_all_other_revisions_transform(dom, e);
503        debug_assert_eq!(v.len(), 1);
504        v[0]
505    } else {
506        e
507    };
508
509    // Strip PT.UniqueId / PT.RunIds attributes from all descendants.
510    let unique_id = PT::unique_id();
511    let run_ids = PT::run_ids();
512    for d in dom.descendants_and_self(e, None) {
513        dom.set_attribute_value(d, &unique_id, None);
514        dom.set_attribute_value(d, &run_ids, None);
515    }
516
517    // Remove empty w:numPr elements.
518    let num_pr = W::num_pr();
519    for np in dom.descendants(e, Some(&num_pr)) {
520        if !dom.has_elements(np) {
521            dom.remove(np);
522        }
523    }
524    e
525}
526
527// ─────────────────────────────────────────────────────────────────────────────
528// P0 — document-scope accept/reject (mirror of AcceptRevisionsDocument /
529// RejectRevisionsDocument, RevisionProcessor.ts:909/:155). Needed by M4.B
530// HashBlockLevelContent, which hashes source1's accepted projection and
531// source2's rejected projection. pt:Unid is preserved (only PT.UniqueId/RunIds
532// are stripped by accept), so the projection's hashes correlate back.
533// ─────────────────────────────────────────────────────────────────────────────
534
535/// `AcceptRevisionsDocument` at element scope — accept all tracked revisions in
536/// the `root` element's subtree, returning the new root. Runs the FULL
537/// part-content pipeline (A.10), matching `AcceptRevisionsForPart` (:1314).
538pub fn accept_revisions_document(dom: &mut Dom, root: NodeId) -> NodeId {
539    accept_revisions_for_part_content(dom, root)
540}
541
542/// The "skipping" parent used by `ReverseRevisionsTransform` — nearest ancestor
543/// whose name is not `w:sdtContent`/`w:sdt`/`w:smartTag`.
544fn effective_parent(dom: &Dom, node: NodeId) -> Option<NodeId> {
545    let skip = [W::sdt_content(), W::sdt(), W::smart_tag()];
546    dom.ancestors(node, None)
547        .into_iter()
548        .find(|&a| dom.name(a).is_some_and(|n| !skip.contains(&n)))
549}
550
551/// Port of `ReverseRevisionsForPartTransform` — invert the *sense* of each
552/// revision (del↔ins, moveFrom↔moveTo, delText→t, custom-xml ranges, …),
553/// context-aware via the effective parent. Builds a fresh subtree.
554///
555/// Faithful quirk preserved: the `InInsert` flag is effectively always false
556/// (the TS creates a fresh `ReverseRevisionsInfo{InInsert:true}` for inserted
557/// runs but never threads it into the recursion), so the `w:t`→`w:delText`
558/// (InInsert) and `instrText`→`delInstrText` (InInsert) branches never fire.
559fn reverse_revisions_transform(dom: &mut Dom, node: NodeId) -> NodeId {
560    if !dom.is_element(node) {
561        return dom.clone_subtree(node);
562    }
563    let name = dom.name(node).unwrap();
564    let parent = effective_parent(dom, node);
565    let parent_name = parent.and_then(|p| dom.name(p));
566    let grandparent_is_ppr = parent
567        .and_then(|p| dom.parent(p))
568        .and_then(|gp| dom.name(gp))
569        .is_some_and(|n| n == W::p_pr());
570
571    // Deleted paragraph mark (del in rPr/pPr) → empty w:ins.
572    if name == W::del() && parent_name.as_ref() == Some(&W::r_pr()) && grandparent_is_ppr {
573        return dom.new_element(W::ins());
574    }
575    // Inserted paragraph mark (ins in rPr/pPr) → empty w:del.
576    if name == W::ins() && parent_name.as_ref() == Some(&W::r_pr()) && grandparent_is_ppr {
577        return dom.new_element(W::del());
578    }
579    // Deleted / inserted table row (del/ins in trPr) → empty swap.
580    if name == W::del() && parent_name.as_ref() == Some(&W::tr_pr()) {
581        return dom.new_element(W::ins());
582    }
583    if name == W::ins() && parent_name.as_ref() == Some(&W::tr_pr()) {
584        return dom.new_element(W::del());
585    }
586    // Any OTHER deleted content → w:ins (reversed children); any other inserted
587    // content → w:del. REJECT-LOSSLESS-01: the C# reference only flips del/ins
588    // whose effective parent is w:p / w:hyperlink / m:r, leaving a content del/ins
589    // nested in a transparent run container (`w:fldSimple`, `mc:Choice`/`mc:Fallback`,
590    // …) as identity — which the trailing accept then DROPS (del) or KEEPS (ins),
591    // losing the base/revised text (field results, AlternateContent). Since on reject
592    // a content deletion must always be RESTORED and a content insertion always
593    // REMOVED, flipping every remaining del↔ins is both correct and lossless. Reached
594    // only AFTER the paragraph-mark / table-row markers above (which carry no run
595    // children and must stay empty); `parent`/`parent_name` are still consulted there.
596    if name == W::del() {
597        return rebuild_named(dom, W::ins(), node, false);
598    }
599    if name == W::ins() {
600        return rebuild_named(dom, W::del(), node, false);
601    }
602
603    // moveFrom↔moveTo and their ranges (attributes preserved).
604    let swap_pairs: &[(&str, &str)] = &[
605        ("moveFrom", "moveTo"),
606        ("moveFromRangeStart", "moveToRangeStart"),
607        ("moveFromRangeEnd", "moveToRangeEnd"),
608        ("moveTo", "moveFrom"),
609        ("moveToRangeStart", "moveFromRangeStart"),
610        ("moveToRangeEnd", "moveFromRangeEnd"),
611        ("customXmlDelRangeStart", "customXmlInsRangeStart"),
612        ("customXmlDelRangeEnd", "customXmlInsRangeEnd"),
613        ("customXmlInsRangeStart", "customXmlDelRangeStart"),
614        ("customXmlInsRangeEnd", "customXmlDelRangeEnd"),
615        ("customXmlMoveFromRangeStart", "customXmlMoveToRangeStart"),
616        ("customXmlMoveFromRangeEnd", "customXmlMoveToRangeEnd"),
617        ("customXmlMoveToRangeStart", "customXmlMoveFromRangeStart"),
618        ("customXmlMoveToRangeEnd", "customXmlMoveFromRangeEnd"),
619        ("delInstrText", "instrText"),
620        ("delText", "t"),
621    ];
622    if name.namespace_name() == W::URI
623        && let Some((_, to)) = swap_pairs
624            .iter()
625            .find(|(from, _)| *from == name.local_name())
626    {
627        return rebuild_named(dom, W::name(to), node, true);
628    }
629
630    // Identity: rebuild with attributes + reversed children.
631    rebuild_named(dom, name, node, true)
632}
633
634/// Build `<new_name attrs? children…>` from `src`'s children (reversed).
635fn rebuild_named(dom: &mut Dom, new_name: XName, src: NodeId, keep_attrs: bool) -> NodeId {
636    let ne = dom.new_element(new_name);
637    if keep_attrs {
638        dom.copy_attributes(src, ne);
639    }
640    for c in dom.nodes(src) {
641        let t = reverse_revisions_transform(dom, c);
642        dom.add(ne, t);
643    }
644    ne
645}
646
647/// `ins` / `del` / `moveFrom` / `moveTo`, the paragraph-mark revisions
648/// `CT_ParaRPr` puts first.
649fn paragraph_mark_revision(name: &XName) -> bool {
650    name.namespace_name() == W::URI
651        && matches!(name.local_name(), "ins" | "del" | "moveFrom" | "moveTo")
652}
653
654/// A row-history mark `CT_TrPr` allows and the saved `CT_TrPrBase` does
655/// not: `w:ins`, `w:del`, then `w14:conflictIns`, `w14:conflictDel`.
656fn row_history_mark(name: &XName) -> bool {
657    if name.namespace_name() == W::URI {
658        return matches!(name.local_name(), "ins" | "del");
659    }
660    name.namespace_name() == W14::URI && matches!(name.local_name(), "conflictIns" | "conflictDel")
661}
662
663/// #1724: the cell was inserted, either on the live `w:tcPr` or on the
664/// `w:tcPr` a `w:tcPrChange` is about to put back. `CT_TcPrInner` can hold
665/// `w:cellIns`, so the restored mark is the cell's own insertion.
666fn inserted_cell(dom: &Dom, tc: NodeId) -> bool {
667    dom.elements(tc, Some(&W::tc_pr())).into_iter().any(|tcpr| {
668        dom.element(tcpr, &W::cell_ins()).is_some()
669            || dom
670                .element(tcpr, &W::tc_pr_change())
671                .and_then(|change| dom.element(change, &W::tc_pr()))
672                .is_some_and(|saved| dom.element(saved, &W::cell_ins()).is_some())
673    })
674}
675
676/// #1724 `c3`: a live `w:cellMerge` with `w:vMerge="rest"` and
677/// `w:vMergeOrig="cont"`. Word's Reject All of that one-row shape keeps
678/// the cell and removes its text. Read it here, before the transform
679/// drops the `w:cellMerge`.
680fn continued_merge_cell(dom: &Dom, tc: NodeId) -> bool {
681    let v_merge_orig = W::name("vMergeOrig");
682    dom.elements(tc, Some(&W::tc_pr())).into_iter().any(|tcpr| {
683        dom.elements(tcpr, Some(&W::cell_merge()))
684            .into_iter()
685            .any(|mark| {
686                dom.attribute(mark, &W::v_merge()) == Some("rest")
687                    && dom.attribute(mark, &v_merge_orig) == Some("cont")
688            })
689    })
690}
691
692/// Port of `RejectRevisionsForPartTransform` — revert the *non-invertible*
693/// revisions (property changes) and drop inserted structural markers. Returns
694/// `None` to drop the node.
695///
696/// A property element reverting to its saved copy keeps the revisions a
697/// selective resolution left tracked in it ([`carry_kept_revisions`]).
698fn reject_revisions_for_part_transform(dom: &mut Dom, node: NodeId) -> Option<NodeId> {
699    if !dom.is_element(node) {
700        return Some(dom.clone_subtree(node));
701    }
702    let name = dom.name(node).unwrap();
703
704    // Inserted numbering properties: numPr containing w:ins → drop.
705    if name == W::num_pr() && dom.element(node, &W::ins()).is_some() {
706        return None;
707    }
708    // Property-change reverts: replace the prop element by the change's saved copy.
709    let change_reverts: &[(&str, &str, &str)] = &[
710        ("pPr", "pPrChange", "pPr"),
711        ("sectPr", "sectPrChange", "sectPr"),
712        ("tblGrid", "tblGridChange", "tblGrid"),
713        ("tcPr", "tcPrChange", "tcPr"),
714        ("trPr", "trPrChange", "trPr"),
715        ("tblPrEx", "tblPrExChange", "tblPrEx"),
716        ("tblPr", "tblPrChange", "tblPr"),
717    ];
718    if name.namespace_name() == W::URI
719        && let Some((_, change, saved)) = change_reverts
720            .iter()
721            .find(|(prop, _, _)| *prop == name.local_name())
722        && let Some(chg) = dom.element(node, &W::name(change))
723    {
724        // the saved <w:pPr>/<w:tcPr>/… inside the *Change element
725        let new_prop = match dom.element(chg, &W::name(saved)) {
726            Some(sp) => dom.clone_subtree(sp),
727            None => dom.new_element(W::name(saved)),
728        };
729        // The saved pPr (CT_PPrBase) holds neither the paragraph mark's
730        // run properties nor a section break (#1708), so the live ones stay,
731        // last as the schema orders them: rPr, then sectPr. A source that
732        // left either in the saved copy gets the live state back, once:
733        // never a doubled rPr, nor a section break the paragraph lacks.
734        if name == W::p_pr() {
735            for e in dom.elements(new_prop, None) {
736                if dom
737                    .name(e)
738                    .is_some_and(|n| n == W::r_pr() || n == W::sect_pr())
739                {
740                    dom.remove(e);
741                }
742            }
743            for kept in [W::r_pr(), W::sect_pr()] {
744                if let Some(live) = dom.element(node, &kept) {
745                    let live_clone = dom.clone_subtree(live);
746                    dom.add(new_prop, live_clone);
747                }
748            }
749        }
750        // #1713: the saved trPr (CT_TrPrBase) has no row insertion or
751        // deletion. The live w:ins/w:del stay, so the reversal below still
752        // finds the row's own revision and Reject All removes an inserted
753        // row whose properties also changed.
754        // #1723: that base type also has no w14:conflictIns/conflictDel.
755        // They follow w:ins/w:del, which is where CT_TrPr puts them. A
756        // saved copy of either is dropped: two of one kind is invalid, and
757        // the live mark is the one Word keeps. Renaming them to w:ins/w:del
758        // waits until after accept (demote_row_conflict_marks): a w:ins in
759        // trPr would reverse into a w:del and Reject All would delete the
760        // row.
761        if name == W::tr_pr() {
762            for e in dom.elements(new_prop, None) {
763                if dom.name(e).is_some_and(|n| row_history_mark(&n)) {
764                    dom.remove(e);
765                }
766            }
767            for mark in dom.elements(node, None) {
768                if dom.name(mark).is_some_and(|n| row_history_mark(&n)) {
769                    let mark_clone = dom.clone_subtree(mark);
770                    dom.add(new_prop, mark_clone);
771                }
772            }
773        }
774        // R9: a sectPrChange records the section's properties, never its
775        // header and footer references (CT_SectPrBase has none): the live
776        // ones stay, first as the schema orders them (205503ead9).
777        if name == W::sect_pr() {
778            let refs: Vec<NodeId> = dom
779                .elements(node, None)
780                .into_iter()
781                .filter(|&e| {
782                    dom.name(e)
783                        .is_some_and(|n| n == W::header_reference() || n == W::footer_reference())
784                })
785                .collect();
786            for r in refs.into_iter().rev() {
787                let c = dom.clone_subtree(r);
788                dom.add_first(new_prop, c);
789            }
790        }
791        carry_kept_revisions(dom, node, new_prop, false);
792        return reject_revisions_for_part_transform(dom, new_prop);
793    }
794    // rPrChange: replace rPr by the change's saved rPr.
795    if name == W::r_pr()
796        && let Some(chg) = dom.element(node, &W::r_pr_change())
797    {
798        // Identify a paragraph mark (`w:pPr/w:rPr`) while `node` is still
799        // parented. A run's `w:rPr` is not one.
800        let paragraph_mark = dom.parent(node).is_some_and(|p| dom.name_is(p, &W::p_pr()));
801        let saved = dom.element(chg, &W::r_pr());
802        let new_rpr = match saved {
803            Some(sp) => dom.clone_subtree(sp),
804            None => dom.new_element(W::r_pr()),
805        };
806        // #1722: the reversal below joins on the live ins/del/moveFrom/moveTo.
807        // `CT_ParaRPrOriginal` can hold the same four, so a saved copy of one
808        // is removed and the live mark is put back, first, in that order. Two
809        // of one kind is invalid, and a saved insertion would join after a
810        // selective freeze had already kept the live mark. A run's `rPr` is
811        // left as the snapshot wrote it.
812        if paragraph_mark {
813            for e in dom.elements(new_rpr, None) {
814                if dom.name(e).is_some_and(|n| paragraph_mark_revision(&n)) {
815                    dom.remove(e);
816                }
817            }
818            let live: Vec<NodeId> = dom
819                .elements(node, None)
820                .into_iter()
821                .filter(|&e| dom.name(e).is_some_and(|n| paragraph_mark_revision(&n)))
822                .collect();
823            for mark in live.into_iter().rev() {
824                let cloned = dom.clone_subtree(mark);
825                dom.add_first(new_rpr, cloned);
826            }
827        }
828        carry_kept_revisions(dom, node, new_rpr, true);
829        return reject_revisions_for_part_transform(dom, new_rpr);
830    }
831    // numberingChange / cellDel / cellMerge → drop.
832    if name == W::numbering_change() || name == W::cell_del() || name == W::cell_merge() {
833        return None;
834    }
835    // #1724: a cellIns on the live tcPr (c0, gb2) or on the tcPr the
836    // change restores (c1) drops the cell. A restored cellDel is not an
837    // insertion: the drop below removes the marker and the cell stays.
838    // Checking the rebuilt tcPr instead would keep gb2, whose saved copy
839    // has no cellIns.
840    if name == W::tc() && inserted_cell(dom, node) {
841        return None;
842    }
843    // #1724 c3: decided on the live cellMerge, which the rebuild drops.
844    let clear_blocks = name == W::tc() && continued_merge_cell(dom, node);
845
846    // Identity: rebuild with attributes + transformed children.
847    let ne = dom.new_element(name);
848    dom.copy_attributes(node, ne);
849    let mut kept_block = false;
850    for c in dom.nodes(node) {
851        if clear_blocks && dom.name(c).is_some_and(|n| n == W::p() || n == W::tbl()) {
852            continue;
853        }
854        if let Some(t) = reject_revisions_for_part_transform(dom, c) {
855            if clear_blocks && dom.name(t).is_some_and(|n| n == W::p() || n == W::tbl()) {
856                kept_block = true;
857            }
858            dom.add(ne, t);
859        }
860    }
861    // A cell has to hold a block. The continued merge's paragraphs and
862    // nested tables are gone, so the cell keeps an empty paragraph.
863    // Do not write w:vMerge: Word's c3 output has none.
864    if clear_blocks && !kept_block {
865        let empty = dom.new_element(W::p());
866        dom.add(ne, empty);
867    }
868    Some(ne)
869}
870
871/// `RejectRevisionsDocument` at element scope: revert property changes, invert
872/// the sense of every remaining revision, strip rsids, then accept. The net
873/// effect is the document's *original* (pre-revision) projection.
874///
875/// `RejectRevisionsDocument` at element scope — reject every tracked
876/// revision in `root`'s subtree (revert → reverse → remove rsid → accept),
877/// returning the new root.
878///
879/// When the subtree has no tracked-revision elements the full reject
880/// path is identity; only `RemoveRsid` is needed (in-place). The return
881/// value is the same `root` `NodeId`.
882pub fn reject_revisions_document(dom: &mut Dom, root: NodeId) -> NodeId {
883    reject_content(dom, root, false, &mut Vec::new())
884}
885
886fn reject_content(
887    dom: &mut Dom,
888    root: NodeId,
889    keep_comments: bool,
890    kept: &mut Vec<String>,
891) -> NodeId {
892    if !element_has_tracked_revisions(dom, root) {
893        return remove_rsid_transform(dom, root).expect("reject clean: root not dropped by rsid");
894    }
895    let reverted =
896        reject_revisions_for_part_transform(dom, root).expect("reject: root must not be dropped");
897    // O.0 (#1243): before the reversal, drop only the orphan moveTo range
898    // markers. The reversal would turn them into moveFrom ranges whose
899    // unwrapped content A.2 deletes on the accept pass below, but Word keeps
900    // an orphan moveTo range's content on Reject (#1235). Orphan moveFrom
901    // markers survive the reversal as moveTo markers — inert for A.2/A.4,
902    // stripped by A.10 — so their content is kept too (#1243).
903    let reverted = normalize_orphan_moves(dom, reverted, OrphanMovePass::RejectMoveToMarkers);
904    let reversed = reverse_revisions_transform(dom, reverted);
905    let derssid = remove_rsid_transform(dom, reversed).expect("reject: root not dropped by rsid");
906    let accepted = accept_content(dom, derssid, keep_comments, kept);
907    // #1723: only now. The short-circuit above (no w: revision at all)
908    // never reaches here, so a bare conflict mark is left as Word wrote it.
909    demote_row_conflict_marks(dom, accepted);
910    accepted
911}
912
913/// Word's Reject All of a row writes `w14:conflictIns` / `w14:conflictDel`
914/// back as a plain `w:ins` / `w:del` on that row. The mark keeps its own
915/// id, author and date. A conflict mark on a run or a paragraph mark is
916/// not this case.
917fn demote_row_conflict_marks(dom: &mut Dom, root: NodeId) {
918    let conflict_ins = W14::name("conflictIns");
919    let conflict_del = W14::name("conflictDel");
920    let marks: Vec<(NodeId, bool)> = dom
921        .descendants(root, None)
922        .into_iter()
923        .filter_map(|mark| {
924            let ins = dom.name_is(mark, &conflict_ins);
925            if !ins && !dom.name_is(mark, &conflict_del) {
926                return None;
927            }
928            let in_row = dom
929                .parent(mark)
930                .is_some_and(|parent| dom.name_is(parent, &W::tr_pr()));
931            in_row.then_some((mark, ins))
932        })
933        .collect();
934    for (mark, ins) in marks {
935        dom.set_name(mark, if ins { W::ins() } else { W::del() });
936    }
937}
938
939// ───────────────────────────── A.0 — part-pipeline walkers ──────────────────
940
941/// `TagTypeEnum` (RevisionProcessor.cs :2389): how an element appears in the
942/// doc-order tag stream.
943#[derive(Debug, Clone, Copy, PartialEq, Eq)]
944pub enum TagType {
945    /// An element open tag (one or more children follow).
946    Element,
947    /// An element that carries no children of any kind (no elements and no
948    /// text); serializes as a self-closing tag in XML.
949    EmptyElement,
950    /// An element close tag (its children are exhausted).
951    EndElement,
952}
953
954/// `Tag` (RevisionProcessor.cs :2393): one open/empty/close event.
955#[derive(Debug, Clone, Copy, PartialEq, Eq)]
956pub struct Tag {
957    /// The element this tag event names.
958    pub element: NodeId,
959    /// Whether this is an open / empty / close event.
960    pub tag_type: TagType,
961}
962
963/// A.0 — `DescendantAndSelfTags` (RevisionProcessor.cs :2397): stream
964/// `element` and its descendants as open / empty / close tags in document
965/// order.
966///
967/// Faithful to C#: a child with no nodes AT ALL (no elements and no
968/// text) is `EmptyElement`; a child with only text still opens and closes;
969/// the root element itself always gets an open/close pair, never
970/// `EmptyElement`.
971pub fn descendant_and_self_tags(dom: &Dom, element: NodeId) -> Vec<Tag> {
972    let mut out = vec![Tag {
973        element,
974        tag_type: TagType::Element,
975    }];
976    // DOM-ITER-04: stack of (element children, next index, last advanced element).
977    // Element-child lists still materialize (EndElement needs the finished id),
978    // but empty checks use `child_count` (no `nodes()` clone).
979    let mut stack: Vec<(Vec<NodeId>, usize)> = vec![(element_children_vec(dom, element), 0)];
980    while let Some(top) = stack.last_mut() {
981        if top.1 < top.0.len() {
982            let current = top.0[top.1];
983            top.1 += 1;
984            if dom.child_count(current) == 0 {
985                out.push(Tag {
986                    element: current,
987                    tag_type: TagType::EmptyElement,
988                });
989                continue;
990            }
991            out.push(Tag {
992                element: current,
993                tag_type: TagType::Element,
994            });
995            stack.push((element_children_vec(dom, current), 0));
996            continue;
997        }
998        stack.pop();
999        if let Some(parent_frame) = stack.last() {
1000            // C#: EndElement for `iteratorStack.Peek().Current` — the element
1001            // whose children were just exhausted.
1002            out.push(Tag {
1003                element: parent_frame.0[parent_frame.1 - 1],
1004                tag_type: TagType::EndElement,
1005            });
1006        }
1007    }
1008    out.push(Tag {
1009        element,
1010        tag_type: TagType::EndElement,
1011    });
1012    out
1013}
1014
1015/// Direct element children (document order) without the `elements()` filter path.
1016fn element_children_vec(dom: &Dom, id: NodeId) -> Vec<NodeId> {
1017    let mut out = Vec::new();
1018    let n = dom.child_count(id);
1019    for i in 0..n {
1020        let c = dom.child_at(id, i);
1021        if dom.is_element(c) {
1022            out.push(c);
1023        }
1024    }
1025    out
1026}
1027
1028/// `BlockContentInfo` (RevisionProcessor.cs :52): prev / this / next links
1029/// for block-level content. [`iterate_block_content_elements`] fills all
1030/// three (`this_block_content_element` always `Some`);
1031/// [`get_paragraph_info`] fills only the previous sibling and `this`.
1032#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1033pub struct BlockContentInfo {
1034    /// Previous block-content element in document order (`Some` after the
1035    /// first chain element).
1036    pub previous_block_content_element: Option<NodeId>,
1037    /// The chain element itself (always `Some` from
1038    /// [`iterate_block_content_elements`]).
1039    pub this_block_content_element: Option<NodeId>,
1040    /// Next block-content element in document order (`None` at the end).
1041    pub next_block_content_element: Option<NodeId>,
1042}
1043
1044/// First paragraph, table, or opaque equation block among `roots`' descendants-and-self, document order.
1045/// DOM-ITER-04: early-exit iterative walk (no full `descendants_and_self` Vec).
1046fn first_block_content(dom: &Dom, roots: &[NodeId]) -> Option<NodeId> {
1047    let (p, tbl) = (W::p(), W::tbl());
1048    let is_block = |e: NodeId| {
1049        dom.name(e).is_some_and(|n| {
1050            n == p || n == tbl || n == M::name("oMath") || n == M::name("oMathPara")
1051        })
1052    };
1053    for &r in roots {
1054        if is_block(r) {
1055            return Some(r);
1056        }
1057        let mut stack: Vec<(NodeId, usize)> = vec![(r, 0)];
1058        while let Some((node, i)) = stack.last_mut() {
1059            let n = dom.child_count(*node);
1060            if *i >= n {
1061                stack.pop();
1062                continue;
1063            }
1064            let c = dom.child_at(*node, *i);
1065            *i += 1;
1066            if !dom.is_element(c) {
1067                continue;
1068            }
1069            if is_block(c) {
1070                return Some(c);
1071            }
1072            stack.push((c, 0));
1073        }
1074    }
1075    None
1076}
1077
1078/// Element siblings after `id`, document order.
1079fn elements_after_self(dom: &Dom, id: NodeId) -> Vec<NodeId> {
1080    dom.nodes_after_self(id)
1081        .into_iter()
1082        .filter(|&n| dom.is_element(n))
1083        .collect()
1084}
1085
1086/// A.0 — `IterateBlockContentElements` (:1909) + `AnnotateBlockContentElements`
1087/// (:1855): the doc-order chain of paragraphs, tables, and equation blocks under
1088/// `element`, linked prev/this/next. FAITHFUL: the next-search starts at the
1089/// current element's FOLLOWING siblings (climbing ancestors up to `element`),
1090/// so a table's inner paragraphs never appear once the table itself matched.
1091pub fn iterate_block_content_elements(dom: &Dom, element: NodeId) -> Vec<BlockContentInfo> {
1092    // DOM-ITER-04: one element-children collect (was two `elements()` calls).
1093    let kids = element_children_vec(dom, element);
1094    if kids.is_empty() {
1095        return Vec::new();
1096    }
1097    let Some(first) = first_block_content(dom, &kids) else {
1098        return Vec::new();
1099    };
1100
1101    let mut chain: Vec<NodeId> = vec![first];
1102    'outer: loop {
1103        let mut current = *chain.last().unwrap();
1104        loop {
1105            if let Some(next) = first_block_content(dom, &elements_after_self(dom, current)) {
1106                chain.push(next);
1107                break;
1108            }
1109            let Some(parent) = dom.parent(current) else {
1110                break 'outer;
1111            };
1112            current = parent;
1113            // When we've backed up the tree to the contentContainer, we're done.
1114            if current == element {
1115                break 'outer;
1116            }
1117        }
1118    }
1119
1120    (0..chain.len())
1121        .map(|i| BlockContentInfo {
1122            previous_block_content_element: (i > 0).then(|| chain[i - 1]),
1123            this_block_content_element: Some(chain[i]),
1124            next_block_content_element: chain.get(i + 1).copied(),
1125        })
1126        .collect()
1127}
1128
1129/// `W.BlockLevelContentContainers` (PtOpenXmlUtil.cs :5569), plus
1130/// `w:comment`: the C# pipeline never visits `comments.xml`, but Word's
1131/// Accept/Reject All does, and a deleted or inserted paragraph mark inside
1132/// a comment merges the comment's own paragraphs — never across the
1133/// `w:comment` boundary. Text boxes are not in this list: both names live
1134/// in [`crate::ooxml::text_box_names`] (#1318).
1135fn block_level_content_containers() -> [XName; 7] {
1136    [
1137        W::body(),
1138        W::tc(),
1139        W::hdr(),
1140        W::ftr(),
1141        W::endnote(),
1142        W::footnote(),
1143        W::comment(),
1144    ]
1145}
1146
1147/// `w:txbxContent` or the Strict `wne:txbxContent`.
1148fn is_text_box(name: &XName) -> bool {
1149    crate::ooxml::text_box_names().contains(name)
1150}
1151
1152fn is_block_level_content_container(name: &XName) -> bool {
1153    block_level_content_containers().contains(name) || is_text_box(name)
1154}
1155
1156/// A.0 — `GetParagraphInfo` (:2917) + `InitializeParagraphInfo` (:2890): for a
1157/// child of a block-level content container, `this` = the first
1158/// descendant-or-self in {`w:p`, `w:tc`, either text-box name} — nulled when
1159/// that first hit is a `tc` or a text box (means "no own paragraph") — and
1160/// `previous` = the previous element sibling (content element of any kind).
1161///
1162/// # Panics
1163/// Like the C# `ArgumentException`, panics when the parent is not a
1164/// block-level content container.
1165pub fn get_paragraph_info(dom: &Dom, content_element: NodeId) -> BlockContentInfo {
1166    let parent = dom
1167        .parent(content_element)
1168        .expect("GetParagraphInfo called for element without parent");
1169    let parent_name = dom.name(parent);
1170    assert!(
1171        parent_name.is_some_and(|n| is_block_level_content_container(&n)),
1172        "GetParagraphInfo called for element that is not child of content container"
1173    );
1174
1175    let (p, tc) = (W::p(), W::tc());
1176    let mut paragraph = dom
1177        .descendants_and_self(content_element, None)
1178        .into_iter()
1179        .find(|&e| {
1180            dom.name(e)
1181                .is_some_and(|n| n == p || n == tc || is_text_box(&n))
1182        });
1183    if let Some(hit) = paragraph
1184        && dom.name(hit).is_some_and(|n| n == tc || is_text_box(&n))
1185    {
1186        paragraph = None;
1187    }
1188
1189    let previous = dom
1190        .nodes_before_self(content_element)
1191        .into_iter()
1192        .rev()
1193        .find(|&n| dom.is_element(n));
1194
1195    BlockContentInfo {
1196        previous_block_content_element: previous,
1197        this_block_content_element: paragraph,
1198        next_block_content_element: None,
1199    }
1200}
1201
1202/// A.0 — `ContentElementsBeforeSelf` (:2926): previous element siblings,
1203/// nearest first.
1204pub fn content_elements_before_self(dom: &Dom, element: NodeId) -> Vec<NodeId> {
1205    dom.nodes_before_self(element)
1206        .into_iter()
1207        .rev()
1208        .filter(|&n| dom.is_element(n))
1209        .collect()
1210}
1211
1212// ───────────────────────────── A.1 — field-code fixup ───────────────────────
1213
1214/// A.1 — `TransformInstrTextToDelInstrText` (:1433): rename `w:instrText` to
1215/// `w:delInstrText` (attrs + nodes carried as-is), rebuilding everything else.
1216fn transform_instr_text_to_del_instr_text(dom: &mut Dom, node: NodeId) -> NodeId {
1217    if !dom.is_element(node) {
1218        return dom.clone_subtree(node);
1219    }
1220    let name = dom.name(node).unwrap();
1221    if name == W::instr_text() {
1222        let ne = dom.new_element(W::del_instr_text());
1223        dom.copy_attributes(node, ne);
1224        // C# takes element.Nodes() as-is (no recursion below instrText).
1225        for c in dom.nodes(node) {
1226            let cc = dom.clone_subtree(c);
1227            dom.add(ne, cc);
1228        }
1229        return ne;
1230    }
1231    let ne = dom.new_element(name);
1232    dom.copy_attributes(node, ne);
1233    for c in dom.nodes(node) {
1234        let tc = transform_instr_text_to_del_instr_text(dom, c);
1235        dom.add(ne, tc);
1236    }
1237    ne
1238}
1239
1240/// A.1 — `FixUpDeletedOrInsertedFieldCodesTransform` (:1354): inside each
1241/// `w:p`, group-adjacent the child elements by kind — 2 = `w:del` holding
1242/// `w:r/w:fldChar`, 3 = `w:ins` holding `w:r/w:fldChar`, 4 = `w:r` with
1243/// `w:instrText`, 1 = other. A key-4 group strictly BETWEEN two key-2 groups
1244/// is wrapped in a new `w:del` with `instrText` → `delInstrText`; between two
1245/// key-3 groups it is wrapped in a new `w:ins` (instrText kept). Boundary or
1246/// mixed-flank groups pass through. FAITHFUL: the paragraph branch iterates
1247/// child ELEMENTS only (direct text under `w:p` is dropped, as in C#), and
1248/// the wrapping del/ins carries no author/date attributes.
1249pub fn fix_up_deleted_or_inserted_field_codes_transform(dom: &mut Dom, node: NodeId) -> NodeId {
1250    // ACCEPT-SKIP-A1: no field marks → identity (keep parent links; do not detach).
1251    let fld = W::fld_char();
1252    let instr = W::instr_text();
1253    if !element_or_desc_has_name(dom, node, &fld) && !element_or_desc_has_name(dom, node, &instr) {
1254        return node;
1255    }
1256    if !dom.is_element(node) {
1257        return node;
1258    }
1259    let name = dom.name(node).unwrap();
1260    if name == W::p() {
1261        let key_of = |dom: &Dom, e: NodeId| -> u8 {
1262            let n = dom.name(e).unwrap();
1263            let holds_fld_char = |d: &Dom| {
1264                d.elements(e, Some(&W::r()))
1265                    .into_iter()
1266                    .any(|r| d.element(r, &W::fld_char()).is_some())
1267            };
1268            if n == W::del() && holds_fld_char(dom) {
1269                2
1270            } else if n == W::ins() && holds_fld_char(dom) {
1271                3
1272            } else if n == W::r() && dom.element(e, &W::instr_text()).is_some() {
1273                4
1274            } else {
1275                1
1276            }
1277        };
1278        let children = dom.elements(node, None);
1279        let grouped = crate::util::group_adjacent(children, |&e| key_of(dom, e));
1280        let g_len = grouped.len();
1281
1282        let new_paragraph = dom.new_element(W::p());
1283        dom.copy_attributes(node, new_paragraph);
1284        for (i, (key, group)) in grouped.iter().enumerate() {
1285            match key {
1286                1..=3 => {
1287                    for &e in group {
1288                        let t = fix_up_deleted_or_inserted_field_codes_transform(dom, e);
1289                        dom.add(new_paragraph, t);
1290                    }
1291                }
1292                4 => {
1293                    let flanked_by = |k: u8| {
1294                        i != 0 && i != g_len - 1 && grouped[i - 1].0 == k && grouped[i + 1].0 == k
1295                    };
1296                    if flanked_by(2) {
1297                        let del = dom.new_element(W::del());
1298                        for &e in group {
1299                            let t = transform_instr_text_to_del_instr_text(dom, e);
1300                            dom.add(del, t);
1301                        }
1302                        dom.add(new_paragraph, del);
1303                    } else if flanked_by(3) {
1304                        let ins = dom.new_element(W::ins());
1305                        for &e in group {
1306                            let t = fix_up_deleted_or_inserted_field_codes_transform(dom, e);
1307                            dom.add(ins, t);
1308                        }
1309                        dom.add(new_paragraph, ins);
1310                    } else {
1311                        for &e in group {
1312                            let t = fix_up_deleted_or_inserted_field_codes_transform(dom, e);
1313                            dom.add(new_paragraph, t);
1314                        }
1315                    }
1316                }
1317                _ => unreachable!("Internal error"),
1318            }
1319        }
1320        return new_paragraph;
1321    }
1322    let ne = dom.new_element(name);
1323    dom.copy_attributes(node, ne);
1324    for c in dom.nodes(node) {
1325        let tc = fix_up_deleted_or_inserted_field_codes_transform(dom, c);
1326        dom.add(ne, tc);
1327    }
1328    ne
1329}
1330
1331// ────────── O.0 — orphan move normalization (#1235, #1243) ───────────
1332
1333/// Which orphan-move cleanup a resolution path runs (#1243).
1334#[derive(Clone, Copy, PartialEq, Eq)]
1335enum OrphanMovePass {
1336    /// Accept (and Reject, on its reversed tree): orphan `moveTo` elements
1337    /// become `w:ins` and orphan `moveFrom` elements become `w:del`; range
1338    /// markers stay. Word deletes an orphan `moveFromRange`'s unwrapped
1339    /// content on Accept (#1243), which is A.2's own reading of the
1340    /// markers, and A.10 strips every leftover marker afterwards.
1341    AcceptElements,
1342    /// Reject, before the reversal: drop only orphan `moveToRange…`
1343    /// markers (no element conversion). The reversal would otherwise turn
1344    /// them into `moveFromRange` markers whose unwrapped content A.2
1345    /// deletes on the accept pass below, while Word keeps an orphan
1346    /// `moveToRange`'s content on Reject (#1235).
1347    RejectMoveToMarkers,
1348}
1349
1350/// #1235, #1243: a `w:moveTo` / `w:moveFrom` is an ORPHAN when no range of
1351/// the other kind shares its `w:name` in the same part — a bare `moveTo`
1352/// has no `w:name` at all, so it is an orphan unless it sits inside a
1353/// paired `moveToRange`. Word keeps an orphan `moveTo` like an insertion
1354/// and an orphan `moveFrom` like a deletion; only the elements themselves
1355/// carry moved content.
1356///
1357/// [`OrphanMovePass::AcceptElements`] rewrites those elements to
1358/// `w:ins`/`w:del` and leaves every range marker in place: Word deletes the
1359/// unwrapped content of a `moveFromRange` on Accept whether or not a
1360/// `moveToRange` shares its `w:name` (#1243), so A.2 (A.4 for the
1361/// `customXml…` markers) must still see an orphan `moveFromRange`.
1362/// [`OrphanMovePass::RejectMoveToMarkers`] drops only orphan
1363/// `moveToRange`/`customXmlMoveToRange` markers, before the reversal turns
1364/// them into `moveFromRange` markers whose content A.2 would wrongly
1365/// delete — Word keeps it (#1235). A well-formed move —
1366/// `moveFromRange`/`moveToRange` sharing a `w:name` — keeps its markers
1367/// and its `moveFrom`/`moveTo` elements and is untouched.
1368fn normalize_orphan_moves(dom: &mut Dom, root: NodeId, pass: OrphanMovePass) -> NodeId {
1369    let ns = W::URI;
1370    let mut from_names: HashSet<String> = HashSet::new();
1371    let mut to_names: HashSet<String> = HashSet::new();
1372    for e in dom.descendants_and_self(root, None) {
1373        let Some(n) = dom.name(e) else { continue };
1374        if n.namespace_name() != ns {
1375            continue;
1376        }
1377        match n.local_name() {
1378            "moveFromRangeStart" | "customXmlMoveFromRangeStart" => {
1379                if let Some(v) = dom.attribute(e, &W::name("name")) {
1380                    from_names.insert(v.to_string());
1381                }
1382            }
1383            "moveToRangeStart" | "customXmlMoveToRangeStart" => {
1384                if let Some(v) = dom.attribute(e, &W::name("name")) {
1385                    to_names.insert(v.to_string());
1386                }
1387            }
1388            _ => {}
1389        }
1390    }
1391    match pass {
1392        // No moveTo range markers exist → nothing to drop before the
1393        // reversal.
1394        OrphanMovePass::RejectMoveToMarkers if to_names.is_empty() => return root,
1395        OrphanMovePass::AcceptElements if from_names.is_empty() && to_names.is_empty() => {
1396            // Ranges cannot tell orphan from paired without names, but a bare
1397            // `w:moveTo` / `w:moveFrom` is still orphaned: it has no `w:name`
1398            // to pair with anything.
1399            let has_move = dom.descendants_and_self(root, None).into_iter().any(|e| {
1400                dom.name(e)
1401                    .is_some_and(|n| n == W::move_to() || n == W::move_from())
1402            });
1403            if !has_move {
1404                return root;
1405            }
1406        }
1407        _ => {}
1408    }
1409
1410    let mut to_ins: HashSet<NodeId> = HashSet::new();
1411    let mut to_del: HashSet<NodeId> = HashSet::new();
1412    let mut drop_markers: HashSet<NodeId> = HashSet::new();
1413    // id → w:name of every currently open range, by flavor.
1414    let mut open_from: HashMap<String, String> = HashMap::new();
1415    let mut open_to: HashMap<String, String> = HashMap::new();
1416    for tag in descendant_and_self_tags(dom, root) {
1417        let e = tag.element;
1418        let Some(n) = dom.name(e) else { continue };
1419        if n.namespace_name() != ns {
1420            continue;
1421        }
1422        match n.local_name() {
1423            "moveFromRangeStart" | "customXmlMoveFromRangeStart" => {
1424                let id = dom.attribute(e, &W::id()).unwrap_or("").to_string();
1425                let name = dom.attribute(e, &W::name("name")).unwrap_or("").to_string();
1426                open_from.insert(id, name);
1427            }
1428            "moveFromRangeEnd" | "customXmlMoveFromRangeEnd" => {
1429                let id = dom.attribute(e, &W::id()).unwrap_or("");
1430                open_from.remove(id);
1431            }
1432            "moveToRangeStart" | "customXmlMoveToRangeStart" => {
1433                let id = dom.attribute(e, &W::id()).unwrap_or("").to_string();
1434                let name = dom.attribute(e, &W::name("name")).unwrap_or("").to_string();
1435                if pass == OrphanMovePass::RejectMoveToMarkers && !from_names.contains(&name) {
1436                    drop_markers.insert(e);
1437                }
1438                open_to.insert(id, name);
1439            }
1440            "moveToRangeEnd" | "customXmlMoveToRangeEnd" => {
1441                let id = dom.attribute(e, &W::id()).unwrap_or("");
1442                if let Some(name) = open_to.remove(id)
1443                    && pass == OrphanMovePass::RejectMoveToMarkers
1444                    && !from_names.contains(&name)
1445                {
1446                    drop_markers.insert(e);
1447                }
1448            }
1449            "moveTo"
1450                if tag.tag_type != TagType::EndElement
1451                    && pass == OrphanMovePass::AcceptElements =>
1452            {
1453                let inside_paired_range = open_to.values().any(|name| from_names.contains(name));
1454                if !inside_paired_range {
1455                    to_ins.insert(e);
1456                }
1457            }
1458            "moveFrom"
1459                if tag.tag_type != TagType::EndElement
1460                    && pass == OrphanMovePass::AcceptElements =>
1461            {
1462                let inside_paired_range = open_from.values().any(|name| to_names.contains(name));
1463                if !inside_paired_range {
1464                    to_del.insert(e);
1465                }
1466            }
1467            _ => {}
1468        }
1469    }
1470    if to_ins.is_empty() && to_del.is_empty() && drop_markers.is_empty() {
1471        return root;
1472    }
1473    normalize_orphan_moves_transform(dom, root, &to_ins, &to_del, &drop_markers)
1474        .expect("the part root is never a move element or range marker")
1475}
1476
1477/// Rebuild for [`normalize_orphan_moves`]: orphan `moveTo`/`moveFrom`
1478/// re-emerge as `w:ins`/`w:del` (attributes preserved), orphan range markers
1479/// vanish, everything else rebuilds recursively.
1480fn normalize_orphan_moves_transform(
1481    dom: &mut Dom,
1482    node: NodeId,
1483    to_ins: &HashSet<NodeId>,
1484    to_del: &HashSet<NodeId>,
1485    drop_markers: &HashSet<NodeId>,
1486) -> Option<NodeId> {
1487    if !dom.is_element(node) {
1488        return Some(dom.clone_subtree(node));
1489    }
1490    if drop_markers.contains(&node) {
1491        return None;
1492    }
1493    let new_name = if to_ins.contains(&node) {
1494        W::ins()
1495    } else if to_del.contains(&node) {
1496        W::del()
1497    } else {
1498        dom.name(node).unwrap()
1499    };
1500    let ne = dom.new_element(new_name);
1501    dom.copy_attributes(node, ne);
1502    for c in dom.nodes(node) {
1503        if let Some(tc) = normalize_orphan_moves_transform(dom, c, to_ins, to_del, drop_markers) {
1504            dom.add(ne, tc);
1505        }
1506    }
1507    Some(ne)
1508}
1509
1510// ───────────────────────────── A.2 — moveFrom ranges ────────────────────────
1511
1512/// A.2 — `AcceptMoveFromRanges` (:1530): walk the tag stream; while one or
1513/// more `moveFromRangeStart` ids are open, record every other element's open
1514/// tag (start-list) and close tag (end-list; empty elements land in both).
1515/// When a `moveFromRangeEnd` MATCHES an open id, that range's records flush
1516/// into the global lists; an unmatched start never flushes (inert). Elements
1517/// present in BOTH global lists — i.e. strictly inside a matched range — are
1518/// deleted via a rebuild; with nothing to delete the input element is
1519/// returned unchanged (identity, like C#). The range markers themselves are
1520/// never collected (AcceptAllOtherRevisions strips them later).
1521pub fn accept_move_from_ranges(dom: &mut Dom, document: NodeId) -> NodeId {
1522    let to_delete = move_from_range_deleted_elements(dom, document);
1523    if to_delete.is_empty() {
1524        return document;
1525    }
1526    accept_move_from_ranges_transform(dom, document, &to_delete)
1527        .expect("the document root is never in a moveFrom range")
1528}
1529
1530/// Elements wholly removed by completed move-from ranges. The bookmark
1531/// prepass uses the same deletion set before wrappers/anchors are hoisted,
1532/// so range-only moved characters count as deleted just like wrapped ones.
1533fn move_from_range_deleted_elements(dom: &Dom, document: NodeId) -> HashSet<NodeId> {
1534    elements_inside_matched_ranges(
1535        dom,
1536        document,
1537        &W::move_from_range_start(),
1538        &W::move_from_range_end(),
1539    )
1540}
1541
1542/// Elements wholly inside a matched custom-XML move-from range. Accept
1543/// deletes those elements; the annotation prepass has to count them deleted
1544/// before that transform runs.
1545fn custom_xml_move_from_deleted_elements(dom: &Dom, document: NodeId) -> HashSet<NodeId> {
1546    elements_inside_matched_ranges(
1547        dom,
1548        document,
1549        &W::name("customXmlMoveFromRangeStart"),
1550        &W::name("customXmlMoveFromRangeEnd"),
1551    )
1552}
1553
1554fn elements_inside_matched_ranges(
1555    dom: &Dom,
1556    document: NodeId,
1557    start: &XName,
1558    end: &XName,
1559) -> HashSet<NodeId> {
1560    use std::collections::{HashMap, HashSet};
1561
1562    let mut start_tags_in_range: Vec<NodeId> = Vec::new();
1563    let mut end_tags_in_range: Vec<NodeId> = Vec::new();
1564    // id → (potential start tags, potential end tags)
1565    let mut potential: HashMap<String, (Vec<NodeId>, Vec<NodeId>)> = HashMap::new();
1566
1567    for tag in descendant_and_self_tags(dom, document) {
1568        let name = dom.name(tag.element).unwrap();
1569        if &name == start {
1570            let id = dom
1571                .attribute(tag.element, &W::id())
1572                .unwrap_or("")
1573                .to_string();
1574            potential.insert(id, (Vec::new(), Vec::new()));
1575            continue;
1576        }
1577        if &name == end {
1578            let id = dom.attribute(tag.element, &W::id()).unwrap_or("");
1579            if let Some((starts, ends)) = potential.remove(id) {
1580                start_tags_in_range.extend(starts);
1581                end_tags_in_range.extend(ends);
1582            }
1583            continue;
1584        }
1585        if potential.is_empty() {
1586            continue;
1587        }
1588        match tag.tag_type {
1589            TagType::Element => {
1590                for (starts, _) in potential.values_mut() {
1591                    starts.push(tag.element);
1592                }
1593            }
1594            TagType::EmptyElement => {
1595                for (starts, ends) in potential.values_mut() {
1596                    starts.push(tag.element);
1597                    ends.push(tag.element);
1598                }
1599            }
1600            TagType::EndElement => {
1601                for (_, ends) in potential.values_mut() {
1602                    ends.push(tag.element);
1603                }
1604            }
1605        }
1606    }
1607
1608    let end_set: HashSet<NodeId> = end_tags_in_range.into_iter().collect();
1609    // A range is a pair of markers, not a container: Word ends one inside the
1610    // first cell of the table after a moved heading (30f20e787b). The
1611    // properties of a container the range only enters stay with it (a table
1612    // keeps its tblPr and tblGrid); one wholly inside goes with its container.
1613    // A paragraph's pPr inside the range is its mark, not moved text: its
1614    // deleted or moved-from state is what A.5a joins paragraphs by (Word),
1615    // and a paragraph that survives keeps its formatting.
1616    start_tags_in_range
1617        .into_iter()
1618        .filter(|&e| {
1619            end_set.contains(&e)
1620                // Empty/partially surviving range anchors were hoisted from
1621                // moveFrom after wholly deleted bookmarks were removed.
1622                // The move range must not discard those anchors a second time.
1623                && !dom.name(e).is_some_and(|name| is_inline_range_marker(&name))
1624                && !is_container_property(dom, e)
1625                && !dom
1626                    .ancestors(e, None)
1627                    .into_iter()
1628                    .any(|a| is_container_property(dom, a))
1629        })
1630        .collect()
1631}
1632
1633/// Is `e` the property element of its container (a paragraph's pPr, a
1634/// table's tblPr or tblGrid, a row's trPr or tblPrEx, a cell's tcPr, a
1635/// content control's sdtPr or sdtEndPr)?
1636fn is_container_property(dom: &Dom, e: NodeId) -> bool {
1637    dom.name(e).is_some_and(|n| {
1638        n.namespace_name() == W::URI
1639            && matches!(
1640                n.local_name(),
1641                "pPr" | "tblPr" | "tblGrid" | "tblPrEx" | "trPr" | "tcPr" | "sdtPr" | "sdtEndPr"
1642            )
1643    })
1644}
1645
1646/// A.2 — `AcceptMoveFromRangesTransform` (:2629): rebuild, dropping the
1647/// elements marked for deletion (and thereby their subtrees).
1648fn accept_move_from_ranges_transform(
1649    dom: &mut Dom,
1650    node: NodeId,
1651    to_delete: &std::collections::HashSet<NodeId>,
1652) -> Option<NodeId> {
1653    if !dom.is_element(node) {
1654        return Some(dom.clone_subtree(node));
1655    }
1656    if to_delete.contains(&node) {
1657        return None;
1658    }
1659    let ne = dom.new_element(dom.name(node).unwrap());
1660    dom.copy_attributes(node, ne);
1661    for c in dom.nodes(node) {
1662        if let Some(tc) = accept_move_from_ranges_transform(dom, c, to_delete) {
1663            dom.add(ne, tc);
1664        } else {
1665            // A whole inline/block container can fall inside the move range;
1666            // preserve its surviving anchors without keeping the container.
1667            for marker in hoist_range_markers_from(dom, c) {
1668                dom.add(ne, marker);
1669            }
1670        }
1671    }
1672    Some(ne)
1673}
1674
1675// ─────────────────────── A.3 — paragraph end tags in moveFrom ───────────────
1676
1677/// A.3 — `CollapseParagraphTransform` (:1821): a `w:p` collapses to its
1678/// element children minus `w:pPr` (clones — C# XLinq re-parents by cloning);
1679/// other elements rebuild recursively; non-elements pass through.
1680pub fn collapse_paragraph_transform(dom: &mut Dom, node: NodeId) -> Vec<NodeId> {
1681    if !dom.is_element(node) {
1682        return vec![dom.clone_subtree(node)];
1683    }
1684    let name = dom.name(node).unwrap();
1685    if name == W::p() {
1686        let keep: Vec<NodeId> = dom
1687            .elements(node, None)
1688            .into_iter()
1689            .filter(|&e| dom.name(e) != Some(W::p_pr()))
1690            .collect();
1691        return keep.into_iter().map(|e| dom.clone_subtree(e)).collect();
1692    }
1693    let ne = dom.new_element(name);
1694    dom.copy_attributes(node, ne);
1695    for c in dom.nodes(node) {
1696        for tc in collapse_paragraph_transform(dom, c) {
1697            dom.add(ne, tc);
1698        }
1699    }
1700    vec![ne]
1701}
1702
1703/// A.3 — `CoalesqueParagraphEndTagsInMoveFromTransform` (:2645): produce the
1704/// first group member, with its (first descendant) paragraph replaced by one
1705/// carrying the paragraph's own children plus the COLLAPSED content of the
1706/// group's subsequent members. NOTE: unreachable from the accept transform in
1707/// practice — see the FAITHFUL-BUG note on
1708/// [`accept_paragraph_end_tags_in_move_from_transform`].
1709pub fn coalesque_paragraph_end_tags_in_move_from_transform(
1710    dom: &mut Dom,
1711    node: NodeId,
1712    group: &[NodeId],
1713) -> NodeId {
1714    if !dom.is_element(node) {
1715        return dom.clone_subtree(node);
1716    }
1717    let name = dom.name(node).unwrap();
1718    if name == W::p() {
1719        let np = dom.new_element(W::p());
1720        dom.copy_attributes(node, np);
1721        for e in dom.elements(node, None) {
1722            let ce = dom.clone_subtree(e);
1723            dom.add(np, ce);
1724        }
1725        for &member in group.iter().skip(1) {
1726            for collapsed in collapse_paragraph_transform(dom, member) {
1727                dom.add(np, collapsed);
1728            }
1729        }
1730        return np;
1731    }
1732    let ne = dom.new_element(name);
1733    dom.copy_attributes(node, ne);
1734    for c in dom.nodes(node) {
1735        let tc = coalesque_paragraph_end_tags_in_move_from_transform(dom, c, group);
1736        dom.add(ne, tc);
1737    }
1738    ne
1739}
1740
1741/// A.3 — `AcceptParagraphEndTagsInMoveFromTransform` (:1610): group a content
1742/// container's children by whether their paragraph mark sits in an OPEN
1743/// moveFrom range (`moveFromRangeStart` child without `moveFromRangeEnd`), or
1744/// they are a `w:p` directly following such a paragraph.
1745///
1746/// FAITHFUL-BUG (preserved; TS port identical, RevisionProcessor.ts:1313 with
1747/// a "needs rewritten" note at :971): the branch condition is inverted — the
1748/// coalescing path only executes when there is a single all-`Other` group,
1749/// where it degenerates to a pass-through; whenever an in-range group exists
1750/// the code takes the plain recursive rebuild instead. Net effect: a deep
1751/// identity rebuild. Both the TS goldens and the C# RP baselines were
1752/// generated with this behavior, so we reproduce it rather than "fix" it.
1753///
1754/// ACCEPT-SKIP-A3: when the subtree has no `w:moveFromRangeStart`, every
1755/// grouping key is "Other" and the transform is a pure identity rebuild —
1756/// transfer `node` without cloning (common path for ins/del-only redlines).
1757pub fn accept_paragraph_end_tags_in_move_from_transform(dom: &mut Dom, node: NodeId) -> NodeId {
1758    // ACCEPT-SKIP-A3: no moveFromRangeStart → identity (keep parent links).
1759    if !element_or_desc_has_name(dom, node, &W::move_from_range_start()) {
1760        return node;
1761    }
1762    if !dom.is_element(node) {
1763        return dom.clone_subtree(node);
1764    }
1765    let name = dom.name(node).unwrap();
1766    if is_block_level_content_container(&name) {
1767        let mfrs = W::move_from_range_start();
1768        let mfre = W::move_from_range_end();
1769        let mark_in_open_range = |dom: &Dom, p: NodeId| {
1770            !dom.elements(p, Some(&mfrs)).is_empty() && dom.elements(p, Some(&mfre)).is_empty()
1771        };
1772        let key_of = |dom: &Dom, c: NodeId| -> bool {
1773            // true = ParagraphEndTagInMoveFromRange, false = Other
1774            let pi = get_paragraph_info(dom, c);
1775            if let Some(this) = pi.this_block_content_element
1776                && mark_in_open_range(dom, this)
1777            {
1778                return true;
1779            }
1780            let previous = content_elements_before_self(dom, c).into_iter().find(|&e| {
1781                get_paragraph_info(dom, e)
1782                    .this_block_content_element
1783                    .is_some()
1784            });
1785            if let Some(prev) = previous {
1786                let pi2 = get_paragraph_info(dom, prev);
1787                if dom.name(c) == Some(W::p())
1788                    && mark_in_open_range(dom, pi2.this_block_content_element.unwrap())
1789                {
1790                    return true;
1791                }
1792            }
1793            false
1794        };
1795        let children = dom.elements(node, None);
1796        let grouped = crate::util::group_adjacent(children, |&c| key_of(dom, c));
1797
1798        if grouped.len() == 1 && !grouped[0].0 {
1799            // "Nothing to do": rebuild the container with its children cloned
1800            // as-is (C# attaches the original elements to a new parent, which
1801            // XLinq clones; descendants are NOT re-transformed here).
1802            let ne = dom.new_element(name);
1803            dom.copy_attributes(node, ne);
1804            for (key, group) in grouped {
1805                if !key {
1806                    for e in group {
1807                        let ce = dom.clone_subtree(e);
1808                        dom.add(ne, ce);
1809                    }
1810                } else {
1811                    // Unreachable given the branch guard; kept for shape
1812                    // parity with the C# select.
1813                    let first = group[0];
1814                    let t = coalesque_paragraph_end_tags_in_move_from_transform(dom, first, &group);
1815                    dom.add(ne, t);
1816                }
1817            }
1818            return ne;
1819        }
1820        // FAITHFUL-BUG: in-range groups exist → plain recursive rebuild, no
1821        // coalescing.
1822        let ne = dom.new_element(name);
1823        dom.copy_attributes(node, ne);
1824        for c in dom.nodes(node) {
1825            let tc = accept_paragraph_end_tags_in_move_from_transform(dom, c);
1826            dom.add(ne, tc);
1827        }
1828        return ne;
1829    }
1830    let ne = dom.new_element(name);
1831    dom.copy_attributes(node, ne);
1832    for c in dom.nodes(node) {
1833        let tc = accept_paragraph_end_tags_in_move_from_transform(dom, c);
1834        dom.add(ne, tc);
1835    }
1836    ne
1837}
1838
1839// ─────────────── A.4 — deleted / moved-from content controls ────────────────
1840
1841/// A.4 — `AcceptDeletedAndMovedFromContentControls` (:2491): walk the tag
1842/// stream tracking two range kinds. `customXmlDelRange` collects ONLY `w:sdt`
1843/// tags; `customXmlMoveFromRange` collects every element (the `w:sdt` block
1844/// feeds both trackers). An `w:sdt` strictly inside a matched del range is
1845/// COLLAPSED to its `sdtContent` children; any element strictly inside a
1846/// matched moveFrom range is DELETED. Unmatched starts never flush; with
1847/// nothing collected the input element is returned unchanged (identity).
1848pub fn accept_deleted_and_moved_from_content_controls(dom: &mut Dom, root: NodeId) -> NodeId {
1849    use std::collections::{HashMap, HashSet};
1850
1851    let cxdel_s = W::name("customXmlDelRangeStart");
1852    let cxdel_e = W::name("customXmlDelRangeEnd");
1853    let cxmf_s = W::name("customXmlMoveFromRangeStart");
1854    let cxmf_e = W::name("customXmlMoveFromRangeEnd");
1855    let mfrs = W::move_from_range_start();
1856    let mfre = W::move_from_range_end();
1857    let sdt = W::sdt();
1858
1859    let mut del_starts: Vec<NodeId> = Vec::new();
1860    let mut del_ends: Vec<NodeId> = Vec::new();
1861    let mut mf_starts: Vec<NodeId> = Vec::new();
1862    let mut mf_ends: Vec<NodeId> = Vec::new();
1863    let mut potential_del: HashMap<String, (Vec<NodeId>, Vec<NodeId>)> = HashMap::new();
1864    let mut potential_mf: HashMap<String, (Vec<NodeId>, Vec<NodeId>)> = HashMap::new();
1865
1866    for tag in descendant_and_self_tags(dom, root) {
1867        let name = dom.name(tag.element).unwrap();
1868        if name == cxdel_s {
1869            let id = dom
1870                .attribute(tag.element, &W::id())
1871                .unwrap_or("")
1872                .to_string();
1873            potential_del.insert(id, (Vec::new(), Vec::new()));
1874            continue;
1875        }
1876        if name == cxdel_e {
1877            let id = dom.attribute(tag.element, &W::id()).unwrap_or("");
1878            if let Some((starts, ends)) = potential_del.remove(id) {
1879                del_starts.extend(starts);
1880                del_ends.extend(ends);
1881            }
1882            continue;
1883        }
1884        if name == cxmf_s {
1885            let id = dom
1886                .attribute(tag.element, &W::id())
1887                .unwrap_or("")
1888                .to_string();
1889            potential_mf.insert(id, (Vec::new(), Vec::new()));
1890            continue;
1891        }
1892        if name == cxmf_e {
1893            let id = dom.attribute(tag.element, &W::id()).unwrap_or("");
1894            if let Some((starts, ends)) = potential_mf.remove(id) {
1895                mf_starts.extend(starts);
1896                mf_ends.extend(ends);
1897            }
1898            continue;
1899        }
1900        if name == sdt {
1901            match tag.tag_type {
1902                TagType::Element => {
1903                    for (starts, _) in potential_del.values_mut().chain(potential_mf.values_mut()) {
1904                        starts.push(tag.element);
1905                    }
1906                }
1907                TagType::EmptyElement => {
1908                    for (starts, ends) in
1909                        potential_del.values_mut().chain(potential_mf.values_mut())
1910                    {
1911                        starts.push(tag.element);
1912                        ends.push(tag.element);
1913                    }
1914                }
1915                TagType::EndElement => {
1916                    for (_, ends) in potential_del.values_mut().chain(potential_mf.values_mut()) {
1917                        ends.push(tag.element);
1918                    }
1919                }
1920            }
1921            continue;
1922        }
1923        if !potential_mf.is_empty() && name != mfrs && name != mfre {
1924            match tag.tag_type {
1925                TagType::Element => {
1926                    for (starts, _) in potential_mf.values_mut() {
1927                        starts.push(tag.element);
1928                    }
1929                }
1930                TagType::EmptyElement => {
1931                    for (starts, ends) in potential_mf.values_mut() {
1932                        starts.push(tag.element);
1933                        ends.push(tag.element);
1934                    }
1935                }
1936                TagType::EndElement => {
1937                    for (_, ends) in potential_mf.values_mut() {
1938                        ends.push(tag.element);
1939                    }
1940                }
1941            }
1942        }
1943    }
1944
1945    let del_end_set: HashSet<NodeId> = del_ends.into_iter().collect();
1946    let to_collapse: HashSet<NodeId> = del_starts
1947        .into_iter()
1948        .filter(|e| del_end_set.contains(e))
1949        .collect();
1950    let mf_end_set: HashSet<NodeId> = mf_ends.into_iter().collect();
1951    let to_delete: HashSet<NodeId> = mf_starts
1952        .into_iter()
1953        .filter(|e| mf_end_set.contains(e))
1954        .collect();
1955
1956    if to_collapse.is_empty() && to_delete.is_empty() {
1957        return root;
1958    }
1959    let out: Vec<NodeId> = accept_deleted_and_moved_from_content_controls_transform(
1960        dom,
1961        root,
1962        &to_collapse,
1963        &to_delete,
1964    );
1965    debug_assert_eq!(out.len(), 1, "the root is neither collapsed nor deleted");
1966    out[0]
1967}
1968
1969/// A.4 — `AcceptDeletedAndMovedFromContentControlsTransform` (:2468): splice
1970/// a collapsed sdt's `sdtContent` child nodes (transformed) in its place,
1971/// drop deleted elements, rebuild the rest.
1972fn accept_deleted_and_moved_from_content_controls_transform(
1973    dom: &mut Dom,
1974    node: NodeId,
1975    to_collapse: &std::collections::HashSet<NodeId>,
1976    to_delete: &std::collections::HashSet<NodeId>,
1977) -> Vec<NodeId> {
1978    if !dom.is_element(node) {
1979        return vec![dom.clone_subtree(node)];
1980    }
1981    let name = dom.name(node).unwrap();
1982    if name == W::sdt() && to_collapse.contains(&node) {
1983        let content = dom
1984            .element(node, &W::sdt_content())
1985            .expect("collapsed w:sdt must carry sdtContent (C# NREs otherwise)");
1986        let mut out = Vec::new();
1987        for c in dom.nodes(content) {
1988            out.extend(accept_deleted_and_moved_from_content_controls_transform(
1989                dom,
1990                c,
1991                to_collapse,
1992                to_delete,
1993            ));
1994        }
1995        return out;
1996    }
1997    if to_delete.contains(&node) {
1998        return vec![];
1999    }
2000    let ne = dom.new_element(name);
2001    dom.copy_attributes(node, ne);
2002    for c in dom.nodes(node) {
2003        for tc in
2004            accept_deleted_and_moved_from_content_controls_transform(dom, c, to_collapse, to_delete)
2005        {
2006            dom.add(ne, tc);
2007        }
2008    }
2009    vec![ne]
2010}
2011
2012// ─────────────── A.5a — deleted / moved-from paragraph marks ────────────────
2013
2014/// A.5a — `IsRunContent` (:2356): `Some(true)` = run-level content,
2015/// `Some(false)` = marker/non-content, `None` = unknown. Unknown children
2016/// conservatively keep the paragraph; they are not evidence of deletion.
2017fn is_run_content(name: &XName) -> Option<bool> {
2018    // An authored compatibility wrapper carries its complete presentation
2019    // alternatives, like math or a field wrapper. Capability selection belongs
2020    // to consumers; paragraph-mark resolution must preserve both alternatives.
2021    if *name == crate::namespaces::MC::name("AlternateContent") {
2022        return Some(true);
2023    }
2024    if name.namespace_name() == crate::namespaces::M::URI {
2025        return Some(true);
2026    }
2027    // A revision kept tracked holds content the paragraph keeps; its move
2028    // range markers hold none.
2029    if name.namespace_name() == FROZEN_NS {
2030        return Some(!name.local_name().contains("Range"));
2031    }
2032    if name.namespace_name() != W::URI {
2033        return None;
2034    }
2035    match name.local_name() {
2036        "r" | "fldSimple" | "hyperlink" | "subDoc" | "smartTag" | "smartTagPr" => Some(true),
2037        "bookmarkStart"
2038        | "bookmarkEnd"
2039        | "commentRangeStart"
2040        | "commentRangeEnd"
2041        | "customXmlDelRangeStart"
2042        | "customXmlDelRangeEnd"
2043        | "customXmlInsRangeStart"
2044        | "customXmlInsRangeEnd"
2045        | "customXmlMoveFromRangeStart"
2046        | "customXmlMoveFromRangeEnd"
2047        | "customXmlMoveToRangeStart"
2048        | "customXmlMoveToRangeEnd"
2049        | "del"
2050        | "moveFrom"
2051        | "moveFromRangeStart"
2052        | "moveFromRangeEnd"
2053        | "moveToRangeStart"
2054        | "moveToRangeEnd"
2055        | "permStart"
2056        | "permEnd"
2057        | "proofErr" => Some(false),
2058        _ => None,
2059    }
2060}
2061
2062/// A.5a — `CollapseTransform` (:2331): recursively look through run wrappers
2063/// and `sdtContent`, dropping properties in this disposable content probe.
2064/// Like Docxodus #281, recurse when splicing: wrappers can nest around an
2065/// insertion or move destination (#1704). Keep deletions opaque so their
2066/// runs do not count as surviving content. The output tree retains its
2067/// authored wrappers; only the paragraph-deletion probe is flattened here.
2068fn collapse_transform(dom: &mut Dom, node: NodeId) -> Vec<NodeId> {
2069    if !dom.is_element(node) {
2070        return vec![dom.clone_subtree(node)];
2071    }
2072    let name = dom.name(node).unwrap();
2073    // An authored field can have no cached result yet; its instruction is
2074    // still content. Only see through the field when resolving its revisions.
2075    if name == W::fld_simple() && !element_has_tracked_revisions(dom, node) {
2076        return vec![dom.clone_subtree(node)];
2077    }
2078    if name.namespace_name() == W::URI
2079        && matches!(
2080            name.local_name(),
2081            "dir"
2082                | "bdo"
2083                | "bdr"
2084                | "ins"
2085                | "moveTo"
2086                | "smartTag"
2087                | "customXml"
2088                | "fldSimple"
2089                | "hyperlink"
2090        )
2091    {
2092        let mut out = Vec::new();
2093        for child in dom.nodes(node) {
2094            out.extend(collapse_transform(dom, child));
2095        }
2096        return out;
2097    }
2098    if name == W::sdt() {
2099        let mut out = Vec::new();
2100        for sc in dom.elements(node, Some(&W::sdt_content())) {
2101            for child in dom.nodes(sc) {
2102                out.extend(collapse_transform(dom, child));
2103            }
2104        }
2105        return out;
2106    }
2107    if name == W::p_pr() || name == W::name("smartTagPr") || name == W::name("customXmlPr") {
2108        return vec![];
2109    }
2110    let ne = dom.new_element(name);
2111    dom.copy_attributes(node, ne);
2112    for c in dom.nodes(node) {
2113        for tc in collapse_transform(dom, c) {
2114            dom.add(ne, tc);
2115        }
2116    }
2117    vec![ne]
2118}
2119
2120/// A.5a — `AllParaContentIsDeleted` (:2310): after collapsing wrappers, does
2121/// the paragraph hold NO run-level content?
2122///
2123/// An unrecognized child (including malformed paragraph-level ruby, #1711)
2124/// keeps its content rather than panicking or silently deleting it. This is
2125/// not a schema repair: `validate` diagnoses known malformed shapes.
2126fn all_para_content_is_deleted(dom: &mut Dom, p: NodeId) -> bool {
2127    let collapsed = collapse_transform(dom, p);
2128    debug_assert_eq!(collapsed.len(), 1, "w:p rebuilds to a single element");
2129    let test_p = collapsed[0];
2130    !dom.elements(test_p, None).into_iter().any(|ce| {
2131        let n = dom.name(ce).unwrap();
2132        if n == M::name("oMath") || n == M::name("oMathPara") {
2133            // Word stores math revisions inside the equation. A.5 runs before
2134            // A.7 removes those internal revisions; probe that same transform
2135            // on this already-cloned CollapseTransform tree so a fully removed
2136            // equation cannot keep an otherwise deleted terminal pilcrow alive.
2137            // Authored empty equations, mixed owners and independent anchors
2138            // retain the ownership decisions of the ordinary math transform.
2139            return accept_all_other_revisions_transform(dom, ce)
2140                .into_iter()
2141                .any(|node| {
2142                    dom.name(node)
2143                        .is_some_and(|name| is_run_content(&name).unwrap_or(true))
2144                });
2145        }
2146        is_run_content(&n).unwrap_or(true)
2147    })
2148}
2149
2150/// Does every row of `tbl` carry `trPr/w:del` (and is there a row)?
2151fn table_rows_all_deleted(dom: &Dom, tbl: NodeId) -> bool {
2152    let rows = wrapped_children(dom, tbl, &W::tr());
2153    !rows.is_empty()
2154        && rows.into_iter().all(|tr| {
2155            dom.element(tr, &W::tr_pr())
2156                .is_some_and(|pr| dom.element(pr, &W::del()).is_some())
2157        })
2158}
2159
2160/// `p / pPr / rPr / (del | moveFrom)` — is the paragraph mark deleted or
2161/// moved from?
2162fn paragraph_mark_is_deleted_or_moved_from(dom: &Dom, p: NodeId) -> bool {
2163    // At most one w:pPr / w:rPr; use singular element lookups to avoid Vec churn.
2164    dom.element(p, &W::p_pr())
2165        .and_then(|ppr| dom.element(ppr, &W::r_pr()))
2166        .is_some_and(|rpr| {
2167            dom.elements(rpr, None).into_iter().any(|e| {
2168                dom.name(e)
2169                    .is_some_and(|n| n == W::del() || n == W::move_from())
2170            })
2171        })
2172}
2173
2174/// ACCEPT-SKIP-A5: non-allocating presence of any paragraph whose mark is
2175/// deleted or moved-from under `root`.
2176fn has_deleted_or_moved_from_paragraph_mark(dom: &Dom, root: NodeId) -> bool {
2177    fn walk(dom: &Dom, id: NodeId) -> bool {
2178        if dom.name(id).as_ref() == Some(&W::p())
2179            && paragraph_mark_is_deleted_or_moved_from(dom, id)
2180        {
2181            return true;
2182        }
2183        let n = dom.child_count(id);
2184        for i in 0..n {
2185            if walk(dom, dom.child_at(id, i)) {
2186                return true;
2187            }
2188        }
2189        false
2190    }
2191    walk(dom, root)
2192}
2193
2194/// A.5a — `AcceptDeletedAndMoveFromParagraphMarksTransform` (:2119): the
2195/// 3-state grouping machine over a container's block-content chain. A run of
2196/// deleted-mark paragraphs PLUS the immediately following normal paragraph
2197/// form one DeletedRange group, which merges into a single paragraph carrying
2198/// `g.Last()`'s pPr (:2271, the RP052 fix) and every member's collapsed
2199/// content; the merged paragraph is nuked when its content is entirely
2200/// deleted, its last member's mark is deleted or moved away (C#: deleted
2201/// only), and it is the container's last block content (or a table follows)
2202/// (:2276). Tables (and m:* block content)
2203/// bound groups and reset the state. FAITHful: the container rebuild keeps
2204/// only `w:tcPr` children + the chain elements + the body-level `sectPr`
2205/// (re-appended last); other non-chain children are dropped, and merged
2206/// paragraphs lose the original `w:p` attributes — exactly like the C#.
2207pub fn accept_deleted_and_move_from_paragraph_marks_transform(
2208    dom: &mut Dom,
2209    node: NodeId,
2210) -> NodeId {
2211    accept_paragraph_marks_with_owners(dom, node, &mut HashMap::new())
2212}
2213
2214// Original paragraph owners are private reconstruction evidence. Keeping them
2215// in Rust avoids adding scratch attributes to the public transform's output.
2216fn accept_paragraph_marks_with_owners(
2217    dom: &mut Dom,
2218    node: NodeId,
2219    paragraph_owners: &mut HashMap<NodeId, Vec<NodeId>>,
2220) -> NodeId {
2221    if !dom.is_element(node) {
2222        return dom.clone_subtree(node);
2223    }
2224    let name = dom.name(node).unwrap();
2225    if !is_block_level_content_container(&name) {
2226        let ne = dom.new_element(name);
2227        dom.copy_attributes(node, ne);
2228        for c in dom.nodes(node) {
2229            let tc = accept_paragraph_marks_with_owners(dom, c, paragraph_owners);
2230            dom.add(ne, tc);
2231        }
2232        if dom.name_is(node, &W::p()) {
2233            paragraph_owners.insert(ne, vec![node]);
2234        }
2235        return ne;
2236    }
2237
2238    let body_sect_pr = if name == W::body() {
2239        dom.element(node, &W::sect_pr())
2240    } else {
2241        None
2242    };
2243
2244    let chain = iterate_block_content_elements(dom, node);
2245    // (is_deleted_range, grouping_key) aligned with the chain.
2246    let mut infos: Vec<(bool, i32)> = Vec::with_capacity(chain.len());
2247    let mut current_key = 0i32;
2248    let mut state = 0u8; // 0 = non-deleted, 1 = in deleted, 2 = paragraph following
2249    // Does the deleted-mark run so far keep anything once its marks go?
2250    let mut run_brings = false;
2251    // Deleted marks Word keeps, each with the paragraph after it, whose
2252    // properties the kept paragraph takes.
2253    let mut held_marks: HashMap<NodeId, NodeId> = HashMap::new();
2254    for c in &chain {
2255        let this = c.this_block_content_element.unwrap();
2256        let tn = dom.name(this).unwrap();
2257        if tn == W::p() {
2258            let brings = !brings_nothing(dom, this);
2259            let mark_goes = paragraph_mark_is_deleted_or_moved_from(dom, this);
2260            let held = mark_goes
2261                && c.next_block_content_element.is_some_and(|next| {
2262                    dom.name_is(next, &W::p())
2263                        && holds_mark(dom, this, next, brings || (state == 1 && run_brings))
2264                });
2265            if held {
2266                held_marks.insert(this, c.next_block_content_element.unwrap());
2267            }
2268            if mark_goes && !held {
2269                match state {
2270                    0 | 2 => {
2271                        state = 1;
2272                        current_key += 1;
2273                        run_brings = brings;
2274                        infos.push((true, current_key));
2275                    }
2276                    _ => {
2277                        run_brings |= brings;
2278                        infos.push((true, current_key));
2279                    }
2280                }
2281            } else {
2282                match state {
2283                    0 => {
2284                        current_key += 1;
2285                        infos.push((false, current_key));
2286                    }
2287                    1 => {
2288                        // the paragraph following a deleted run JOINS its group
2289                        state = 2;
2290                        infos.push((true, current_key));
2291                    }
2292                    _ => {
2293                        state = 0;
2294                        current_key += 1;
2295                        infos.push((false, current_key));
2296                    }
2297                }
2298            }
2299        } else if tn == W::tbl()
2300            && state == 1
2301            && c.next_block_content_element
2302                .is_some_and(|n| dom.name(n) == Some(W::p()))
2303            && table_rows_all_deleted(dom, this)
2304        {
2305            // Word: a table whose rows are all deleted vanishes on accept
2306            // and does not end the deleted-mark run, which goes on to join
2307            // the paragraph after it.
2308            infos.push((true, current_key));
2309        } else if tn == W::tbl() || tn.namespace_name() == M::URI {
2310            current_key += 1;
2311            infos.push((false, current_key));
2312            state = 0;
2313        } else {
2314            // defensive parity with C#: keep state and key (chain only ever
2315            // yields w:p / w:tbl, so this arm is unreachable in practice)
2316            infos.push((false, current_key));
2317        }
2318    }
2319
2320    let zipped: Vec<(BlockContentInfo, (bool, i32))> = chain.into_iter().zip(infos).collect();
2321    let grouped = crate::util::group_adjacent(zipped, |z| z.1.1);
2322
2323    // Prebuild rebuilt block nodes, keyed by the original block element(s)
2324    // they replace. Deleted-range merges map many originals → one paragraph.
2325    // None = nuked empty deleted trailing para; markers_from_nuke are comment
2326    // anchors hoisted out of that discarded para so they still emit.
2327    let mut rebuilt: Vec<(Vec<NodeId>, Option<NodeId>, Vec<NodeId>)> = Vec::new();
2328    for (_key, group) in &grouped {
2329        if group[0].1.0 {
2330            // DeletedRange: merge into one paragraph.
2331            let last_this = group.last().unwrap().0.this_block_content_element.unwrap();
2332            let np = dom.new_element(W::p());
2333            if let Some(&next) = held_marks.get(&last_this) {
2334                if let Some(ppr) = held_mark_properties(dom, next) {
2335                    dom.add(np, ppr);
2336                }
2337            } else {
2338                for ppr in dom.elements(last_this, Some(&W::p_pr())) {
2339                    let c = dom.clone_subtree(ppr);
2340                    dom.add(np, c);
2341                }
2342            }
2343            let mut orig_ids = Vec::new();
2344            for z in group {
2345                let this = z.0.this_block_content_element.unwrap();
2346                orig_ids.push(this);
2347                if dom.name(this) == Some(W::tbl()) {
2348                    // A wholly deleted table absorbed into the run.
2349                    continue;
2350                }
2351                for collapsed in collapse_paragraph_transform(dom, this) {
2352                    dom.add(np, collapsed);
2353                }
2354            }
2355            paragraph_owners.insert(
2356                np,
2357                orig_ids
2358                    .iter()
2359                    .copied()
2360                    .filter(|&source| dom.name_is(source, &W::p()))
2361                    .collect(),
2362            );
2363            // Word also drops an emptied moved-away paragraph before a table
2364            // (its Reject All of 30f20e787b's moved heading).
2365            let last_mark_goes = paragraph_mark_is_deleted_or_moved_from(dom, last_this);
2366            let next = group.last().unwrap().0.next_block_content_element;
2367            // An opaque equation also ends the paragraph-mark merge chain.
2368            // A fully deleted carrier before that barrier has no surviving
2369            // mark or content to own an empty paragraph in the projection.
2370            let next_is_end_or_block_barrier = next.is_none()
2371                || next.is_some_and(|n| {
2372                    dom.name(n).is_some_and(|name| {
2373                        name == W::tbl() || name == M::name("oMath") || name == M::name("oMathPara")
2374                    })
2375                });
2376            if all_para_content_is_deleted(dom, np)
2377                && last_mark_goes
2378                && next_is_end_or_block_barrier
2379            {
2380                // Nuke empty deleted para, but keep comment anchors that lived
2381                // and bookmarks that lived inside its w:del runs (starts 9/10
2382                // between delText).
2383                let markers = hoist_range_markers_from(dom, np);
2384                rebuilt.push((orig_ids, None, markers));
2385            } else {
2386                rebuilt.push((orig_ids, Some(np), Vec::new()));
2387            }
2388        } else {
2389            for z in group {
2390                let this = z.0.this_block_content_element.unwrap();
2391                let rebuilt_name = dom.name(this).unwrap();
2392                let re = dom.new_element(rebuilt_name);
2393                dom.copy_attributes(this, re);
2394                let held = held_marks.get(&this).copied();
2395                if let Some(next) = held
2396                    && let Some(ppr) = held_mark_properties(dom, next)
2397                {
2398                    dom.add(re, ppr);
2399                }
2400                for c in dom.nodes(this) {
2401                    if held.is_some() && dom.name_is(c, &W::p_pr()) {
2402                        continue;
2403                    }
2404                    let tc = accept_paragraph_marks_with_owners(dom, c, paragraph_owners);
2405                    dom.add(re, tc);
2406                }
2407                if dom.name_is(this, &W::p()) {
2408                    paragraph_owners.insert(re, vec![this]);
2409                }
2410                rebuilt.push((vec![this], Some(re), Vec::new()));
2411            }
2412        }
2413    }
2414
2415    let ne = dom.new_element(name.clone());
2416    dom.copy_attributes(node, ne);
2417    for e in dom.elements(node, Some(&W::tc_pr())) {
2418        let ce = dom.clone_subtree(e);
2419        dom.add(ne, ce);
2420    }
2421    // Emit in original element-child order so body-level commentRange*/bookmark*
2422    // between tables and paragraphs are preserved. The prior rebuild only kept
2423    // p/tbl chain members and dropped other body children — that deleted outer
2424    // nested commentRangeEnd after tables (ids 2/66) and broke comment carry.
2425    let mut emitted: HashSet<usize> = HashSet::new();
2426    for c in dom.elements(node, None) {
2427        let Some(cn) = dom.name(c) else {
2428            continue;
2429        };
2430        if cn == W::tc_pr() || cn == W::sect_pr() {
2431            continue;
2432        }
2433        if is_body_level_range_marker(&cn) {
2434            let clone = dom.clone_subtree(c);
2435            dom.add(ne, clone);
2436            continue;
2437        }
2438        // Direct block content (p/tbl child of body/cell).
2439        if let Some(ri) = rebuilt.iter().position(|(ids, _, _)| ids.contains(&c))
2440            && emitted.insert(ri)
2441        {
2442            let (_ids, rebuilt_node, markers) = &rebuilt[ri];
2443            if let Some(rebuilt_node) = rebuilt_node {
2444                dom.add(ne, *rebuilt_node);
2445            }
2446            for &m in markers {
2447                dom.add(ne, m);
2448            }
2449            continue;
2450        }
2451        // Nested block content under wrappers (w:sdt → sdtContent → p).
2452        // The chain walks into sdt-wrapped paragraphs, but emit used to only
2453        // match *direct* body children — so a surviving sdt's paragraph was
2454        // rebuilt then never attached (m28 a5b_mixed: left=0 SDTs). Emit any
2455        // rebuilt entry whose original id is under this child; nuked entries
2456        // (None) drop the fully-deleted sdt while A.5b re-wraps survivors.
2457        for (ri, (ids, rebuilt_node, markers)) in rebuilt.iter().enumerate() {
2458            if emitted.contains(&ri) {
2459                continue;
2460            }
2461            let nested = ids
2462                .iter()
2463                .any(|&id| id == c || dom.ancestors(id, None).into_iter().any(|a| a == c));
2464            if !nested {
2465                continue;
2466            }
2467            emitted.insert(ri);
2468            if let Some(rebuilt_node) = rebuilt_node {
2469                dom.add(ne, *rebuilt_node);
2470            }
2471            for &m in markers {
2472                dom.add(ne, m);
2473            }
2474        }
2475    }
2476    if let Some(sp) = body_sect_pr {
2477        let c = dom.clone_subtree(sp);
2478        dom.add(ne, c);
2479    }
2480    ne
2481}
2482
2483/// Body/cell-level markers that must survive block-content rebuild (not p/tbl).
2484fn is_body_level_range_marker(name: &XName) -> bool {
2485    name.namespace_name() == W::URI
2486        && matches!(
2487            name.local_name(),
2488            "commentRangeStart"
2489                | "commentRangeEnd"
2490                | "bookmarkStart"
2491                | "bookmarkEnd"
2492                | "permStart"
2493                | "permEnd"
2494        )
2495}
2496
2497fn is_inline_range_marker(name: &XName) -> bool {
2498    name.namespace_name() == W::URI
2499        && matches!(
2500            name.local_name(),
2501            "commentRangeStart"
2502                | "commentRangeEnd"
2503                | "bookmarkStart"
2504                | "bookmarkEnd"
2505                | "permStart"
2506                | "permEnd"
2507        )
2508}
2509
2510/// Permission ranges follow Word's character-range rule, including paragraph
2511/// marks: discard both endpoints only when their nonempty span disappears.
2512/// Originally empty ranges have nothing to lose and remain in place.
2513fn drop_wholly_deleted_permissions(dom: &mut Dom, root: NodeId) {
2514    let (start, end) = (W::perm_start(), W::perm_end());
2515    let dropped = bookmarks::wholly_deleted_endpoints(dom, root, &start, &end);
2516    for endpoint in dropped {
2517        dom.remove(endpoint);
2518    }
2519}
2520
2521/// Pull comment, bookmark and permission markers out of a subtree being discarded
2522/// (e.g. accepted `w:del`) so anchors between delText runs are not lost.
2523fn hoist_range_markers_from(dom: &mut Dom, node: NodeId) -> Vec<NodeId> {
2524    let mut out = Vec::new();
2525    for e in dom.descendants(node, None) {
2526        let Some(n) = dom.name(e) else {
2527            continue;
2528        };
2529        if is_inline_range_marker(&n) {
2530            out.push(dom.clone_subtree(e));
2531        }
2532    }
2533    out
2534}
2535
2536// ─────────────── A.5b — content-control re-wrap after mark merge ────────────
2537
2538/// A.5b — `AnnotateRunElementsWithId` (:1935): number every descendant `w:r`
2539/// with `pt:UniqueId` 0.. in document order (in place).
2540pub fn annotate_run_elements_with_id(dom: &mut Dom, element: NodeId) {
2541    let unique_id = PT::unique_id();
2542    for (run_id, r) in (0..).zip(dom.descendants(element, Some(&W::r()))) {
2543        dom.set_attribute_value(r, &unique_id, Some(&run_id.to_string()));
2544    }
2545}
2546
2547/// Number every descendant `w:p` (`pt:UniqueId` `p0`, `p1`, …) so A.5b can
2548/// find a control's paragraphs when it has no run to anchor on (an empty
2549/// control keeps its paragraph mark, and so its place). Not in the C#, which
2550/// anchors on runs only and drops such a control whenever another paragraph
2551/// mark of the part is deleted.
2552fn annotate_paragraph_elements_with_id(dom: &mut Dom, element: NodeId) {
2553    let unique_id = PT::unique_id();
2554    for (paragraph_id, p) in (0..).zip(dom.descendants(element, Some(&W::p()))) {
2555        dom.set_attribute_value(p, &unique_id, Some(&format!("p{paragraph_id}")));
2556    }
2557}
2558
2559/// Number what a paragraph holds besides its properties and its runs
2560/// (`pt:UniqueId` `c0`, `c1`, …: an equation, a hyperlink, a field), so an
2561/// emptied control can anchor on the content of the paragraph after it when
2562/// that content starts with no run (the #1714 A/B: Word keeps the control
2563/// before an equation, as before a run).
2564fn annotate_paragraph_content_with_id(dom: &mut Dom, element: NodeId) {
2565    let unique_id = PT::unique_id();
2566    let (p_pr, r) = (W::p_pr(), W::r());
2567    let mut content_id = 0;
2568    for p in dom.descendants(element, Some(&W::p())) {
2569        for child in dom.elements(p, None) {
2570            if dom.name_is(child, &p_pr) || dom.name_is(child, &r) {
2571                continue;
2572            }
2573            dom.set_attribute_value(child, &unique_id, Some(&format!("c{content_id}")));
2574            content_id += 1;
2575        }
2576    }
2577}
2578
2579/// Descendants of `element` in document order, not descending into a text
2580/// box (`w:txbxContent` or Strict `wne:txbxContent`).
2581fn descendants_trimmed(dom: &Dom, element: NodeId) -> Vec<NodeId> {
2582    let mut out = Vec::new();
2583    let mut stack: Vec<NodeId> = dom.elements(element, None).into_iter().rev().collect();
2584    while let Some(e) = stack.pop() {
2585        out.push(e);
2586        if dom.name(e).is_none_or(|name| !is_text_box(&name)) {
2587            for c in dom.elements(e, None).into_iter().rev() {
2588                stack.push(c);
2589            }
2590        }
2591    }
2592    out
2593}
2594
2595/// A.5b — `AnnotateContentControlsWithRunIds` (:1945): give every descendant
2596/// `w:sdt` a `pt:RunIds` (comma-joined `pt:UniqueId`s of its runs, trimmed at
2597/// either text-box name) and its own `pt:UniqueId` (in place).
2598pub fn annotate_content_controls_with_run_ids(dom: &mut Dom, element: NodeId) {
2599    let unique_id = PT::unique_id();
2600    let run_ids_name = PT::run_ids();
2601    for (sdt_id, e) in (0..).zip(dom.descendants(element, Some(&W::sdt()))) {
2602        let ids: Vec<String> = descendants_trimmed(dom, e)
2603            .into_iter()
2604            .filter(|&d2| dom.name(d2) == Some(W::r()))
2605            .filter_map(|r| dom.attribute(r, &unique_id).map(str::to_string))
2606            .collect();
2607        dom.set_attribute_value(e, &run_ids_name, Some(&ids.join(",")));
2608        dom.set_attribute_value(e, &unique_id, Some(&sdt_id.to_string()));
2609    }
2610}
2611
2612/// `Order_sdt` (:2090): schema order for rebuilt `w:sdt` children.
2613fn order_sdt(name: &XName) -> i32 {
2614    if name.namespace_name() != W::URI {
2615        return 999;
2616    }
2617    match name.local_name() {
2618        "sdtPr" => 10,
2619        "sdtEndPr" => 20,
2620        "sdtContent" => 30,
2621        "bookmarkStart" => 40,
2622        "bookmarkEnd" => 50,
2623        _ => 999,
2624    }
2625}
2626
2627/// A.5b — `AddBlockLevelContentControls` (:1964): re-create the `w:sdt`
2628/// wrappers the paragraph-mark transform stripped. For every original sdt
2629/// (by `pt:UniqueId`) missing from `new_document`, locate its runs (by
2630/// `pt:RunIds`) in the new document, find their deepest common ancestor, and
2631/// either wrap the whole paragraph or wrap the child range in a rebuilt sdt
2632/// (children in `Order_sdt` order). Mutates `new_document` in place.
2633///
2634/// FAITHFUL-BUG (TS identical): in the whole-paragraph branch the C# orders
2635/// `contentControl.Elements()` — the ORIGINAL sdt's elements, including its
2636/// original `sdtContent` — instead of the freshly-built control, so the
2637/// replacement is a clone of the original sdt (pre-transform content).
2638///
2639/// # Panics
2640/// Like the C# (`.First()`), when an annotated run of a missing sdt no longer
2641/// exists in `new_document`.
2642pub fn add_block_level_content_controls(
2643    dom: &mut Dom,
2644    new_document: NodeId,
2645    original: NodeId,
2646) -> NodeId {
2647    add_content_controls_with_owners(dom, new_document, original, None)
2648}
2649
2650fn add_content_controls_with_owners(
2651    dom: &mut Dom,
2652    new_document: NodeId,
2653    original: NodeId,
2654    paragraph_owners: Option<&HashMap<NodeId, Vec<NodeId>>>,
2655) -> NodeId {
2656    use std::collections::HashSet;
2657
2658    let sdt = W::sdt();
2659    let unique_id = PT::unique_id();
2660    let run_ids_name = PT::run_ids();
2661
2662    let original_ccs = dom.descendants(original, Some(&sdt));
2663    let existing_ids: HashSet<String> = dom
2664        .descendants(new_document, Some(&sdt))
2665        .into_iter()
2666        .filter_map(|e| dom.attribute(e, &unique_id).map(str::to_string))
2667        .collect();
2668
2669    // Index new-document runs once (O(1) lookup). The *run* nodes and their
2670    // pt:UniqueId attrs are stable for the duration of re-wrap; new w:sdt
2671    // wrappers may be attached under new_document later in the loop, but that
2672    // does not invalidate this run index. First occurrence wins for duplicate
2673    // UniqueIds — matches the old `.find()` document-order semantics.
2674    let mut run_by_id: HashMap<String, NodeId> = HashMap::new();
2675    for r in dom.descendants(new_document, Some(&W::r())) {
2676        if let Some(id) = dom.attribute(r, &unique_id) {
2677            run_by_id.entry(id.to_string()).or_insert(r);
2678        }
2679    }
2680
2681    // Document order of the new document's nodes; wrapping keeps it.
2682    let order: HashMap<NodeId, usize> = dom
2683        .descendants(new_document, None)
2684        .into_iter()
2685        .enumerate()
2686        .map(|(i, n)| (n, i))
2687        .collect();
2688    let mut paragraph_by_id: HashMap<String, NodeId> = HashMap::new();
2689    for p in dom.descendants(new_document, Some(&W::p())) {
2690        if let Some(id) = dom.attribute(p, &unique_id) {
2691            paragraph_by_id.entry(id.to_string()).or_insert(p);
2692        }
2693    }
2694    let mut original_run_by_id: HashMap<String, NodeId> = HashMap::new();
2695    for r in dom.descendants(original, Some(&W::r())) {
2696        if let Some(id) = dom.attribute(r, &unique_id) {
2697            original_run_by_id.entry(id.to_string()).or_insert(r);
2698        }
2699    }
2700    // What a paragraph holds besides runs, by its `c` id: where an emptied
2701    // control goes when no run follows it.
2702    let mut original_content_by_id: HashMap<String, NodeId> = HashMap::new();
2703    for p in dom.descendants(original, Some(&W::p())) {
2704        for child in dom.elements(p, None) {
2705            if let Some(id) = dom.attribute(child, &unique_id) {
2706                original_content_by_id
2707                    .entry(id.to_string())
2708                    .or_insert(child);
2709            }
2710        }
2711    }
2712
2713    for cc in original_ccs {
2714        let cc_id = dom.attribute(cc, &unique_id).unwrap_or("").to_string();
2715        if existing_ids.contains(&cc_id) {
2716            continue;
2717        }
2718        let run_ids: Vec<String> = dom
2719            .attribute(cc, &run_ids_name)
2720            .unwrap_or("")
2721            .split(',')
2722            .map(str::to_string)
2723            .collect();
2724        let runs: Vec<String> = dom
2725            .descendants(cc, Some(&W::r()))
2726            .into_iter()
2727            .filter_map(|r| dom.attribute(r, &unique_id).map(str::to_string))
2728            .filter(|id| run_ids.contains(id))
2729            .collect();
2730        // O(1) index via run_by_id. Runs whose content was entirely a deleted
2731        // revision no longer exist after acceptance — filter_map skips them
2732        // and empty controls fall through to `continue` below (upstream C#
2733        // used .First() and crashed on fully-deleted sdt).
2734        // A run an earlier whole-paragraph wrap took out of the document (a
2735        // control nested in one already restored from its clone) is gone.
2736        // When every paragraph of the control goes, its deleted or moved-away
2737        // text does not anchor it either: a control holding nothing else goes
2738        // with its paragraphs, else its clone would replace the paragraph
2739        // their marks merged into. A control whose text alone is deleted
2740        // keeps its mark and so stays, emptied.
2741        let paragraphs = dom.descendants(cc, Some(&W::p()));
2742        let owned_paragraphs = paragraphs.iter().copied().collect::<HashSet<_>>();
2743        let block_removed = !paragraphs.is_empty()
2744            && paragraphs.iter().all(|&p| {
2745                dom.element(p, &W::p_pr())
2746                    .and_then(|ppr| dom.element(ppr, &W::r_pr()))
2747                    .is_some_and(|rpr| {
2748                        dom.element(rpr, &W::del()).is_some()
2749                            || dom.element(rpr, &W::move_from()).is_some()
2750                    })
2751            });
2752        let mut runs_in_new_document: Vec<NodeId> = runs
2753            .iter()
2754            .filter_map(|id| run_by_id.get(id).copied())
2755            .filter(|&r| {
2756                let ancestors = dom.ancestors(r, None);
2757                ancestors.contains(&new_document)
2758                    && !(block_removed
2759                        && ancestors.iter().any(|&a| {
2760                            dom.name(a)
2761                                .is_some_and(|n| n == W::del() || n == W::move_from())
2762                        }))
2763            })
2764            .collect();
2765        // A paragraph the merge joined to this control's brings something to
2766        // the join when it keeps words or sits in a control of its own; one
2767        // that brings nothing goes, and leaves the control a block (Word 16,
2768        // the #1694 A/B).
2769        let cc_ancestors = dom.ancestors(cc, None);
2770        let brings = |dom: &Dom, source: NodeId| {
2771            !brings_nothing(dom, source)
2772                || std::iter::successors(dom.parent(source), |&a| dom.parent(a))
2773                    .any(|a| dom.name_is(a, &sdt) && a != cc && !cc_ancestors.contains(&a))
2774        };
2775        let foreign = |dom: &Dom, owners: &[NodeId]| {
2776            owners
2777                .iter()
2778                .any(|&source| !owned_paragraphs.contains(&source) && brings(dom, source))
2779        };
2780        // A control whose paragraphs all go keeps its place, emptied: inline
2781        // in the paragraph they join when that paragraph holds something
2782        // else, else a block around it.
2783        if block_removed
2784            && runs_in_new_document.is_empty()
2785            && let Some(paragraph_owners) = paragraph_owners
2786            && let Some(&last_own) = paragraphs.last()
2787            && let Some((&joined, owners)) = paragraph_owners.iter().find(|(joined, owners)| {
2788                owners.contains(&last_own)
2789                    && owners
2790                        .last()
2791                        .is_some_and(|last| !owned_paragraphs.contains(last))
2792                    && std::iter::successors(dom.parent(**joined), |&a| dom.parent(a))
2793                        .any(|a| a == new_document)
2794            })
2795        {
2796            let after: &[NodeId] = owners
2797                .iter()
2798                .rposition(|source| owned_paragraphs.contains(source))
2799                .map(|last| &owners[last + 1..])
2800                .unwrap_or_default();
2801            // The first of the joined paragraph's children that came from a
2802            // paragraph after the control: a run, or content without one
2803            // (an equation, #1714).
2804            let from_after = |dom: &Dom, node: NodeId| {
2805                dom.attribute(node, &unique_id)
2806                    .and_then(|id| {
2807                        original_run_by_id
2808                            .get(id)
2809                            .or_else(|| original_content_by_id.get(id))
2810                    })
2811                    .is_some_and(|&source| {
2812                        std::iter::successors(dom.parent(source), |&a| dom.parent(a))
2813                            .any(|a| after.contains(&a))
2814                    })
2815            };
2816            let later = dom.elements(joined, None).into_iter().find(|&child| {
2817                dom.descendants_and_self(child, None)
2818                    .into_iter()
2819                    .any(|node| from_after(dom, node))
2820            });
2821            let emptied = dom.new_element(sdt.clone());
2822            dom.copy_attributes(cc, emptied);
2823            let props: Vec<NodeId> = dom
2824                .elements(cc, None)
2825                .into_iter()
2826                .filter(|&e| dom.name(e) != Some(W::sdt_content()))
2827                .collect();
2828            let mut kids: Vec<NodeId> = props.into_iter().map(|e| dom.clone_subtree(e)).collect();
2829            let content = dom.new_element(W::sdt_content());
2830            kids.push(content);
2831            kids.sort_by_key(|&e| order_sdt(&dom.name(e).unwrap()));
2832            for e in kids {
2833                dom.add(emptied, e);
2834            }
2835            if !foreign(dom, owners) {
2836                dom.add_before_self(joined, emptied);
2837                dom.remove(joined);
2838                dom.add(content, joined);
2839                continue;
2840            }
2841            match later {
2842                Some(child) => dom.add_before_self(child, emptied),
2843                None => dom.add(joined, emptied),
2844            }
2845            continue;
2846        }
2847        // No run left to anchor it: the control stands on the paragraphs
2848        // that kept their marks, emptied. A paragraph nested in the
2849        // control's own content (a cell of the table it wraps) anchors it
2850        // through that content, else the control would be rebuilt inside
2851        // the table.
2852        if runs_in_new_document.is_empty() && !block_removed {
2853            let wrapper = |n: XName| n == sdt || n == W::sdt_content();
2854            let content = dom.element(cc, &W::sdt_content());
2855            let mut anchors: Vec<NodeId> = Vec::new();
2856            for &p in &paragraphs {
2857                let levels = dom
2858                    .ancestors(p, None)
2859                    .into_iter()
2860                    .take_while(|&a| Some(a) != content)
2861                    .filter(|&a| dom.name(a).is_some_and(|n| !wrapper(n)))
2862                    .count();
2863                let Some(mut anchor) = dom
2864                    .attribute(p, &unique_id)
2865                    .and_then(|id| paragraph_by_id.get(id).copied())
2866                    .filter(|&p| dom.ancestors(p, None).contains(&new_document))
2867                else {
2868                    continue;
2869                };
2870                let mut climbed = 0;
2871                while climbed < levels {
2872                    let Some(parent) = dom.parent(anchor).filter(|&a| a != new_document) else {
2873                        break;
2874                    };
2875                    if dom.name(parent).is_some_and(|n| !wrapper(n)) {
2876                        climbed += 1;
2877                    }
2878                    anchor = parent;
2879                }
2880                if !anchors.contains(&anchor) {
2881                    anchors.push(anchor);
2882                }
2883            }
2884            runs_in_new_document = anchors;
2885        }
2886
2887        // A block control owns paragraphs/tables, not merely the runs that
2888        // happen to survive inside them. Restore that source ownership before
2889        // choosing the insertion level; a cell paragraph is not the owner of
2890        // a control whose sdtContent originally held the whole table.
2891        if let Some(content) = dom.element(cc, &W::sdt_content()) {
2892            let original_runs: HashMap<String, NodeId> = dom
2893                .descendants(cc, Some(&W::r()))
2894                .into_iter()
2895                .filter_map(|run| Some((dom.attribute(run, &unique_id)?.to_string(), run)))
2896                .collect();
2897            let mut anchors = Vec::new();
2898            for &run in &runs_in_new_document {
2899                let owned = dom
2900                    .attribute(run, &unique_id)
2901                    .and_then(|id| original_runs.get(id).copied())
2902                    .and_then(|source| {
2903                        let mut path = dom
2904                            .ancestors_and_self(source, None)
2905                            .into_iter()
2906                            .take_while(|&n| n != content)
2907                            .collect::<Vec<_>>();
2908                        path.reverse();
2909                        // Nested block SDTs are transparent on the source
2910                        // ownership path. Select their first actual block,
2911                        // then promote to its transformed counterpart. The
2912                        // outer control is restored first; inner controls
2913                        // subsequently wrap that same transformed payload.
2914                        let mut top = None;
2915                        for node in path {
2916                            let name = dom.name(node)?;
2917                            if name == W::sdt() || name == W::sdt_content() {
2918                                continue;
2919                            }
2920                            if name == W::p() || name == W::tbl() {
2921                                top = Some(node);
2922                            }
2923                            break;
2924                        }
2925                        let top = top?;
2926                        let name = dom.name(top)?;
2927                        let nested = dom
2928                            .ancestors(source, None)
2929                            .into_iter()
2930                            .take_while(|&n| n != top)
2931                            .filter(|&n| dom.name(n).as_ref() == Some(&name))
2932                            .count();
2933                        let owner = dom
2934                            .ancestors(run, None)
2935                            .into_iter()
2936                            .filter(|&n| dom.name(n).as_ref() == Some(&name))
2937                            .nth(nested)?;
2938                        if name == W::p() {
2939                            if let Some(paragraph_owners) = paragraph_owners {
2940                                // Every contributing source pilcrow must belong
2941                                // to this control, including runless successors.
2942                                let owners = paragraph_owners.get(&owner)?;
2943                                if foreign(dom, owners) {
2944                                    return None;
2945                                }
2946                            } else {
2947                                // The standalone public rewrap helper has no
2948                                // merge map. Only an unchanged paragraph ID can
2949                                // prove complete ownership; otherwise keep its
2950                                // established run-range reconstruction.
2951                                let owner_id = dom.attribute(owner, &unique_id)?;
2952                                if !paragraphs.iter().any(|&source| {
2953                                    dom.attribute(source, &unique_id) == Some(owner_id)
2954                                }) {
2955                                    return None;
2956                                }
2957                            }
2958                        }
2959                        Some(owner)
2960                    })
2961                    .unwrap_or(run);
2962                if !anchors.contains(&owned) {
2963                    anchors.push(owned);
2964                }
2965            }
2966            runs_in_new_document = anchors;
2967        }
2968
2969        // A paragraph made only of this control's paragraphs belongs inside
2970        // it, runs or not: a runless blank, an equation (`m:r`, no `w:r`).
2971        // Word keeps both in the control (#2006).
2972        if let Some(paragraph_owners) = paragraph_owners
2973            && !runs_in_new_document.is_empty()
2974            && !owned_paragraphs.is_empty()
2975        {
2976            let mut joined: Vec<NodeId> = paragraph_owners
2977                .iter()
2978                .filter(|(joined, owners)| {
2979                    !owners.is_empty()
2980                        && owners.iter().all(|o| owned_paragraphs.contains(o))
2981                        && !runs_in_new_document.contains(joined)
2982                        && order.contains_key(joined)
2983                        && std::iter::successors(dom.parent(**joined), |&a| dom.parent(a))
2984                            .any(|a| a == new_document)
2985                })
2986                .map(|(&joined, _)| joined)
2987                .collect();
2988            if !joined.is_empty() {
2989                // An anchor inside a joined paragraph (one of its runs) is
2990                // covered by the paragraph itself.
2991                runs_in_new_document.retain(|&anchor| {
2992                    !dom.ancestors(anchor, None)
2993                        .iter()
2994                        .any(|a| joined.contains(a))
2995                });
2996                runs_in_new_document.append(&mut joined);
2997                runs_in_new_document.sort_by_key(|n| order.get(n).copied().unwrap_or(usize::MAX));
2998            }
2999        }
3000
3001        // deepest common ancestor of all the runs (nearest-first intersection)
3002        let Some(first_run) = runs_in_new_document.first().copied() else {
3003            continue;
3004        };
3005        let mut intersection: Vec<NodeId> = dom.ancestors(first_run, None);
3006        for &run in &runs_in_new_document[1..] {
3007            let anc: HashSet<NodeId> = dom.ancestors(run, None).into_iter().collect();
3008            intersection.retain(|a| anc.contains(a));
3009        }
3010        // A revision wrapper is no place for a block control: rebuilt inside
3011        // the `w:del` holding all its text, the control would go with it.
3012        let Some(&common_ancestor) = intersection.iter().find(|&&a| {
3013            dom.name(a).is_none_or(|n| {
3014                n != W::del() && n != W::ins() && n != W::move_from() && n != W::move_to()
3015            })
3016        }) else {
3017            continue;
3018        };
3019
3020        let child_containing = |dom: &Dom, run: NodeId| -> NodeId {
3021            dom.ancestors_and_self(run, None)
3022                .into_iter()
3023                .find(|&c| dom.parent(c) == Some(common_ancestor))
3024                .expect("common ancestor child containing the run")
3025        };
3026        let first_run_child = child_containing(dom, *runs_in_new_document.first().unwrap());
3027        let last_run_child = child_containing(dom, *runs_in_new_document.last().unwrap());
3028
3029        // Children that "count" for the whole-paragraph test.
3030        let significant: Vec<NodeId> = dom
3031            .elements(common_ancestor, None)
3032            .into_iter()
3033            .filter(|&e| {
3034                let n = dom.name(e).unwrap();
3035                n != W::p_pr() && n != W::comment_range_start() && n != W::comment_range_end()
3036            })
3037            .collect();
3038        let foreign_pilcrow_owner = paragraph_owners
3039            .and_then(|owners| owners.get(&common_ancestor))
3040            .is_some_and(|owners| foreign(dom, owners));
3041        if dom.name(common_ancestor) == Some(W::p())
3042            && !foreign_pilcrow_owner
3043            && significant.first() == Some(&first_run_child)
3044            && significant.last() == Some(&last_run_child)
3045        {
3046            // Whole-paragraph wrap. FAITHFUL-BUG: the replacement is built
3047            // from the ORIGINAL content control's elements (clone-on-attach),
3048            // ordered by Order_sdt — not from a control holding the merged
3049            // paragraph.
3050            let new_cc = dom.new_element(dom.name(cc).unwrap());
3051            dom.copy_attributes(cc, new_cc);
3052            let mut cc_children = dom.elements(cc, None);
3053            cc_children.sort_by_key(|&e| order_sdt(&dom.name(e).unwrap()));
3054            for e in cc_children {
3055                let clone = dom.clone_subtree(e);
3056                dom.add(new_cc, clone);
3057            }
3058            dom.add_before_self(common_ancestor, new_cc);
3059            dom.remove(common_ancestor);
3060            continue;
3061        }
3062
3063        // Range wrap: children before / in / after the run-child range.
3064        let children = dom.elements(common_ancestor, None);
3065        let first_idx = children.iter().position(|&c| c == first_run_child).unwrap();
3066        let last_idx = children.iter().position(|&c| c == last_run_child).unwrap();
3067        let before: Vec<NodeId> = children[..first_idx].to_vec();
3068        let in_range: Vec<NodeId> = children[first_idx..=last_idx].to_vec();
3069        let after: Vec<NodeId> = children[last_idx + 1..].to_vec();
3070
3071        for &c in &children {
3072            dom.remove(c);
3073        }
3074        let new_cc = dom.new_element(dom.name(cc).unwrap());
3075        dom.copy_attributes(cc, new_cc);
3076        let sdt_content = dom.new_element(W::sdt_content());
3077        for &e in &in_range {
3078            dom.add(sdt_content, e); // detached → moved, like the C#
3079        }
3080        let cc_props: Vec<NodeId> = dom
3081            .elements(cc, None)
3082            .into_iter()
3083            .filter(|&e| dom.name(e) != Some(W::sdt_content()))
3084            .collect();
3085        let mut cc_kids: Vec<NodeId> = cc_props.into_iter().map(|e| dom.clone_subtree(e)).collect();
3086        cc_kids.push(sdt_content);
3087        cc_kids.sort_by_key(|&e| order_sdt(&dom.name(e).unwrap()));
3088        for e in cc_kids {
3089            dom.add(new_cc, e);
3090        }
3091        for &e in &before {
3092            dom.add(common_ancestor, e);
3093        }
3094        dom.add(common_ancestor, new_cc);
3095        for &e in &after {
3096            dom.add(common_ancestor, e);
3097        }
3098    }
3099    new_document
3100}
3101
3102/// `brings_nothing` with the revision containers still live: a `w:del`,
3103/// `w:ins`, `w:moveFrom` or `w:moveTo` in the paragraph counts as content,
3104/// so `emptied` answers "nothing authored here at all". With `emptied`
3105/// true those containers count as nothing — the paragraph's words all go.
3106fn paragraph_empties(dom: &Dom, paragraph: NodeId, emptied: bool) -> bool {
3107    let reference = W::comment_reference();
3108    dom.elements(paragraph, None).into_iter().all(|child| {
3109        dom.name(child).is_none_or(|name| {
3110            name == W::p_pr()
3111                || (emptied && (name == W::del() || name == W::move_from()))
3112                || name == W::bookmark_start()
3113                || name == W::bookmark_end()
3114                || name == W::proof_err()
3115                || name == W::comment_range_start()
3116                || name == W::comment_range_end()
3117                || name == W::perm_start()
3118                || name == W::perm_end()
3119                || (name == W::r()
3120                    && dom
3121                        .elements(child, None)
3122                        .into_iter()
3123                        .all(|e| dom.name_is(e, &W::r_pr()) || dom.name_is(e, &reference)))
3124        })
3125    })
3126}
3127
3128/// Does `paragraph` (a source paragraph, before the mark merge) leave nothing
3129/// once its marks go: no run with content outside a deletion or a move away,
3130/// nothing else but its properties and markers? The markers are bookmarks,
3131/// proofing marks, a comment's range and its reference run, and permission
3132/// ranges. Anything not known to be empty brings something (#1694: only
3133/// these shapes were checked against Word, rounds 1 to 9).
3134fn brings_nothing(dom: &Dom, paragraph: NodeId) -> bool {
3135    paragraph_empties(dom, paragraph, true)
3136}
3137
3138/// Does Word keep the deleted mark of paragraph `a` before `b`? It does
3139/// where the join would cross the edge of a block control holding more than
3140/// one paragraph, and the paragraph outside that control keeps something:
3141/// words (`a_keeps` for `a`, with the deleted-mark run before it) or a
3142/// control the other paragraph is not in. Such a control cannot become
3143/// inline, and Word does not take a paragraph out of it to join one outside
3144/// (the #1694 A/B: hn13, hn20, hn32–hn35, hn39, hn40). An outside paragraph
3145/// that keeps nothing goes, as at any join (hn23, hn24, hn31).
3146///
3147/// A control ending at `a` still holds more than one paragraph only while
3148/// one of its marks stays: once they all go, its paragraphs join the one
3149/// after it, and it can become inline there (round 9: k01, k06, k08).
3150fn holds_mark(dom: &Dom, a: NodeId, b: NodeId, a_keeps: bool) -> bool {
3151    let sdt = W::sdt();
3152    let around_a = dom.ancestors(a, Some(&sdt));
3153    let around_b = dom.ancestors(b, Some(&sdt));
3154    let own = |around: &[NodeId], other: &[NodeId]| around.iter().any(|s| !other.contains(s));
3155    let a_keeps = a_keeps || own(&around_a, &around_b);
3156    let b_keeps = !brings_nothing(dom, b) || own(&around_b, &around_a);
3157    let paragraphs = |s: NodeId| dom.descendants(s, Some(&W::p()));
3158    // Several paragraphs, one of them keeping its mark: each control's
3159    // paragraphs are listed once.
3160    let multi_keeping_a_mark = |s: NodeId| {
3161        let ps = paragraphs(s);
3162        ps.len() > 1
3163            && ps
3164                .into_iter()
3165                .any(|p| !paragraph_mark_is_deleted_or_moved_from(dom, p))
3166    };
3167    (a_keeps
3168        && around_b
3169            .iter()
3170            .any(|&s| !around_a.contains(&s) && paragraphs(s).len() > 1))
3171        || (b_keeps
3172            && around_a
3173                .iter()
3174                .any(|&s| !around_b.contains(&s) && multi_keeping_a_mark(s)))
3175}
3176
3177/// The properties of a paragraph whose deleted mark Word kept: those of the
3178/// paragraph after it, as if the two had joined (the #1694 A/B, hn41; style
3179/// and numbering included, round 9: c02). No mark of the next paragraph's
3180/// goes with them, nor its section break (c03); the kept paragraph's own
3181/// section break goes with the deleted mark that carried it (c04, e05).
3182fn held_mark_properties(dom: &mut Dom, next: NodeId) -> Option<NodeId> {
3183    let ppr = dom.new_element(W::p_pr());
3184    if let Some(source) = dom.element(next, &W::p_pr()) {
3185        for child in dom.elements(source, None) {
3186            if dom.name_is(child, &W::sect_pr()) {
3187                continue;
3188            }
3189            let copy = dom.clone_subtree(child);
3190            if dom.name_is(copy, &W::r_pr()) {
3191                for mark in dom.elements(copy, None) {
3192                    if dom.name_is(mark, &W::del()) || dom.name_is(mark, &W::move_from()) {
3193                        dom.remove(mark);
3194                    }
3195                }
3196            }
3197            dom.add(ppr, copy);
3198        }
3199    }
3200    dom.has_elements(ppr).then_some(ppr)
3201}
3202
3203/// A.5b — `AcceptDeletedAndMoveFromParagraphMarks` (:2098): annotate runs and
3204/// content controls (on the ORIGINAL, in place), run the A.5a transform, then
3205/// re-wrap the content controls the transform stripped.
3206///
3207/// ACCEPT-SKIP-A5: when no paragraph mark is `pPr/rPr/(del|moveFrom)`, the
3208/// A.5a grouping machine is a pure identity rebuild and annotate/rewrap do
3209/// nothing useful — transfer `element` without cloning.
3210pub fn accept_deleted_and_move_from_paragraph_marks(dom: &mut Dom, element: NodeId) -> NodeId {
3211    // ACCEPT-SKIP-A5: no deleted/moved-from paragraph marks → identity.
3212    if !has_deleted_or_moved_from_paragraph_mark(dom, element) {
3213        return element;
3214    }
3215    annotate_run_elements_with_id(dom, element);
3216    annotate_paragraph_elements_with_id(dom, element);
3217    annotate_paragraph_content_with_id(dom, element);
3218    annotate_content_controls_with_run_ids(dom, element);
3219    let mut paragraph_owners = HashMap::new();
3220    let new_element = accept_paragraph_marks_with_owners(dom, element, &mut paragraph_owners);
3221    add_content_controls_with_owners(dom, new_element, element, Some(&paragraph_owners))
3222}
3223
3224// ─────────────── A.6 — rows left empty by moveFrom ──────────────────────────
3225
3226/// `BlockLevelElements` (:2766) — the direct-cell-child names that make a
3227/// cell non-empty for [`remove_rows_left_empty_by_move_from`].
3228fn a6_block_level_elements() -> [XName; 8] {
3229    [
3230        W::p(),
3231        W::tbl(),
3232        W::sdt(),
3233        W::del(),
3234        W::ins(),
3235        M::name("oMath"),
3236        M::name("oMathPara"),
3237        W::move_to(),
3238    ]
3239}
3240
3241/// A.6 — `RemoveRowsLeftEmptyByMoveFrom` (:2777): drop every `w:tr` whose
3242/// cells all lost their block-level content to an accepted moveFrom; rebuild
3243/// everything else. The pipeline gates this on the input having carried
3244/// `w:moveFrom` (captured BEFORE AcceptMoveFromMoveTo consumes the markers).
3245pub fn remove_rows_left_empty_by_move_from(dom: &mut Dom, node: NodeId) -> NodeId {
3246    remove_rows_left_empty_by_move_from_inner(dom, node).expect("the root element is not a w:tr")
3247}
3248
3249fn remove_rows_left_empty_by_move_from_inner(dom: &mut Dom, node: NodeId) -> Option<NodeId> {
3250    if !dom.is_element(node) {
3251        return Some(dom.clone_subtree(node));
3252    }
3253    let name = dom.name(node).unwrap();
3254    if name == W::tr() {
3255        let block = a6_block_level_elements();
3256        let non_empty_cells = dom.elements(node, Some(&W::tc())).into_iter().any(|tc| {
3257            dom.elements(tc, None)
3258                .into_iter()
3259                .any(|tcc| dom.name(tcc).is_some_and(|n| block.contains(&n)))
3260        });
3261        if !non_empty_cells {
3262            return None;
3263        }
3264    }
3265    let had_rows = name == W::tbl() && dom.element(node, &W::tr()).is_some();
3266    let ne = dom.new_element(name);
3267    dom.copy_attributes(node, ne);
3268    for c in dom.nodes(node) {
3269        if let Some(tc) = remove_rows_left_empty_by_move_from_inner(dom, c) {
3270            dom.add(ne, tc);
3271        }
3272    }
3273    // A table this pass emptied of rows goes with them: the earlier pass
3274    // emptied the cells of a table whose rows were all deleted, and a
3275    // rowless `w:tbl` is no table Word writes.
3276    if had_rows && dom.element(ne, &W::tr()).is_none() {
3277        return None;
3278    }
3279    Some(ne)
3280}
3281
3282// ─────────────── A.7 — deleted cells + tcPr order ───────────────────────────
3283
3284/// `Order_tcPr` (:1466): schema order for rebuilt `w:tcPr` children.
3285fn order_tc_pr(name: &XName) -> i32 {
3286    if name.namespace_name() != W::URI {
3287        return 999;
3288    }
3289    match name.local_name() {
3290        "cnfStyle" => 10,
3291        "tcW" => 20,
3292        "gridSpan" => 30,
3293        "hMerge" => 40,
3294        "vMerge" => 50,
3295        "tcBorders" => 60,
3296        "shd" => 70,
3297        "noWrap" => 80,
3298        "tcMar" => 90,
3299        "textDirection" => 100,
3300        "tcFitText" => 110,
3301        "vAlign" => 120,
3302        "hideMark" => 130,
3303        "headers" => 140,
3304        _ => 999,
3305    }
3306}
3307
3308/// A.7 — `AcceptDeletedCellsTransform` (:2674): inside each `w:tr`, group
3309/// adjacent children by (deleted-cell?, anchor), where a cell is "deleted"
3310/// when it carries `w:cellDel` OR the next `w:tc` after it does, and the
3311/// anchor is the nearest preceding (or self) `w:tc` WITHOUT `cellDel`. A
3312/// group led by its anchor collapses to one cell whose `gridSpan` widens by
3313/// the number of absorbed cells, `tcPr` children re-ordered per Order_tcPr;
3314/// a group starting with a deleted cell (no anchor) is dropped. FAITHFUL:
3315/// the rebuilt cell loses the original `w:tc` attributes, and an anchor cell
3316/// without `w:tcPr` panics (C# NREs on `currentTcPr.Elements()`).
3317///
3318/// ACCEPT-SKIP-A7: when the subtree has no `w:cellDel`, transfer `node`
3319/// without a full-tree identity rebuild (common path for redlines that only
3320/// carry ins/del).
3321pub fn accept_deleted_cells_transform(dom: &mut Dom, node: NodeId) -> NodeId {
3322    let cell_del = W::cell_del();
3323    // ACCEPT-SKIP-A7: no cellDel → identity (keep parent links).
3324    if !element_or_desc_has_name(dom, node, &cell_del) {
3325        return node;
3326    }
3327    if !dom.is_element(node) {
3328        return node;
3329    }
3330    let name = dom.name(node).unwrap();
3331    if name != W::tr() {
3332        let ne = dom.new_element(name);
3333        dom.copy_attributes(node, ne);
3334        for c in dom.nodes(node) {
3335            let tc = accept_deleted_cells_transform(dom, c);
3336            dom.add(ne, tc);
3337        }
3338        return ne;
3339    }
3340
3341    let tc_name = W::tc();
3342    let cell_del = W::cell_del();
3343    let has_cell_del = |dom: &Dom, e: NodeId| !dom.descendants(e, Some(&cell_del)).is_empty();
3344
3345    let children = dom.elements(node, None);
3346    // key: (is_deleted_cell_group, disambiguator)
3347    let key_of = |dom: &Dom, e: NodeId| -> (bool, Option<NodeId>) {
3348        let cell_after = dom
3349            .nodes_after_self(e)
3350            .into_iter()
3351            .find(|&s| dom.name(s).as_ref() == Some(&tc_name));
3352        let cell_after_is_deleted = cell_after.is_some_and(|ca| has_cell_del(dom, ca));
3353        if dom.name(e).as_ref() == Some(&tc_name) && (cell_after_is_deleted || has_cell_del(dom, e))
3354        {
3355            let anchor = std::iter::once(e)
3356                .chain(content_elements_before_self(dom, e))
3357                .find(|&z| dom.name(z).as_ref() == Some(&tc_name) && !has_cell_del(dom, z));
3358            return (true, anchor);
3359        }
3360        (false, Some(e))
3361    };
3362    let grouped = crate::util::group_adjacent(children, |&e| key_of(dom, e));
3363
3364    let tr = dom.new_element(W::tr());
3365    dom.copy_attributes(node, tr);
3366    for ((is_deleted, _anchor), group) in grouped {
3367        if !is_deleted {
3368            for e in group {
3369                let c = dom.clone_subtree(e);
3370                dom.add(tr, c);
3371            }
3372            continue;
3373        }
3374        let first = group[0];
3375        if has_cell_del(dom, first) {
3376            continue; // no anchor precedes: the whole group is dropped
3377        }
3378        let tcpr_name = W::tc_pr();
3379        let grid_span_name = W::grid_span();
3380        // Anchor cells always carry tcPr in the C# path (NRE otherwise); unwrap once.
3381        let current_tc_pr = dom
3382            .element(first, &tcpr_name)
3383            .expect("anchor cell must carry w:tcPr (C# NREs on currentTcPr.Elements())");
3384        let grid_span: i32 = dom
3385            .element(current_tc_pr, &grid_span_name)
3386            .and_then(|g| dom.attribute(g, &W::val()))
3387            .and_then(|v| v.parse().ok())
3388            .unwrap_or(1);
3389        let new_grid_span = grid_span + group.len() as i32 - 1;
3390
3391        let gs = dom.new_element(grid_span_name.clone());
3392        dom.set_attribute_value(gs, &W::val(), Some(&new_grid_span.to_string()));
3393        let mut tcpr_kids: Vec<NodeId> = vec![gs];
3394        let rest: Vec<NodeId> = dom
3395            .elements(current_tc_pr, None)
3396            .into_iter()
3397            .filter(|&e| dom.name(e).as_ref() != Some(&grid_span_name))
3398            .collect();
3399        for e in rest {
3400            tcpr_kids.push(dom.clone_subtree(e));
3401        }
3402        tcpr_kids.sort_by_key(|&e| order_tc_pr(&dom.name(e).unwrap()));
3403
3404        let ordered_tc_pr = dom.new_element(tcpr_name.clone());
3405        for e in tcpr_kids {
3406            dom.add(ordered_tc_pr, e);
3407        }
3408        let new_tc = dom.new_element(tc_name.clone());
3409        dom.add(new_tc, ordered_tc_pr);
3410        let body_kids: Vec<NodeId> = dom
3411            .elements(first, None)
3412            .into_iter()
3413            .filter(|&e| dom.name(e).as_ref() != Some(&tcpr_name))
3414            .collect();
3415        for e in body_kids {
3416            let c = dom.clone_subtree(e);
3417            dom.add(new_tc, c);
3418        }
3419        dom.add(tr, new_tc);
3420    }
3421    tr
3422}
3423
3424// ─────────────── A.8 — merge adjacent tables ────────────────────────────────
3425
3426/// R8: the `tblPrEx`-able properties of `member` that `first` (whose
3427/// `tblPr` the merged table keeps) does not share.
3428fn own_tbl_pr_ex(dom: &Dom, first: NodeId, member: NodeId) -> Vec<NodeId> {
3429    let ex_of = |t: NodeId| -> Vec<NodeId> {
3430        dom.element(t, &W::tbl_pr())
3431            .map(|pr| {
3432                dom.elements(pr, None)
3433                    .into_iter()
3434                    .filter(|&c| tbl_pr_ex_rank(dom, c).is_some())
3435                    .collect()
3436            })
3437            .unwrap_or_default()
3438    };
3439    let shared: HashSet<String> = ex_of(first)
3440        .into_iter()
3441        .map(|c| dom.serialize_element(c))
3442        .collect();
3443    ex_of(member)
3444        .into_iter()
3445        .filter(|&c| !shared.contains(&dom.serialize_element(c)))
3446        .collect()
3447}
3448
3449/// R8: row `tr`'s `tblPrEx` with its table's `own` properties under the
3450/// row's own, in schema order.
3451fn row_tbl_pr_ex(dom: &mut Dom, tr: NodeId, own: &[NodeId]) -> NodeId {
3452    let row_ex: Vec<NodeId> = dom
3453        .element(tr, &W::tbl_pr_ex())
3454        .map(|ex| dom.elements(ex, None))
3455        .unwrap_or_default();
3456    let mut kids: Vec<NodeId> = row_ex.clone();
3457    for &c in own {
3458        if !row_ex.iter().any(|&r| dom.name(r) == dom.name(c)) {
3459            kids.push(c);
3460        }
3461    }
3462    kids.sort_by_key(|&c| tbl_pr_ex_rank(dom, c).unwrap_or(TBL_PR_EX.len()));
3463    let ex = dom.new_element(W::tbl_pr_ex());
3464    for c in kids {
3465        let cc = dom.clone_subtree(c);
3466        dom.add(ex, cc);
3467    }
3468    ex
3469}
3470
3471/// Matching children in order, through wrappers but not into nested tables.
3472fn wrapped_children(dom: &Dom, parent: NodeId, name: &XName) -> Vec<NodeId> {
3473    let mut children = Vec::new();
3474    for child in dom.elements(parent, None) {
3475        if dom.name_is(child, name) {
3476            children.push(child);
3477        } else if dom.name(child) == Some(W::sdt())
3478            || dom.name(child) == Some(W::sdt_content())
3479            || dom.name(child) == Some(W::custom_xml())
3480        {
3481            children.extend(wrapped_children(dom, child, name));
3482        }
3483    }
3484    children
3485}
3486
3487/// A.8 — `FixWidths` (:1484): clone the table and rewrite each `w:tcW`'s
3488/// `w:w` to the sum of the grid columns its cell spans (per the ORIGINAL
3489/// table's `tblGrid`). FAITHFUL: cells without a `tcW` do not advance the
3490/// grid cursor, exactly like the C#.
3491fn fix_widths(dom: &mut Dom, tbl: NodeId) -> NodeId {
3492    let grid_lines: Vec<i64> = dom
3493        .elements(tbl, Some(&W::tbl_grid()))
3494        .into_iter()
3495        .flat_map(|g| dom.elements(g, Some(&W::grid_col())))
3496        .map(|gc| {
3497            dom.attribute(gc, &W::w())
3498                .and_then(|v| v.parse().ok())
3499                .expect("gridCol w:w must be an integer (C# casts)")
3500        })
3501        .collect();
3502    let new_tbl = dom.clone_subtree(tbl);
3503    for tr in wrapped_children(dom, new_tbl, &W::tr()) {
3504        let mut last_used: i64 = -1;
3505        for tc in wrapped_children(dom, tr, &W::tc()) {
3506            // Singular tcPr / tcW / gridSpan — avoid multi-Vec flat_map scans.
3507            let tc_w = dom
3508                .element(tc, &W::tc_pr())
3509                .and_then(|p| dom.element(p, &W::tc_w()))
3510                .filter(|&w| dom.attribute(w, &W::w()).is_some());
3511            let Some(tc_w) = tc_w else { continue };
3512            let grid_span: i64 = dom
3513                .element(tc, &W::tc_pr())
3514                .and_then(|p| dom.element(p, &W::grid_span()))
3515                .and_then(|g| dom.attribute(g, &W::val()))
3516                .and_then(|v| v.parse().ok())
3517                .unwrap_or(1);
3518            let z = std::cmp::min(grid_lines.len() as i64 - 1, last_used + grid_span);
3519            let w: i64 = grid_lines
3520                .iter()
3521                .enumerate()
3522                .filter(|(i, _)| (*i as i64) > last_used && (*i as i64) <= z)
3523                .map(|(_, g)| g)
3524                .sum();
3525            dom.set_attribute_value(tc_w, &W::w(), Some(&w.to_string()));
3526            last_used += grid_span;
3527        }
3528    }
3529    new_tbl
3530}
3531
3532/// True when a table subtree carries row/cell/run revision marks. Used to
3533/// gate adjacent-table merge so clean content tables stay separate.
3534fn table_has_revision_marks(dom: &Dom, tbl: NodeId) -> bool {
3535    for tag in ["ins", "del", "moveFrom", "moveTo", "cellIns", "cellDel"] {
3536        if element_or_desc_has_name(dom, tbl, &W::name(tag)) {
3537            return true;
3538        }
3539    }
3540    false
3541}
3542
3543/// Which runs of adjacent tables A.8 merges.
3544#[derive(Clone, Copy, PartialEq, Eq)]
3545enum TableMerge {
3546    /// M112 (compare): a run with a revision-marked member.
3547    Revised,
3548    /// Word's save after Accept / Reject All: a run of tables alike in every
3549    /// property only a whole table carries (R8).
3550    WordSave,
3551}
3552
3553/// The `tblPr` children a row can override through `w:tblPrEx`
3554/// (`CT_TblPrExBase`), in schema order.
3555const TBL_PR_EX: [&str; 9] = [
3556    "tblW",
3557    "jc",
3558    "tblCellSpacing",
3559    "tblInd",
3560    "tblBorders",
3561    "shd",
3562    "tblLayout",
3563    "tblCellMar",
3564    "tblLook",
3565];
3566
3567fn tbl_pr_ex_rank(dom: &Dom, e: NodeId) -> Option<usize> {
3568    let n = dom.name(e)?;
3569    (n.namespace_name() == W::URI)
3570        .then(|| TBL_PR_EX.iter().position(|&l| l == n.local_name()))
3571        .flatten()
3572}
3573
3574/// A table's whole-table properties (its `tblPr` minus what `tblPrEx` can
3575/// carry), serialized: Word joins adjacent tables whose keys agree. A grid
3576/// change still tracked (a selective resolution kept it) is the table's own,
3577/// so it keys the table apart.
3578fn whole_table_key(dom: &Dom, tbl: NodeId) -> String {
3579    let mut key = String::from("tbl");
3580    if let Some(pr) = dom.element(tbl, &W::tbl_pr()) {
3581        for c in dom.elements(pr, None) {
3582            if tbl_pr_ex_rank(dom, c).is_none() {
3583                key.push_str(&dom.serialize_element(c));
3584            }
3585        }
3586    }
3587    for grid in dom.elements(tbl, Some(&W::tbl_grid())) {
3588        for change in dom.elements(grid, Some(&W::name("tblGridChange"))) {
3589            key.push_str(&dom.serialize_element(change));
3590        }
3591    }
3592    key
3593}
3594
3595/// The grouping key of A.8 for `e` (empty: not a table).
3596fn table_merge_key(dom: &Dom, e: NodeId, mode: TableMerge) -> String {
3597    if dom.name(e) != Some(W::tbl()) {
3598        return String::new();
3599    }
3600    if mode == TableMerge::WordSave {
3601        return whole_table_key(dom, e);
3602    }
3603    let bidi = dom
3604        .elements(e, Some(&W::tbl_pr()))
3605        .into_iter()
3606        .any(|p| dom.element(p, &W::name("bidiVisual")).is_some());
3607    if bidi {
3608        "tbl|bidiVisual".to_string()
3609    } else {
3610        "tbl".to_string()
3611    }
3612}
3613
3614/// True if any element under `root` has ≥2 adjacent direct `w:tbl` children
3615/// that A.8 merges in `mode`.
3616fn subtree_needs_adjacent_table_merge(dom: &Dom, root: NodeId, mode: TableMerge) -> bool {
3617    fn walk(dom: &Dom, id: NodeId, mode: TableMerge) -> bool {
3618        if !dom.is_element(id) {
3619            return false;
3620        }
3621        // Scan direct element children for adjacent tbl runs.
3622        let kids = dom.elements(id, None);
3623        let mut prev_key = String::new();
3624        let mut run_has_rev = false;
3625        for &k in &kids {
3626            let key = table_merge_key(dom, k, mode);
3627            if key.is_empty() {
3628                prev_key = key;
3629                run_has_rev = false;
3630                continue;
3631            }
3632            let joins = key == prev_key;
3633            match mode {
3634                TableMerge::WordSave if joins => return true,
3635                TableMerge::WordSave => {}
3636                TableMerge::Revised => {
3637                    run_has_rev = (joins && run_has_rev) || table_has_revision_marks(dom, k);
3638                    if joins && run_has_rev {
3639                        return true;
3640                    }
3641                }
3642            }
3643            prev_key = key;
3644        }
3645        kids.into_iter().any(|k| walk(dom, k, mode))
3646    }
3647    walk(dom, root, mode)
3648}
3649
3650/// A.8 — `MergeAdjacentTablesTransform` (:464): where an element has direct
3651/// `w:tbl` children, merge each run of ≥2 adjacent tables sharing the same
3652/// bidiVisual-kind into one table: `tblPr` from the first, `tblGrid` = the
3653/// diffs of the union of every member's cumulative grid widths, and each
3654/// member's rows re-fit (`FixWidths`) with cells re-spanned over the finer
3655/// grid (`gridSpan`, `Order_tcPr` order).
3656///
3657/// M112 (file_130 Word parity): C#/PowerTools fires on ANY adjacent tables.
3658/// Word Compare does **not** merge clean (no-revision) adjacent tables —
3659/// file_131's metadata tables stay as two tables (1-col + 2-col). Merging
3660/// them into one 2-col 12-row table shifts LO page geometry and costs ~1–2
3661/// score points on large-doc near-90 pairs. Gate: only merge a group when
3662/// at least one member carries revision marks (ins/del/move/cellIns/cellDel).
3663///
3664/// ACCEPT-SKIP-A8: when no mergeable adjacent revision-bearing table group
3665/// exists anywhere under `node`, transfer without a full-tree rebuild.
3666pub fn merge_adjacent_tables_transform(dom: &mut Dom, node: NodeId) -> NodeId {
3667    merge_adjacent_tables(dom, node, TableMerge::Revised)
3668}
3669
3670/// R8 — Word's save after Accept / Reject All: adjacent tables alike in every
3671/// whole-table property are one table in Word's model (72cc9f4ac6,
3672/// 3d4318d7e9); a later member's own `tblPrEx`-able properties ride on its
3673/// rows. Identity when nothing merges.
3674fn merge_adjacent_tables_like_word(dom: &mut Dom, node: NodeId) -> NodeId {
3675    merge_adjacent_tables(dom, node, TableMerge::WordSave)
3676}
3677
3678fn merge_adjacent_tables(dom: &mut Dom, node: NodeId, mode: TableMerge) -> NodeId {
3679    // ACCEPT-SKIP-A8: nothing to merge → identity (keep parent links).
3680    if !subtree_needs_adjacent_table_merge(dom, node, mode) {
3681        return node;
3682    }
3683    if !dom.is_element(node) {
3684        return node;
3685    }
3686    let name = dom.name(node).unwrap();
3687    let tbl_name = W::tbl();
3688    if dom.element(node, &tbl_name).is_none() {
3689        let ne = dom.new_element(name);
3690        dom.copy_attributes(node, ne);
3691        for c in dom.nodes(node) {
3692            let tc = merge_adjacent_tables(dom, c, mode);
3693            dom.add(ne, tc);
3694        }
3695        return ne;
3696    }
3697
3698    let children = dom.elements(node, None);
3699    let grouped = crate::util::group_adjacent(children, |&e| table_merge_key(dom, e, mode));
3700
3701    let ne = dom.new_element(name);
3702    dom.copy_attributes(node, ne);
3703    for (key, group) in grouped {
3704        if key.is_empty() || group.len() == 1 {
3705            for e in group {
3706                let c = dom.clone_subtree(e);
3707                dom.add(ne, c);
3708            }
3709            continue;
3710        }
3711        // M112: leave clean adjacent tables unmerged (Word Compare shape).
3712        if mode == TableMerge::Revised && !group.iter().any(|&t| table_has_revision_marks(dom, t)) {
3713            for e in group {
3714                let c = dom.clone_subtree(e);
3715                dom.add(ne, c);
3716            }
3717            continue;
3718        }
3719        // union of cumulative grid widths across the group, ascending
3720        let mut rolled: Vec<i64> = Vec::new();
3721        for &tbl in &group {
3722            let mut sum = 0i64;
3723            for g in dom.elements(tbl, Some(&W::tbl_grid())) {
3724                for gc in dom.elements(g, Some(&W::grid_col())) {
3725                    let v: i64 = dom
3726                        .attribute(gc, &W::w())
3727                        .and_then(|v| v.parse().ok())
3728                        .expect("gridCol w:w must be an integer (C# casts)");
3729                    sum += v;
3730                    rolled.push(sum);
3731                }
3732            }
3733        }
3734        rolled.sort_unstable();
3735        rolled.dedup();
3736
3737        let new_table = dom.new_element(tbl_name.clone());
3738        for pr in dom.elements(group[0], Some(&W::tbl_pr())) {
3739            let c = dom.clone_subtree(pr);
3740            dom.add(new_table, c);
3741        }
3742        let new_grid = dom.new_element(W::tbl_grid());
3743        for (i, &r) in rolled.iter().enumerate() {
3744            let v = if i == 0 { r } else { r - rolled[i - 1] };
3745            let gc = dom.new_element(W::grid_col());
3746            dom.set_attribute_value(gc, &W::w(), Some(&v.to_string()));
3747            dom.add(new_grid, gc);
3748        }
3749        dom.add(new_table, new_grid);
3750
3751        for &tbl in &group {
3752            let own_ex = if mode == TableMerge::WordSave && tbl != group[0] {
3753                own_tbl_pr_ex(dom, group[0], tbl)
3754            } else {
3755                Vec::new()
3756            };
3757            let fixed = fix_widths(dom, tbl);
3758            for tr in wrapped_children(dom, fixed, &W::tr()) {
3759                let new_row = dom.new_element(W::tr());
3760                dom.copy_attributes(tr, new_row);
3761                if !own_ex.is_empty() {
3762                    let ex = row_tbl_pr_ex(dom, tr, &own_ex);
3763                    dom.add(new_row, ex);
3764                }
3765                for property in [W::tbl_pr_ex(), W::tr_pr()] {
3766                    if !own_ex.is_empty() && property == W::tbl_pr_ex() {
3767                        continue;
3768                    }
3769                    for e in dom.elements(tr, Some(&property)) {
3770                        let c = dom.clone_subtree(e);
3771                        dom.add(new_row, c);
3772                    }
3773                }
3774                for child in dom.elements(tr, None) {
3775                    if dom.name(child) == Some(W::tbl_pr_ex())
3776                        || dom.name(child) == Some(W::tr_pr())
3777                    {
3778                        continue;
3779                    }
3780                    let c = dom.clone_subtree(child);
3781                    dom.add(new_row, c);
3782                }
3783                let mut width_to_left = 0i64;
3784                for tc in wrapped_children(dom, new_row, &W::tc()) {
3785                    let w: Option<i64> = dom
3786                        .element(tc, &W::tc_pr())
3787                        .and_then(|p| dom.element(p, &W::tc_w()))
3788                        .and_then(|t| dom.attribute(t, &W::w()))
3789                        .and_then(|v| v.parse().ok());
3790                    let Some(w) = w else { continue };
3791                    let cell_start = width_to_left;
3792                    width_to_left += w;
3793                    // rolled_pairs = [0] ++ rolled; start = first >= cell_start
3794                    let rolled_pairs: Vec<i64> =
3795                        std::iter::once(0).chain(rolled.iter().copied()).collect();
3796                    let start = rolled_pairs.iter().position(|&gv| gv >= cell_start);
3797                    let Some(start_idx) = start else { continue };
3798                    let start_value = rolled_pairs[start_idx];
3799                    let grids_required = rolled_pairs[start_idx..]
3800                        .iter()
3801                        .take_while(|&&gv| gv - start_value < w)
3802                        .count() as i64;
3803
3804                    let mut tcpr_kids: Vec<NodeId> = Vec::new();
3805                    let props: Vec<NodeId> = dom
3806                        .elements(tc, Some(&W::tc_pr()))
3807                        .into_iter()
3808                        .flat_map(|p| dom.elements(p, None))
3809                        .filter(|&e| dom.name(e) != Some(W::grid_span()))
3810                        .collect();
3811                    for e in props {
3812                        tcpr_kids.push(dom.clone_subtree(e));
3813                    }
3814                    if grids_required != 1 {
3815                        let gs = dom.new_element(W::grid_span());
3816                        dom.set_attribute_value(gs, &W::val(), Some(&grids_required.to_string()));
3817                        tcpr_kids.push(gs);
3818                    }
3819                    tcpr_kids.sort_by_key(|&e| order_tc_pr(&dom.name(e).unwrap()));
3820                    let ordered_tc_pr = dom.new_element(W::tc_pr());
3821                    for e in tcpr_kids {
3822                        dom.add(ordered_tc_pr, e);
3823                    }
3824                    let new_cell = dom.new_element(W::tc());
3825                    dom.add(new_cell, ordered_tc_pr);
3826                    let body_kids: Vec<NodeId> = dom
3827                        .elements(tc, None)
3828                        .into_iter()
3829                        .filter(|&e| dom.name(e) != Some(W::tc_pr()))
3830                        .collect();
3831                    for e in body_kids {
3832                        let c = dom.clone_subtree(e);
3833                        dom.add(new_cell, c);
3834                    }
3835                    dom.replace_with(tc, &[new_cell]);
3836                }
3837                dom.replace_with(tr, &[new_row]);
3838            }
3839            for child in dom.elements(fixed, None) {
3840                if dom.name(child) == Some(W::tbl_pr()) || dom.name(child) == Some(W::tbl_grid()) {
3841                    continue;
3842                }
3843                let c = dom.clone_subtree(child);
3844                dom.add(new_table, c);
3845            }
3846        }
3847        dom.add(ne, new_table);
3848    }
3849    ne
3850}
3851
3852// ─────────────── A.9 — empty paragraph in empty cells ───────────────────────
3853
3854/// True if any `w:tc` under `root` has no element children other than `w:tcPr`
3855/// (the A.9 empty-cell predicate). Non-allocating DFS for ACCEPT-SKIP-02.
3856fn has_empty_table_cell(dom: &Dom, root: NodeId) -> bool {
3857    let tc = W::tc();
3858    let tcpr = W::tc_pr();
3859    fn walk(dom: &Dom, id: NodeId, tc: &XName, tcpr: &XName) -> bool {
3860        if let Some(name) = dom.name(id)
3861            && name == *tc
3862        {
3863            // empty = no element child other than w:tcPr (incl. zero children)
3864            let mut only_tcpr = true;
3865            for i in 0..dom.child_count(id) {
3866                let c = dom.child_at(id, i);
3867                if dom.is_element(c) && dom.name(c).is_some_and(|n| n != *tcpr) {
3868                    only_tcpr = false;
3869                    break;
3870                }
3871            }
3872            if only_tcpr {
3873                return true;
3874            }
3875        }
3876        for i in 0..dom.child_count(id) {
3877            if walk(dom, dom.child_at(id, i), tc, tcpr) {
3878                return true;
3879            }
3880        }
3881        false
3882    }
3883    walk(dom, root, &tc, &tcpr)
3884}
3885
3886/// A.9 — `AddEmptyParagraphToAnyEmptyCells` (:1448): a `w:tc` with no element
3887/// children other than `w:tcPr` gains an empty `w:p`.
3888///
3889/// ACCEPT-INPLACE-A9: mutate empty cells in place (append `w:p`) instead of
3890/// rebuilding the entire subtree. Returns the same `node` root (callers that
3891/// rebind `e = add_empty...(dom, e)` stay correct).
3892pub fn add_empty_paragraph_to_any_empty_cells(dom: &mut Dom, node: NodeId) -> NodeId {
3893    if !dom.is_element(node) {
3894        return node;
3895    }
3896    let tc = W::tc();
3897    let tcpr = W::tc_pr();
3898    // Collect empty cells first — cannot mutate while walking.
3899    let mut empty: Vec<NodeId> = Vec::new();
3900    collect_empty_table_cells(dom, node, &tc, &tcpr, &mut empty);
3901    for cell in empty {
3902        let p = dom.new_element(W::p());
3903        dom.add(cell, p);
3904    }
3905    node
3906}
3907
3908fn collect_empty_table_cells(
3909    dom: &Dom,
3910    id: NodeId,
3911    tc: &XName,
3912    tcpr: &XName,
3913    out: &mut Vec<NodeId>,
3914) {
3915    if let Some(name) = dom.name(id)
3916        && name == *tc
3917    {
3918        let mut only_tcpr = true;
3919        for i in 0..dom.child_count(id) {
3920            let c = dom.child_at(id, i);
3921            if dom.is_element(c) && dom.name(c).is_some_and(|n| n != *tcpr) {
3922                only_tcpr = false;
3923                break;
3924            }
3925        }
3926        if only_tcpr {
3927            out.push(id);
3928        }
3929    }
3930    for i in 0..dom.child_count(id) {
3931        let c = dom.child_at(id, i);
3932        if dom.is_element(c) {
3933            collect_empty_table_cells(dom, c, tc, tcpr, out);
3934        }
3935    }
3936}
3937
3938/// The content of a control (`w:sdt`) holds nothing a resolution left
3939/// behind: no children at all, or paragraphs that all bring nothing. A
3940/// nested `w:sdt`, a `w:tbl` or a surviving run counts as content, so only
3941/// the innermost of nested emptied controls qualifies (Word 16, hn30).
3942/// `emptied` selects the paragraph test: live revision containers still
3943/// count as content before the transforms (`authored`), as nothing after
3944/// them (`resolved`).
3945fn emptied_content(dom: &Dom, content: NodeId, resolved: bool) -> bool {
3946    dom.elements(content, None)
3947        .into_iter()
3948        .all(|child| dom.name_is(child, &W::p()) && paragraph_empties(dom, child, resolved))
3949}
3950
3951/// Stamp on a control that was already empty before the transforms ran,
3952/// so [`mark_emptied_controls`] marks only controls this resolution
3953/// emptied. Lives and dies inside `accept_content`; never serialized.
3954fn authored_empty(dom: &Dom, control: NodeId) -> bool {
3955    dom.element(control, &W::sdt_content())
3956        .is_some_and(|content| emptied_content(dom, content, false))
3957}
3958
3959/// Where the `w:` children of `w:sdtPr` that precede `w:showingPlcHdr` in
3960/// `CT_SdtPr` end: before `dataBinding`, `label`, `tabIndex`, the type
3961/// child and every extension-namespace child.
3962fn before_showing_plc_hdr(dom: &Dom, sdt_pr: NodeId) -> Option<NodeId> {
3963    const BEFORE: &[&str] = &[
3964        "rPr",
3965        "alias",
3966        "tag",
3967        "id",
3968        "lock",
3969        "placeholder",
3970        "temporary",
3971    ];
3972    dom.elements(sdt_pr, None).into_iter().find(|&e| {
3973        dom.name(e)
3974            .is_some_and(|n| n.namespace_name() != W::URI || !BEFORE.contains(&n.local_name()))
3975    })
3976}
3977
3978/// Word's answer to an emptied content control, Accept All and Reject All
3979/// alike (#1703, the #1694 A/B): `w:showingPlcHdr` in the control's
3980/// `w:sdtPr` and a bare run of five spaces —
3981/// `<w:r><w:t xml:space="preserve">     </w:t></w:r>` — inside the
3982/// control's paragraph for a block control, directly in `w:sdtContent`
3983/// for an inline one. A `pt:AuthoredEmpty` stamp tells a control emptied
3984/// by this resolution from one authored empty, and gallery controls
3985/// (`w:docPartObj`/`w:docPartList`) and controls naming a
3986/// `w:placeholder/w:docPart` stay as the resolution left them — Word
3987/// marks neither.
3988fn mark_emptied_controls(dom: &mut Dom, root: NodeId) {
3989    let authored = PT::name("AuthoredEmpty");
3990    for control in dom.descendants(root, Some(&W::sdt())) {
3991        let already = dom.attribute(control, &authored).is_some();
3992        dom.set_attribute_value(control, &authored, None);
3993        if already {
3994            continue;
3995        }
3996        let Some(content) = dom.element(control, &W::sdt_content()) else {
3997            continue;
3998        };
3999        if !emptied_content(dom, content, true) {
4000            continue;
4001        }
4002        // Word's controls carry a `w:sdtPr` (the A/B's were empty); one
4003        // without is a compare artifact, not a control Word authored, and
4004        // stays as the resolution left it.
4005        let Some(sdt_pr) = dom.element(control, &W::sdt_pr()) else {
4006            continue;
4007        };
4008        // Word leaves a gallery control (w:docPartObj/w:docPartList)
4009        // alone: its accepted "Page Numbers (Bottom of Page)" footer
4010        // control keeps an empty paragraph, no placeholder (the Word
4011        // corpus, b4cd671041). A control naming a w:placeholder/w:docPart
4012        // shows that part's text, not five spaces (#1703 open questions).
4013        if dom.elements(sdt_pr, None).iter().any(|&e| {
4014            dom.name(e).is_some_and(|n| {
4015                n.namespace_name() == W::URI
4016                    && (matches!(n.local_name(), "docPartObj" | "docPartList")
4017                        || (n.local_name() == "placeholder"
4018                            && dom.element(e, &W::name("docPart")).is_some()))
4019            })
4020        }) {
4021            continue;
4022        }
4023        if dom.element(sdt_pr, &W::name("showingPlcHdr")).is_none() {
4024            let showing = dom.new_element(W::name("showingPlcHdr"));
4025            match before_showing_plc_hdr(dom, sdt_pr) {
4026                Some(later) => dom.add_before_self(later, showing),
4027                None => dom.add(sdt_pr, showing),
4028            }
4029        }
4030        let run = dom.new_element(W::r());
4031        let t = dom.new_element(W::t());
4032        dom.set_attribute_value(t, &XNamespace::xml().name("space"), Some("preserve"));
4033        dom.add_text(t, "     ");
4034        dom.add(run, t);
4035        let block = dom.elements(content, Some(&W::p())).first().copied();
4036        match block {
4037            Some(paragraph) => dom.add(paragraph, run),
4038            None if dom.ancestors(control, Some(&W::p())).is_empty() => {
4039                let paragraph = dom.new_element(W::p());
4040                dom.add(content, paragraph);
4041                dom.add(paragraph, run);
4042            }
4043            None => dom.add(content, run),
4044        }
4045    }
4046}
4047
4048// ─────────────── A.10 — the full AcceptRevisionsForPart pipeline ────────────
4049
4050/// The `w:del` or `w:moveFrom` that holds `node`, when accept will remove it.
4051#[doc(hidden)]
4052pub fn accept_deleted(dom: &Dom, node: NodeId) -> Option<NodeId> {
4053    let mut cur = dom.parent(node);
4054    while let Some(ancestor) = cur {
4055        if dom.name_is(ancestor, &W::del()) || dom.name_is(ancestor, &W::move_from()) {
4056            return Some(ancestor);
4057        }
4058        cur = dom.parent(ancestor);
4059    }
4060    None
4061}
4062
4063/// Spans whose field characters accept removes: the deletion that holds the
4064/// `begin` and the one that holds the matching `end`.
4065fn deleted_field_spans(dom: &Dom, root: NodeId) -> Vec<(NodeId, NodeId)> {
4066    let mut stack: Vec<(NodeId, bool)> = Vec::new();
4067    let mut spans = Vec::new();
4068    dom.for_each_descendant_element(root, Some(&W::fld_char()), |fld| {
4069        let deleted = accept_deleted(dom, fld);
4070        match dom.attribute(fld, &W::fld_char_type()) {
4071            Some("begin") => stack.push((deleted.unwrap_or(fld), deleted.is_some())),
4072            Some("end") => {
4073                if let Some((begin, true)) = stack.pop()
4074                    && let Some(end) = deleted
4075                {
4076                    spans.push((begin, end));
4077                }
4078            }
4079            _ => {}
4080        }
4081    });
4082    spans
4083}
4084
4085/// Accept drops the result of a field whose begin and end are both
4086/// tracked-deleted. Those characters may be two deletions with the result
4087/// between them; Word removes the result with the field (#1285). A result
4088/// already inside the same deletion needs nothing: accept removes it.
4089///
4090/// The result is marked deleted here, before the comment, bookmark and
4091/// permission prepasses, so its ranges settle as in any other deletion: a
4092/// range wholly inside it goes (or is rescued), one that reaches past it
4093/// keeps its surviving characters and both ends. Range markers stay where
4094/// they are; only content moves into a `w:del` (an insertion becomes one).
4095///
4096/// The begin and end must share a parent. A field whose result crosses a
4097/// paragraph keeps its result, as before #1285: what Word does with the
4098/// paragraph marks inside it is not yet probed.
4099fn delete_deleted_field_results(dom: &mut Dom, root: NodeId) {
4100    for (begin_del, end_del) in deleted_field_spans(dom, root) {
4101        if begin_del == end_del {
4102            continue;
4103        }
4104        let Some(parent) = dom.parent(begin_del) else {
4105            continue;
4106        };
4107        if dom.parent(end_del) != Some(parent) {
4108            continue;
4109        }
4110        // Collected before the loop below moves them into new wrappers.
4111        let mut between = Vec::new();
4112        let mut inside = false;
4113        for i in 0..dom.child_count(parent) {
4114            let child = dom.child_at(parent, i);
4115            if child == end_del {
4116                break;
4117            }
4118            if inside && dom.is_element(child) {
4119                between.push(child);
4120            } else if child == begin_del {
4121                inside = true;
4122            }
4123        }
4124        let attributes = dom.attributes(begin_del);
4125        for child in between {
4126            if is_range_marker(dom, child)
4127                || dom.name_is(child, &W::del())
4128                || dom.name_is(child, &W::move_from())
4129            {
4130                continue;
4131            }
4132            if dom.name_is(child, &W::ins()) {
4133                dom.set_name(child, W::del());
4134                continue;
4135            }
4136            let del = dom.new_element(W::del());
4137            for (name, value) in &attributes {
4138                dom.set_attribute_value(del, name, Some(value));
4139            }
4140            dom.add_before_self(child, del);
4141            dom.remove(child);
4142            dom.add(del, child);
4143        }
4144    }
4145}
4146
4147/// A range or proofing marker: it holds no character of its own.
4148fn is_range_marker(dom: &Dom, node: NodeId) -> bool {
4149    dom.name(node).is_some_and(|name| {
4150        name.namespace_name() == W::URI
4151            && matches!(
4152                name.local_name(),
4153                "bookmarkStart"
4154                    | "bookmarkEnd"
4155                    | "commentRangeStart"
4156                    | "commentRangeEnd"
4157                    | "permStart"
4158                    | "permEnd"
4159                    | "moveFromRangeStart"
4160                    | "moveFromRangeEnd"
4161                    | "moveToRangeStart"
4162                    | "moveToRangeEnd"
4163                    | "proofErr"
4164            )
4165    })
4166}
4167
4168/// A.10 — `AcceptRevisionsForPart` (:1314) at content scope: the exact
4169/// 15-step transform order. `contains_move_from` is captured AFTER the
4170/// field-code fixup but BEFORE AcceptMoveFromMoveTo consumes the `w:moveFrom`
4171/// wrappers, gating RemoveRowsLeftEmptyByMoveFrom exactly like the C#.
4172///
4173/// ACCEPT-SKIP-01: when the subtree has no tracked-revision elements, skip
4174/// every revision-semantic full-tree rebuild (field fixup, move*, all-other,
4175/// deleted-cells, merge-adjacent). Still runs RemoveRsid, A.9 empty-cell
4176/// fill (not revision-gated in C#), and UniqueId/numPr cleanup.
4177pub fn accept_revisions_for_part_content(dom: &mut Dom, root: NodeId) -> NodeId {
4178    accept_content(dom, root, false, &mut Vec::new())
4179}
4180
4181fn accept_content(
4182    dom: &mut Dom,
4183    root: NodeId,
4184    keep_comments: bool,
4185    kept: &mut Vec<String>,
4186) -> NodeId {
4187    let has_rev = element_has_tracked_revisions(dom, root);
4188    let e = remove_rsid_transform(dom, root).expect("root not dropped by rsid removal");
4189    let e = if has_rev {
4190        // #1703: flag the controls empty already; the post-pass cannot tell
4191        // them from the ones the transforms below empty.
4192        let authored = PT::name("AuthoredEmpty");
4193        for control in dom.descendants(e, Some(&W::sdt())) {
4194            if authored_empty(dom, control) {
4195                dom.set_attribute_value(control, &authored, Some("1"));
4196            }
4197        }
4198        // O.0: normalize orphan move elements first — the comment/bookmark
4199        // prepasses and A.2/A.4 all treat matched moveFrom-range content as
4200        // deleted, so orphan `moveTo`/`moveFrom` elements must be `w:ins`/
4201        // `w:del` before any of them runs (#1235). No range marker is
4202        // dropped here: Word deletes an orphan moveFrom range's unwrapped
4203        // content on Accept (#1243), which is A.2's own doing, and A.10
4204        // strips every leftover marker afterwards.
4205        let e = normalize_orphan_moves(dom, e, OrphanMovePass::AcceptElements);
4206        // #1285: a field whose begin and end are both deleted takes its
4207        // result with it, ranges settled like any deletion's.
4208        delete_deleted_field_results(dom, e);
4209        if keep_comments {
4210            kept.extend(comments::keep_wholly_deleted_comments(dom, e));
4211        }
4212        comments::drop_wholly_deleted_comments(dom, e);
4213        bookmarks::drop_wholly_deleted_bookmarks(dom, e);
4214        drop_wholly_deleted_permissions(dom, e);
4215        let e = fix_up_deleted_or_inserted_field_codes_transform(dom, e);
4216        let contains_move_from = !dom.descendants(e, Some(&W::move_from())).is_empty();
4217        let e = {
4218            let v = accept_move_from_move_to_transform(dom, e);
4219            debug_assert_eq!(v.len(), 1);
4220            v[0]
4221        };
4222        let e = accept_move_from_ranges(dom, e);
4223        let e = accept_paragraph_end_tags_in_move_from_transform(dom, e);
4224        let e = accept_deleted_and_moved_from_content_controls(dom, e);
4225        let e = accept_deleted_and_move_from_paragraph_marks(dom, e);
4226        let e = if contains_move_from {
4227            remove_rows_left_empty_by_move_from(dom, e)
4228        } else {
4229            e
4230        };
4231        let e = {
4232            let v = accept_all_other_revisions_transform(dom, e);
4233            debug_assert_eq!(v.len(), 1);
4234            v[0]
4235        };
4236        let e = accept_deleted_cells_transform(dom, e);
4237        let e = merge_adjacent_tables_transform(dom, e);
4238        bookmarks::drop_unpaired_bookmarks(dom, e);
4239        // #1703: a control the resolution emptied shows Word's placeholder.
4240        mark_emptied_controls(dom, e);
4241        e
4242    } else {
4243        e
4244    };
4245    // ACCEPT-SKIP-02: A.9 is a full-tree rebuild; skip when no empty cells.
4246    let e = if has_empty_table_cell(dom, e) {
4247        add_empty_paragraph_to_any_empty_cells(dom, e)
4248    } else {
4249        e
4250    };
4251    // #1223: a `w:comment` must keep at least one `w:p`. Rejecting a
4252    // comment's only insertion or accepting a wholly deleted one can empty
4253    // it; Word writes an empty `w:p` there.
4254    if dom.name(e) == Some(W::name("comments")) {
4255        ensure_comment_paragraphs(dom, e);
4256    }
4257
4258    // Strip PT.UniqueId / PT.RunIds attributes from all descendants.
4259    let unique_id = PT::unique_id();
4260    let run_ids = PT::run_ids();
4261    for d in dom.descendants_and_self(e, None) {
4262        dom.set_attribute_value(d, &unique_id, None);
4263        dom.set_attribute_value(d, &run_ids, None);
4264    }
4265    // Remove empty w:numPr elements.
4266    let num_pr = W::num_pr();
4267    for np in dom.descendants(e, Some(&num_pr)) {
4268        if !dom.has_elements(np) {
4269            dom.remove(np);
4270        }
4271    }
4272    e
4273}
4274
4275// ─────────────── A.11 — package-scope accept / reject ───────────────────────
4276
4277/// A property element `live` reverting to its saved copy `reverted` keeps
4278/// the revisions left tracked in it (frozen by a selective resolution): a
4279/// paragraph mark's insertion or deletion ahead of the run properties
4280/// (`first`), a row's or a cell's marks after the rest.
4281fn carry_kept_revisions(dom: &mut Dom, live: NodeId, reverted: NodeId, first: bool) {
4282    let kept: Vec<NodeId> = dom
4283        .elements(live, None)
4284        .into_iter()
4285        .filter(|&e| dom.name(e).is_some_and(|n| n.namespace_name() == FROZEN_NS))
4286        .collect();
4287    let kept: Vec<NodeId> = kept.into_iter().map(|e| dom.clone_subtree(e)).collect();
4288    if first {
4289        for c in kept.into_iter().rev() {
4290            dom.add_first(reverted, c);
4291        }
4292    } else {
4293        for c in kept {
4294            dom.add(reverted, c);
4295        }
4296    }
4297}
4298
4299/// Give every `w:comment` under a `w:comments` root without a block child
4300/// (`w:p`, `w:tbl`, `w:sdt`, `w:customXml`) an empty paragraph (#1223).
4301fn ensure_comment_paragraphs(dom: &mut Dom, root: NodeId) {
4302    let block = [W::p(), W::tbl(), W::sdt(), W::custom_xml()];
4303    for comment in dom.elements(root, Some(&W::comment())) {
4304        if !dom
4305            .elements(comment, None)
4306            .into_iter()
4307            .any(|c| dom.name(c).is_some_and(|n| block.contains(&n)))
4308        {
4309            let p = dom.new_element(W::p());
4310            dom.add(comment, p);
4311        }
4312    }
4313}
4314
4315/// A.11 — `AcceptRevisionsForStylesTransform` (:1300): drop `pPrChange`/
4316/// `rPrChange` from the styles part, rebuild the rest.
4317fn accept_revisions_for_styles_transform(dom: &mut Dom, node: NodeId) -> Option<NodeId> {
4318    if !dom.is_element(node) {
4319        return Some(dom.clone_subtree(node));
4320    }
4321    let name = dom.name(node).unwrap();
4322    if name == W::p_pr_change() || name == W::r_pr_change() {
4323        return None;
4324    }
4325    let ne = dom.new_element(name);
4326    dom.copy_attributes(node, ne);
4327    for c in dom.nodes(node) {
4328        if let Some(tc) = accept_revisions_for_styles_transform(dom, c) {
4329            dom.add(ne, tc);
4330        }
4331    }
4332    Some(ne)
4333}
4334
4335/// A.11 — `RejectRevisionsForStylesTransform` (:391): a `pPr` holding a
4336/// `pPrChange` reverts to the change's inner `pPr` (same for `rPr`); a change
4337/// element without its inner properties drops the whole node (C# recurses
4338/// null).
4339fn reject_revisions_for_styles_transform(dom: &mut Dom, node: NodeId) -> Option<NodeId> {
4340    if !dom.is_element(node) {
4341        return Some(dom.clone_subtree(node));
4342    }
4343    let name = dom.name(node).unwrap();
4344    if name == W::p_pr()
4345        && let Some(chg) = dom.element(node, &W::p_pr_change())
4346    {
4347        let inner = dom.element(chg, &W::p_pr());
4348        return inner.and_then(|i| reject_revisions_for_styles_transform(dom, i));
4349    }
4350    if name == W::r_pr()
4351        && let Some(chg) = dom.element(node, &W::r_pr_change())
4352    {
4353        let inner = dom.element(chg, &W::r_pr());
4354        return inner.and_then(|i| reject_revisions_for_styles_transform(dom, i));
4355    }
4356    let ne = dom.new_element(name);
4357    dom.copy_attributes(node, ne);
4358    for c in dom.nodes(node) {
4359        if let Some(tc) = reject_revisions_for_styles_transform(dom, c) {
4360            dom.add(ne, tc);
4361        }
4362    }
4363    Some(ne)
4364}
4365
4366/// The part `rel` of the main part targets (`numbering`, `comments`),
4367/// resolved against the main part; `None` when the package has none.
4368fn related_part(pkg: &crate::opc::PartFs, rel: &str) -> Option<String> {
4369    let main = pkg.main_document_part()?;
4370    let rels = pkg.read_rels_for(&main)?;
4371    rels.items
4372        .iter()
4373        .find(|r| {
4374            r.target_mode.as_deref() != Some("External")
4375                && r.rel_type.rsplit('/').next() == Some(rel)
4376        })
4377        .map(|r| pkg.resolve_rel_target(&main, &r.target))
4378}
4379
4380/// The main document's numbering part, when it has one.
4381fn numbering_part(pkg: &crate::opc::PartFs) -> Option<String> {
4382    related_part(pkg, "numbering")
4383}
4384
4385/// The main document's comments part (`word/comments.xml`), when it has
4386/// one. Its revisions resolve like every other part's and are listed as
4387/// `comments.rN` (#1706).
4388#[doc(hidden)]
4389pub fn comments_part(pkg: &crate::opc::PartFs) -> Option<String> {
4390    related_part(pkg, "comments")
4391}
4392
4393/// The parts `AcceptRevisions`/`RejectRevisions` (:1277/:31) walk, in the C#
4394/// order — main, headers, footers, endnotes, footnotes, then styles
4395/// (flagged) — with the comments part Word's own Accept/Reject All also
4396/// settles (#1223) between the notes and the styles.
4397#[doc(hidden)]
4398pub fn revision_bearing_parts(pkg: &crate::opc::PartFs) -> Vec<(String, bool)> {
4399    let main = pkg
4400        .main_document_part()
4401        .unwrap_or_else(|| "word/document.xml".to_string());
4402    let mut headers = Vec::new();
4403    let mut footers = Vec::new();
4404    let mut endnotes = Vec::new();
4405    let mut footnotes = Vec::new();
4406    let mut comments = Vec::new();
4407    let mut styles = Vec::new();
4408    if let Some(rels) = pkg.read_rels_for(&main) {
4409        for r in &rels.items {
4410            if r.target_mode.as_deref() == Some("External") {
4411                continue;
4412            }
4413            let bucket = match r.rel_type.rsplit('/').next().unwrap_or("") {
4414                "header" => &mut headers,
4415                "footer" => &mut footers,
4416                "endnotes" => &mut endnotes,
4417                "footnotes" => &mut footnotes,
4418                "comments" => &mut comments,
4419                "styles" => &mut styles,
4420                _ => continue,
4421            };
4422            bucket.push(pkg.resolve_rel_target(&main, &r.target));
4423        }
4424    }
4425    let mut out = vec![(main, false)];
4426    for p in headers
4427        .into_iter()
4428        .chain(footers)
4429        .chain(endnotes)
4430        .chain(footnotes)
4431        .chain(comments)
4432    {
4433        out.push((p, false));
4434    }
4435    for p in styles {
4436        out.push((p, true));
4437    }
4438    out
4439}
4440
4441fn process_part<F>(pkg: &mut crate::opc::PartFs, part: &str, f: F)
4442where
4443    F: FnOnce(&mut Dom, NodeId) -> Option<NodeId>,
4444{
4445    let Some(xml) = pkg.part_string(part) else {
4446        return;
4447    };
4448    let mut dom = Dom::new();
4449    let doc = dom.parse_xdocument(&xml);
4450    let Some(root) = dom.root(doc) else {
4451        return;
4452    };
4453    let Some(new_root) = f(&mut dom, root) else {
4454        return;
4455    };
4456    dom.replace_with(root, &[new_root]);
4457    pkg.set_part(part, dom.serialize_document(doc).into_bytes());
4458}
4459
4460/// A.11 — `AcceptRevisions` (:1277) at package scope: run the full part
4461/// pipeline over main + headers + footers + endnotes + footnotes, and the
4462/// styles transform over the styles part.
4463pub fn accept_revisions_package(pkg: &mut crate::opc::PartFs) {
4464    resolve_package(pkg, Resolution::Accept, None);
4465}
4466
4467/// A.11 — `RejectRevisions` (:31) at package scope: per content part, the
4468/// revert → reverse → rsid-strip → full-accept composition (the C# phases the
4469/// same steps across all parts; parts are independent, so per-part composition
4470/// is equivalent); the styles part reverts its property changes then accepts
4471/// the leftovers.
4472pub fn reject_revisions_package(pkg: &mut crate::opc::PartFs) {
4473    resolve_package(pkg, Resolution::Reject, None);
4474}
4475
4476/// Revision elements renamed into this namespace sit a resolution out and
4477/// come back unchanged (`jubarte::changes`).
4478#[doc(hidden)]
4479pub const FROZEN_NS: &str = "urn:jubarte:frozen-revision";
4480
4481/// Package-wide ids reserved before any revision is frozen or removed.
4482/// Annotation ids and XML parts outside the revision pipeline have other scopes.
4483#[doc(hidden)]
4484pub struct RevisionIds {
4485    next: u64,
4486    used: HashSet<u64>,
4487}
4488
4489impl RevisionIds {
4490    #[doc(hidden)]
4491    pub fn new(pkg: &crate::opc::PartFs) -> Self {
4492        let mut used = HashSet::new();
4493        for (part, _) in revision_bearing_parts(pkg) {
4494            let Some(xml) = pkg.part_string(&part) else {
4495                continue;
4496            };
4497            let mut dom = Dom::new();
4498            let doc = dom.parse_xdocument(&xml);
4499            let Some(root) = dom.root(doc) else { continue };
4500            for node in dom.descendants_and_self(root, None) {
4501                if dom
4502                    .name(node)
4503                    .is_some_and(|name| crate::validate_dom::has_unique_revision_id(&name))
4504                    && let Some(id) = dom
4505                        .attribute(node, &W::id())
4506                        .and_then(|id| id.parse::<u64>().ok())
4507                {
4508                    used.insert(id);
4509                }
4510            }
4511        }
4512        Self::from_used(used)
4513    }
4514
4515    #[doc(hidden)]
4516    pub fn from_used(used: HashSet<u64>) -> Self {
4517        let next = used.iter().max().map_or(0, |id| id.saturating_add(1));
4518        Self { next, used }
4519    }
4520
4521    /// Keep max + 1 until Word's signed 32-bit range is exhausted, then
4522    /// allocate the lowest unused id. Reserve copies immediately, too.
4523    #[doc(hidden)]
4524    pub fn allocate(&mut self) -> u64 {
4525        const MAX: u64 = i32::MAX as u64;
4526        if self.next > MAX {
4527            self.next = 0;
4528        }
4529        while self.used.contains(&self.next) {
4530            self.next += 1;
4531        }
4532        assert!(self.next <= MAX, "revision id space exhausted");
4533        let id = self.next;
4534        self.used.insert(id);
4535        self.next += 1;
4536        id
4537    }
4538}
4539
4540/// A copied property history is a distinct record. Allocate at the copy
4541/// site, leaving the original's attribution, payload and id untouched.
4542#[doc(hidden)]
4543pub fn clone_with_fresh_property_ids(
4544    dom: &mut Dom,
4545    source: NodeId,
4546    next_id: &mut RevisionIds,
4547) -> NodeId {
4548    let copy = dom.clone_subtree(source);
4549    refresh_property_ids(dom, copy, |_| next_id.allocate());
4550    copy
4551}
4552
4553/// Give every property history under `copy`, `copy` included, an id from
4554/// `allocate`, which is passed the id the record had, leaving its
4555/// attribution and payload untouched: a copy of a record is a distinct
4556/// record.
4557#[doc(hidden)]
4558pub fn refresh_property_ids(
4559    dom: &mut Dom,
4560    copy: NodeId,
4561    mut allocate: impl FnMut(Option<u64>) -> u64,
4562) {
4563    for node in std::iter::once(copy).chain(dom.descendants(copy, None)) {
4564        if dom.name(node).is_some_and(|name| {
4565            matches!(name.namespace_name(), W::URI | FROZEN_NS)
4566                && matches!(name.local_name(), "rPrChange" | "pPrChange")
4567        }) {
4568            let old = dom
4569                .attribute(node, &W::id())
4570                .and_then(|id| id.parse::<u64>().ok());
4571            dom.set_attribute_value(node, &W::id(), Some(&allocate(old).to_string()));
4572        }
4573    }
4574}
4575
4576/// Called with each revision-bearing part's name and parsed root before it
4577/// is resolved; renames the revisions to keep into [`FROZEN_NS`].
4578pub(crate) type Freeze<'a> = &'a dyn Fn(&str, &mut Dom, NodeId);
4579
4580/// Accept or reject every revision `freeze` leaves in place. Bookmark and
4581/// comment ids are identifiers: the ones kept keep their ids, whatever is
4582/// left (#1264). Return the removed comments' original ids.
4583#[doc(hidden)]
4584pub fn resolve_package(
4585    pkg: &mut crate::opc::PartFs,
4586    resolution: Resolution,
4587    freeze: Option<Freeze<'_>>,
4588) -> Vec<String> {
4589    resolve_with_comments(pkg, resolution, freeze, false, &mut Vec::new())
4590}
4591
4592/// [`resolve_package`] for an edit plan, the only entry point that can
4593/// rescue removed anchors.
4594#[doc(hidden)]
4595pub fn resolve_package_for_edit(
4596    pkg: &mut crate::opc::PartFs,
4597    resolution: Resolution,
4598    freeze: Option<Freeze<'_>>,
4599    keep_comments: bool,
4600) -> (Vec<String>, Vec<String>) {
4601    let mut kept = Vec::new();
4602    let removed = resolve_with_comments(pkg, resolution, freeze, keep_comments, &mut kept);
4603    (removed, kept)
4604}
4605
4606fn resolve_with_comments(
4607    pkg: &mut crate::opc::PartFs,
4608    resolution: Resolution,
4609    freeze: Option<Freeze<'_>>,
4610    keep_comments: bool,
4611    kept_comments: &mut Vec<String>,
4612) -> Vec<String> {
4613    let parts = revision_bearing_parts(pkg);
4614    let mut next_id = RevisionIds::new(pkg);
4615    let levels = numbering_part(pkg)
4616        .and_then(|p| pkg.part_string(&p))
4617        .map(|xml| style_records::Levels::parse(&xml))
4618        .unwrap_or_default();
4619    // #1223 settles revisions inside comment bodies. A comments part with
4620    // none is neither settled nor tidied, as before #1223, so a redline
4621    // carries it as Word's does (#1467); a comment whose anchors are gone
4622    // is still pruned from it.
4623    let comments = comments_part(pkg);
4624    let mut untouched_comments = None;
4625    for (part, is_styles) in parts.clone() {
4626        let is_comments = comments.as_ref() == Some(&part);
4627        process_part(pkg, &part, |dom, root| {
4628            if is_comments && !element_has_tracked_revisions(dom, root) {
4629                untouched_comments = Some(part.clone());
4630                return None;
4631            }
4632            if let Some(freeze) = freeze {
4633                freeze(&part, dom, root);
4634            }
4635            let resolved = match (is_styles, resolution) {
4636                (true, Resolution::Accept) => accept_revisions_for_styles_transform(dom, root),
4637                (true, Resolution::Reject) => {
4638                    let recorded = style_records::recorded_blocks(dom, root);
4639                    let rejected = reject_revisions_for_styles_transform(dom, root)?;
4640                    style_records::restore_against_built_ins(
4641                        dom,
4642                        rejected,
4643                        &recorded,
4644                        &levels,
4645                        &mut next_id,
4646                    );
4647                    accept_revisions_for_styles_transform(dom, rejected)
4648                }
4649                (false, _) => {
4650                    sections::carry_vanishing_section_references(dom, root, resolution);
4651                    Some(match resolution {
4652                        Resolution::Accept => {
4653                            accept_content(dom, root, keep_comments, kept_comments)
4654                        }
4655                        Resolution::Reject => {
4656                            reject_content(dom, root, keep_comments, kept_comments)
4657                        }
4658                    })
4659                }
4660            }?;
4661            thaw(dom, resolved);
4662            Some(resolved)
4663        });
4664    }
4665    let stories = story_parts(&parts);
4666    let removed_comments = comments::prune_orphan_comments(pkg, &stories, comments.as_deref());
4667    notes::prune_orphan_notes(pkg, &stories);
4668    let tidied: Vec<String> = stories
4669        .into_iter()
4670        .filter(|part| untouched_comments.as_ref() != Some(part))
4671        .collect();
4672    word_save::tidy(pkg, &tidied);
4673    removed_comments
4674}
4675
4676/// Rename every frozen revision element under `root` back into `w:`.
4677fn thaw(dom: &mut Dom, root: NodeId) {
4678    let frozen: Vec<(NodeId, String)> = dom
4679        .descendants_and_self(root, None)
4680        .into_iter()
4681        .filter_map(|e| {
4682            let name = dom.name(e)?;
4683            (name.namespace_name() == FROZEN_NS).then(|| (e, name.local_name().to_string()))
4684        })
4685        .collect();
4686    for (e, local) in &frozen {
4687        dom.set_name(*e, W::name(local));
4688    }
4689}
4690
4691/// The content parts of [`revision_bearing_parts`] (styles left out).
4692fn story_parts(parts: &[(String, bool)]) -> Vec<String> {
4693    parts
4694        .iter()
4695        .filter(|(_, is_styles)| !is_styles)
4696        .map(|(p, _)| p.clone())
4697        .collect()
4698}
4699
4700#[cfg(test)]
4701#[cfg_attr(all(coverage_nightly, test), coverage(off))]
4702mod revision_boundary_coverage_tests {
4703    use super::*;
4704
4705    fn parse(body: &str) -> (Dom, NodeId) {
4706        let mut dom = Dom::new();
4707        let doc = dom.parse_xdocument(&format!(
4708            "<w:body xmlns:w='{}' xmlns:x='urn:fixture' x:owner='story'>{body}</w:body>",
4709            W::URI
4710        ));
4711        let root = dom.root(doc).unwrap();
4712        (dom, root)
4713    }
4714
4715    fn paragraph(text: &str) -> String {
4716        format!("<w:p><w:r><w:t>{text}</w:t></w:r></w:p>")
4717    }
4718
4719    fn cell(text: &str, properties: &str) -> String {
4720        format!(
4721            "<w:tc><w:tcPr>{properties}</w:tcPr>{}</w:tc>",
4722            paragraph(text)
4723        )
4724    }
4725
4726    fn table(properties: &str, widths: &[i64], row_properties: &str, cells: &str) -> String {
4727        let grid: String = widths
4728            .iter()
4729            .map(|w| format!("<w:gridCol w:w='{w}'/>"))
4730            .collect();
4731        format!(
4732            "<w:tbl><w:tblPr>{properties}</w:tblPr><w:tblGrid>{grid}</w:tblGrid><w:tr x:owner='row'>{row_properties}{cells}</w:tr></w:tbl>"
4733        )
4734    }
4735
4736    fn local_children(dom: &Dom, node: NodeId) -> Vec<String> {
4737        dom.elements(node, None)
4738            .into_iter()
4739            .map(|n| dom.name(n).unwrap().local_name().to_string())
4740            .collect()
4741    }
4742
4743    fn widths(dom: &Dom, table: NodeId) -> Vec<String> {
4744        let grid = dom.element(table, &W::tbl_grid()).unwrap();
4745        dom.elements(grid, Some(&W::grid_col()))
4746            .into_iter()
4747            .map(|n| dom.attribute(n, &W::w()).unwrap().to_string())
4748            .collect()
4749    }
4750
4751    fn span(dom: &Dom, cell: NodeId) -> Option<String> {
4752        dom.element(cell, &W::tc_pr())
4753            .and_then(|p| dom.element(p, &W::grid_span()))
4754            .and_then(|s| dom.attribute(s, &W::val()))
4755            .map(str::to_string)
4756    }
4757
4758    #[test]
4759    fn revised_table_union_preserves_rows_payload_and_unrelated_clean_groups() {
4760        let a = table(
4761            "<w:tblStyle w:val='A'/>",
4762            &[1000, 2000],
4763            "<w:trPr><w:ins w:id='7'/></w:trPr>",
4764            &(cell("A", "<w:tcW w:w='9' w:type='dxa'/>")
4765                + &cell("B", "<w:shd w:fill='123456'/><w:tcW w:w='8' w:type='dxa'/>")),
4766        );
4767        let b = table(
4768            "<w:tblStyle w:val='B'/>",
4769            &[1500, 1500],
4770            "<w:trPr><w:cantSplit/></w:trPr>",
4771            &(cell("C", "<w:tcW w:w='7'/>")
4772                + &cell("D", "<w:tcW w:w='6'/><w:gridSpan w:val='1'/>")),
4773        );
4774        let clean = table("", &[3000], "", &cell("clean", "<w:tcW w:w='3000'/>"));
4775        let (mut dom, root) = parse(&(a + &b + &paragraph("separator") + &clean + &clean));
4776        let original = dom.serialize_element(root);
4777        let result = merge_adjacent_tables_transform(&mut dom, root);
4778        assert_ne!(result, root);
4779        assert_eq!(dom.serialize_element(root), original);
4780        assert_eq!(
4781            dom.attribute(result, &XName::get("owner", "urn:fixture")),
4782            Some("story")
4783        );
4784        assert_eq!(local_children(&dom, result), ["tbl", "p", "tbl", "tbl"]);
4785        let merged = dom.elements(result, Some(&W::tbl()))[0];
4786        assert_eq!(widths(&dom, merged), ["1000", "500", "1500"]);
4787        let style = dom
4788            .element(
4789                dom.element(merged, &W::tbl_pr()).unwrap(),
4790                &W::name("tblStyle"),
4791            )
4792            .unwrap();
4793        assert_eq!(dom.attribute(style, &W::val()), Some("A"));
4794        let rows = dom.elements(merged, Some(&W::tr()));
4795        assert_eq!(rows.len(), 2);
4796        assert_eq!(
4797            dom.attribute(rows[1], &XName::get("owner", "urn:fixture")),
4798            Some("row")
4799        );
4800        let cells: Vec<NodeId> = rows
4801            .iter()
4802            .flat_map(|&r| dom.elements(r, Some(&W::tc())))
4803            .collect();
4804        assert_eq!(
4805            cells.iter().map(|&c| dom.value(c)).collect::<Vec<_>>(),
4806            ["A", "B", "C", "D"]
4807        );
4808        assert_eq!(
4809            cells.iter().map(|&c| span(&dom, c)).collect::<Vec<_>>(),
4810            [None, Some("2".into()), Some("2".into()), None]
4811        );
4812        assert_eq!(
4813            local_children(&dom, dom.element(cells[1], &W::tc_pr()).unwrap()),
4814            ["tcW", "gridSpan", "shd"]
4815        );
4816        assert_eq!(dom.descendants(merged, Some(&W::ins())).len(), 1);
4817        assert_eq!(
4818            dom.descendants(merged, Some(&W::name("cantSplit"))).len(),
4819            1
4820        );
4821        assert_eq!(dom.value(result), "ABCDseparatorcleanclean");
4822    }
4823
4824    #[test]
4825    fn fix_widths_clamps_spans_and_leaves_widthless_cells_out_of_cursor() {
4826        let cells = cell("no-width", "<w:shd w:fill='ABABAB'/>")
4827            + &cell(
4828                "wide",
4829                "<w:tcW w:w='17' w:type='dxa'/><w:gridSpan w:val='2'/>",
4830            )
4831            + &cell("last", "<w:tcW w:w='18'/><w:gridSpan w:val='bad'/>")
4832            + &cell("past-grid", "<w:tcW w:w='19'/><w:gridSpan w:val='5'/>");
4833        let (mut dom, root) = parse(&table("", &[1000, 2000, 3000], "", &cells));
4834        let source = dom.element(root, &W::tbl()).unwrap();
4835        let original = dom.serialize_element(source);
4836        let fixed = fix_widths(&mut dom, source);
4837        let row = dom.element(fixed, &W::tr()).unwrap();
4838        let cells = dom.elements(row, Some(&W::tc()));
4839        let actual: Vec<Option<String>> = cells
4840            .iter()
4841            .map(|&c| {
4842                dom.element(c, &W::tc_pr())
4843                    .and_then(|p| dom.element(p, &W::tc_w()))
4844                    .and_then(|w| dom.attribute(w, &W::w()))
4845                    .map(str::to_string)
4846            })
4847            .collect();
4848        assert_eq!(
4849            actual,
4850            [
4851                None,
4852                Some("3000".into()),
4853                Some("3000".into()),
4854                Some("0".into())
4855            ]
4856        );
4857        let width = dom
4858            .element(dom.element(cells[1], &W::tc_pr()).unwrap(), &W::tc_w())
4859            .unwrap();
4860        assert_eq!(dom.attribute(width, &W::type_()), Some("dxa"));
4861        assert_eq!(dom.value(fixed), "no-widthwidelastpast-grid");
4862        assert_eq!(dom.serialize_element(source), original);
4863    }
4864
4865    #[test]
4866    fn nested_merge_clones_widthless_cell_and_keeps_control_identity() {
4867        let cells = cell("opaque", "<w:shd w:fill='101010'/><w:cellIns w:id='8'/>")
4868            + &cell("sized", "<w:tcW w:w='100'/>");
4869        let a = table("", &[100], "", &cells);
4870        let b = table("", &[100], "", &cell("second", "<w:tcW w:w='100'/>"));
4871        let (mut dom, root) = parse(&format!(
4872            "<w:sdt><w:sdtPr><w:tag w:val='owner'/></w:sdtPr><w:sdtContent>{a}{b}</w:sdtContent></w:sdt>{}",
4873            paragraph("tail")
4874        ));
4875        let opaque = dom.descendants(root, Some(&W::tc()))[0];
4876        let expected = dom.serialize_element(opaque);
4877        let result = merge_adjacent_tables_transform(&mut dom, root);
4878        assert_eq!(dom.descendants(result, Some(&W::tbl())).len(), 1);
4879        assert_eq!(dom.descendants(result, Some(&W::sdt())).len(), 1);
4880        let tag = dom.descendants(result, Some(&W::name("tag")))[0];
4881        assert_eq!(dom.attribute(tag, &W::val()), Some("owner"));
4882        assert_eq!(
4883            dom.serialize_element(dom.descendants(result, Some(&W::tc()))[0]),
4884            expected
4885        );
4886        assert_eq!(dom.value(result), "opaquesizedsecondtail");
4887    }
4888
4889    #[test]
4890    fn word_save_merges_row_exceptions_with_row_values_taking_precedence() {
4891        let a = table(
4892            "<w:tblStyle w:val='same'/><w:jc w:val='center'/><w:tblW w:w='100'/><w:shd w:fill='AAAAAA'/>",
4893            &[100],
4894            "",
4895            &cell("first", "<w:tcW w:w='100'/>"),
4896        );
4897        let b = table(
4898            "<w:tblStyle w:val='same'/><w:jc w:val='center'/><w:tblW w:w='200'/><w:shd w:fill='BBBBBB'/><w:tblLayout w:type='fixed'/>",
4899            &[100],
4900            "<w:tblPrEx><w:shd w:fill='CCCCCC'/><x:payload x:owner='exception'/></w:tblPrEx><w:trPr><w:cantSplit/></w:trPr>",
4901            &cell("second", "<w:tcW w:w='100'/>"),
4902        );
4903        let (mut dom, root) = parse(&(a + &b));
4904        let result = merge_adjacent_tables_like_word(&mut dom, root);
4905        let tables = dom.elements(result, Some(&W::tbl()));
4906        assert_eq!(tables.len(), 1);
4907        let rows = dom.elements(tables[0], Some(&W::tr()));
4908        assert!(dom.element(rows[0], &W::tbl_pr_ex()).is_none());
4909        let ex = dom.element(rows[1], &W::tbl_pr_ex()).unwrap();
4910        assert_eq!(
4911            local_children(&dom, ex),
4912            ["tblW", "shd", "tblLayout", "payload"]
4913        );
4914        assert_eq!(
4915            dom.attribute(dom.element(ex, &W::tbl_w()).unwrap(), &W::w()),
4916            Some("200")
4917        );
4918        assert_eq!(
4919            dom.attribute(dom.element(ex, &W::shd()).unwrap(), &W::fill()),
4920            Some("CCCCCC")
4921        );
4922        assert_eq!(dom.elements(rows[1], Some(&W::tbl_pr_ex())).len(), 1);
4923        assert_eq!(
4924            dom.descendants(rows[1], Some(&W::name("cantSplit"))).len(),
4925            1
4926        );
4927        assert_eq!(dom.value(result), "firstsecond");
4928    }
4929
4930    #[test]
4931    fn table_merge_identity_respects_whole_properties_grid_history_and_bidi() {
4932        let plain = table("", &[100], "", &cell("plain", "<w:tcW w:w='100'/>"));
4933        let marked = table(
4934            "<w:bidiVisual/>",
4935            &[100],
4936            "<w:trPr><w:del/></w:trPr>",
4937            &cell("marked", "<w:tcW w:w='100'/>"),
4938        );
4939        for body in [
4940            plain.clone() + &plain,
4941            plain.clone() + &marked,
4942            marked.clone() + &paragraph("break") + &marked,
4943        ] {
4944            let (mut dom, root) = parse(&body);
4945            let before = dom.serialize_element(root);
4946            assert_eq!(merge_adjacent_tables_transform(&mut dom, root), root);
4947            assert_eq!(dom.serialize_element(root), before);
4948        }
4949        let other_style = table(
4950            "<w:tblStyle w:val='different'/>",
4951            &[100],
4952            "",
4953            &cell("style", "<w:tcW w:w='100'/>"),
4954        );
4955        let changed_grid = plain.replacen("</w:tblGrid>", "<w:tblGridChange w:id='2'><w:tblGrid><w:gridCol w:w='50'/></w:tblGrid></w:tblGridChange></w:tblGrid>", 1);
4956        let foreign = table(
4957            "<x:payload x:owner='whole'/>",
4958            &[100],
4959            "",
4960            &cell("foreign", "<w:tcW w:w='100'/>"),
4961        );
4962        for body in [
4963            plain.clone() + &other_style,
4964            plain.clone() + &changed_grid,
4965            plain + &foreign,
4966        ] {
4967            let (mut dom, root) = parse(&body);
4968            assert_eq!(merge_adjacent_tables_like_word(&mut dom, root), root);
4969        }
4970    }
4971
4972    #[test]
4973    fn accepting_deleted_cells_keeps_anchor_payload_and_expands_existing_span() {
4974        let cells = cell("leading-deletion", "<w:cellDel/>")
4975            + &cell(
4976                "anchor",
4977                "<w:shd w:fill='EEEEEE'/><w:gridSpan w:val='2'/><w:tcW w:w='700'/><x:payload x:owner='cell'/>",
4978            )
4979            + &cell("deleted-one", "<w:cellDel/>")
4980            + &cell("deleted-two", "<w:cellDel/>")
4981            + &cell("tail", "<w:tcW w:w='300'/>");
4982        let (mut dom, root) = parse(&table(
4983            "",
4984            &[100, 100, 100, 100, 100, 100],
4985            "<w:trPr><w:cantSplit/></w:trPr>",
4986            &cells,
4987        ));
4988        let original = dom.serialize_element(root);
4989        let result = accept_deleted_cells_transform(&mut dom, root);
4990        let row = dom.descendants(result, Some(&W::tr()))[0];
4991        assert_eq!(
4992            dom.attribute(row, &XName::get("owner", "urn:fixture")),
4993            Some("row")
4994        );
4995        let cells = dom.elements(row, Some(&W::tc()));
4996        assert_eq!(cells.len(), 2);
4997        assert_eq!(dom.value(result), "anchortail");
4998        assert_eq!(span(&dom, cells[0]), Some("4".into()));
4999        assert_eq!(span(&dom, cells[1]), None);
5000        assert_eq!(
5001            local_children(&dom, dom.element(cells[0], &W::tc_pr()).unwrap()),
5002            ["tcW", "gridSpan", "shd", "payload"]
5003        );
5004        assert!(dom.descendants(result, Some(&W::cell_del())).is_empty());
5005        assert_eq!(dom.serialize_element(root), original);
5006    }
5007
5008    #[test]
5009    fn deleted_cell_anchor_defaults_bad_span_and_orders_all_schema_properties() {
5010        let property_names = [
5011            "headers",
5012            "hideMark",
5013            "vAlign",
5014            "tcFitText",
5015            "textDirection",
5016            "tcMar",
5017            "noWrap",
5018            "shd",
5019            "tcBorders",
5020            "vMerge",
5021            "hMerge",
5022            "tcW",
5023            "cnfStyle",
5024        ];
5025        let properties: String = property_names.iter().map(|p| format!("<w:{p}/>")).collect();
5026        let cells = cell(
5027            "anchor",
5028            &(properties + "<w:gridSpan w:val='not-an-integer'/><x:gridSpan x:owner='foreign'/>"),
5029        ) + &cell("deleted", "<w:cellDel/>");
5030        let (mut dom, root) = parse(&table("", &[100, 100], "", &cells));
5031        let result = accept_deleted_cells_transform(&mut dom, root);
5032        let cell = dom.descendants(result, Some(&W::tc()))[0];
5033        let pr = dom.element(cell, &W::tc_pr()).unwrap();
5034        assert_eq!(span(&dom, cell), Some("2".into()));
5035        assert_eq!(
5036            local_children(&dom, pr),
5037            [
5038                "cnfStyle",
5039                "tcW",
5040                "gridSpan",
5041                "hMerge",
5042                "vMerge",
5043                "tcBorders",
5044                "shd",
5045                "noWrap",
5046                "tcMar",
5047                "textDirection",
5048                "tcFitText",
5049                "vAlign",
5050                "hideMark",
5051                "headers",
5052                "gridSpan"
5053            ]
5054        );
5055        assert_eq!(
5056            dom.descendants(result, Some(&XName::get("gridSpan", "urn:fixture")))
5057                .len(),
5058            1
5059        );
5060        assert_eq!(dom.value(result), "anchor");
5061    }
5062
5063    #[test]
5064    fn custom_xml_deleted_control_unwraps_nested_controls_but_retains_order_and_anchors() {
5065        let (mut dom, root) = parse(
5066            "<w:customXmlDelRangeStart w:id='4'/><w:sdt><w:sdtPr><w:tag w:val='outer'/></w:sdtPr><w:sdtContent><w:bookmarkStart w:id='3' w:name='kept'/><w:p><w:r><w:t>before</w:t></w:r><w:sdt><w:sdtPr><w:tag w:val='inner'/></w:sdtPr><w:sdtContent><w:r><w:t>inside</w:t></w:r><x:payload x:owner='run'/></w:sdtContent></w:sdt><w:r><w:t>after</w:t></w:r></w:p><w:bookmarkEnd w:id='3'/></w:sdtContent></w:sdt><w:customXmlDelRangeEnd w:id='4'/><w:p><w:r><w:t>tail</w:t></w:r></w:p>",
5067        );
5068        let result = accept_deleted_and_moved_from_content_controls(&mut dom, root);
5069        assert!(dom.descendants(result, Some(&W::sdt())).is_empty());
5070        assert_eq!(dom.value(result), "beforeinsideaftertail");
5071        assert_eq!(
5072            local_children(&dom, result),
5073            [
5074                "customXmlDelRangeStart",
5075                "bookmarkStart",
5076                "p",
5077                "bookmarkEnd",
5078                "customXmlDelRangeEnd",
5079                "p"
5080            ]
5081        );
5082        assert_eq!(dom.descendants(result, Some(&W::bookmark_start())).len(), 1);
5083        assert_eq!(
5084            dom.descendants(result, Some(&XName::get("payload", "urn:fixture")))
5085                .len(),
5086            1
5087        );
5088    }
5089
5090    #[test]
5091    fn custom_xml_move_deletes_whole_control_and_plain_content_but_keeps_outside_control() {
5092        let (mut dom, root) = parse(
5093            "<w:customXmlMoveFromRangeStart w:id='9'/><w:sdt><w:sdtPr><w:tag w:val='deleted'/></w:sdtPr><w:sdtContent><w:p><w:r><w:t>gone</w:t></w:r></w:p></w:sdtContent></w:sdt><w:p><w:r><w:t>also-gone</w:t></w:r></w:p><w:customXmlMoveFromRangeEnd w:id='9'/><w:sdt><w:sdtPr><w:tag w:val='kept'/></w:sdtPr><w:sdtContent><w:p><w:r><w:t>retained</w:t></w:r></w:p></w:sdtContent></w:sdt>",
5094        );
5095        let result = accept_deleted_and_moved_from_content_controls(&mut dom, root);
5096        assert_eq!(dom.value(result), "retained");
5097        assert_eq!(
5098            local_children(&dom, result),
5099            [
5100                "customXmlMoveFromRangeStart",
5101                "customXmlMoveFromRangeEnd",
5102                "sdt"
5103            ]
5104        );
5105        let controls = dom.descendants(result, Some(&W::sdt()));
5106        assert_eq!(controls.len(), 1);
5107        let tag = dom.descendants(controls[0], Some(&W::name("tag")))[0];
5108        assert_eq!(dom.attribute(tag, &W::val()), Some("kept"));
5109    }
5110
5111    #[test]
5112    fn unmatched_custom_ranges_leave_control_payload_and_parent_links_untouched() {
5113        for kind in ["customXmlDelRange", "customXmlMoveFromRange"] {
5114            for end in [String::new(), format!("<w:{kind}End w:id='other'/>")] {
5115                let (mut dom, root) = parse(&format!(
5116                    "<w:{kind}Start w:id='unmatched'/><w:sdt><w:sdtPr/><w:sdtContent>{}</w:sdtContent></w:sdt>{end}",
5117                    paragraph("retained")
5118                ));
5119                let before = dom.serialize_element(root);
5120                let control = dom.element(root, &W::sdt()).unwrap();
5121                assert_eq!(
5122                    accept_deleted_and_moved_from_content_controls(&mut dom, root),
5123                    root
5124                );
5125                assert_eq!(dom.parent(control), Some(root));
5126                assert_eq!(dom.serialize_element(root), before);
5127            }
5128        }
5129    }
5130
5131    #[test]
5132    fn move_range_that_enters_table_keeps_container_properties_and_surviving_content() {
5133        let (mut dom, root) = parse(
5134            "<w:moveFromRangeStart w:id='7'/><w:p><w:r><w:t>heading-gone</w:t></w:r></w:p><w:tbl><w:tblPr><w:tblStyle w:val='retained'/></w:tblPr><w:tblGrid><w:gridCol w:w='2400'/></w:tblGrid><w:tr><w:trPr><w:cantSplit/></w:trPr><w:tc><w:tcPr><w:tcW w:w='2400'/></w:tcPr><w:p><w:pPr><w:keepNext/></w:pPr><w:r><w:t>prefix-gone</w:t></w:r><w:moveFromRangeEnd w:id='7'/><w:r><w:t>remaining</w:t></w:r></w:p></w:tc></w:tr></w:tbl>",
5135        );
5136        let result = accept_move_from_ranges(&mut dom, root);
5137        assert_eq!(dom.value(result), "remaining");
5138        assert_eq!(dom.descendants(result, Some(&W::tbl())).len(), 1);
5139        assert_eq!(dom.descendants(result, Some(&W::name("tblStyle"))).len(), 1);
5140        assert_eq!(dom.descendants(result, Some(&W::grid_col())).len(), 1);
5141        assert_eq!(
5142            dom.descendants(result, Some(&W::name("cantSplit"))).len(),
5143            1
5144        );
5145        assert_eq!(dom.descendants(result, Some(&W::tc_w())).len(), 1);
5146        assert_eq!(dom.descendants(result, Some(&W::name("keepNext"))).len(), 1);
5147        assert_eq!(
5148            dom.descendants(result, Some(&W::move_from_range_end()))
5149                .len(),
5150            1
5151        );
5152    }
5153
5154    #[test]
5155    fn accept_cell_merge_converts_restart_and_continue_only_inside_cell_properties() {
5156        for (value, expected) in [
5157            ("rest", Some("restart")),
5158            ("cont", Some("continue")),
5159            ("unknown", None),
5160        ] {
5161            let (mut dom, root) = parse(&format!(
5162                "<w:tc><w:tcPr><w:cellMerge w:id='4' w:vMerge='{value}' w:vMergeOrig='cont'/></w:tcPr>{}</w:tc>",
5163                paragraph("cell")
5164            ));
5165            let output = accept_all_other_revisions_transform(&mut dom, root);
5166            assert_eq!(output.len(), 1);
5167            let result = output[0];
5168            let merges = dom.descendants(result, Some(&W::v_merge()));
5169            match expected {
5170                Some(expected) => {
5171                    assert_eq!(merges.len(), 1);
5172                    assert_eq!(dom.attribute(merges[0], &W::val()), Some(expected));
5173                    assert!(dom.descendants(result, Some(&W::cell_merge())).is_empty());
5174                }
5175                None => {
5176                    assert!(merges.is_empty());
5177                    let marker = dom.descendants(result, Some(&W::cell_merge()))[0];
5178                    assert_eq!(dom.attribute(marker, &W::v_merge()), Some("unknown"));
5179                }
5180            }
5181            assert_eq!(dom.value(result), "cell");
5182        }
5183        let (mut dom, root) =
5184            parse("<x:payload><w:cellMerge w:id='5' w:vMerge='rest'/></x:payload>");
5185        let output = accept_all_other_revisions_transform(&mut dom, root);
5186        assert_eq!(dom.descendants(output[0], Some(&W::cell_merge())).len(), 1);
5187        assert!(dom.descendants(output[0], Some(&W::v_merge())).is_empty());
5188    }
5189
5190    #[test]
5191    fn internally_deleted_equations_leave_no_math_shell_but_keep_live_and_empty_math() {
5192        for inserted in [false, true] {
5193            for para in [false, true] {
5194                let marker = if inserted { "ins" } else { "del" };
5195                let equation = format!(
5196                    "<m:oMath><m:f><m:fPr><m:ctrlPr><w:{marker} w:id='3'><w:rPr><w:b/></w:rPr></w:{marker}></m:ctrlPr></m:fPr><m:num><m:r><w:{marker} w:id='4'><w:rPr><w:rFonts w:ascii='Cambria Math'/></w:rPr><m:t>x</m:t></w:{marker}></m:r></m:num><m:den><m:r><w:{marker} w:id='5'><m:t>y</m:t></w:{marker}></m:r></m:den></m:f></m:oMath>"
5197                );
5198                let equation = if para {
5199                    format!(
5200                        "<m:oMathPara><m:oMathParaPr><m:jc m:val='center'/></m:oMathParaPr>{equation}</m:oMathPara>"
5201                    )
5202                } else {
5203                    equation
5204                };
5205                let live = "<m:oMath><m:r><m:t>live</m:t></m:r></m:oMath>";
5206                let empty = "<m:oMath><m:r/></m:oMath>";
5207                let body = format!(
5208                    "<w:p xmlns:m='{}'><w:pPr><w:spacing w:after='240'/></w:pPr>{equation}{live}{empty}<w:r><w:t>tail</w:t></w:r></w:p>",
5209                    M::URI
5210                );
5211                let (mut dom, root) = parse(&body);
5212                let accepted = accept_revisions_for_part_content(&mut dom, root);
5213                let (mut rejected_dom, rejected_root) = parse(&body);
5214                let rejected = reject_revisions_document(&mut rejected_dom, rejected_root);
5215                for (projection_dom, projection, keep_changed) in [
5216                    (&dom, accepted, inserted),
5217                    (&rejected_dom, rejected, !inserted),
5218                ] {
5219                    assert_eq!(
5220                        projection_dom
5221                            .descendants(projection, Some(&M::name("oMath")))
5222                            .len(),
5223                        if keep_changed { 3 } else { 2 }
5224                    );
5225                    assert_eq!(
5226                        projection_dom
5227                            .descendants(projection, Some(&M::name("oMathPara")))
5228                            .len(),
5229                        usize::from(keep_changed && para)
5230                    );
5231                    assert_eq!(
5232                        projection_dom.value(projection),
5233                        if keep_changed {
5234                            "xylivetail"
5235                        } else {
5236                            "livetail"
5237                        }
5238                    );
5239                    let spacing = projection_dom.descendants(projection, Some(&W::spacing_el()))[0];
5240                    assert_eq!(
5241                        projection_dom.attribute(spacing, &W::name("after")),
5242                        Some("240")
5243                    );
5244                    assert!(
5245                        projection_dom
5246                            .descendants(projection, Some(&W::del()))
5247                            .is_empty()
5248                    );
5249                    assert!(
5250                        projection_dom
5251                            .descendants(projection, Some(&W::ins()))
5252                            .is_empty()
5253                    );
5254                }
5255            }
5256        }
5257        // A live empty run in an otherwise deleted equation is an authored
5258        // owner, so deleting another run cannot delete its enclosing equation.
5259        let (mut dom, root) = parse(&format!(
5260            "<w:p><m:oMath xmlns:m='{}'><m:r><w:del w:id='8'><m:t>gone</m:t></w:del></m:r><m:r/></m:oMath></w:p>",
5261            M::URI
5262        ));
5263        let result = accept_revisions_for_part_content(&mut dom, root);
5264        assert_eq!(dom.descendants(result, Some(&M::name("oMath"))).len(), 1);
5265        assert_eq!(dom.descendants(result, Some(&M::name("r"))).len(), 2);
5266        assert_eq!(dom.value(result), "");
5267    }
5268
5269    #[test]
5270    fn display_math_preserves_independent_empty_equation_and_mixed_run_payload() {
5271        let (mut dom, root) = parse(&format!(
5272            "<w:p><m:oMathPara xmlns:m='{}'><m:oMath><m:r><w:del w:id='8'><m:t>gone</m:t></w:del></m:r></m:oMath><m:oMath/></m:oMathPara><m:oMath xmlns:m='{}'><m:r><w:del w:id='9'><m:t>old</m:t></w:del><m:t>live</m:t></m:r></m:oMath></w:p>",
5273            M::URI,
5274            M::URI
5275        ));
5276        let result = accept_revisions_for_part_content(&mut dom, root);
5277        assert_eq!(dom.value(result), "live");
5278        assert_eq!(
5279            dom.descendants(result, Some(&M::name("oMathPara"))).len(),
5280            1
5281        );
5282        assert_eq!(dom.descendants(result, Some(&M::name("oMath"))).len(), 2);
5283        let display = dom.descendants(result, Some(&M::name("oMathPara")))[0];
5284        let authored_empty = dom.elements(display, Some(&M::name("oMath")));
5285        assert_eq!(authored_empty.len(), 1);
5286        assert!(dom.nodes(authored_empty[0]).is_empty());
5287        assert!(dom.descendants(result, Some(&W::del())).is_empty());
5288    }
5289
5290    #[test]
5291    fn internally_deleted_math_does_not_consume_independent_anchors_controls_or_empty_branches() {
5292        fn semantic(dom: &Dom, node: NodeId) -> String {
5293            let mut attributes = dom
5294                .attributes_iter(node)
5295                .filter(|(name, _)| !dom.is_namespace_declaration(name))
5296                .collect::<Vec<_>>();
5297            attributes.sort_by(|a, b| {
5298                (a.0.namespace_name(), a.0.local_name())
5299                    .cmp(&(b.0.namespace_name(), b.0.local_name()))
5300            });
5301            let children = dom
5302                .nodes(node)
5303                .into_iter()
5304                .map(|child| semantic(dom, child))
5305                .collect::<Vec<_>>();
5306            format!(
5307                "{:?}:{attributes:?}:{:?}:{children:?}",
5308                dom.name(node),
5309                dom.text_value(node)
5310            )
5311        }
5312        let deleted_run = "<m:r><w:del w:id='8'><m:t>gone</m:t></w:del></m:r>";
5313        for live in [
5314            "<w:bookmarkStart w:id='31' w:name='Clause'/><w:bookmarkEnd w:id='31'/>",
5315            "<w:commentRangeStart w:id='41'/><w:commentRangeEnd w:id='41'/>",
5316            "<w:permStart w:id='51' w:edGrp='everyone'/><w:permEnd w:id='51'/>",
5317            "<w:r><w:rPr><w:b/></w:rPr><w:t>ordinary-live</w:t></w:r>",
5318            "<w:customXml w:uri='urn:source' w:element='Clause'><w:customXmlPr><w:attr w:name='owner' w:val='authored'/></w:customXmlPr><w:r><w:t>custom-live</w:t></w:r></w:customXml>",
5319            "<w:sdt><w:sdtPr><w:id w:val='61'/><w:tag w:val='Clause'/></w:sdtPr><w:sdtContent><w:r><w:rPr><w:i/></w:rPr><w:t>control-live</w:t></w:r></w:sdtContent></w:sdt>",
5320            "<m:rad><m:radPr><m:degHide m:val='1'/></m:radPr><m:deg/><m:e/></m:rad>",
5321        ] {
5322            let body = format!(
5323                "<w:p><m:oMath xmlns:m='{}'>{deleted_run}{live}</m:oMath></w:p>",
5324                M::URI
5325            );
5326            let (mut dom, root) = parse(&body);
5327            let expected_body = format!(
5328                "<w:p><m:oMath xmlns:m='{}'><m:r/>{live}</m:oMath></w:p>",
5329                M::URI
5330            );
5331            let (expected_dom, expected_root) = parse(&expected_body);
5332            let output = accept_all_other_revisions_transform(&mut dom, root);
5333            assert_eq!(output.len(), 1);
5334            assert_eq!(
5335                semantic(&dom, output[0]),
5336                semantic(&expected_dom, expected_root),
5337                "live={live}"
5338            );
5339        }
5340        // An enclosing insertion is an independent lifetime owner. A deleted
5341        // nested run does not by itself prove its equation was wholly deleted.
5342        let (mut dom, root) = parse(&format!(
5343            "<w:p><m:oMath xmlns:m='{}'><w:ins w:id='9'>{deleted_run}</w:ins></m:oMath></w:p>",
5344            M::URI
5345        ));
5346        let output = accept_all_other_revisions_transform(&mut dom, root);
5347        assert_eq!(dom.descendants(output[0], Some(&M::name("oMath"))).len(), 1);
5348        assert_eq!(dom.descendants(output[0], Some(&M::name("r"))).len(), 1);
5349        assert_eq!(dom.value(output[0]), "");
5350    }
5351
5352    #[test]
5353    fn wholly_deleted_math_hoists_owned_range_metadata_instead_of_discarding_it() {
5354        let (mut dom, root) = parse(&format!(
5355            "<w:p><m:oMath xmlns:m='{}'><m:r><w:del w:id='8'><w:bookmarkStart w:id='31' w:name='Clause'/><w:commentRangeStart w:id='41'/><m:t>gone</m:t><w:commentRangeEnd w:id='41'/><w:bookmarkEnd w:id='31'/></w:del></m:r></m:oMath><w:r><w:t>tail</w:t></w:r></w:p>",
5356            M::URI
5357        ));
5358        let output = accept_all_other_revisions_transform(&mut dom, root);
5359        assert!(
5360            dom.descendants(output[0], Some(&M::name("oMath")))
5361                .is_empty()
5362        );
5363        assert_eq!(dom.value(output[0]), "tail");
5364        let paragraph = dom.descendants(output[0], Some(&W::p()))[0];
5365        let children = dom.elements(paragraph, None);
5366        assert_eq!(children.len(), 5);
5367        for (child, name, id) in [
5368            (children[0], "bookmarkStart", "31"),
5369            (children[1], "commentRangeStart", "41"),
5370            (children[2], "commentRangeEnd", "41"),
5371            (children[3], "bookmarkEnd", "31"),
5372        ] {
5373            assert!(dom.name_is(child, &W::name(name)));
5374            assert_eq!(dom.attribute(child, &W::id()), Some(id));
5375        }
5376        assert_eq!(dom.attribute(children[0], &W::name("name")), Some("Clause"));
5377        assert!(dom.name_is(children[4], &W::r()));
5378    }
5379
5380    #[test]
5381    fn accept_deleted_fraction_drops_its_math_payload_and_preserves_live_fraction() {
5382        let (mut dom, root) = parse(&format!(
5383            "<m:oMath xmlns:m='{}'><m:f><m:fPr><m:ctrlPr><w:del w:id='1'/></m:ctrlPr></m:fPr><m:num><m:r><m:t>deleted-numerator</m:t></m:r></m:num><m:den><m:r><m:t>deleted-denominator</m:t></m:r></m:den></m:f><m:f><m:fPr><m:ctrlPr><w:ins w:id='2'/></m:ctrlPr></m:fPr><m:num><m:r><m:t>live-numerator</m:t></m:r></m:num><m:den><m:r><m:t>live-denominator</m:t></m:r></m:den></m:f></m:oMath>",
5384            M::URI
5385        ));
5386        let output = accept_all_other_revisions_transform(&mut dom, root);
5387        assert_eq!(output.len(), 1);
5388        assert_eq!(dom.descendants(output[0], Some(&M::name("f"))).len(), 1);
5389        assert_eq!(dom.value(output[0]), "live-numeratorlive-denominator");
5390        assert!(dom.descendants(output[0], Some(&W::del())).is_empty());
5391        assert!(dom.descendants(output[0], Some(&W::ins())).is_empty());
5392    }
5393
5394    #[test]
5395    fn rejecting_structural_markers_drops_inserted_numbering_and_cell_without_losing_neighbors() {
5396        let (mut dom, root) = parse(
5397            "<w:p><w:pPr><w:keepNext/><w:numPr><w:ilvl w:val='1'/><w:numId w:val='8'/><w:ins w:id='3'/></w:numPr></w:pPr><w:r><w:t>paragraph</w:t></w:r></w:p><w:tbl><w:tr><w:tc><w:tcPr><w:cellIns w:id='4'/></w:tcPr><w:p><w:r><w:t>inserted-cell</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:cellDel w:id='5'/><w:cellMerge w:id='6'/></w:tcPr><w:p><w:pPr><w:numPr><w:numId w:val='9'/><w:numberingChange w:id='7'/></w:numPr></w:pPr><w:r><w:t>original-cell</w:t></w:r></w:p></w:tc></w:tr></w:tbl>",
5398        );
5399        let result = reject_revisions_for_part_transform(&mut dom, root).unwrap();
5400        assert_eq!(dom.value(result), "paragraphoriginal-cell");
5401        assert_eq!(dom.descendants(result, Some(&W::tc())).len(), 1);
5402        assert_eq!(dom.descendants(result, Some(&W::num_pr())).len(), 1);
5403        assert_eq!(dom.descendants(result, Some(&W::name("keepNext"))).len(), 1);
5404        let num_id = dom.descendants(result, Some(&W::name("numId")))[0];
5405        assert_eq!(dom.attribute(num_id, &W::val()), Some("9"));
5406        for name in [
5407            W::ins(),
5408            W::cell_ins(),
5409            W::cell_del(),
5410            W::cell_merge(),
5411            W::numbering_change(),
5412        ] {
5413            assert!(dom.descendants(result, Some(&name)).is_empty());
5414        }
5415    }
5416
5417    #[test]
5418    fn missing_saved_style_properties_drop_changed_block_while_accept_keeps_live_properties() {
5419        let (mut dom, root) = parse(
5420            "<w:style w:styleId='owner'><w:name w:val='style-name'/><w:pPr><w:keepNext/><w:pPrChange w:id='1'/></w:pPr><w:rPr><w:b/><w:rPrChange w:id='2'/></w:rPr><x:payload x:owner='retained'>style-payload</x:payload></w:style>",
5421        );
5422        let accepted = accept_revisions_for_styles_transform(&mut dom, root).unwrap();
5423        let rejected = reject_revisions_for_styles_transform(&mut dom, root).unwrap();
5424        assert_eq!(
5425            dom.descendants(accepted, Some(&W::name("keepNext"))).len(),
5426            1
5427        );
5428        assert_eq!(dom.descendants(accepted, Some(&W::name("b"))).len(), 1);
5429        assert!(
5430            dom.descendants(accepted, Some(&W::p_pr_change()))
5431                .is_empty()
5432        );
5433        assert!(
5434            dom.descendants(accepted, Some(&W::r_pr_change()))
5435                .is_empty()
5436        );
5437        assert!(dom.descendants(rejected, Some(&W::p_pr())).is_empty());
5438        assert!(dom.descendants(rejected, Some(&W::r_pr())).is_empty());
5439        for result in [accepted, rejected] {
5440            let style = dom.element(result, &W::name("style")).unwrap();
5441            assert_eq!(dom.attribute(style, &W::style_id()), Some("owner"));
5442            assert_eq!(dom.value(result), "style-payload");
5443            assert_eq!(
5444                dom.descendants(result, Some(&XName::get("payload", "urn:fixture")))
5445                    .len(),
5446                1
5447            );
5448        }
5449    }
5450
5451    #[test]
5452    fn acceptance_removes_empty_numbering_but_keeps_live_numbering_and_clears_atom_annotations() {
5453        let (mut dom, root) = parse(
5454            "<w:p><w:pPr><w:numPr/></w:pPr><w:r><w:t>plain</w:t></w:r></w:p><w:p><w:pPr><w:numPr><w:numId w:val='4'/></w:numPr></w:pPr><w:r><w:t>numbered</w:t></w:r></w:p>",
5455        );
5456        let run = dom.descendants(root, Some(&W::r()))[0];
5457        dom.set_attribute_value(root, &PT::unique_id(), Some("body-id"));
5458        dom.set_attribute_value(run, &PT::run_ids(), Some("run-id"));
5459        let result = accept_revisions_for_element(&mut dom, root);
5460        assert_eq!(dom.value(result), "plainnumbered");
5461        assert_eq!(dom.descendants(result, Some(&W::num_pr())).len(), 1);
5462        assert_eq!(
5463            dom.attribute(
5464                dom.descendants(result, Some(&W::name("numId")))[0],
5465                &W::val()
5466            ),
5467            Some("4")
5468        );
5469        for node in dom.descendants_and_self(result, None) {
5470            assert!(dom.attribute(node, &PT::unique_id()).is_none());
5471            assert!(dom.attribute(node, &PT::run_ids()).is_none());
5472        }
5473    }
5474
5475    #[test]
5476    fn unmatched_or_contentless_move_ranges_preserve_identity_and_properties() {
5477        for body in [
5478            "<w:moveFromRangeEnd w:id='missing'/><w:p><w:r><w:t>retained</w:t></w:r></w:p>",
5479            "<w:moveFromRangeStart w:id='open'/><w:p><w:r><w:t>retained</w:t></w:r></w:p>",
5480            "<w:moveFromRangeStart w:id='empty'/><w:p><w:pPr><w:keepNext/></w:pPr><w:moveFromRangeEnd w:id='empty'/><w:r><w:t>retained</w:t></w:r></w:p>",
5481        ] {
5482            let (mut dom, root) = parse(body);
5483            let before = dom.serialize_element(root);
5484            let paragraph = dom.element(root, &W::p()).unwrap();
5485            assert_eq!(accept_move_from_ranges(&mut dom, root), root);
5486            assert_eq!(dom.parent(paragraph), Some(root));
5487            assert_eq!(dom.serialize_element(root), before);
5488            assert_eq!(dom.value(root), "retained");
5489        }
5490    }
5491}
5492
5493#[cfg(test)]
5494#[cfg_attr(all(coverage_nightly, test), coverage(off))]
5495mod public_block_control_ownership_tests {
5496    use super::*;
5497    use crate::opc::PartFs;
5498
5499    const MAIN: &str = "word/document.xml";
5500    const DATE: &str = "2001-02-03T04:05:06Z";
5501    const PROPS: &str = "<w:spacing w:after='120'/><w:rPr><w:b/>";
5502    const META: &str = "<w:sdtPr><w:alias w:val='Contract schedule'/><w:tag w:val='source-owner'/><w:id w:val='42'/><w:lock w:val='sdtLocked'/></w:sdtPr><w:sdtEndPr><w:rPr><w:color w:val='234567'/></w:rPr></w:sdtEndPr>";
5503
5504    fn package(content: &str) -> Vec<u8> {
5505        let mut pkg = PartFs::open(include_bytes!(
5506            "../../../tests/fixtures/word_probes/tokens/cell_a.docx"
5507        ))
5508        .unwrap();
5509        for part in pkg.parts() {
5510            pkg.remove_part(&part);
5511        }
5512        let empty=b"<Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships'/>";
5513        pkg.set_part("_rels/.rels", empty.to_vec());
5514        pkg.set_part("word/_rels/document.xml.rels", empty.to_vec());
5515        pkg.add_package_relationship(
5516            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
5517            MAIN,
5518        );
5519        pkg.add_content_type_override(
5520            "/word/document.xml",
5521            "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
5522        );
5523        pkg.set_part(MAIN,format!("<w:document xmlns:w='{}' xmlns:m='{}'><w:body>{content}<w:sectPr><w:pgSz w:w='12240' w:h='15840'/></w:sectPr></w:body></w:document>",W::URI,M::URI).into_bytes());
5524        pkg.to_zip().unwrap()
5525    }
5526    fn resolved(bytes: &[u8], reject: bool) -> (Dom, NodeId) {
5527        let out = if reject {
5528            crate::document_comparer::reject_revisions(bytes).unwrap()
5529        } else {
5530            crate::document_comparer::accept_revisions(bytes).unwrap()
5531        };
5532        let pkg = PartFs::open(&out).unwrap();
5533        let mut dom = Dom::new();
5534        let doc = dom.parse_xdocument(&pkg.part_string(MAIN).unwrap());
5535        let root = dom.root(doc).unwrap();
5536        (dom, root)
5537    }
5538    fn assert_owner(dom: &Dom, root: NodeId) -> NodeId {
5539        let controls = dom.descendants(root, Some(&W::sdt()));
5540        assert_eq!(controls.len(), 1);
5541        let control = controls[0];
5542        assert_eq!(dom.parent(control), dom.element(root, &W::body()));
5543        let props = dom.element(control, &W::sdt_pr()).unwrap();
5544        for (local, value) in [
5545            ("alias", "Contract schedule"),
5546            ("tag", "source-owner"),
5547            ("id", "42"),
5548            ("lock", "sdtLocked"),
5549        ] {
5550            let child = dom.element(props, &W::name(local)).unwrap();
5551            assert_eq!(dom.attribute(child, &W::val()), Some(value));
5552        }
5553        let end = dom.element(control, &W::sdt_end_pr()).unwrap();
5554        let color = dom.descendants(end, Some(&W::name("color")))[0];
5555        assert_eq!(dom.attribute(color, &W::val()), Some("234567"));
5556        dom.element(control, &W::sdt_content()).unwrap()
5557    }
5558    #[test]
5559    fn public_mark_resolution_rewraps_transformed_paragraphs_with_original_control_metadata() {
5560        for kind in ["del", "ins"] {
5561            for reject in [false, true] {
5562                let source = format!(
5563                    "<w:sdt>{META}<w:sdtContent><w:p><w:pPr>{PROPS}<w:{kind} w:id='17' w:author='Source editor' w:date='{DATE}'/></w:rPr></w:pPr><w:r><w:rPr><w:i/></w:rPr><w:t>First</w:t></w:r></w:p><w:p><w:pPr>{PROPS}</w:rPr></w:pPr><w:r><w:rPr><w:u w:val='single'/></w:rPr><w:t>Second</w:t></w:r></w:p></w:sdtContent></w:sdt>"
5564                );
5565                let (dom, root) = resolved(&package(&source), reject);
5566                let content = assert_owner(&dom, root);
5567                let ps = dom.elements(content, Some(&W::p()));
5568                let joined = (kind == "del") != reject;
5569                assert_eq!(
5570                    ps.len(),
5571                    if joined { 1 } else { 2 },
5572                    "{kind} reject={reject}"
5573                );
5574                assert_eq!(dom.value(content), "FirstSecond");
5575                let runs = dom.descendants(content, Some(&W::r()));
5576                assert_eq!(runs.len(), 2);
5577                let first = dom.element(runs[0], &W::r_pr()).unwrap();
5578                let second = dom.element(runs[1], &W::r_pr()).unwrap();
5579                assert!(dom.element(first, &W::name("i")).is_some());
5580                assert!(dom.element(second, &W::name("u")).is_some());
5581                for p in ps {
5582                    let ppr = dom.element(p, &W::p_pr()).unwrap();
5583                    let spacing = dom.element(ppr, &W::spacing_el()).unwrap();
5584                    assert_eq!(dom.attribute(spacing, &W::name("after")), Some("120"));
5585                    let mark = dom.element(ppr, &W::r_pr()).unwrap();
5586                    assert!(dom.element(mark, &W::name("b")).is_some());
5587                }
5588            }
5589        }
5590    }
5591    #[test]
5592    fn public_mark_resolution_preserves_whole_table_payload_at_the_controls_block_level() {
5593        for kind in ["del", "ins"] {
5594            let table = "<w:tbl><w:tblPr><w:tblW w:w='1800' w:type='dxa'/></w:tblPr><w:tblGrid><w:gridCol w:w='1800'/></w:tblGrid><w:tr><w:tc><w:tcPr><w:tcW w:w='1800' w:type='dxa'/><w:shd w:fill='123456'/></w:tcPr><w:p><w:r><w:rPr><w:b/></w:rPr><w:t>Owned cell</w:t></w:r></w:p></w:tc></w:tr></w:tbl>";
5595            let source = format!(
5596                "<w:sdt>{META}<w:sdtContent><w:p><w:pPr><w:rPr><w:{kind} w:id='17' w:author='Source editor' w:date='{DATE}'/></w:rPr></w:pPr></w:p>{table}</w:sdtContent></w:sdt>"
5597            );
5598            let (dom, root) = resolved(&package(&source), kind == "ins");
5599            let content = assert_owner(&dom, root);
5600            let tables = dom.descendants(root, Some(&W::tbl()));
5601            assert_eq!(tables.len(), 1);
5602            assert_eq!(dom.parent(tables[0]), Some(content));
5603            assert_eq!(dom.value(tables[0]), "Owned cell");
5604            let cell = dom.descendants(tables[0], Some(&W::tc()))[0];
5605            let properties = dom.element(cell, &W::tc_pr()).unwrap();
5606            let shade = dom.element(properties, &W::shd()).unwrap();
5607            assert_eq!(dom.attribute(shade, &W::fill()), Some("123456"));
5608            let grid = dom.element(tables[0], &W::tbl_grid()).unwrap();
5609            let column = dom.elements(grid, None)[0];
5610            assert_eq!(dom.attribute(column, &W::w()), Some("1800"));
5611        }
5612    }
5613    #[test]
5614    fn nested_block_controls_keep_each_owner_and_transformed_paragraph_payload() {
5615        for depth in [2, 3] {
5616            for kind in ["del", "ins"] {
5617                for reject in [false, true] {
5618                    let mut source = format!(
5619                        "<w:p><w:pPr>{PROPS}<w:{kind} w:id='17'/></w:rPr></w:pPr><w:r><w:rPr><w:i/></w:rPr><w:t>First</w:t></w:r></w:p><w:p><w:pPr>{PROPS}</w:rPr></w:pPr><w:r><w:rPr><w:u w:val='single'/></w:rPr><w:t>Second</w:t></w:r></w:p>"
5620                    );
5621                    for id in (1..=depth).rev() {
5622                        source = format!(
5623                            "<w:sdt><w:sdtPr><w:id w:val='{id}'/><w:tag w:val='owner-{id}'/><w:alias w:val='Owner {id}'/><w:lock w:val='sdtLocked'/></w:sdtPr><w:sdtEndPr><w:rPr><w:color w:val='234567'/></w:rPr></w:sdtEndPr><w:sdtContent>{source}</w:sdtContent></w:sdt>"
5624                        );
5625                    }
5626                    let (dom, root) = resolved(&package(&source), reject);
5627                    let controls = dom.descendants(root, Some(&W::sdt()));
5628                    assert_eq!(controls.len(), depth);
5629                    let mut parent = dom.element(root, &W::body()).unwrap();
5630                    for (index, &control) in controls.iter().enumerate() {
5631                        assert_eq!(dom.parent(control), Some(parent));
5632                        let props = dom.element(control, &W::sdt_pr()).unwrap();
5633                        for (name, expected) in [
5634                            ("id", (index + 1).to_string()),
5635                            ("tag", format!("owner-{}", index + 1)),
5636                            ("alias", format!("Owner {}", index + 1)),
5637                            ("lock", "sdtLocked".to_string()),
5638                        ] {
5639                            assert_eq!(
5640                                dom.attribute(
5641                                    dom.element(props, &W::name(name)).unwrap(),
5642                                    &W::val()
5643                                ),
5644                                Some(expected.as_str())
5645                            );
5646                        }
5647                        let end = dom.element(control, &W::sdt_end_pr()).unwrap();
5648                        let color = dom.descendants(end, Some(&W::name("color")))[0];
5649                        assert_eq!(dom.attribute(color, &W::val()), Some("234567"));
5650                        parent = dom.element(control, &W::sdt_content()).unwrap();
5651                    }
5652                    let ps = dom.elements(parent, Some(&W::p()));
5653                    assert_eq!(ps.len(), if (kind == "del") != reject { 1 } else { 2 });
5654                    assert_eq!(dom.value(parent), "FirstSecond");
5655                    assert!(!element_has_tracked_revisions(&dom, root));
5656                    let runs = dom.descendants(parent, Some(&W::r()));
5657                    assert_eq!(runs.len(), 2);
5658                    assert!(
5659                        dom.element(dom.element(runs[0], &W::r_pr()).unwrap(), &W::name("i"))
5660                            .is_some()
5661                    );
5662                    assert!(
5663                        dom.element(dom.element(runs[1], &W::r_pr()).unwrap(), &W::name("u"))
5664                            .is_some()
5665                    );
5666                    for p in ps {
5667                        let properties = dom.element(p, &W::p_pr()).unwrap();
5668                        assert_eq!(
5669                            dom.attribute(
5670                                dom.element(properties, &W::spacing_el()).unwrap(),
5671                                &W::name("after")
5672                            ),
5673                            Some("120")
5674                        );
5675                        assert!(
5676                            dom.element(
5677                                dom.element(properties, &W::r_pr()).unwrap(),
5678                                &W::name("b")
5679                            )
5680                            .is_some()
5681                        );
5682                    }
5683                }
5684            }
5685        }
5686    }
5687    #[test]
5688    fn nested_block_controls_keep_outer_table_owner_and_nested_cell_geometry() {
5689        let inner_table = "<w:tbl><w:tblPr><w:tblW w:w='900' w:type='dxa'/></w:tblPr><w:tblGrid><w:gridCol w:w='900'/></w:tblGrid><w:tr><w:tc><w:tcPr><w:tcW w:w='900' w:type='dxa'/><w:shd w:fill='ABCDEF'/></w:tcPr><w:p><w:r><w:rPr><w:b/></w:rPr><w:t>Nested payload</w:t></w:r></w:p></w:tc></w:tr></w:tbl>";
5690        let outer_table = format!(
5691            "<w:tbl><w:tblGrid><w:gridCol w:w='1800'/></w:tblGrid><w:tr><w:tc><w:tcPr><w:tcW w:w='1800' w:type='dxa'/></w:tcPr>{inner_table}<w:p/></w:tc></w:tr></w:tbl>"
5692        );
5693        for kind in ["del", "ins"] {
5694            let source = format!(
5695                "<w:sdt>{META}<w:sdtContent><w:sdt><w:sdtPr><w:id w:val='43'/><w:tag w:val='inner-table-owner'/></w:sdtPr><w:sdtContent><w:p><w:pPr><w:rPr><w:{kind} w:id='17'/></w:rPr></w:pPr></w:p>{outer_table}</w:sdtContent></w:sdt></w:sdtContent></w:sdt>"
5696            );
5697            let (dom, root) = resolved(&package(&source), kind == "ins");
5698            let controls = dom.descendants(root, Some(&W::sdt()));
5699            assert_eq!(controls.len(), 2);
5700            assert_eq!(dom.parent(controls[0]), dom.element(root, &W::body()));
5701            let outer_content = dom.element(controls[0], &W::sdt_content()).unwrap();
5702            assert_eq!(dom.parent(controls[1]), Some(outer_content));
5703            let inner_content = dom.element(controls[1], &W::sdt_content()).unwrap();
5704            let tables = dom.descendants(root, Some(&W::tbl()));
5705            assert_eq!(tables.len(), 2);
5706            assert_eq!(dom.parent(tables[0]), Some(inner_content));
5707            let cells = dom.descendants(root, Some(&W::tc()));
5708            assert_eq!(cells.len(), 2);
5709            assert_eq!(dom.parent(tables[1]), Some(cells[0]));
5710            assert_eq!(dom.value(root), "Nested payload");
5711            assert!(!element_has_tracked_revisions(&dom, root));
5712            for (cell, width) in [(cells[0], "1800"), (cells[1], "900")] {
5713                let props = dom.element(cell, &W::tc_pr()).unwrap();
5714                assert_eq!(
5715                    dom.attribute(dom.element(props, &W::tc_w()).unwrap(), &W::w()),
5716                    Some(width)
5717                );
5718            }
5719            let nested_props = dom.element(cells[1], &W::tc_pr()).unwrap();
5720            assert_eq!(
5721                dom.attribute(dom.element(nested_props, &W::shd()).unwrap(), &W::fill()),
5722                Some("ABCDEF")
5723            );
5724            for (control, id) in [(controls[0], "42"), (controls[1], "43")] {
5725                let props = dom.element(control, &W::sdt_pr()).unwrap();
5726                assert_eq!(
5727                    dom.attribute(dom.element(props, &W::id()).unwrap(), &W::val()),
5728                    Some(id)
5729                );
5730            }
5731        }
5732    }
5733}
5734
5735#[cfg(test)]
5736#[cfg_attr(all(coverage_nightly, test), coverage(off))]
5737mod body_equation_paragraph_mark_ownership_tests {
5738    use super::*;
5739    use crate::opc::PartFs;
5740
5741    fn equation(display: bool) -> String {
5742        let inner = "<m:oMath><m:f><m:fPr><m:type m:val='lin'/></m:fPr><m:num><m:r><m:rPr><m:sty m:val='p'/></m:rPr><w:rPr><w:rFonts w:ascii='Cambria Math' w:hAnsi='Cambria Math'/><w:color w:val='234567'/></w:rPr><m:t>x</m:t></m:r></m:num><m:den><m:r><m:t>y</m:t></m:r></m:den></m:f></m:oMath>";
5743        if display {
5744            format!(
5745                "<m:oMathPara><m:oMathParaPr><m:jc m:val='center'/></m:oMathParaPr>{inner}</m:oMathPara>"
5746            )
5747        } else {
5748            inner.into()
5749        }
5750    }
5751    fn semantic(dom: &Dom, node: NodeId) -> String {
5752        if !dom.is_element(node) {
5753            return dom.text_value(node).unwrap_or_default().into();
5754        }
5755        let name = dom.name(node).unwrap();
5756        let mut attrs = dom
5757            .attributes_iter(node)
5758            .filter(|(n, _)| {
5759                n.namespace_name() != "http://www.w3.org/2000/xmlns/" && n.local_name() != "xmlns"
5760            })
5761            .collect::<Vec<_>>();
5762        attrs.sort_by_key(|(n, v)| {
5763            (
5764                n.namespace_name().to_string(),
5765                n.local_name().to_string(),
5766                *v,
5767            )
5768        });
5769        format!(
5770            "{:?}{attrs:?}[{}]",
5771            name,
5772            dom.nodes(node)
5773                .into_iter()
5774                .map(|n| semantic(dom, n))
5775                .collect::<Vec<_>>()
5776                .join("|")
5777        )
5778    }
5779    fn parse(content: &str) -> (Dom, NodeId) {
5780        let mut dom = Dom::new();
5781        let doc = dom.parse_xdocument(&format!("<w:document xmlns:w='{}' xmlns:m='{}'><w:body>{content}<w:sectPr><w:pgSz w:w='12240' w:h='15840'/></w:sectPr></w:body></w:document>", W::URI, M::URI));
5782        let root = dom.root(doc).unwrap();
5783        (dom, root)
5784    }
5785    fn assert_math(dom: &Dom, root: NodeId, expected: &str, display: bool) {
5786        let body = dom.element(root, &W::body()).unwrap();
5787        let math = dom.elements(
5788            body,
5789            Some(&M::name(if display { "oMathPara" } else { "oMath" })),
5790        );
5791        assert_eq!(math.len(), 1);
5792        assert_eq!(semantic(dom, math[0]), expected);
5793        let kids = dom.elements(body, None);
5794        assert_eq!(
5795            kids.iter()
5796                .map(|&n| dom.name(n).unwrap())
5797                .collect::<Vec<_>>(),
5798            vec![
5799                W::p(),
5800                M::name(if display { "oMathPara" } else { "oMath" }),
5801                W::p(),
5802                W::sect_pr()
5803            ]
5804        );
5805        assert_eq!(dom.value(kids[0]), "before");
5806        assert_eq!(dom.value(kids[2]), "after");
5807    }
5808    #[test]
5809    fn equation_is_an_opaque_block_barrier_for_deleted_paragraph_marks() {
5810        for display in [false, true] {
5811            let math = equation(display);
5812            let (mut dom, root) = parse(&format!(
5813                "<w:p><w:pPr><w:rPr><w:del w:id='7' w:author='Comparer'/></w:rPr></w:pPr><w:r><w:t>before</w:t></w:r></w:p>{math}<w:p><w:r><w:t>after</w:t></w:r></w:p>"
5814            ));
5815            let body = dom.element(root, &W::body()).unwrap();
5816            let source_math = dom.elements(body, None)[1];
5817            let expected = semantic(&dom, source_math);
5818            let chain = iterate_block_content_elements(&dom, body);
5819            assert_eq!(chain.len(), 3);
5820            assert_eq!(chain[1].this_block_content_element, Some(source_math));
5821            let result = accept_deleted_and_move_from_paragraph_marks_transform(&mut dom, root);
5822            assert_math(&dom, result, &expected, display);
5823        }
5824    }
5825    #[test]
5826    fn public_accept_and_reject_preserve_unchanged_body_math_among_revised_marks() {
5827        for display in [false, true] {
5828            for reject in [false, true] {
5829                let mark = if reject { "ins" } else { "del" };
5830                let math = equation(display);
5831                let content = format!(
5832                    "<w:p><w:pPr><w:rPr><w:{mark} w:id='7' w:author='Comparer' w:date='2001-02-03T04:05:06Z'/></w:rPr></w:pPr><w:r><w:t>before</w:t></w:r></w:p>{math}<w:p><w:r><w:t>after</w:t></w:r></w:p>"
5833                );
5834                let (dom, root) = parse(&content);
5835                let body = dom.element(root, &W::body()).unwrap();
5836                let expected = semantic(&dom, dom.elements(body, None)[1]);
5837                let xml = dom.serialize_element(root);
5838                let mut pkg = PartFs::open(include_bytes!(
5839                    "../../../tests/fixtures/word_probes/tokens/cell_a.docx"
5840                ))
5841                .unwrap();
5842                pkg.set_part("word/document.xml", xml.into_bytes());
5843                let bytes = pkg.to_zip().unwrap();
5844                let result = if reject {
5845                    crate::document_comparer::reject_revisions(&bytes)
5846                } else {
5847                    crate::document_comparer::accept_revisions(&bytes)
5848                }
5849                .unwrap();
5850                let pkg = PartFs::open(&result).unwrap();
5851                let mut result_dom = Dom::new();
5852                let doc =
5853                    result_dom.parse_xdocument(&pkg.part_string("word/document.xml").unwrap());
5854                let result_root = result_dom.root(doc).unwrap();
5855                assert_math(&result_dom, result_root, &expected, display);
5856                assert!(!has_deleted_or_moved_from_paragraph_mark(
5857                    &result_dom,
5858                    result_root
5859                ));
5860            }
5861        }
5862    }
5863
5864    #[test]
5865    fn terminal_internal_equation_revisions_preserve_exact_surviving_paragraph_owners() {
5866        fn normalize_empty_properties(dom: &mut Dom, root: NodeId) {
5867            for node in dom.descendants(root, None).into_iter().rev() {
5868                if [W::p_pr(), W::r_pr()]
5869                    .iter()
5870                    .any(|name| dom.name_is(node, name))
5871                    && dom.nodes(node).is_empty()
5872                    && dom
5873                        .attributes(node)
5874                        .iter()
5875                        .all(|(name, _)| dom.is_namespace_declaration(name))
5876                {
5877                    dom.remove(node);
5878                }
5879            }
5880        }
5881        let prefix = "<w:p><w:pPr><w:spacing w:after='360'/></w:pPr><w:r><w:rPr><w:b/><w:color w:val='123456'/></w:rPr><w:t>Authored prefix</w:t></w:r></w:p>";
5882        let live_equation = "<m:oMath><m:r><w:rPr><w:rFonts w:ascii='Cambria Math' w:hAnsi='Cambria Math'/><w:i/></w:rPr><m:t>live</m:t></m:r></m:oMath>";
5883        for reject in [false, true] {
5884            let mark = if reject { "ins" } else { "del" };
5885            let changed = format!(
5886                "<m:r><w:{mark} w:id='71' w:author='Equation editor' w:date='2026-01-02T03:04:05Z'><w:rPr><w:rFonts w:ascii='Cambria Math' w:hAnsi='Cambria Math'/><w:color w:val='234567'/></w:rPr><m:t>changed</m:t></w:{mark}></m:r>"
5887            );
5888            for (label, equation, surviving) in [
5889                (
5890                    "only revised equation",
5891                    format!("<m:oMath>{changed}</m:oMath>"),
5892                    String::new(),
5893                ),
5894                (
5895                    "independent live equation",
5896                    format!("<m:oMath>{changed}</m:oMath>{live_equation}"),
5897                    live_equation.to_string(),
5898                ),
5899                (
5900                    "independent empty equation",
5901                    format!("<m:oMath>{changed}</m:oMath><m:oMath/>"),
5902                    "<m:oMath/>".to_string(),
5903                ),
5904                (
5905                    "authored empty run",
5906                    format!("<m:oMath>{changed}<m:r/></m:oMath>"),
5907                    "<m:oMath><m:r/><m:r/></m:oMath>".to_string(),
5908                ),
5909            ] {
5910                let input = format!(
5911                    "{prefix}<w:p><w:pPr><w:rPr><w:{mark} w:id='72' w:author='Equation editor' w:date='2026-01-02T03:04:05Z'/></w:rPr></w:pPr>{equation}</w:p>"
5912                );
5913                let expected = if surviving.is_empty() {
5914                    prefix.to_string()
5915                } else {
5916                    format!("{prefix}<w:p>{surviving}</w:p>")
5917                };
5918                let (mut dom, root) = parse(&input);
5919                let independent = dom.clone_subtree(root);
5920                let source = dom.serialize_element(independent);
5921                let result = if reject {
5922                    reject_revisions_document(&mut dom, root)
5923                } else {
5924                    accept_revisions_document(&mut dom, root)
5925                };
5926                normalize_empty_properties(&mut dom, result);
5927                let (mut expected_dom, expected_root) = parse(&expected);
5928                normalize_empty_properties(&mut expected_dom, expected_root);
5929                assert_eq!(
5930                    semantic(&dom, result),
5931                    semantic(&expected_dom, expected_root),
5932                    "{label}/reject={reject}: full surviving paragraph, run properties and equation owners"
5933                );
5934                assert_eq!(
5935                    dom.serialize_element(independent),
5936                    source,
5937                    "independent authored source remains unchanged"
5938                );
5939                let repeated = if reject {
5940                    reject_revisions_document(&mut dom, result)
5941                } else {
5942                    accept_revisions_document(&mut dom, result)
5943                };
5944                normalize_empty_properties(&mut dom, repeated);
5945                assert_eq!(
5946                    semantic(&dom, repeated),
5947                    semantic(&expected_dom, expected_root),
5948                    "idempotent {label}/reject={reject}"
5949                );
5950            }
5951        }
5952    }
5953}
5954
5955#[cfg(test)]
5956#[cfg_attr(all(coverage_nightly, test), coverage(off))]
5957mod deleted_title_equation_barrier_tests {
5958    use super::*;
5959    use crate::opc::PartFs;
5960    fn equation(text: &str, marker: Option<&str>, display: bool) -> String {
5961        let content = format!(
5962            "<m:rPr><m:sty m:val='p'/></m:rPr><w:rPr><w:rFonts w:ascii='Cambria Math' w:hAnsi='Cambria Math'/><w:color w:val='234567'/></w:rPr><m:t>{text}</m:t>"
5963        );
5964        let content = marker.map_or_else(|| content.clone(), |m| format!("<w:{m} w:id='8' w:author='Comparer' w:date='2001-02-03T04:05:06Z'>{content}</w:{m}>"));
5965        // The producer tracks the complete mathematical run payload,
5966        // including m:rPr. Leaving those properties outside the marker
5967        // authors an independent empty run that resolution must preserve.
5968        let math = format!("<m:oMath><m:r>{content}</m:r></m:oMath>");
5969        if display {
5970            format!(
5971                "<m:oMathPara><m:oMathParaPr><m:jc m:val='center'/></m:oMathParaPr>{math}</m:oMathPara>"
5972            )
5973        } else {
5974            math
5975        }
5976    }
5977    fn title(text: &str, marker: Option<&str>, revised: bool) -> String {
5978        let mark = marker.map_or(String::new(), |m| {
5979            format!(
5980                "<w:rPr><w:{m} w:id='7' w:author='Comparer' w:date='2001-02-03T04:05:06Z'/></w:rPr>"
5981            )
5982        });
5983        let text_tag = if marker == Some("del") {
5984            "delText"
5985        } else {
5986            "t"
5987        };
5988        let run = format!(
5989            "<w:r><w:rPr><w:b/><w:color w:val='123456'/></w:rPr><w:{text_tag}>{text}</w:{text_tag}></w:r>"
5990        );
5991        let run = marker.map_or_else(|| run.clone(), |m| format!("<w:{m} w:id='9' w:author='Comparer' w:date='2001-02-03T04:05:06Z'>{run}</w:{m}>"));
5992        format!(
5993            "<w:p><w:pPr><w:spacing w:after='{}'/><w:ind w:left='{}'/>{mark}</w:pPr>{run}</w:p>",
5994            if revised { 240 } else { 120 },
5995            if revised { 360 } else { 180 }
5996        )
5997    }
5998    fn parse(content: &str) -> (Dom, NodeId) {
5999        let mut dom = Dom::new();
6000        let doc = dom.parse_xdocument(&format!("<w:document xmlns:w='{}' xmlns:m='{}'><w:body>{content}<w:sectPr><w:pgSz w:w='12240' w:h='15840'/></w:sectPr></w:body></w:document>", W::URI, M::URI));
6001        let root = dom.root(doc).unwrap();
6002        (dom, root)
6003    }
6004    fn semantic(dom: &Dom, node: NodeId) -> String {
6005        if !dom.is_element(node) {
6006            return dom.text_value(node).unwrap_or_default().into();
6007        }
6008        let name = dom.name(node).unwrap();
6009        let mut attrs = dom
6010            .attributes_iter(node)
6011            .filter(|(n, _)| {
6012                n.namespace_name() != "http://www.w3.org/2000/xmlns/" && n.local_name() != "xmlns"
6013            })
6014            .collect::<Vec<_>>();
6015        attrs.sort_by_key(|(n, v)| {
6016            (
6017                n.namespace_name().to_string(),
6018                n.local_name().to_string(),
6019                *v,
6020            )
6021        });
6022        format!(
6023            "{:?}{attrs:?}[{}]",
6024            name,
6025            dom.nodes(node)
6026                .into_iter()
6027                .map(|n| semantic(dom, n))
6028                .collect::<Vec<_>>()
6029                .join("|")
6030        )
6031    }
6032    #[test]
6033    fn deleted_title_before_equation_is_removed_without_consuming_the_equation() {
6034        for display in [false, true] {
6035            let math = equation("old-equation", Some("del"), display);
6036            let (mut dom, root) =
6037                parse(&format!("{}{math}", title("old-title", Some("del"), false)));
6038            let body = dom.element(root, &W::body()).unwrap();
6039            let original_math = dom.elements(body, None)[1];
6040            let expected_math = semantic(&dom, original_math);
6041            let result = accept_deleted_and_move_from_paragraph_marks_transform(&mut dom, root);
6042            let body = dom.element(result, &W::body()).unwrap();
6043            let children = dom.elements(body, None);
6044            assert_eq!(children.len(), 2);
6045            assert_eq!(semantic(&dom, children[0]), expected_math);
6046            assert!(dom.name_is(children[1], &W::sect_pr()));
6047        }
6048    }
6049    #[test]
6050    fn public_replaced_titles_and_equations_recover_complete_owned_sources() {
6051        for display in [false, true] {
6052            let content = format!(
6053                "{}{}{}{}",
6054                title("old-title", Some("del"), false),
6055                equation("old-equation", Some("del"), display),
6056                title("new-title", Some("ins"), true),
6057                equation("new-equation", Some("ins"), display)
6058            );
6059            let (dom, root) = parse(&content);
6060            let mut pkg = PartFs::open(include_bytes!(
6061                "../../../tests/fixtures/word_probes/tokens/cell_a.docx"
6062            ))
6063            .unwrap();
6064            pkg.set_part(
6065                "word/document.xml",
6066                dom.serialize_element(root).into_bytes(),
6067            );
6068            let bytes = pkg.to_zip().unwrap();
6069            for reject in [false, true] {
6070                let output = if reject {
6071                    crate::document_comparer::reject_revisions(&bytes)
6072                } else {
6073                    crate::document_comparer::accept_revisions(&bytes)
6074                }
6075                .unwrap();
6076                let output = PartFs::open(&output).unwrap();
6077                let mut actual = Dom::new();
6078                let doc = actual.parse_xdocument(&output.part_string("word/document.xml").unwrap());
6079                let root = actual.root(doc).unwrap();
6080                let body = actual.element(root, &W::body()).unwrap();
6081                let source = if reject {
6082                    format!(
6083                        "{}{}",
6084                        title("old-title", None, false),
6085                        equation("old-equation", None, display)
6086                    )
6087                } else {
6088                    format!(
6089                        "{}{}",
6090                        title("new-title", None, true),
6091                        equation("new-equation", None, display)
6092                    )
6093                };
6094                let (expected, root) = parse(&source);
6095                let expected_body = expected.element(root, &W::body()).unwrap();
6096                assert_eq!(
6097                    semantic(&actual, body),
6098                    semantic(&expected, expected_body),
6099                    "display={display} reject={reject}"
6100                );
6101            }
6102        }
6103    }
6104}
6105
6106#[cfg(test)]
6107#[cfg_attr(all(coverage_nightly, test), coverage(off))]
6108mod complete_field_instruction_metadata_boundary_tests {
6109    use super::*;
6110    #[test]
6111    fn repaired_complete_field_codes_preserve_source_comments_processing_instructions_and_formats()
6112    {
6113        for marker in ["ins", "del"] {
6114            for code_pieces in [1usize, 2] {
6115                let mut dom = Dom::new();
6116                let codes = if code_pieces == 1 {
6117                    vec![" REF Clause "]
6118                } else {
6119                    vec![" REF ", "Clause "]
6120                };
6121                let codes=codes.iter().map(|code|format!("<w:r><w:rPr><!--authored run format--><?owner keep?><w:b/><w:color w:val='123456'/></w:rPr><w:instrText xml:space='preserve'>{code}</w:instrText></w:r>")).collect::<String>();
6122                let doc=dom.parse_xdocument(&format!("<w:p xmlns:w='{}'><w:pPr><w:spacing w:after='120'/></w:pPr><w:{marker} w:id='11' w:author='Field owner' w:date='2001-02-03T04:05:06Z'><w:r><w:fldChar w:fldCharType='begin'/></w:r></w:{marker}>{codes}<w:{marker} w:id='12' w:author='Field owner' w:date='2001-02-03T04:05:06Z'><w:r><w:fldChar w:fldCharType='separate'/></w:r><w:r><w:{}>cached clause</w:{}></w:r><w:r><w:fldChar w:fldCharType='end'/></w:r></w:{marker}><w:bookmarkStart w:id='31' w:name='Clause'/><w:bookmarkEnd w:id='31'/></w:p>",W::URI,if marker=="del" {"delText"} else {"t"},if marker=="del" {"delText"} else {"t"}));
6123                let root = dom.root(doc).unwrap();
6124                let source = dom.serialize_element(root);
6125                let source_codes = dom
6126                    .elements(root, Some(&W::r()))
6127                    .iter()
6128                    .map(|&run| dom.serialize_element(run))
6129                    .collect::<Vec<_>>();
6130                let children = dom.elements(root, None);
6131                let first = dom.serialize_element(children[1]);
6132                let last = dom.serialize_element(children[children.len() - 3]);
6133                // Transform helpers may transfer clean child nodes. As the
6134                // package pipeline does, repair an independent working copy.
6135                let working = dom.clone_subtree(root);
6136                let result = fix_up_deleted_or_inserted_field_codes_transform(&mut dom, working);
6137                let wrappers = dom.elements(result, Some(&W::name(marker)));
6138                assert_eq!(wrappers.len(), 3);
6139                assert_eq!(dom.serialize_element(wrappers[0]), first);
6140                assert_eq!(dom.serialize_element(wrappers[2]), last);
6141                assert!(
6142                    !dom.has_attributes(wrappers[1]),
6143                    "A.1 generated field-code wrapper has no invented attribution"
6144                );
6145                let actual_codes = dom
6146                    .elements(wrappers[1], Some(&W::r()))
6147                    .iter()
6148                    .map(|&run| dom.serialize_element(run))
6149                    .collect::<Vec<_>>();
6150                let expected_codes = if marker == "del" {
6151                    source_codes
6152                        .iter()
6153                        .map(|s| s.replace("instrText", "delInstrText"))
6154                        .collect::<Vec<_>>()
6155                } else {
6156                    source_codes
6157                };
6158                assert_eq!(
6159                    actual_codes, expected_codes,
6160                    "only the field instruction tag changes; all mixed source nodes and formats survive"
6161                );
6162                assert_eq!(
6163                    dom.descendants(result, Some(&W::fld_char()))
6164                        .iter()
6165                        .map(|&node| dom.attribute(node, &W::name("fldCharType")).unwrap())
6166                        .collect::<Vec<_>>(),
6167                    vec!["begin", "separate", "end"]
6168                );
6169                assert_eq!(
6170                    dom.attribute(
6171                        dom.element(result, &W::bookmark_start()).unwrap(),
6172                        &W::name("name")
6173                    ),
6174                    Some("Clause")
6175                );
6176                assert_eq!(
6177                    dom.serialize_element(root),
6178                    source,
6179                    "repair uses independent nodes, leaving source owners intact"
6180                );
6181            }
6182        }
6183    }
6184}
6185
6186#[cfg(test)]
6187#[cfg_attr(all(coverage_nightly, test), coverage(off))]
6188mod alternate_content_paragraph_owner_tests {
6189    use super::*;
6190    use crate::namespaces::{A, MC, W14};
6191
6192    fn root(dom: &mut Dom, body: &str) -> NodeId {
6193        let doc = dom.parse_xdocument(&format!("<w:document xmlns:w='{}' xmlns:mc='{}' xmlns:w14='{}' xmlns:a='{}' mc:Ignorable='w14'><w:body>{body}<w:sectPr><w:pgSz w:w='12240' w:h='15840'/></w:sectPr></w:body></w:document>", W::URI, MC::URI, W14::URI, A::URI));
6194        dom.root(doc).unwrap()
6195    }
6196
6197    fn semantic(dom: &Dom, node: NodeId, out: &mut Vec<String>) {
6198        if dom.is_element(node) {
6199            let name = dom.name(node).unwrap();
6200            let mut attrs = dom
6201                .attributes_iter(node)
6202                .filter(|(n, _)| !dom.is_namespace_declaration(n))
6203                .map(|(n, v)| (n.clark(), v))
6204                .collect::<Vec<_>>();
6205            attrs.sort();
6206            if [W::p_pr(), W::r_pr()].contains(&name)
6207                && attrs.is_empty()
6208                && dom.nodes(node).is_empty()
6209            {
6210                return;
6211            }
6212            out.push(format!("begin:{}:{attrs:?}", name.clark()));
6213            for child in dom.nodes(node) {
6214                semantic(dom, child, out);
6215            }
6216            out.push(format!("end:{}", name.clark()));
6217        } else if dom.is_text(node) {
6218            out.push(format!("text:{:?}", dom.text_value(node)));
6219        } else {
6220            out.push(dom.serialize_element(node));
6221        }
6222    }
6223
6224    #[test]
6225    fn authored_property_only_alternatives_survive_but_wholly_deleted_wrappers_do_not() {
6226        let payload = "<mc:AlternateContent><mc:Choice Requires='w14'><w:r><w:rPr><w:b/><w14:textFill><a:solidFill><a:srgbClr val='123456'/></a:solidFill></w14:textFill></w:rPr></w:r></mc:Choice><mc:Fallback><w:r><w:rPr><w:lang w:val='fr-FR'/></w:rPr></w:r></mc:Fallback></mc:AlternateContent>";
6227        let first_props = "<w:pPr><w:spacing w:before='120'/></w:pPr>";
6228        let closing_props = "<w:pPr><w:spacing w:after='240'/><w:jc w:val='right'/></w:pPr>";
6229        let tail = "<w:r><w:rPr><w:i/></w:rPr><w:t>Independent tail</w:t></w:r>";
6230        for wholly_deleted in [false, true] {
6231            for reject in [false, true] {
6232                let content = if wholly_deleted {
6233                    format!(
6234                        "<w:del w:id='42' w:author='Original owner' w:date='2000-01-01T00:00:00Z'>{payload}</w:del>"
6235                    )
6236                } else {
6237                    payload.to_owned()
6238                };
6239                let input = format!(
6240                    "<w:p><w:pPr><w:spacing w:before='120'/><w:rPr><w:del w:id='41' w:author='Original owner' w:date='2000-01-01T00:00:00Z'/></w:rPr></w:pPr>{content}</w:p><w:p>{closing_props}{tail}</w:p>"
6241                );
6242                let expected = if reject {
6243                    format!("<w:p>{first_props}{payload}</w:p><w:p>{closing_props}{tail}</w:p>")
6244                } else {
6245                    format!(
6246                        "<w:p>{closing_props}{}{tail}</w:p>",
6247                        if wholly_deleted { "" } else { payload }
6248                    )
6249                };
6250                let mut dom = Dom::new();
6251                let authored = root(&mut dom, &input);
6252                let actual = if reject {
6253                    reject_revisions_document(&mut dom, authored)
6254                } else {
6255                    accept_revisions_document(&mut dom, authored)
6256                };
6257                let expected = root(&mut dom, &expected);
6258                let mut actual_events = Vec::new();
6259                let mut expected_events = Vec::new();
6260                semantic(&dom, actual, &mut actual_events);
6261                semantic(&dom, expected, &mut expected_events);
6262                assert_eq!(
6263                    actual_events, expected_events,
6264                    "wholly_deleted={wholly_deleted} reject={reject}: authored alternatives preserve exact effects/language even without text; outer revision remains authoritative"
6265                );
6266            }
6267        }
6268    }
6269
6270    #[test]
6271    fn surviving_alternate_content_keeps_both_presentations_across_deleted_paragraph_marks() {
6272        let payload = "<mc:AlternateContent><mc:Choice Requires='w14'><w:r><w:rPr><w:b/><w14:textFill><a:solidFill><a:srgbClr val='123456'/></a:solidFill></w14:textFill></w:rPr><w:t>Native presentation</w:t><w:tab/></w:r></mc:Choice><mc:Fallback><w:r><w:rPr><w:color w:val='654321'/></w:rPr><w:t>Fallback presentation</w:t><w:br/></w:r></mc:Fallback></mc:AlternateContent>";
6273        let closing_props = "<w:pPr><w:spacing w:after='240'/><w:jc w:val='right'/></w:pPr>";
6274        let tail = "<w:r><w:rPr><w:i/></w:rPr><w:t>Independent tail</w:t></w:r>";
6275        for moved in [false, true] {
6276            for reject in [false, true] {
6277                let marker = if moved { "moveFrom" } else { "del" };
6278                let first_props = "<w:pPr><w:spacing w:before='120'/></w:pPr>";
6279                let marked_props = format!(
6280                    "<w:pPr><w:spacing w:before='120'/><w:rPr><w:{marker} w:id='41' w:author='Original owner' w:date='2000-01-01T00:00:00Z'/></w:rPr></w:pPr>"
6281                );
6282                let input =
6283                    format!("<w:p>{marked_props}{payload}</w:p><w:p>{closing_props}{tail}</w:p>");
6284                let expected = if reject {
6285                    format!("<w:p>{first_props}{payload}</w:p><w:p>{closing_props}{tail}</w:p>")
6286                } else {
6287                    format!("<w:p>{closing_props}{payload}{tail}</w:p>")
6288                };
6289                let mut dom = Dom::new();
6290                let authored = root(&mut dom, &input);
6291                let independent = dom.clone_subtree(authored);
6292                let snapshot = dom.serialize_element(independent);
6293                let actual = if reject {
6294                    reject_revisions_document(&mut dom, authored)
6295                } else {
6296                    accept_revisions_document(&mut dom, authored)
6297                };
6298                let expected = root(&mut dom, &expected);
6299                let mut actual_events = Vec::new();
6300                let mut expected_events = Vec::new();
6301                semantic(&dom, actual, &mut actual_events);
6302                semantic(&dom, expected, &mut expected_events);
6303                assert_eq!(
6304                    actual_events, expected_events,
6305                    "moved={moved} reject={reject}: exact source alternatives, authored effects and final paragraph owner"
6306                );
6307                assert_eq!(dom.serialize_element(independent), snapshot);
6308            }
6309        }
6310    }
6311}