Skip to main content

jubarte_doc/
changes.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Tracked changes one at a time: list each with an id, accept or reject a
6//! selection and keep the rest tracked, as Word's Accept/Reject This Change
7//! does.
8//!
9//! A change is one revision element (`w:ins`, `w:del`, `w:moveFrom`,
10//! `w:moveTo`, `w:cellIns`, `w:cellDel`, `w:*PrChange`, ...), named
11//! by its short id: `r12` in the body, `header1.r1`, `footnotes.r1`,
12//! `comments.r9` or `styles.r0` in another story, the story being a header,
13//! footer, notes or comments part's file stem (`header1`, `footnotes`,
14//! `comments`, as `jubarte read` names them)
15//! ([`crate::ids::ChangeId::short`]). Resolving some changes never renumbers the rest, so an
16//! id listed before stays valid after. Word moves text as one change:
17//! selecting either side of a move selects both sides and their range
18//! markers. A revision inside a comment body (`word/comments.xml`) is
19//! `comments.rN`, the same id accept and reject select (#1706).
20
21use std::collections::{HashMap, HashSet};
22use std::fmt;
23
24use serde::{Deserialize, Serialize};
25
26use crate::namespaces::{MC, W};
27use crate::opc::PartFs;
28use crate::revision_processor::{FROZEN_NS, Resolution, resolve_package, revision_bearing_parts};
29use crate::xmllinq::{Dom, NodeId, XName};
30
31mod logical;
32
33/// What a change does.
34#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum ChangeKind {
37    /// Inserted text, paragraph mark, row or cell.
38    Insertion,
39    /// Deleted text, paragraph mark, row or cell.
40    Deletion,
41    /// One side of a move.
42    Move,
43    /// Changed run, paragraph, section, table, row or cell properties.
44    Formatting,
45    /// One author's deletion and the insertion right after it, listed as
46    /// one change ([`list_logical_changes`]). No single element has this
47    /// kind, so a filter of it is refused ([`ChangeFilter::normalized`]).
48    Replacement,
49}
50
51/// Which side of a move a change is.
52#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
53#[serde(rename_all = "snake_case")]
54pub enum MoveSide {
55    /// Where the text was moved from (`w:moveFrom`): accepting removes it.
56    From,
57    /// Where the text was moved to (`w:moveTo`): rejecting removes it.
58    To,
59}
60
61/// One tracked change.
62#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
63pub struct Change {
64    /// The short id: `r12` in the body, `header1.r1` in another story
65    /// ([`crate::ids::ChangeId::short`]).
66    pub id: String,
67    /// The same id as [`Self::id`].
68    #[serde(rename = "ref")]
69    pub r#ref: String,
70    /// What the change does.
71    pub kind: ChangeKind,
72    /// What it applies to: `text`, `paragraph_mark`, `table_row`,
73    /// `table_cell` or `properties`.
74    pub target: &'static str,
75    /// Revision author.
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub author: Option<String>,
78    /// The valid UTC instant, written in the author's local offset when both
79    /// times record a whole-minute difference within ±14:00; otherwise `Z`.
80    /// Without a valid `w16du:dateUtc`, `w:date` as stored.
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub date: Option<String>,
83    /// The text the change covers: inserted, deleted or moved text, or the
84    /// text of the run or paragraph whose properties changed.
85    pub text: String,
86    /// The paragraph the change sits in (`p12`, `header1.p2`): the
87    /// nearest listed paragraph around it, or a row's, cell's or table's
88    /// first. `None` in `styles` and outside any paragraph.
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub paragraph: Option<String>,
91    /// The move's name, shared by both of its sides.
92    #[serde(skip_serializing_if = "Option::is_none")]
93    pub move_name: Option<String>,
94    /// The side of the move, for a move.
95    #[serde(skip_serializing_if = "Option::is_none")]
96    pub move_side: Option<MoveSide>,
97    /// The change whose content holds this one: an inserted, deleted or
98    /// moved run, row or cell around it, or the mark of the paragraph whose
99    /// properties it changes. Resolving that change so its content goes
100    /// (accepting a deletion or the moved-from side, rejecting an insertion
101    /// or the moved-to side) takes this one along.
102    #[serde(skip_serializing_if = "Option::is_none")]
103    pub inside: Option<String>,
104    /// The comments (`c4`, and a reply's `c5`) whose reference mark this
105    /// change holds: resolving it so its content goes (as for
106    /// [`Self::inside`]) removes their threads, as Word does (#1159).
107    #[serde(default, skip_serializing_if = "Vec::is_empty")]
108    pub holds_comments: Vec<String>,
109    /// The marks of a logical change ([`list_logical_changes`]) that Word
110    /// wrote as several elements, in reading order: empty for one element.
111    #[serde(default, skip_serializing_if = "Vec::is_empty")]
112    pub members: Vec<ChangeMember>,
113}
114
115impl Change {
116    /// The ids of the elements this change is made of, in reading order:
117    /// its [`Self::members`]', or its own for a change of one element.
118    pub fn element_ids(&self) -> impl Iterator<Item = &str> {
119        let own = self.members.is_empty().then_some(self.id.as_str());
120        own.into_iter()
121            .chain(self.members.iter().map(|m| m.id.as_str()))
122    }
123}
124
125/// One mark of a logical change: an element Word wrote for it.
126#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
127pub struct ChangeMember {
128    /// The element's own id (`r7`), as [`list_changes`] lists it.
129    pub id: String,
130    /// What the element does: an insertion or a deletion.
131    pub kind: ChangeKind,
132    /// `text` or `paragraph_mark`.
133    pub target: &'static str,
134    /// The element's own date, as [`Change::date`] reports it.
135    #[serde(skip_serializing_if = "Option::is_none")]
136    pub date: Option<String>,
137    /// The text it covers (empty for a paragraph mark).
138    pub text: String,
139}
140
141/// Private audit view: public `Change` serialization stays unchanged.
142pub(crate) struct AuditStory {
143    pub part: String,
144    pub paragraphs: Vec<(String, String)>,
145    /// What [`run_characters`] counts in each paragraph, in order.
146    pub contents: Vec<String>,
147    pub changes: Vec<AuditChange>,
148    pub markers: Vec<AuditMarker>,
149}
150
151/// A carrier omitted from the change listing. Only its own cursor slot can
152/// disappear transparently; any visible descendants keep their positions.
153pub(crate) struct AuditMarker {
154    pub kind: String,
155    pub paragraph: Option<usize>,
156    pub owner: String,
157    pub start: usize,
158}
159
160pub(crate) struct AuditChange {
161    pub change: Change,
162    pub owner: String,
163    /// Document positions the change covers. A run's formatting history
164    /// covers its run, so the touching fragments of one record, after an
165    /// edit split the run, cover continuous text (#1656).
166    pub start: usize,
167    pub end: usize,
168    /// The old properties a formatting change recorded
169    /// ([`recorded_properties`]); `None` for every other change.
170    pub payload: Option<String>,
171    /// The characters a run formatting change's run covers in its
172    /// paragraph ([`run_characters`]); `None` for every other change.
173    pub characters: Option<(usize, usize)>,
174}
175
176/// Read paragraph text including deletions, and document positions for the
177/// same carriers as `list_changes`. Positions count visible atoms and every
178/// revision, including carriers omitted from the public listing.
179pub(crate) fn audit_stories(docx: &[u8]) -> Result<Vec<AuditStory>, ChangeError> {
180    let pkg = open(docx)?;
181    let main = main_part(&pkg);
182    let mut stories = Vec::new();
183    for (part, _) in revision_bearing_parts(&pkg) {
184        let Some(xml) = pkg.part_string(&part) else {
185            continue;
186        };
187        let mut dom = Dom::new();
188        let document = dom.parse_xdocument(&xml);
189        let Some(root) = dom.root(document) else {
190            continue;
191        };
192        let story = story_id(&main, &part);
193        let found = carriers(&dom, root, &story);
194        let revision_nodes: HashSet<_> = found.iter().map(|c| c.node).collect();
195        let mut spans = HashMap::new();
196        let mut cursor = 0;
197        let mut pending = vec![(root, false)];
198        while let Some((node, closing)) = pending.pop() {
199            if closing {
200                if let Some(span) = spans.get_mut(&node) {
201                    let (_, end): &mut (usize, usize) = span;
202                    *end = cursor;
203                }
204                continue;
205            }
206            spans.insert(node, (cursor, cursor));
207            let visible = dom.name(node).is_some_and(|name| {
208                name.namespace_name() == W::URI
209                    && matches!(
210                        name.local_name(),
211                        "t" | "delText"
212                            | "instrText"
213                            | "delInstrText"
214                            | "tab"
215                            | "br"
216                            | "cr"
217                            | "drawing"
218                            | "pict"
219                            | "object"
220                            | "sym"
221                            | "noBreakHyphen"
222                            | "softHyphen"
223                            | "footnoteReference"
224                            | "endnoteReference"
225                    )
226            });
227            let empty_text = dom.name(node).is_some_and(|name| {
228                matches!(
229                    name.local_name(),
230                    "t" | "delText" | "instrText" | "delInstrText"
231                )
232            }) && dom.value(node).is_empty();
233            if revision_nodes.contains(&node) || (visible && !empty_text) {
234                cursor += 1;
235            }
236            pending.push((node, true));
237            for index in (0..dom.child_count(node)).rev() {
238                pending.push((dom.child_at(node, index), false));
239            }
240        }
241        let paragraphs = crate::inspect::story_paragraph_nodes(&dom, root)
242            .into_iter()
243            .enumerate()
244            .map(|(index, node)| (crate::ids::paragraph_id(&story, index), text_of(&dom, node)))
245            .collect();
246        let paragraph_nodes = paragraph_index(&dom, root);
247        let (characters, contents) = run_characters(&dom, root, &HashSet::new());
248        let markers = found
249            .iter()
250            .filter(|carrier| carrier.change.is_none())
251            .map(|carrier| {
252                let paragraph = paragraph_of(&dom, carrier.node, &paragraph_nodes);
253                AuditMarker {
254                    kind: dom.name(carrier.node).unwrap().local_name().to_string(),
255                    paragraph,
256                    owner: if paragraph.is_none() {
257                        audit_owner(&dom, carrier.node)
258                    } else {
259                        String::new()
260                    },
261                    start: spans[&carrier.node].0,
262                }
263            })
264            .collect();
265        let changes = found
266            .into_iter()
267            .filter_map(|carrier| {
268                let change = carrier.change?;
269                let owner = if change.paragraph.is_none() {
270                    audit_owner(&dom, carrier.node)
271                } else {
272                    String::new()
273                };
274                let run = formatted_run(&dom, carrier.node);
275                let (start, end) = spans[&run.unwrap_or(carrier.node)];
276                let payload = (change.kind == ChangeKind::Formatting)
277                    .then(|| recorded_properties(&dom, carrier.node));
278                Some(AuditChange {
279                    change,
280                    owner,
281                    start,
282                    end,
283                    payload,
284                    characters: run.and_then(|run| characters.get(&run).copied()),
285                })
286            })
287            .collect();
288        stories.push(AuditStory {
289            part,
290            paragraphs,
291            contents,
292            changes,
293            markers,
294        });
295    }
296    Ok(stories)
297}
298
299/// The run a `w:r/w:rPr/w:rPrChange` formats; `None` for any other
300/// record, a paragraph mark's or a style's included.
301fn formatted_run(dom: &Dom, record: NodeId) -> Option<NodeId> {
302    if !dom.name_is(record, &W::r_pr_change()) {
303        return None;
304    }
305    let rpr = dom.parent(record).filter(|&n| dom.name_is(n, &W::r_pr()))?;
306    dom.parent(rpr).filter(|&n| dom.name_is(n, &W::r()))
307}
308
309/// The properties a formatting record kept, spelled without revision ids
310/// or namespace prefixes: its own attributes past id, author and date, then
311/// each element as `{namespace}local`, its attributes
312/// `{namespace}local="value"` sorted, its children in document order (the
313/// first matching `mc:Choice` wins) and a leaf's text. A value that lists
314/// prefixes (`Requires`, `mc:Ignorable`, …) lists their namespaces, and an
315/// on/off `w:val` is spelled one way. Two records with the same payload
316/// recorded the same old formatting.
317pub(crate) fn recorded_properties(dom: &Dom, record: NodeId) -> String {
318    fn attributes(dom: &Dom, node: NodeId, skip: &[XName]) -> String {
319        let Some(name) = dom.name(node) else {
320            return String::new();
321        };
322        let mut attributes: Vec<String> = dom
323            .attributes(node)
324            .into_iter()
325            .filter(|(attribute, _)| {
326                !dom.is_namespace_declaration(attribute) && !skip.contains(attribute)
327            })
328            .filter_map(|(attribute, value)| {
329                let value =
330                    if crate::xmllinq::serialize::is_namespace_prefix_list(&name, &attribute) {
331                        value
332                            .split_whitespace()
333                            .map(|prefix| {
334                                crate::validate::namespace_in_scope(dom, node, prefix).map_or_else(
335                                    || format!("{prefix}:"),
336                                    |uri| format!("{{{uri}}}"),
337                                )
338                            })
339                            .collect::<Vec<_>>()
340                            .join(" ")
341                    } else if attribute == W::val() && on_off(&name) {
342                        match value.as_str() {
343                            // `<w:b/>` and `<w:b w:val="true"/>` are both on.
344                            "1" | "true" | "on" => return None,
345                            "0" | "false" | "off" => "0".to_string(),
346                            _ => value,
347                        }
348                    } else {
349                        value
350                    };
351                Some(format!(
352                    "{{{}}}{}={value:?}",
353                    attribute.namespace_name(),
354                    attribute.local_name()
355                ))
356            })
357            .collect();
358        attributes.sort();
359        attributes.join(",")
360    }
361    fn canonical(dom: &Dom, node: NodeId) -> String {
362        let Some(name) = dom.name(node) else {
363            return String::new();
364        };
365        let children: Vec<String> = dom
366            .elements(node, None)
367            .into_iter()
368            .map(|child| canonical(dom, child))
369            .collect();
370        let text = if children.is_empty() {
371            dom.value(node)
372        } else {
373            String::new()
374        };
375        format!(
376            "{{{}}}{}[{}]({}){text:?}",
377            name.namespace_name(),
378            name.local_name(),
379            attributes(dom, node, &[W::id()]),
380            children.join(",")
381        )
382    }
383    let own = attributes(dom, record, &[W::id(), W::author(), W::date()]);
384    let children: Vec<String> = dom
385        .elements(record, None)
386        .into_iter()
387        .map(|child| canonical(dom, child))
388        .collect();
389    format!("[{own}]({})", children.join(","))
390}
391
392/// A `CT_OnOff` property: its `w:val` is on when absent.
393fn on_off(name: &XName) -> bool {
394    name.namespace_name() == W::URI
395        && matches!(
396            name.local_name(),
397            "b" | "bCs"
398                | "i"
399                | "iCs"
400                | "caps"
401                | "smallCaps"
402                | "strike"
403                | "dstrike"
404                | "outline"
405                | "shadow"
406                | "emboss"
407                | "imprint"
408                | "noProof"
409                | "snapToGrid"
410                | "vanish"
411                | "webHidden"
412                | "specVanish"
413                | "rtl"
414                | "cs"
415                | "oMath"
416                | "keepNext"
417                | "keepLines"
418                | "pageBreakBefore"
419                | "widowControl"
420                | "suppressLineNumbers"
421                | "suppressAutoHyphens"
422                | "kinsoku"
423                | "wordWrap"
424                | "overflowPunct"
425                | "topLinePunct"
426                | "autoSpaceDE"
427                | "autoSpaceDN"
428                | "bidi"
429                | "adjustRightInd"
430                | "contextualSpacing"
431                | "mirrorIndents"
432                | "suppressOverlap"
433                | "titlePg"
434                | "rtlGutter"
435                | "noEndnote"
436                | "formProt"
437                | "bidiVisual"
438                | "hidden"
439                | "cantSplit"
440                | "tblHeader"
441                | "noWrap"
442                | "tcFitText"
443                | "hideMark"
444        )
445}
446
447/// A properties element (`w:pPr`, `w:rPr`, …): no content lives in it.
448fn properties(name: &XName) -> bool {
449    name.namespace_name() == W::URI
450        && matches!(
451            name.local_name(),
452            "pPr" | "rPr" | "sectPr" | "tblPr" | "tblPrEx" | "tblGrid" | "trPr" | "tcPr" | "sdtPr"
453        )
454}
455
456/// One character per visible element that is not text: what a run holding
457/// a tab, a break or a drawing covers.
458#[doc(hidden)]
459pub fn atom(name: &XName) -> Option<char> {
460    if name.namespace_name() != W::URI {
461        return None;
462    }
463    Some(match name.local_name() {
464        "tab" | "ptab" => '\t',
465        "br" | "cr" => '\n',
466        "drawing" | "pict" | "object" => '\u{FFFC}',
467        "sym" => '\u{FFFD}',
468        "noBreakHyphen" => '\u{2011}',
469        "softHyphen" => '\u{AD}',
470        "footnoteReference" | "endnoteReference" => '\u{E000}',
471        "instrText" | "delInstrText" => '\u{E001}',
472        _ => return None,
473    })
474}
475
476/// Whether `run` covers any character [`run_characters`] counts: text
477/// outside its properties, or an atom ([`atom`]).
478#[doc(hidden)]
479pub fn run_has_characters(dom: &Dom, run: NodeId) -> bool {
480    let (t, del_text) = (W::t(), W::del_text());
481    let mut pending: Vec<NodeId> = dom.elements(run, None);
482    while let Some(node) = pending.pop() {
483        let Some(name) = dom.name(node) else {
484            continue;
485        };
486        if properties(&name) {
487            continue;
488        }
489        if dom.name_is(node, &t) || dom.name_is(node, &del_text) {
490            if !dom.value(node).is_empty() {
491                return true;
492            }
493        } else if atom(&name).is_some() {
494            return true;
495        }
496        pending.extend(dom.elements(node, None));
497    }
498    false
499}
500
501/// What each run covers in its story paragraph: the characters of its
502/// `w:t` and `w:delText`, one more per tab, break, drawing or other atom
503/// ([`atom`]), a text box's runs at their place; and each paragraph's
504/// counted content, in order. Content under a `skipped` element counts for
505/// nothing, and a paragraph whose inserted mark is `skipped` continues into
506/// the next, as rejecting that mark joins them.
507fn run_characters(
508    dom: &Dom,
509    root: NodeId,
510    skipped: &HashSet<NodeId>,
511) -> (HashMap<NodeId, (usize, usize)>, Vec<String>) {
512    let (r, t, del_text) = (W::r(), W::t(), W::del_text());
513    let mut spans = HashMap::new();
514    let mut contents = Vec::new();
515    let mut cursor = 0;
516    for paragraph in crate::inspect::story_paragraph_nodes(dom, root) {
517        let mut content = String::new();
518        let mut pending = vec![(paragraph, false, false)];
519        while let Some((node, closing, skipping)) = pending.pop() {
520            if closing {
521                if let Some(span) = spans.get_mut(&node) {
522                    let (_, end): &mut (usize, usize) = span;
523                    *end = cursor;
524                }
525                continue;
526            }
527            let skipping = skipping || skipped.contains(&node);
528            // Properties hold no content (a `w:tabs/w:tab` is a tab stop).
529            if node != paragraph && dom.name(node).is_some_and(|name| properties(&name)) {
530                continue;
531            }
532            if dom.name_is(node, &r) {
533                spans.insert(node, (cursor, cursor));
534            } else if !skipping {
535                if dom.name_is(node, &t) || dom.name_is(node, &del_text) {
536                    let text = dom.value(node);
537                    cursor += text.chars().count();
538                    content.push_str(&text);
539                } else if let Some(atom) = dom.name(node).and_then(|name| atom(&name)) {
540                    cursor += 1;
541                    content.push(atom);
542                }
543            }
544            pending.push((node, true, skipping));
545            for index in (0..dom.child_count(node)).rev() {
546                pending.push((dom.child_at(node, index), false, skipping));
547            }
548        }
549        contents.push(content);
550        let joined = dom
551            .element(paragraph, &W::p_pr())
552            .and_then(|p_pr| dom.element(p_pr, &W::r_pr()))
553            .and_then(|r_pr| dom.element(r_pr, &W::ins()))
554            .is_some_and(|mark| skipped.contains(&mark));
555        if !joined {
556            cursor = 0;
557        }
558    }
559    (spans, contents)
560}
561
562/// A formatting change: the old properties it recorded
563/// ([`recorded_properties`]) and, a run's, the characters it covers
564/// ([`run_characters`]).
565#[derive(Clone, Debug, PartialEq, Eq)]
566#[doc(hidden)]
567pub struct Recorded {
568    pub payload: String,
569    pub characters: Option<(usize, usize)>,
570}
571
572/// Each formatting change's [`Recorded`], under the story-scoped id
573/// [`list_changes`] gives it (`r3`, `styles.r3`). A `w:id` repeated in one
574/// story keeps every record, in document order.
575pub(crate) type Records = HashMap<String, Vec<Recorded>>;
576
577/// The comments of a package's comments part: each comment's `w:id`, and
578/// for each comment-body change (`comments.r9`, as [`list_changes`] names
579/// it) the `w:id` of the comment that holds it, `None` when the change's
580/// id repeats in two comments. A comment an edit removes takes its body's
581/// changes with it (#1706).
582#[derive(Debug, Default)]
583#[doc(hidden)]
584pub struct CommentBodies {
585    pub comments: HashSet<String>,
586    pub owners: HashMap<String, Option<String>>,
587}
588
589/// [`CommentBodies`] of `docx`; empty when it has no comments part.
590#[doc(hidden)]
591pub fn comment_bodies(docx: &[u8]) -> Result<CommentBodies, ChangeError> {
592    let pkg = open(docx)?;
593    let mut bodies = CommentBodies::default();
594    let Some(part) = crate::revision_processor::comments_part(&pkg) else {
595        return Ok(bodies);
596    };
597    let story = story_id(&main_part(&pkg), &part);
598    let comment = W::comment();
599    let id = W::id();
600    for_each_story(&pkg, |dom, root, name| {
601        if name != story {
602            return;
603        }
604        dom.for_each_descendant_element(root, Some(&comment), |c| {
605            if let Some(val) = dom.attribute(c, &id) {
606                bodies.comments.insert(val.to_string());
607            }
608        });
609        for carrier in carriers(dom, root, name) {
610            let Some(change) = carrier.change else {
611                continue;
612            };
613            // The nearest comment with an id that holds the carrier, walked up without a Vec.
614            let mut holder = None;
615            let mut node = dom.parent(carrier.node);
616            while let Some(n) = node {
617                if dom.name_is(n, &comment)
618                    && let Some(val) = dom.attribute(n, &id)
619                {
620                    holder = Some(val.to_string());
621                    break;
622                }
623                node = dom.parent(n);
624            }
625            if let Some(holder) = holder {
626                bodies
627                    .owners
628                    .entry(change.id)
629                    .and_modify(|owner| {
630                        if owner.as_ref() != Some(&holder) {
631                            *owner = None;
632                        }
633                    })
634                    .or_insert(Some(holder));
635            }
636        }
637    });
638    Ok(bodies)
639}
640
641/// [`list_changes`] and its formatting changes' [`Records`], from one
642/// parse of each story. The content of a change `skip` names, and the
643/// paragraph mark it inserts, count for nothing in the characters.
644#[doc(hidden)]
645pub fn changes_and_records(
646    docx: &[u8],
647    skip: &dyn Fn(&Change) -> bool,
648) -> Result<(Vec<Change>, Records), ChangeError> {
649    let pkg = open(docx)?;
650    let mut changes = Vec::new();
651    let mut records = Records::new();
652    for_each_story(&pkg, |dom, root, story| {
653        let found = carriers(dom, root, story);
654        let formatting = |carrier: &Carrier| {
655            carrier
656                .change
657                .as_ref()
658                .is_some_and(|c| c.kind == ChangeKind::Formatting)
659        };
660        if found.iter().any(formatting) {
661            let skipped: HashSet<_> = found
662                .iter()
663                .filter(|carrier| carrier.change.as_ref().is_some_and(skip))
664                .map(|carrier| carrier.node)
665                .collect();
666            let (characters, _) = run_characters(dom, root, &skipped);
667            for carrier in found.iter().filter(|carrier| formatting(carrier)) {
668                let Some(change) = &carrier.change else {
669                    continue;
670                };
671                records
672                    .entry(change.id.clone())
673                    .or_default()
674                    .push(Recorded {
675                        payload: recorded_properties(dom, carrier.node),
676                        characters: formatted_run(dom, carrier.node)
677                            .and_then(|run| characters.get(&run).copied()),
678                    });
679            }
680        }
681        changes.extend(found.into_iter().filter_map(|c| c.change));
682    });
683    Ok((changes, records))
684}
685
686/// Owner paths use semantic ids where OOXML defines them, otherwise the
687/// element's ordinal among same-named siblings. Revision ids never enter it.
688fn audit_owner(dom: &Dom, node: NodeId) -> String {
689    let mut path = Vec::new();
690    for ancestor in dom.ancestors(node, None).into_iter().rev() {
691        let Some(name) = dom.name(ancestor) else {
692            continue;
693        };
694        let local = name.local_name();
695        let identity = ["styleId", "abstractNumId", "numId", "ilvl", "id"]
696            .into_iter()
697            .find_map(|attr| {
698                dom.attribute(ancestor, &W::name(attr))
699                    .map(|id| format!("{attr}={id}"))
700            })
701            .unwrap_or_else(|| {
702                let ordinal = dom
703                    .nodes_before_self(ancestor)
704                    .into_iter()
705                    .filter(|&sibling| dom.name(sibling).as_ref() == Some(&name))
706                    .count();
707                ordinal.to_string()
708            });
709        path.push(format!("{local}[{identity}]"));
710    }
711    path.join("/")
712}
713
714/// Which changes to resolve. A change is selected when it matches every
715/// list given; a list left out matches any change, so the default filter
716/// selects every change, and an empty list selects none.
717#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
718#[serde(deny_unknown_fields)]
719pub struct ChangeFilter {
720    /// Change ids (`r12`, `header1.r1`); an id not in the document is an
721    /// error.
722    #[serde(default, skip_serializing_if = "Option::is_none")]
723    pub ids: Option<Vec<String>>,
724    /// Revision authors.
725    #[serde(default, skip_serializing_if = "Option::is_none")]
726    pub authors: Option<Vec<String>>,
727    /// Change kinds.
728    #[serde(default, skip_serializing_if = "Option::is_none")]
729    pub kinds: Option<Vec<ChangeKind>>,
730}
731
732impl ChangeFilter {
733    /// Build a filter that selects the changes `ids` names (`r12`,
734    /// `header1.r1`, `r1+2`).
735    pub fn ids<I: IntoIterator<Item = S>, S: Into<String>>(ids: I) -> Self {
736        Self {
737            ids: Some(ids.into_iter().map(Into::into).collect()),
738            ..Self::default()
739        }
740    }
741
742    /// The filter with every id in its settled short spelling, the form
743    /// [`Change::id`] holds and [`Self::check`] and [`Self::matches`]
744    /// compare: `r12`, `header1.r1`, a pair `r1+2` as its two ids, each
745    /// once. Only settled ids parse ([`crate::ids::parse_change_ids`]):
746    /// `12`, 0.12's `#12` and the expired `body:rev:12` are
747    /// [`ChangeError::InvalidId`], naming the spelling to use.
748    ///
749    /// # Errors
750    ///
751    /// [`ChangeError::InvalidId`] for an id that does not parse, and for
752    /// the kind [`ChangeKind::Replacement`], which no element has: it would
753    /// select nothing.
754    pub fn normalized(&self) -> Result<Self, ChangeError> {
755        if self
756            .kinds
757            .as_ref()
758            .is_some_and(|kinds| kinds.contains(&ChangeKind::Replacement))
759        {
760            return Err(ChangeError::InvalidId(
761                "the kind replacement names a logical change, not its marks: select a replacement by its id (r3+4), or its marks by kind (deletion, insertion)".into(),
762            ));
763        }
764        let Some(ids) = &self.ids else {
765            return Ok(self.clone());
766        };
767        let mut out: Vec<String> = Vec::with_capacity(ids.len());
768        for id in ids {
769            let parsed = crate::ids::parse_change_ids(id)
770                .map_err(|e| ChangeError::InvalidId(e.to_string()))?;
771            for one in parsed {
772                let one = one.short();
773                if !out.contains(&one) {
774                    out.push(one);
775                }
776            }
777        }
778        Ok(Self {
779            ids: Some(out),
780            ..self.clone()
781        })
782    }
783
784    /// The first error the filter's ids meet in `listed`: an id that names
785    /// no change, or one that names several. Expects a [`Self::normalized`]
786    /// filter.
787    ///
788    /// # Errors
789    ///
790    /// [`ChangeError::UnknownChange`] when an id is not in `listed`;
791    /// [`ChangeError::Ambiguous`] when an id names more than one change.
792    pub fn check(&self, listed: &[Change]) -> Result<(), ChangeError> {
793        for id in self.ids.iter().flatten() {
794            let named: Vec<&Change> = listed.iter().filter(|c| &c.id == id).collect();
795            match named.len() {
796                0 => return Err(ChangeError::UnknownChange(id.clone())),
797                1 => {}
798                _ => {
799                    return Err(ChangeError::Ambiguous {
800                        id: id.clone(),
801                        candidates: named.into_iter().cloned().collect(),
802                    });
803                }
804            }
805        }
806        Ok(())
807    }
808
809    /// Whether `change` is selected.
810    pub fn matches(&self, change: &Change) -> bool {
811        self.ids.as_ref().is_none_or(|ids| ids.contains(&change.id))
812            && self
813                .authors
814                .as_ref()
815                .is_none_or(|authors| change.author.as_ref().is_some_and(|a| authors.contains(a)))
816            && self
817                .kinds
818                .as_ref()
819                .is_none_or(|kinds| kinds.contains(&change.kind))
820    }
821}
822
823/// Why changes could not be listed or resolved.
824#[derive(Clone, Debug, PartialEq, Eq)]
825pub enum ChangeError {
826    /// The package could not be read or written.
827    Package(String),
828    /// A filter id names no change in the document.
829    UnknownChange(String),
830    /// A filter id is not a change id ([`crate::ids::parse_change_ids`]),
831    /// or a filter kind is one no element has ([`ChangeFilter::normalized`]).
832    InvalidId(String),
833    /// A filter id names more than one listed change: a
834    /// duplicate `w:id` in one story.
835    Ambiguous {
836        /// The id.
837        id: String,
838        /// The changes it names, in document order.
839        candidates: Vec<Change>,
840    },
841    /// The filter's ids name only some of the marks of one logical change
842    /// ([`list_logical_changes`]), or only part of one side of a
843    /// replacement.
844    PartOfChange {
845        /// The marks named, as one id (`r7+8`).
846        named: String,
847        /// The whole change (`r7+8+9+10`).
848        whole: String,
849        /// For part of one side of a replacement: the side (`r20+21`) and
850        /// its kind.
851        side: Option<(String, ChangeKind)>,
852    },
853    /// Settling the selection would leave `w:ins` or `w:del` on a
854    /// container's final paragraph mark. The mark was not already that
855    /// container's final mark. A cell in this shape hangs Word's Accept
856    /// All and Reject All (#1669, #1693). No document is returned.
857    ExposedFinalMark {
858        /// `cell`, `body`, `header`, `footer`, `note`, `textbox`, or
859        /// `comment`.
860        container: &'static str,
861        /// Path of the container (`w:body[0]/w:tbl[0]/w:tr[0]/w:tc[1]`).
862        path: String,
863        /// Path of the paragraph that would keep the mark.
864        paragraph: String,
865        /// The remaining mark's short id (`r1`, `header1.r1`), or
866        /// `(no w:id)` for a mark without one.
867        revision: String,
868        /// `ins` or `del`.
869        kind: &'static str,
870    },
871}
872
873impl fmt::Display for ChangeError {
874    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
875        match self {
876            ChangeError::Package(m) => write!(f, "invalid package: {m}"),
877            ChangeError::UnknownChange(id) => write!(f, "no tracked change {id}"),
878            ChangeError::InvalidId(message) => f.write_str(message),
879            ChangeError::Ambiguous { id, candidates } => {
880                // Only these elements' ids are renumbered by validate --repair.
881                let repairable = candidates.iter().all(|c| {
882                    matches!(
883                        c.kind,
884                        ChangeKind::Insertion | ChangeKind::Deletion | ChangeKind::Move
885                    ) && c.target != "table_cell"
886                });
887                write!(f, "{id} names {} changes", candidates.len())?;
888                if repairable {
889                    f.write_str(" (duplicate w:id; validate --repair renumbers them)")?;
890                }
891                let listed: Vec<String> = candidates
892                    .iter()
893                    .map(|c| {
894                        let place = c
895                            .paragraph
896                            .as_deref()
897                            .map(|p| format!(" in {p}"))
898                            .unwrap_or_default();
899                        format!("{id} {} {:?}{place}", kind_name(c.kind), c.text)
900                    })
901                    .collect();
902                write!(f, ": {}", listed.join("; "))
903            }
904            ChangeError::PartOfChange {
905                named,
906                whole,
907                side: None,
908            } => write!(
909                f,
910                "{named} is part of {whole}; name the whole change ({whole})"
911            ),
912            ChangeError::PartOfChange {
913                named,
914                whole,
915                side: Some((side, kind)),
916            } => {
917                let kind = if *kind == ChangeKind::Deletion {
918                    "deleted"
919                } else {
920                    "inserted"
921                };
922                write!(
923                    f,
924                    "{named} is part of {side}, the {kind} side of {whole}; name that side ({side}) or the whole change ({whole})"
925                )
926            }
927            ChangeError::ExposedFinalMark {
928                container,
929                path,
930                paragraph,
931                revision,
932                kind,
933            } => write!(
934                f,
935                "refusing to leave {kind} {revision} on the final mark of {container} {path} at paragraph {paragraph}"
936            ),
937        }
938    }
939}
940
941impl std::error::Error for ChangeError {}
942
943fn kind_name(kind: ChangeKind) -> &'static str {
944    match kind {
945        ChangeKind::Insertion => "insertion",
946        ChangeKind::Deletion => "deletion",
947        ChangeKind::Move => "move",
948        ChangeKind::Formatting => "formatting",
949        ChangeKind::Replacement => "replacement",
950    }
951}
952
953/// `jubarte changes`' listing: one line per change, `{ref}\t{kind}\t{target}
954/// \t{author}\t{paragraph}\t{text}[\t({n} elements)][\tinside {ref}][\tholds
955/// comment {c}'s mark]` (`-` for an absent author or paragraph; the text
956/// quoted, its first 60 characters; `({n} elements)` for a logical change
957/// Word wrote as several; `holds comment marks {c}, {c}` for several), then
958/// `{n} change(s)`. A row has six fields, and one more for each suffix.
959pub fn changes_text(changes: &[Change]) -> String {
960    let mut out = String::new();
961    for c in changes {
962        let preview: String = c.text.chars().take(60).collect();
963        let paragraph = c.paragraph.as_deref().unwrap_or("-");
964        let elements = match c.members.len() {
965            0 => String::new(),
966            n => format!("\t({n} elements)"),
967        };
968        let inside = c
969            .inside
970            .as_deref()
971            .map(|id| format!("\tinside {id}"))
972            .unwrap_or_default();
973        let holds = match c.holds_comments.as_slice() {
974            [] => String::new(),
975            [one] => format!("\tholds comment {one}'s mark"),
976            many => format!("\tholds comment marks {}", many.join(", ")),
977        };
978        out.push_str(&format!(
979            "{}\t{}\t{}\t{}\t{paragraph}\t{preview:?}{elements}{inside}{holds}\n",
980            c.r#ref,
981            kind_name(c.kind),
982            c.target,
983            c.author.as_deref().unwrap_or("-"),
984        ));
985    }
986    out.push_str(&format!("{} change(s)\n", changes.len()));
987    out
988}
989
990/// Every tracked change, story by story (body, headers, footers, endnotes,
991/// footnotes, comments, styles), in document order. A revision inside a
992/// comment body is `comments.r9` (#1706).
993///
994/// # Errors
995///
996/// [`ChangeError::Package`] when the package is not a readable zip.
997pub fn list_changes(docx: &[u8]) -> Result<Vec<Change>, ChangeError> {
998    Ok(changes_in(&open(docx)?))
999}
1000
1001/// Every logical change, story by story, in document order: the changes
1002/// `jubarte changes` lists. One author's touching insertions, or touching
1003/// deletions, are one change with a composite id (`r7+8+9+10`) and
1004/// [`Change::members`]; a deletion run followed by the same author's
1005/// insertion run is one [`ChangeKind::Replacement`] (module `logical`
1006/// has the rule). Every other element is listed as [`list_changes`]
1007/// lists it.
1008///
1009/// # Errors
1010///
1011/// [`ChangeError::Package`] when the package is not a readable zip.
1012pub fn list_logical_changes(docx: &[u8]) -> Result<Vec<Change>, ChangeError> {
1013    Ok(logical_changes_in(&open(docx)?))
1014}
1015
1016/// The id of the marks `ids` names together, in their order: `r7+8`,
1017/// `header1.r1+2`. One mark keeps its own id, whatever its spelling.
1018#[doc(hidden)]
1019pub fn composite_id(ids: &[String]) -> String {
1020    match ids {
1021        [one] => one.clone(),
1022        _ => logical::joined(ids.iter().map(String::as_str)),
1023    }
1024}
1025
1026/// The changes `authors` wrote, matched as [`ChangeFilter::authors`]
1027/// matches them (exact names); every change when `authors` is empty. A
1028/// logical change has one author, so it is kept or left whole: the filter
1029/// `jubarte changes --author` applies (#1690).
1030pub fn by_authors(changes: Vec<Change>, authors: &[String]) -> Vec<Change> {
1031    if authors.is_empty() {
1032        return changes;
1033    }
1034    let filter = ChangeFilter {
1035        authors: Some(authors.to_vec()),
1036        ..ChangeFilter::default()
1037    };
1038    changes.into_iter().filter(|c| filter.matches(c)).collect()
1039}
1040
1041/// The logical changes of an opened package ([`list_logical_changes`]).
1042#[doc(hidden)]
1043pub fn logical_changes_in(pkg: &PartFs) -> Vec<Change> {
1044    let mut out = Vec::new();
1045    for_each_story(pkg, |dom, root, story| {
1046        out.extend(logical::logical(dom, root, &carriers(dom, root, story)));
1047    });
1048    out
1049}
1050
1051/// Refuse ids that name only some marks of a logical change
1052/// ([`ChangeError::PartOfChange`]): the check `accept` and `reject` make,
1053/// for an edit plan's `resolve_revisions` and the edit flags to make on
1054/// their source before they resolve anything.
1055#[doc(hidden)]
1056pub fn check_whole_changes(docx: &[u8], filter: &ChangeFilter) -> Result<(), ChangeError> {
1057    let filter = filter.normalized()?;
1058    if filter.ids.is_none() {
1059        return Ok(());
1060    }
1061    logical::check_whole(&filter, &logical_changes_in(&open(docx)?))
1062}
1063
1064/// [`list_changes`] for a view that already renders the package: no
1065/// admission, and a part that does not parse lists nothing, so the view's
1066/// count fails only where the package itself does.
1067#[doc(hidden)]
1068pub fn list_changes_tolerant(docx: &[u8]) -> Result<Vec<Change>, ChangeError> {
1069    Ok(changes_in(&tolerant(docx)?))
1070}
1071
1072/// [`list_logical_changes`] as [`list_changes_tolerant`] lists the marks:
1073/// the changes a view's tags name.
1074#[doc(hidden)]
1075pub fn list_logical_changes_tolerant(docx: &[u8]) -> Result<Vec<Change>, ChangeError> {
1076    Ok(logical_changes_in(&tolerant(docx)?))
1077}
1078
1079/// The package a view reads, opened without admission. Its parts parse
1080/// permissively, so one nesting deeper than the view reads is refused
1081/// before the parser recurses into it (#1353 review).
1082fn tolerant(docx: &[u8]) -> Result<PartFs, ChangeError> {
1083    use crate::xmllinq::parse::{PERMISSIVE_MAX_DEPTH, nests_deeper};
1084
1085    let normalized = crate::strict_translation::strict_to_transitional_docx(docx)
1086        .map_err(|e| ChangeError::Package(e.to_string()))?;
1087    let pkg = PartFs::open(&normalized).map_err(|e| ChangeError::Package(e.to_string()))?;
1088    for (part, _) in revision_bearing_parts(&pkg) {
1089        if pkg
1090            .part_string(&part)
1091            .is_some_and(|xml| nests_deeper(&xml, PERMISSIVE_MAX_DEPTH))
1092        {
1093            return Err(ChangeError::Package(format!(
1094                "{part}: XML nesting too deep"
1095            )));
1096        }
1097    }
1098    Ok(pkg)
1099}
1100
1101/// The changes of an opened (transitional) package, as [`list_changes`]
1102/// lists them. A comment-body revision is `comments.rN` (#1706).
1103#[doc(hidden)]
1104pub fn changes_in(pkg: &PartFs) -> Vec<Change> {
1105    let mut out = Vec::new();
1106    for_each_story(pkg, |dom, root, story| {
1107        out.extend(
1108            carriers(dom, root, story)
1109                .into_iter()
1110                .filter_map(|c| c.change),
1111        );
1112    });
1113    out
1114}
1115
1116/// Each listed story's parsed part, in [`list_changes`] order: every
1117/// revision-bearing part, including comment bodies (`comments.rN`).
1118fn for_each_story(pkg: &PartFs, mut each: impl FnMut(&Dom, NodeId, &str)) {
1119    let main = main_part(pkg);
1120    for (part, _) in revision_bearing_parts(pkg) {
1121        let Some(xml) = pkg.part_string(&part) else {
1122            continue;
1123        };
1124        let mut dom = Dom::new();
1125        let doc = dom.parse_xdocument(&xml);
1126        let Some(root) = dom.root(doc) else {
1127            continue;
1128        };
1129        each(&dom, root, &story_id(&main, &part));
1130    }
1131}
1132
1133/// Accept the changes `filter` selects; the others stay tracked. A Strict
1134/// package is written back transitional, as the comparer writes it; with
1135/// nothing selected the bytes come back untouched.
1136///
1137/// # Errors
1138///
1139/// [`ChangeError::InvalidId`] for an id `filter` accepts that is not a
1140/// change id; [`ChangeError::UnknownChange`] for an id not present in the
1141/// document; [`ChangeError::Ambiguous`] for an id that names more than one
1142/// listed change; [`ChangeError::PartOfChange`] when the ids name only some
1143/// of the marks of a logical change ([`list_logical_changes`]), so that it
1144/// would be half settled ([`accept_elements`] settles marks one by one);
1145/// [`ChangeError::Package`] when the package cannot be read or rewritten;
1146/// [`ChangeError::ExposedFinalMark`] when settling the selection would
1147/// leave `w:ins` or `w:del` on a container's final paragraph mark that
1148/// was not already final (#1693).
1149pub fn accept_changes(docx: &[u8], filter: &ChangeFilter) -> Result<Vec<u8>, ChangeError> {
1150    resolve(docx, filter, Resolution::Accept).map(|(document, _, _)| document)
1151}
1152
1153/// Reject the changes `filter` selects; the others stay tracked. A Strict
1154/// package is written back transitional, as [`accept_changes`] writes it.
1155///
1156/// # Errors
1157///
1158/// As [`accept_changes`].
1159pub fn reject_changes(docx: &[u8], filter: &ChangeFilter) -> Result<Vec<u8>, ChangeError> {
1160    resolve(docx, filter, Resolution::Reject).map(|(document, _, _)| document)
1161}
1162
1163/// A resolved document and the comments removed with its revisions.
1164#[derive(Clone, Debug)]
1165pub struct ResolvedChanges {
1166    /// The document after resolving the selected changes.
1167    pub document: Vec<u8>,
1168    /// Removed comments, including replies, with their original ids and text.
1169    /// Surviving comments keep their ids in `document` (#1264).
1170    pub removed_comments: Vec<crate::comments::CommentRecord>,
1171    /// Why each of `removed_comments` went, in its order: `anchor removed
1172    /// by accepting r13`, naming the change that held its mark, or its
1173    /// thread root's (#1159).
1174    pub removed_why: Vec<String>,
1175    /// Tracked changes still inside comment bodies after the resolution.
1176    /// An id, author or kind selection names them as `comments.rN`; one
1177    /// that does not name them leaves them tracked (#1706, #1223).
1178    pub comment_changes_left: usize,
1179    /// Threads rescued onto empty anchors, in source comment ids; the CLI's
1180    /// `--keep-nested-comment` opt-in (#1279). Empty when settlement
1181    /// removed the threads (Word's behaviour, and the default).
1182    pub kept_comments: Vec<crate::comment_settlement::KeptComment>,
1183}
1184
1185/// `anchor removed by accepting r13`: the verb of `resolution`, and the
1186/// change of `changes` (the source's) that held the reference mark of a
1187/// comment of `thread` (the root's first, then each reply's). The change
1188/// must be one the verb removes the content of (a deletion or moved-from
1189/// side accepted, an insertion or moved-to side rejected) and one the pass
1190/// settled: an id of `settled`, or the other side of a move it holds, which
1191/// it names as `settled` does; `None` settled every change. Of changes
1192/// nested in one another the innermost is named. A thread also goes when
1193/// the changes resolved remove all its range's text, its mark outside them
1194/// (Word prunes a dead range): that names no change.
1195pub(crate) fn why_removed(
1196    changes: &[Change],
1197    thread: &[String],
1198    resolution: Resolution,
1199    settled: Option<&[String]>,
1200    wholes: &HashMap<String, String>,
1201) -> String {
1202    let (verb, kind, side) = match resolution {
1203        Resolution::Accept => ("accepting", ChangeKind::Deletion, MoveSide::From),
1204        Resolution::Reject => ("rejecting", ChangeKind::Insertion, MoveSide::To),
1205    };
1206    let removes = |ch: &Change| {
1207        ch.kind == kind || (ch.kind == ChangeKind::Move && ch.move_side == Some(side))
1208    };
1209    // The id the pass selected for `ch`: its own, or its move's other side.
1210    let named = |ch: &Change| -> Option<String> {
1211        let Some(settled) = settled else {
1212            return Some(ch.id.clone());
1213        };
1214        if settled.contains(&ch.id) {
1215            return Some(ch.id.clone());
1216        }
1217        let name = ch.move_name.as_ref()?;
1218        changes
1219            .iter()
1220            .find(|other| {
1221                other.id != ch.id
1222                    && other.move_name.as_ref() == Some(name)
1223                    && settled.contains(&other.id)
1224            })
1225            .map(|other| other.id.clone())
1226    };
1227    let holder = thread.iter().find_map(|c| {
1228        let held: Vec<&Change> = changes
1229            .iter()
1230            .filter(|ch| ch.holds_comments.contains(c) && removes(ch) && named(ch).is_some())
1231            .collect();
1232        held.iter()
1233            .find(|ch| {
1234                !held
1235                    .iter()
1236                    .any(|inner| inner.inside.as_ref() == Some(&ch.id))
1237            })
1238            .and_then(|ch| named(ch))
1239    });
1240    match holder {
1241        Some(change) => format!(
1242            "anchor removed by {verb} {}",
1243            wholes.get(&change).unwrap_or(&change)
1244        ),
1245        None => format!("anchor removed by {verb} the changes that held all its text"),
1246    }
1247}
1248
1249/// Each mark of a change of several marks, by its id, with the id of that
1250/// change: a removed comment's reason names the whole change, as `changes`
1251/// lists it and a selection names it (#1261).
1252pub(crate) fn member_wholes(docx: &[u8]) -> Result<HashMap<String, String>, ChangeError> {
1253    Ok(list_logical_changes_tolerant(docx)?
1254        .into_iter()
1255        .flat_map(|change| {
1256            change
1257                .members
1258                .into_iter()
1259                .map(move |member| (member.id, change.id.clone()))
1260        })
1261        .collect())
1262}
1263
1264/// Accept selected changes and report comments that disappeared with them.
1265///
1266/// # Errors
1267/// As [`accept_changes`], or when the removed comments cannot be read.
1268pub fn accept_changes_with_report(
1269    docx: &[u8],
1270    filter: &ChangeFilter,
1271) -> Result<ResolvedChanges, ChangeError> {
1272    resolve_with_report(docx, filter, Resolution::Accept)
1273}
1274
1275/// Reject selected changes and report comments that disappeared with them.
1276///
1277/// # Errors
1278/// As [`reject_changes`], or when the removed comments cannot be read.
1279pub fn reject_changes_with_report(
1280    docx: &[u8],
1281    filter: &ChangeFilter,
1282) -> Result<ResolvedChanges, ChangeError> {
1283    resolve_with_report(docx, filter, Resolution::Reject)
1284}
1285
1286/// Accept selected changes, keeping wholly removed comment threads on
1287/// empty anchors (#1279). The CLI's `--keep-nested-comment` opt-in; the
1288/// default removes them, as Word does.
1289///
1290/// # Errors
1291/// As [`accept_changes_with_report`].
1292pub fn accept_changes_keeping_comments(
1293    docx: &[u8],
1294    filter: &ChangeFilter,
1295) -> Result<ResolvedChanges, ChangeError> {
1296    resolve_keeping_comments(docx, filter, Resolution::Accept)
1297}
1298
1299/// Reject selected changes, keeping wholly removed comment threads on
1300/// empty anchors (#1279). The CLI's `--keep-nested-comment` opt-in; the
1301/// default removes them, as Word does.
1302///
1303/// # Errors
1304/// As [`reject_changes_with_report`].
1305pub fn reject_changes_keeping_comments(
1306    docx: &[u8],
1307    filter: &ChangeFilter,
1308) -> Result<ResolvedChanges, ChangeError> {
1309    resolve_keeping_comments(docx, filter, Resolution::Reject)
1310}
1311
1312fn resolve_with_report(
1313    docx: &[u8],
1314    filter: &ChangeFilter,
1315    resolution: Resolution,
1316) -> Result<ResolvedChanges, ChangeError> {
1317    let (document, removed, comment_changes_left) = resolve(docx, filter, resolution)?;
1318    let (removed_comments, removed_why) = if removed.is_empty() {
1319        (Vec::new(), Vec::new())
1320    } else {
1321        removed_comment_report(docx, &removed, filter, resolution)?
1322    };
1323    Ok(ResolvedChanges {
1324        document,
1325        removed_comments,
1326        removed_why,
1327        comment_changes_left,
1328        kept_comments: Vec::new(),
1329    })
1330}
1331
1332/// The `removed_comments` / `removed_why` pair for the comment ids
1333/// `removed`: each record (replies included) beside the reason its thread
1334/// went, naming the selected change that held it.
1335fn removed_comment_report(
1336    docx: &[u8],
1337    removed: &[String],
1338    filter: &ChangeFilter,
1339    resolution: Resolution,
1340) -> Result<(Vec<crate::comments::CommentRecord>, Vec<String>), ChangeError> {
1341    let comments =
1342        crate::comments::list_comments_within(docx, crate::admission::InputLimits::compare())
1343            .map_err(|e| ChangeError::Package(e.to_string()))?;
1344    let listed = list_changes_tolerant(docx)?;
1345    let wholes = member_wholes(docx)?;
1346    let filter = filter.normalized()?;
1347    let settled: Vec<String> = listed
1348        .iter()
1349        .filter(|c| filter.matches(c))
1350        .map(|c| c.id.clone())
1351        .collect();
1352    // `removed` keeps each `w:id` as written (`0005`). The reader parsed that
1353    // same id to a number, so match the number, not the spelling.
1354    let removed_ids: HashSet<u32> = removed.iter().filter_map(|id| id.parse().ok()).collect();
1355    let removed_comments: Vec<crate::comments::CommentRecord> = comments
1356        .iter()
1357        .filter(|c| removed_ids.contains(&c.id))
1358        .cloned()
1359        .collect();
1360    // A reply's thread: itself, then each comment it replies to.
1361    let removed_why = removed_comments
1362        .iter()
1363        .map(|c| {
1364            let mut thread = vec![format!("c{}", c.id)];
1365            let mut parent = c.parent;
1366            while let Some(id) = parent.filter(|id| !thread.contains(&format!("c{id}"))) {
1367                thread.push(format!("c{id}"));
1368                parent = comments.iter().find(|p| p.id == id).and_then(|p| p.parent);
1369            }
1370            why_removed(&listed, &thread, resolution, Some(&settled), &wholes)
1371        })
1372        .collect();
1373    Ok((removed_comments, removed_why))
1374}
1375
1376fn resolve(
1377    docx: &[u8],
1378    filter: &ChangeFilter,
1379    resolution: Resolution,
1380) -> Result<(Vec<u8>, Vec<String>, usize), ChangeError> {
1381    resolve_for_edit_or_cli(docx, filter, resolution, None, true)
1382        .map(|out| (out.document, out.removed, out.comment_left))
1383}
1384
1385fn resolve_keeping_comments(
1386    docx: &[u8],
1387    filter: &ChangeFilter,
1388    resolution: Resolution,
1389) -> Result<ResolvedChanges, ChangeError> {
1390    let out = resolve_for_edit_or_cli(docx, filter, resolution, Some(true), true)?;
1391    let document = if out.kept.is_empty() {
1392        out.document
1393    } else {
1394        // Publish the rescued threads on the lowest free comment ids; the
1395        // receipt keeps the source ids (#1279).
1396        let mut pkg = open(&out.document)?;
1397        crate::revision_processor::renumber_rescued_comments(&mut pkg, &out.kept);
1398        pkg.to_zip()
1399            .map_err(|e| ChangeError::Package(e.to_string()))?
1400    };
1401    let (removed_comments, removed_why) = if out.removed.is_empty() {
1402        (Vec::new(), Vec::new())
1403    } else {
1404        removed_comment_report(docx, &out.removed, filter, resolution)?
1405    };
1406    let mut anchors = crate::comment_settlement::AnchorChanges::default();
1407    anchors.extend(Vec::new(), out.kept, resolution, None);
1408    let (_removed_records, kept_comments) = anchors
1409        .records(docx)
1410        .map_err(|e| ChangeError::Package(e.to_string()))?;
1411    Ok(ResolvedChanges {
1412        document,
1413        removed_comments,
1414        removed_why,
1415        comment_changes_left: out.comment_left,
1416        kept_comments,
1417    })
1418}
1419
1420/// Accept the elements `filter` selects, each `w:ins`, `w:del` or other
1421/// mark by its own id ([`list_changes`]), even when it is only part of a
1422/// logical change: for tools that work mark by mark, such as a comparison
1423/// with Word's own handling of each element. [`accept_changes`] refuses
1424/// such a selection.
1425///
1426/// # Errors
1427///
1428/// As [`accept_changes`], but never [`ChangeError::PartOfChange`].
1429pub fn accept_elements(docx: &[u8], filter: &ChangeFilter) -> Result<Vec<u8>, ChangeError> {
1430    resolve_for_edit_or_cli(docx, filter, Resolution::Accept, None, false).map(|out| out.document)
1431}
1432
1433/// Reject the elements `filter` selects, as [`accept_elements`] accepts
1434/// them.
1435///
1436/// # Errors
1437///
1438/// As [`accept_elements`].
1439pub fn reject_elements(docx: &[u8], filter: &ChangeFilter) -> Result<Vec<u8>, ChangeError> {
1440    resolve_for_edit_or_cli(docx, filter, Resolution::Reject, None, false).map(|out| out.document)
1441}
1442
1443/// Serialized document, pruned comment ids, and rescued comment ids.
1444type CommentResolution = (Vec<u8>, Vec<String>, Vec<String>);
1445
1446/// Settlement driven by an edit plan, with stable comment ids and opt-in
1447/// empty anchors. Removed ids come directly from package pruning.
1448#[doc(hidden)]
1449pub fn resolve_for_edit(
1450    docx: &[u8],
1451    filter: &ChangeFilter,
1452    resolution: Resolution,
1453    keep_comments: bool,
1454) -> Result<CommentResolution, ChangeError> {
1455    // The plan's own selection was checked on its source
1456    // ([`check_whole_changes`]); what is left after its accepts may group
1457    // differently.
1458    resolve_for_edit_or_cli(docx, filter, resolution, Some(keep_comments), false)
1459        .map(|out| (out.document, out.removed, out.kept))
1460}
1461
1462fn resolve_for_edit_or_cli(
1463    docx: &[u8],
1464    filter: &ChangeFilter,
1465    resolution: Resolution,
1466    edit: Option<bool>,
1467    whole: bool,
1468) -> Result<ResolutionOutcome, ChangeError> {
1469    let filter = &filter.normalized()?;
1470    let mut pkg = open(docx)?;
1471    let listed = changes_in(&pkg);
1472    filter.check(&listed)?;
1473    if whole && filter.ids.is_some() {
1474        logical::check_whole(filter, &logical_changes_in(&pkg))?;
1475    }
1476    // Comment-body revisions are listed as `comments.rN` and selected like
1477    // every other story (#1706). This count is what a selection leaves in
1478    // the comments part, including when the part is the only story.
1479    let comment_changes = comment_changes_in(&pkg);
1480    // Nothing selected: nothing to resolve, and nothing else to touch.
1481    if !listed
1482        .iter()
1483        .chain(comment_changes.iter())
1484        .any(|c| filter.matches(c))
1485    {
1486        return Ok(ResolutionOutcome {
1487            document: docx.to_vec(),
1488            removed: Vec::new(),
1489            kept: Vec::new(),
1490            comment_left: comment_changes.len(),
1491        });
1492    }
1493    let main = main_part(&pkg);
1494    // An edit plan settles accepts, rejects and its global policy in
1495    // several passes; it judges exposure once, on the settled document
1496    // ([`check_exposed_final_marks`]).
1497    let before_marks = edit.is_none().then(|| exposed_final_marks(&pkg, &main));
1498    let freeze = |part: &str, dom: &mut Dom, root: NodeId| {
1499        let found = carriers(dom, root, &story_id(&main, part));
1500        let selected: HashSet<&Group> = found
1501            .iter()
1502            .filter(|c| c.change.as_ref().is_some_and(|ch| filter.matches(ch)))
1503            .map(|c| &c.group)
1504            .collect();
1505        let with_rows: HashSet<NodeId> = found
1506            .iter()
1507            .filter(|c| selected.contains(&c.group))
1508            .flat_map(|c| final_marks_of_row(dom, c.node))
1509            .collect();
1510        let keep: Vec<NodeId> = found
1511            .iter()
1512            .filter(|c| !selected.contains(&c.group) && !with_rows.contains(&c.node))
1513            .flat_map(|c| {
1514                std::iter::once(c.node)
1515                    .chain(deleted_text(dom, c.node))
1516                    .chain(recorded_marks(dom, c.node))
1517            })
1518            .collect();
1519        for node in keep {
1520            if let Some(name) = dom.name(node) {
1521                dom.set_name(node, XName::get(name.local_name(), FROZEN_NS));
1522            }
1523        }
1524    };
1525    let (removed, kept) = match edit {
1526        Some(keep) => crate::revision_processor::resolve_package_for_edit(
1527            &mut pkg,
1528            resolution,
1529            Some(&freeze),
1530            keep,
1531        ),
1532        None => (
1533            resolve_package(&mut pkg, resolution, Some(&freeze)),
1534            Vec::new(),
1535        ),
1536    };
1537    move_words_past_deleted_tables(&mut pkg, &main);
1538    if let Some(before) = before_marks {
1539        newly_exposed(before, exposed_final_marks(&pkg, &main))?;
1540    }
1541    // The comment-body revisions a selection left tracked (#1223). The
1542    // part may be gone when every comment went.
1543    let comment_left = comment_changes_in(&pkg).len();
1544    let document = pkg
1545        .to_zip()
1546        .map_err(|e| ChangeError::Package(e.to_string()))?;
1547    Ok(ResolutionOutcome {
1548        document,
1549        removed,
1550        kept,
1551        comment_left,
1552    })
1553}
1554
1555/// The same revision on the final marks of the cells `carrier` inserts or
1556/// deletes, when it is a row's (`w:trPr/w:ins`, `w:trPr/w:del`) or a cell's
1557/// (`w:cellIns`, `w:cellDel`), nested tables' cells included. Word writes a
1558/// cell's final mark inserted or deleted only with its row, and a row
1559/// resolved without it leaves the revision on the mark, where Accept All or
1560/// Reject All never returns (#1669): the two resolve together.
1561fn final_marks_of_row(dom: &Dom, carrier: NodeId) -> Vec<NodeId> {
1562    let Some(name) = dom.name(carrier) else {
1563        return Vec::new();
1564    };
1565    let Some(parent) = dom.parent(carrier) else {
1566        return Vec::new();
1567    };
1568    let (kind, top) = match name.local_name() {
1569        kind @ ("ins" | "del") if dom.name_is(parent, &W::tr_pr()) => (kind, dom.parent(parent)),
1570        "cellIns" | "cellDel" if dom.name_is(parent, &W::tc_pr()) => (
1571            if name.local_name() == "cellIns" {
1572                "ins"
1573            } else {
1574                "del"
1575            },
1576            dom.parent(parent),
1577        ),
1578        _ => return Vec::new(),
1579    };
1580    let Some(top) = top else {
1581        return Vec::new();
1582    };
1583    // The cells under `top`, nested tables' too, that no row or cell
1584    // between them and `top` covers by itself (#1684): `top`'s revision is
1585    // the one that covers them. A cell of `top` itself that carries the
1586    // revision (`w:cellIns`, `w:cellDel`) covers its own mark
1587    // (#1680, round 11).
1588    let cell_kind = if kind == "ins" {
1589        W::cell_ins()
1590    } else {
1591        W::cell_del()
1592    };
1593    let covered_below = |cell: NodeId| {
1594        let mut cell = cell;
1595        loop {
1596            if cell == top {
1597                return false;
1598            }
1599            let Some(&row) = dom.ancestors(cell, Some(&W::tr())).first() else {
1600                return false;
1601            };
1602            if row == top {
1603                return dom
1604                    .element(cell, &W::tc_pr())
1605                    .is_some_and(|pr| dom.element(pr, &cell_kind).is_some());
1606            }
1607            if crate::validate_dom::row_revised(dom, row, cell, kind) {
1608                return true;
1609            }
1610            let Some(&outer) = dom.ancestors(row, Some(&W::tc())).first() else {
1611                return false;
1612            };
1613            cell = outer;
1614        }
1615    };
1616    dom.descendants_and_self(top, Some(&W::tc()))
1617        .into_iter()
1618        .filter(|&cell| !covered_below(cell))
1619        .filter_map(|cell| crate::validate_dom::last_block_paragraph(dom, cell))
1620        .filter_map(|p| dom.element(p, &W::p_pr()))
1621        .filter_map(|ppr| dom.element(ppr, &W::r_pr()))
1622        .filter_map(|rpr| dom.element(rpr, &crate::validate_dom::revision_name(kind)))
1623        .collect()
1624}
1625
1626/// Refuse `after` when it holds a final `w:ins` / `w:del` paragraph mark
1627/// that `before` did not: the check an edit plan runs once its accepts,
1628/// rejects and global policy have all settled (#1693, #2096).
1629///
1630/// # Errors
1631///
1632/// [`ChangeError::ExposedFinalMark`] for the first newly exposed mark;
1633/// [`ChangeError::Package`] when either package cannot be read.
1634#[doc(hidden)]
1635pub fn check_exposed_final_marks(before: &[u8], after: &[u8]) -> Result<(), ChangeError> {
1636    let before = open(before)?;
1637    let after = open(after)?;
1638    newly_exposed(
1639        exposed_final_marks(&before, &main_part(&before)),
1640        exposed_final_marks(&after, &main_part(&after)),
1641    )
1642}
1643
1644/// The first of `after` that `before` does not account for. Marks are
1645/// compared as counted keys, not as a set: two cells may carry one `w:id`
1646/// (or none), and one already final must not hide another newly so.
1647fn newly_exposed(before: Vec<ExposedMark>, after: Vec<ExposedMark>) -> Result<(), ChangeError> {
1648    let mut had: HashMap<String, usize> = HashMap::new();
1649    for mark in before {
1650        *had.entry(mark.key).or_default() += 1;
1651    }
1652    for mark in after {
1653        match had.get_mut(&mark.key) {
1654            Some(left) if *left > 0 => *left -= 1,
1655            _ => {
1656                return Err(ChangeError::ExposedFinalMark {
1657                    container: mark.container,
1658                    path: mark.path,
1659                    paragraph: mark.paragraph,
1660                    revision: mark.revision,
1661                    kind: mark.kind,
1662                });
1663            }
1664        }
1665    }
1666    Ok(())
1667}
1668
1669/// A final paragraph mark carrying `w:ins` or `w:del` that no row covers.
1670struct ExposedMark {
1671    key: String,
1672    container: &'static str,
1673    path: String,
1674    paragraph: String,
1675    revision: String,
1676    kind: &'static str,
1677}
1678
1679/// Final `w:ins` / `w:del` marks in `pkg`, one per container that ends on
1680/// them. A cell counts only when its row does not carry the same revision
1681/// ([`crate::validate_dom::uncovered_final_marks`]). The body's, a header's or
1682/// footer's, a note's, a text box's and a comment's last paragraph count
1683/// on their own: Word resolves a body's final mark, so validate does not
1684/// flag it, and a selective pass still must not create one (#1693). Both
1685/// branches of an `mc:AlternateContent` are walked. A final `moveTo` or
1686/// `moveFrom` is not a mark here, and a container whose last block is a
1687/// table has no final paragraph mark.
1688fn exposed_final_marks(pkg: &PartFs, main: &str) -> Vec<ExposedMark> {
1689    let mut out = Vec::new();
1690    for (part, styles) in revision_bearing_parts(pkg) {
1691        if styles {
1692            continue;
1693        }
1694        let Some(xml) = pkg.part_string(&part) else {
1695            continue;
1696        };
1697        let mut dom = Dom::new();
1698        let doc = dom.parse_xdocument(&xml);
1699        let Some(root) = dom.root(doc) else {
1700            continue;
1701        };
1702        let story = story_id(main, &part);
1703        let site = |container: &'static str, node: NodeId| MarkSite {
1704            part: &part,
1705            story: &story,
1706            container,
1707            node,
1708        };
1709        dom.for_each_descendant_element(root, Some(&W::tc()), |cell| {
1710            for (paragraph, kind) in crate::validate_dom::uncovered_final_marks(&dom, cell) {
1711                record_exposed_mark(&mut out, &dom, &site("cell", cell), paragraph, kind);
1712            }
1713        });
1714        if let Some(body) = dom.element(root, &W::body()) {
1715            record_container_mark(&mut out, &dom, &site("body", body));
1716        } else if dom.name_is(root, &W::hdr()) {
1717            record_container_mark(&mut out, &dom, &site("header", root));
1718        } else if dom.name_is(root, &W::ftr()) {
1719            record_container_mark(&mut out, &dom, &site("footer", root));
1720        }
1721        for name in [W::footnote(), W::endnote()] {
1722            dom.for_each_descendant_element(root, Some(&name), |note| {
1723                // Separators and the continuation notice are not content
1724                // notes; the story enumeration skips them too.
1725                let structural = dom.attribute(note, &W::type_()).is_some_and(|kind| {
1726                    matches!(
1727                        kind,
1728                        "separator" | "continuationSeparator" | "continuationNotice"
1729                    )
1730                });
1731                if !structural {
1732                    record_container_mark(&mut out, &dom, &site("note", note));
1733                }
1734            });
1735        }
1736        for name in crate::inspect::text_box_names() {
1737            dom.for_each_descendant_element(root, Some(&name), |text_box| {
1738                record_container_mark(&mut out, &dom, &site("textbox", text_box));
1739            });
1740        }
1741        dom.for_each_descendant_element(root, Some(&W::comment()), |comment| {
1742            record_container_mark(&mut out, &dom, &site("comment", comment));
1743        });
1744    }
1745    out
1746}
1747
1748/// Where a final mark sits: the part, its story, and the container node.
1749struct MarkSite<'a> {
1750    part: &'a str,
1751    story: &'a str,
1752    container: &'static str,
1753    node: NodeId,
1754}
1755
1756/// The last block of `site`, when it is a paragraph whose mark is inserted
1757/// or deleted. A container that ends in a table has no final mark.
1758fn record_container_mark(out: &mut Vec<ExposedMark>, dom: &Dom, site: &MarkSite<'_>) {
1759    let Some(&paragraph) = crate::validate_dom::container_blocks(dom, site.node).last() else {
1760        return;
1761    };
1762    if !dom.name_is(paragraph, &W::p()) {
1763        return;
1764    }
1765    for kind in ["ins", "del"] {
1766        record_exposed_mark(out, dom, site, paragraph, kind);
1767    }
1768}
1769
1770/// Record `paragraph`'s `kind` mark, with or without a `w:id`.
1771fn record_exposed_mark(
1772    out: &mut Vec<ExposedMark>,
1773    dom: &Dom,
1774    site: &MarkSite<'_>,
1775    paragraph: NodeId,
1776    kind: &'static str,
1777) {
1778    let Some(revision) = dom
1779        .element(paragraph, &W::p_pr())
1780        .and_then(|ppr| dom.element(ppr, &W::r_pr()))
1781        .and_then(|rpr| dom.element(rpr, &crate::validate_dom::revision_name(kind)))
1782    else {
1783        return;
1784    };
1785    let wid = dom.attribute(revision, &W::id());
1786    out.push(ExposedMark {
1787        key: format!(
1788            "{}\u{0}{}\u{0}{kind}\u{0}{}",
1789            site.part,
1790            site.container,
1791            wid.unwrap_or_default()
1792        ),
1793        container: site.container,
1794        path: crate::validate::element_path(dom, site.node),
1795        paragraph: crate::validate::element_path(dom, paragraph),
1796        revision: wid.map_or_else(
1797            || "(no w:id)".to_string(),
1798            |wid| crate::ids::ChangeId::new(site.story, wid).short(),
1799        ),
1800        kind,
1801    });
1802}
1803
1804/// The listed changes of the comments part only (empty when the package
1805/// has none). The same changes are in `changes_in` as `comments.rN`.
1806pub fn comment_changes_in(pkg: &PartFs) -> Vec<Change> {
1807    let Some(part) = crate::revision_processor::comments_part(pkg) else {
1808        return Vec::new();
1809    };
1810    let Some(xml) = pkg.part_string(&part) else {
1811        return Vec::new();
1812    };
1813    let mut dom = Dom::new();
1814    let doc = dom.parse_xdocument(&xml);
1815    let Some(root) = dom.root(doc) else {
1816        return Vec::new();
1817    };
1818    carriers(&dom, root, "comments")
1819        .into_iter()
1820        .filter_map(|c| c.change)
1821        .collect()
1822}
1823
1824/// Serialized document, pruned comment ids, rescued comment ids, and the
1825/// comment-body revisions a selection left tracked.
1826struct ResolutionOutcome {
1827    document: Vec<u8>,
1828    removed: Vec<String>,
1829    kept: Vec<String>,
1830    comment_left: usize,
1831}
1832
1833/// The package, Strict normalized to transitional as `inspect` reads it.
1834#[doc(hidden)]
1835pub fn open(docx: &[u8]) -> Result<PartFs, ChangeError> {
1836    crate::admission::admit_package(docx).map_err(|e| ChangeError::Package(e.to_string()))?;
1837    let normalized = crate::strict_translation::strict_to_transitional_docx(docx)
1838        .map_err(|e| ChangeError::Package(e.to_string()))?;
1839    PartFs::open(&normalized).map_err(|e| ChangeError::Package(e.to_string()))
1840}
1841
1842/// A selection can leave a paragraph's inserted words right before a
1843/// deleted table: resolving the deleted mark between them joins the two
1844/// paragraphs. Word 16.115 crashes opening that shape (#1851), so the words
1845/// start the paragraph Accept All joins them to, as compare writes them.
1846/// The story is rewritten only when it holds the shape.
1847fn move_words_past_deleted_tables(pkg: &mut PartFs, main: &str) {
1848    let Some(xml) = pkg.part_string(main) else {
1849        return;
1850    };
1851    let mut dom = Dom::new();
1852    let doc = dom.parse_xdocument(&xml);
1853    let Some(root) = dom.root(doc) else {
1854        return;
1855    };
1856    let shaped = dom.element(root, &W::body()).is_some_and(|body| {
1857        !crate::validate_dom::inserted_text_before_deleted_tables(&dom, body).is_empty()
1858    });
1859    if shaped {
1860        crate::comparer::deleted_tables::move_inserted_text_past_deleted_tables(&mut dom, root);
1861        pkg.set_part(main, dom.serialize_document(doc).into_bytes());
1862    }
1863}
1864
1865fn main_part(pkg: &PartFs) -> String {
1866    pkg.main_document_part()
1867        .unwrap_or_else(|| "word/document.xml".to_string())
1868}
1869
1870/// `body` for the main part, else the part's file stem (`header1`,
1871/// `footnotes`, `comments`, `styles`).
1872fn story_id(main: &str, part: &str) -> String {
1873    if part.trim_start_matches('/') == main.trim_start_matches('/') {
1874        return "body".to_string();
1875    }
1876    crate::ids::part_story(part)
1877}
1878
1879/// The revisions that resolve together: a move's sides and range markers,
1880/// or one element on its own.
1881#[derive(Clone, Debug, PartialEq, Eq, Hash)]
1882enum Group {
1883    Move(String),
1884    Own(NodeId),
1885}
1886
1887/// A revision element: a listed change, or a move range marker.
1888struct Carrier {
1889    node: NodeId,
1890    group: Group,
1891    change: Option<Change>,
1892}
1893
1894/// Formatting changes: each records the properties it replaced.
1895#[doc(hidden)]
1896pub const FORMATTING: &[&str] = &[
1897    "rPrChange",
1898    "pPrChange",
1899    "sectPrChange",
1900    "tblPrChange",
1901    "tblPrExChange",
1902    "tblGridChange",
1903    "trPrChange",
1904    "tcPrChange",
1905    "numberingChange",
1906    "cellMerge",
1907];
1908
1909use crate::util::datetime::revision_date;
1910
1911/// The revision elements under `root`, in document order.
1912fn carriers(dom: &Dom, root: NodeId, story: &str) -> Vec<Carrier> {
1913    let id_attr = W::id();
1914    let name_attr = W::name("name");
1915    // Open move ranges, innermost last: (range id, move name).
1916    let mut open_from: Vec<(String, String)> = Vec::new();
1917    let mut open_to: Vec<(String, String)> = Vec::new();
1918    let mut out = Vec::new();
1919    for e in dom.descendants(root, None) {
1920        let Some(name) = dom.name(e) else {
1921            continue;
1922        };
1923        if name.namespace_name() != W::URI {
1924            continue;
1925        }
1926        let local = name.local_name();
1927        let id = dom.attribute(e, &id_attr).unwrap_or("").to_string();
1928        let kind = match local {
1929            "moveFromRangeStart" | "moveToRangeStart" => {
1930                let move_name = dom
1931                    .attribute(e, &name_attr)
1932                    .map_or_else(|| format!("#{id}"), str::to_string);
1933                let open = if local == "moveFromRangeStart" {
1934                    &mut open_from
1935                } else {
1936                    &mut open_to
1937                };
1938                open.push((id, move_name.clone()));
1939                out.push(Carrier {
1940                    node: e,
1941                    group: Group::Move(move_name),
1942                    change: None,
1943                });
1944                continue;
1945            }
1946            "moveFromRangeEnd" | "moveToRangeEnd" => {
1947                let open = if local == "moveFromRangeEnd" {
1948                    &mut open_from
1949                } else {
1950                    &mut open_to
1951                };
1952                let group = match open.iter().rposition(|(i, _)| *i == id) {
1953                    Some(at) => Group::Move(open.remove(at).1),
1954                    None => Group::Own(e),
1955                };
1956                out.push(Carrier {
1957                    node: e,
1958                    group,
1959                    change: None,
1960                });
1961                continue;
1962            }
1963            _ if in_recorded_properties(dom, e) => continue,
1964            "ins" | "cellIns" => ChangeKind::Insertion,
1965            "del" | "cellDel" => ChangeKind::Deletion,
1966            "moveFrom" | "moveTo" => ChangeKind::Move,
1967            l if FORMATTING.contains(&l) => ChangeKind::Formatting,
1968            _ => continue,
1969        };
1970        let target = target(dom, e, local);
1971        let open = match local {
1972            "moveFrom" => Some((&open_from, "moveFromRangeStart")),
1973            "moveTo" => Some((&open_to, "moveToRangeStart")),
1974            _ => None,
1975        };
1976        let move_name = open.and_then(|(open, start)| {
1977            let enclosing = open.last().map(|(_, n)| n.clone());
1978            if target == "paragraph_mark" {
1979                paragraph_move(dom, e, start).or(enclosing)
1980            } else {
1981                enclosing
1982            }
1983        });
1984        let text = match target {
1985            "paragraph_mark" => String::new(),
1986            "properties" => owner_text(dom, e),
1987            _ => text_of(dom, e),
1988        };
1989        out.push(Carrier {
1990            node: e,
1991            group: move_name.clone().map_or(Group::Own(e), Group::Move),
1992            change: Some(Change {
1993                id: crate::ids::ChangeId::new(story, id.as_str()).short(),
1994                r#ref: crate::ids::ChangeId::new(story, id.as_str()).short(),
1995                kind,
1996                target,
1997                author: dom.attribute(e, &W::author()).map(str::to_string),
1998                date: revision_date(|ns, local| dom.attribute(e, &XName::get(local, ns))),
1999                text,
2000                paragraph: None,
2001                move_name,
2002                move_side: match local {
2003                    "moveFrom" => Some(MoveSide::From),
2004                    "moveTo" => Some(MoveSide::To),
2005                    _ => None,
2006                },
2007                inside: None,
2008                holds_comments: Vec::new(),
2009                members: Vec::new(),
2010            }),
2011        });
2012    }
2013    fold_twins(dom, &mut out);
2014    fold_style_pairs(dom, &mut out);
2015    let ids: HashMap<NodeId, String> = out
2016        .iter()
2017        .filter_map(|c| Some((c.node, c.change.as_ref()?.id.clone())))
2018        .collect();
2019    let paragraphs = (story != "styles").then(|| paragraph_index(dom, root));
2020    for c in &mut out {
2021        if let Some(change) = &mut c.change {
2022            change.holds_comments = held_comment_marks(dom, c.node, change.target);
2023            change.inside = holder(dom, c.node, &ids);
2024            change.paragraph = paragraphs
2025                .as_ref()
2026                .and_then(|index| paragraph_of(dom, c.node, index))
2027                .map(|n| crate::ids::paragraph_id(story, n));
2028        }
2029    }
2030    out
2031}
2032
2033/// The comments whose reference mark the content of change `e` holds
2034/// (`c4`, `c5`), in document order: what resolving the change so its
2035/// content goes removes. A paragraph mark's or formatting change removes
2036/// no content; a row's or cell's change removes the row's or cell's.
2037fn held_comment_marks(dom: &Dom, e: NodeId, target: &str) -> Vec<String> {
2038    let content = match target {
2039        "text" => Some(e),
2040        "table_row" => dom.ancestors(e, Some(&W::tr())).first().copied(),
2041        "table_cell" => dom.ancestors(e, Some(&W::tc())).first().copied(),
2042        _ => None,
2043    };
2044    let mut held = Vec::new();
2045    for mark in content
2046        .map(|c| dom.descendants(c, Some(&W::comment_reference())))
2047        .unwrap_or_default()
2048    {
2049        if let Some(id) = dom.attribute(mark, &W::id()) {
2050            // The comment's own id, as the comment list reads it: a padded
2051            // `w:id` (`0005`) is comment `c5`.
2052            let id = match id.parse::<u32>() {
2053                Ok(number) => format!("c{number}"),
2054                Err(_) => format!("c{id}"),
2055            };
2056            if !held.contains(&id) {
2057                held.push(id);
2058            }
2059        }
2060    }
2061    held
2062}
2063
2064/// Word stores a text box twice, in an `mc:AlternateContent`'s `mc:Choice`
2065/// and its `mc:Fallback`, and gives the Fallback copy of each change its own
2066/// consecutive `w:id`. Each Fallback's carriers pair, in order, with the
2067/// Choice's still-listed carriers of the same kind, target and text (a
2068/// carrier the Choice lacks is skipped, not mispaired): the Choice copy (the
2069/// one the view shows) is listed, and the twin joins its group unlisted, so
2070/// resolving the change resolves both copies. Inner `mc:AlternateContent`s
2071/// pair first, so an outer Fallback meets one listed copy of each nested
2072/// change. A carrier without a partner stays listed.
2073fn fold_twins(dom: &Dom, carriers: &mut [Carrier]) {
2074    let (choice, fallback) = (MC::name("Choice"), MC::name("Fallback"));
2075    // Each listed carrier's mc:Choice / mc:Fallback ancestors.
2076    let branches: Vec<(usize, Vec<NodeId>)> = carriers
2077        .iter()
2078        .enumerate()
2079        .filter(|(_, c)| c.change.is_some())
2080        .map(|(i, c)| {
2081            let mut found = dom.ancestors(c.node, Some(&choice));
2082            found.extend(dom.ancestors(c.node, Some(&fallback)));
2083            (i, found)
2084        })
2085        .filter(|(_, found)| !found.is_empty())
2086        .collect();
2087    let mut fallbacks: Vec<NodeId> = Vec::new();
2088    for (_, found) in &branches {
2089        for &b in found {
2090            if dom.name_is(b, &fallback) && !fallbacks.contains(&b) {
2091                fallbacks.push(b);
2092            }
2093        }
2094    }
2095    // Innermost first.
2096    fallbacks.sort_by_key(|&f| std::cmp::Reverse(dom.ancestors(f, None).len()));
2097    let key = |c: &Carrier| {
2098        c.change
2099            .as_ref()
2100            .map(|ch| (ch.kind, ch.target, ch.text.clone()))
2101    };
2102    for f in fallbacks {
2103        let Some(partner) = dom.parent(f).and_then(|ac| dom.element(ac, &choice)) else {
2104            continue;
2105        };
2106        let under = |b: NodeId, carriers: &[Carrier]| -> Vec<usize> {
2107            branches
2108                .iter()
2109                .filter(|(i, found)| found.contains(&b) && carriers[*i].change.is_some())
2110                .map(|(i, _)| *i)
2111                .collect()
2112        };
2113        let originals = under(partner, carriers);
2114        let mut next = 0;
2115        for twin in under(f, carriers) {
2116            let Some(at) = originals[next..]
2117                .iter()
2118                .position(|&o| key(&carriers[o]) == key(&carriers[twin]))
2119            else {
2120                continue;
2121            };
2122            let original = originals[next + at];
2123            next += at + 1;
2124            carriers[twin].group = carriers[original].group.clone();
2125            carriers[twin].change = None;
2126        }
2127    }
2128}
2129
2130/// Word records a style's paragraph and run formatting changes
2131/// (`w:style/w:pPr/w:pPrChange`, `w:style/w:rPr/w:rPrChange`) under one
2132/// `w:id`: one change. The first is listed; the other joins its group
2133/// unlisted, so resolving it resolves both. Any other record sharing the
2134/// id (a `w:tblStylePr`'s) stays a change of its own.
2135fn fold_style_pairs(dom: &Dom, carriers: &mut [Carrier]) {
2136    let style = W::name("style");
2137    // The style whose own pPr/rPr holds `node`, a pPrChange or rPrChange.
2138    let own_style = |node: NodeId| {
2139        let block = dom.parent(node)?;
2140        let owner = dom.parent(block)?;
2141        let pair = [("pPrChange", "pPr"), ("rPrChange", "rPr")];
2142        let (name, block_name) = (dom.name(node)?, dom.name(block)?);
2143        let shape = (name.local_name(), block_name.local_name());
2144        (pair.contains(&shape) && dom.name_is(owner, &style)).then_some(owner)
2145    };
2146    let mut first: HashMap<(NodeId, String), Group> = HashMap::new();
2147    for c in carriers.iter_mut() {
2148        let Some(change) = &c.change else { continue };
2149        if change.kind != ChangeKind::Formatting {
2150            continue;
2151        }
2152        let Some(owner) = own_style(c.node) else {
2153            continue;
2154        };
2155        let wid = crate::ids::change_id(&change.id).map_or_else(String::new, |c| c.wid);
2156        match first.get(&(owner, wid.clone())) {
2157            Some(group) => {
2158                c.group = group.clone();
2159                c.change = None;
2160            }
2161            None => {
2162                first.insert((owner, wid), c.group.clone());
2163            }
2164        }
2165    }
2166}
2167
2168/// Each listed paragraph of the story under `root` (the body's or a
2169/// header's, footer's or notes part's, as `inspect` numbers them) by node.
2170fn paragraph_index(dom: &Dom, root: NodeId) -> HashMap<NodeId, usize> {
2171    crate::inspect::story_paragraph_nodes(dom, root)
2172        .into_iter()
2173        .enumerate()
2174        .map(|(i, p)| (p, i))
2175        .collect()
2176}
2177
2178/// The paragraph a revision element sits in: the nearest listed paragraph
2179/// around it (a text box's paragraphs are not listed, so its anchor's), or
2180/// the first listed paragraph of the row, cell or table around it.
2181fn paragraph_of(dom: &Dom, e: NodeId, index: &HashMap<NodeId, usize>) -> Option<usize> {
2182    let ancestors = dom.ancestors(e, None);
2183    if let Some(n) = ancestors.iter().find_map(|a| index.get(a)) {
2184        return Some(*n);
2185    }
2186    let holders = [W::tc(), W::tr(), W::tbl()];
2187    std::iter::once(e)
2188        .chain(ancestors)
2189        .filter(|&a| dom.name(a).is_some_and(|n| holders.contains(&n)))
2190        .find_map(|a| {
2191            dom.descendants(a, Some(&W::p()))
2192                .into_iter()
2193                .find_map(|p| index.get(&p).copied())
2194        })
2195}
2196
2197/// True when `e` sits in the properties a formatting change records: a mark
2198/// there is history, part of that change.
2199fn in_recorded_properties(dom: &Dom, e: NodeId) -> bool {
2200    dom.ancestors(e, None).into_iter().any(|a| {
2201        dom.name(a)
2202            .is_some_and(|n| n.namespace_name() == W::URI && FORMATTING.contains(&n.local_name()))
2203    })
2204}
2205
2206/// What a formatting change `e` records: the revision marks inside it (a
2207/// cell's `w:cellIns`, `w:cellDel` or `w:cellMerge` in its `w:tcPrChange`)
2208/// and the one formatting history the schema allows there, a list's
2209/// `w:numberingChange` in its `w:pPrChange`. They sit out with it when it
2210/// stays tracked, or resolving another change would find them live and drop
2211/// or apply them.
2212fn recorded_marks(dom: &Dom, e: NodeId) -> Vec<NodeId> {
2213    if !dom
2214        .name(e)
2215        .is_some_and(|n| FORMATTING.contains(&n.local_name()))
2216    {
2217        return Vec::new();
2218    }
2219    dom.descendants(e, None)
2220        .into_iter()
2221        .filter(|&d| {
2222            dom.name(d).is_some_and(|n| {
2223                n.namespace_name() == W::URI
2224                    && (matches!(
2225                        n.local_name(),
2226                        "ins" | "del" | "moveFrom" | "moveTo" | "cellIns" | "cellDel"
2227                    ) || FORMATTING.contains(&n.local_name()))
2228            })
2229        })
2230        .collect()
2231}
2232
2233/// The move a paragraph mark `e` belongs to: the last range of its side
2234/// (`start`) opening inside its paragraph. Word writes the mark in the
2235/// `pPr`, ahead of the range start of the paragraph it ends.
2236fn paragraph_move(dom: &Dom, e: NodeId, start: &str) -> Option<String> {
2237    let p = dom.ancestors(e, Some(&W::p())).into_iter().next()?;
2238    dom.descendants(p, Some(&W::name(start)))
2239        .into_iter()
2240        .rev()
2241        .find_map(|r| dom.attribute(r, &W::name("name")).map(str::to_string))
2242}
2243
2244/// The id of the innermost change around `e` whose content holds it: an
2245/// ancestor revision element, the row or cell an ancestor `w:tr` / `w:tc`
2246/// marks inserted or deleted, or the mark of the paragraph whose `pPr`
2247/// holds `e` (the paragraph's properties go with its mark).
2248fn holder(dom: &Dom, e: NodeId, ids: &HashMap<NodeId, String>) -> Option<String> {
2249    let (tr, tc, p_pr) = (W::tr(), W::tc(), W::p_pr());
2250    dom.ancestors(e, None).into_iter().find_map(|a| {
2251        if let Some(id) = ids.get(&a) {
2252            return Some(id.clone());
2253        }
2254        let name = dom.name(a)?;
2255        let (props, marks): (XName, &[&str]) = if name == tr {
2256            (W::tr_pr(), &["ins", "del"])
2257        } else if name == tc {
2258            (W::tc_pr(), &["cellIns", "cellDel"])
2259        } else if name == p_pr {
2260            (W::r_pr(), &["ins", "del", "moveFrom", "moveTo"])
2261        } else {
2262            return None;
2263        };
2264        let props = dom.element(a, &props)?;
2265        dom.elements(props, None)
2266            .into_iter()
2267            .filter(|&m| m != e)
2268            .filter(|&m| dom.name(m).is_some_and(|n| marks.contains(&n.local_name())))
2269            .find_map(|m| ids.get(&m).cloned())
2270    })
2271}
2272
2273fn target(dom: &Dom, e: NodeId, local: &str) -> &'static str {
2274    if local.starts_with("cell") {
2275        return "table_cell";
2276    }
2277    if FORMATTING.contains(&local) {
2278        return "properties";
2279    }
2280    let parent = dom.parent(e).and_then(|p| dom.name(p));
2281    let grandparent = dom
2282        .parent(e)
2283        .and_then(|p| dom.parent(p))
2284        .and_then(|g| dom.name(g));
2285    if parent == Some(W::tr_pr()) {
2286        "table_row"
2287    } else if parent == Some(W::r_pr()) && grandparent == Some(W::p_pr()) {
2288        "paragraph_mark"
2289    } else {
2290        "text"
2291    }
2292}
2293
2294/// The `w:delText` / `w:delInstrText` a `w:del` holds itself (not through a
2295/// nested `w:del`): the resolution rewrites deleted text wherever it sits,
2296/// so a kept deletion keeps its text only when that text sits out too.
2297fn deleted_text(dom: &Dom, e: NodeId) -> Vec<NodeId> {
2298    let del = W::del();
2299    if dom.name(e).as_ref() != Some(&del) {
2300        return Vec::new();
2301    }
2302    let (text, instr) = (W::del_text(), W::del_instr_text());
2303    dom.descendants(e, None)
2304        .into_iter()
2305        .filter(|&d| dom.name(d).is_some_and(|n| n == text || n == instr))
2306        .filter(|&d| dom.ancestors(d, Some(&del)).first() == Some(&e))
2307        .collect()
2308}
2309
2310/// Inserted, deleted or moved text under `e`. A tab is `\t` and a break
2311/// is `\n`, in the same order as the text nodes around them. Only a run's
2312/// own `w:tab` and `w:br` count: a tab stop (`w:pPr/w:tabs/w:tab`) is
2313/// layout, not text.
2314fn text_of(dom: &Dom, e: NodeId) -> String {
2315    let (t, del, tab, br, run) = (W::t(), W::del_text(), W::name("tab"), W::name("br"), W::r());
2316    let mut out = String::new();
2317    dom.for_each_descendant_element(e, None, |node| {
2318        let Some(name) = dom.name(node) else {
2319            return;
2320        };
2321        let in_run = || dom.parent(node).is_some_and(|p| dom.name_is(p, &run));
2322        if name == t || name == del {
2323            out.push_str(&dom.value(node));
2324        } else if name == tab && in_run() {
2325            out.push('\t');
2326        } else if name == br && in_run() {
2327            out.push('\n');
2328        }
2329    });
2330    out
2331}
2332
2333/// The text of the run or paragraph whose properties a change records.
2334fn owner_text(dom: &Dom, change: NodeId) -> String {
2335    dom.parent(change)
2336        .and_then(|props| dom.parent(props))
2337        .filter(|&owner| dom.name(owner).is_some_and(|n| n == W::r() || n == W::p()))
2338        .map(|owner| text_of(dom, owner))
2339        .unwrap_or_default()
2340}
2341
2342/// Accept every revision through the processor, rescuing wholly removed
2343/// comment threads onto empty anchors (#1279). The CLI's
2344/// `--keep-nested-comment` opt-in on `convert --track-changes accept`.
2345/// Lives here in the doc layer with the settlement it drives; the
2346/// facade's `document_comparer` module composes it back.
2347///
2348/// # Errors
2349/// Refused input, an unreadable package or unreadable comment records.
2350pub fn accept_revisions_keeping_comments(docx: &[u8]) -> Result<ResolvedChanges, ChangeError> {
2351    accept_changes_keeping_comments(docx, &ChangeFilter::default())
2352}
2353
2354/// Reject every revision through the processor, rescuing wholly removed
2355/// comment threads onto empty anchors (#1279). The CLI's
2356/// `--keep-nested-comment` opt-in on `convert --track-changes reject`.
2357///
2358/// # Errors
2359/// As [`accept_revisions_keeping_comments`].
2360pub fn reject_revisions_keeping_comments(docx: &[u8]) -> Result<ResolvedChanges, ChangeError> {
2361    reject_changes_keeping_comments(docx, &ChangeFilter::default())
2362}
2363
2364#[cfg(test)]
2365#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2366mod run_character_tests {
2367    use super::*;
2368
2369    fn run(inner: &str) -> bool {
2370        let xml = format!(
2371            "<w:r xmlns:w=\"{}\" xmlns:x=\"urn:x\">{inner}</w:r>",
2372            W::URI
2373        );
2374        let mut dom = Dom::new();
2375        let doc = dom.parse_xdocument(&xml);
2376        let root = dom.root(doc).unwrap();
2377        run_has_characters(&dom, root)
2378    }
2379
2380    #[test]
2381    fn a_run_has_characters_only_outside_its_properties() {
2382        assert!(!run(""));
2383        assert!(!run("<w:rPr><w:t>hidden</w:t></w:rPr>"));
2384        assert!(!run("<w:t></w:t><w:delText></w:delText>"));
2385        assert!(run("<w:delText>x</w:delText>"));
2386        assert!(run("<w:tab/>"));
2387        // A foreign wrapper is looked into; a foreign rPr is not properties.
2388        assert!(run("<x:wrap><w:t>x</w:t></x:wrap>"));
2389        assert!(run("<x:rPr><w:t>x</w:t></x:rPr>"));
2390        assert!(!run("<w:lastRenderedPageBreak/>"));
2391        assert_eq!(atom(&XName::get("tab", "urn:x")), None);
2392        assert_eq!(atom(&W::name("sym")), Some('\u{FFFD}'));
2393    }
2394}