Skip to main content

jubarte_doc/debug/
diff.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! `jubarte debug diff A B [C …]`: what differs between two or more
6//! packages, element by element.
7
8use std::collections::HashMap;
9use std::fmt::Write as _;
10
11use super::{Package, WIDTH, clip, clip_from, clip_line, decode_xml, local, story_roles_all};
12use crate::xmllinq::{Dom, NodeId, XName, XNamespace};
13
14/// `jubarte debug diff` options.
15#[derive(Clone, Debug)]
16pub struct DiffOptions {
17    /// Only parts whose name or role contains this.
18    pub part: Option<String>,
19    /// Only the style with this name or id (case-insensitive).
20    pub style: Option<String>,
21    /// Only paragraphs whose text contains this, in any file.
22    pub para_text: Option<String>,
23    /// Keep what the diff drops by default.
24    pub raw: bool,
25    /// Print each shown element's common lines too.
26    pub full: bool,
27    /// Hunks per part (0: all).
28    pub limit: usize,
29}
30
31impl Default for DiffOptions {
32    fn default() -> Self {
33        DiffOptions {
34            part: None,
35            style: None,
36            para_text: None,
37            raw: false,
38            full: false,
39            limit: 60,
40        }
41    }
42}
43
44/// The differences between `files` (label, package bytes), first file first.
45///
46/// Each part becomes a tree whose elements carry a key that names them
47/// across documents: a style by type and name, a paragraph by its text, a
48/// table by its first text, a row by its text, a cell by its position, a
49/// note or comment by its text, a header or footer part by the section role
50/// that shows it. Children align by key (a longest common subsequence,
51/// file by file); within a gap, unmatched elements of one kind pair in
52/// order, so a rewritten paragraph still meets the one it replaced. Each
53/// matched element is a list of lines (property items, run segments), and
54/// a hunk prints the lines not every file holds.
55///
56/// # Errors
57///
58/// `debug diff needs at least two files` when `files` holds fewer than
59/// two; otherwise a message naming which file is not a readable zip.
60pub fn diff(files: &[(&str, &[u8])], opts: &DiffOptions) -> Result<String, String> {
61    if files.len() < 2 {
62        return Err("debug diff needs at least two files".to_string());
63    }
64    let filter = Filter {
65        style: opts.style.as_deref().map(str::to_lowercase),
66        para: opts.para_text.clone(),
67    };
68    let mut trees: Vec<Vec<(String, N)>> = Vec::with_capacity(files.len());
69    for (label, bytes) in files {
70        let pkg = Package::open(bytes).map_err(|e| format!("{label}: {e}"))?;
71        trees.push(package_tree(&pkg, opts, &filter));
72    }
73    let mut keys: Vec<&str> = Vec::new();
74    for t in &trees {
75        for (k, _) in t {
76            if !keys.contains(&k.as_str()) {
77                keys.push(k);
78            }
79        }
80    }
81    let labels: Vec<&str> = files.iter().map(|(l, _)| *l).collect();
82    let mut out = String::new();
83    let _ = writeln!(out, "files: {}", labels.join(" · "));
84    let walker = Walker {
85        labels: &labels,
86        filtered: filter.active(),
87        full: opts.full,
88    };
89    let mut total = 0;
90    for key in keys {
91        let nodes: Vec<Option<&N>> = trees
92            .iter()
93            .map(|t| t.iter().find(|(k, _)| k == key).map(|(_, n)| n))
94            .collect();
95        let mut hunks = Vec::new();
96        walker.walk(
97            &nodes,
98            &vec![true; nodes.len()],
99            &mut Vec::new(),
100            false,
101            &mut hunks,
102        );
103        // --full prints agreeing elements too; only disagreements count.
104        total += hunks.iter().filter(|(_, differs)| *differs).count();
105        let shown = if opts.limit == 0 {
106            hunks.len()
107        } else {
108            opts.limit.min(hunks.len())
109        };
110        for (h, _) in &hunks[..shown] {
111            out.push_str(h);
112        }
113        if shown < hunks.len() {
114            let _ = writeln!(
115                out,
116                "… {} more in {key} (-n 0 prints all)",
117                hunks.len() - shown
118            );
119        }
120    }
121    match total {
122        0 => out.push_str("no differences\n"),
123        1 => out.push_str("1 difference\n"),
124        n => {
125            let _ = writeln!(out, "{n} differences");
126        }
127    }
128    Ok(out)
129}
130
131/// What `--style` and `--para-text` keep.
132struct Filter {
133    /// Lower-cased style name or id.
134    style: Option<String>,
135    para: Option<String>,
136}
137
138impl Filter {
139    fn active(&self) -> bool {
140        self.style.is_some() || self.para.is_some()
141    }
142}
143
144/// One element of a part, normalized.
145struct N {
146    /// Element kind (`p`, `style`, `rPr`, …): unmatched elements of one kind
147    /// pair within a gap.
148    kind: String,
149    /// What names the element across documents.
150    key: String,
151    /// How a hunk's path shows it.
152    label: String,
153    /// Property items, run segments, attributes: what the diff compares.
154    lines: Vec<String>,
155    kids: Vec<N>,
156    /// A property block: a missing one is an empty one, not news.
157    block: bool,
158    /// The filter selects this element (and all below it).
159    hit: bool,
160    /// The filter selects something below it.
161    sub_hit: bool,
162}
163
164impl N {
165    fn new(kind: &str, key: String, label: String) -> Self {
166        N {
167            kind: kind.to_string(),
168            key,
169            label,
170            lines: Vec::new(),
171            kids: Vec::new(),
172            block: false,
173            hit: false,
174            sub_hit: false,
175        }
176    }
177
178    fn with_kids(mut self, kids: Vec<N>) -> Self {
179        self.sub_hit = kids.iter().any(|k| k.hit || k.sub_hit);
180        self.kids = kids;
181        self
182    }
183}
184
185const W_NS: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
186const R_NS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
187const MC_NS: &str = "http://schemas.openxmlformats.org/markup-compatibility/2006";
188
189/// Property blocks: their children are items, compared as a set.
190const BLOCKS: [&str; 10] = [
191    "pPr", "rPr", "tblPr", "trPr", "tcPr", "tblPrEx", "sectPr", "sdtPr", "sdtEndPr", "tblGrid",
192];
193
194/// Property-change records: a block holding the recorded old block.
195const CHANGES: [&str; 9] = [
196    "pPrChange",
197    "rPrChange",
198    "tblPrChange",
199    "tblPrExChange",
200    "trPrChange",
201    "tcPrChange",
202    "sectPrChange",
203    "tblGridChange",
204    "numberingChange",
205];
206
207/// Revision marks and their range markers: their id, author and date are
208/// renumbered and restamped by every save.
209const REVISION_MARKS: [&str; 18] = [
210    "ins",
211    "del",
212    "moveFrom",
213    "moveTo",
214    "cellIns",
215    "cellDel",
216    "cellMerge",
217    "moveFromRangeStart",
218    "moveFromRangeEnd",
219    "moveToRangeStart",
220    "moveToRangeEnd",
221    "customXmlInsRangeStart",
222    "customXmlInsRangeEnd",
223    "customXmlDelRangeStart",
224    "customXmlDelRangeEnd",
225    "customXmlMoveFromRangeStart",
226    "customXmlMoveToRangeStart",
227    "numberingChange",
228];
229
230/// Elements whose `w:id` only links them to a partner Word renumbers.
231const LINK_IDS: [&str; 12] = [
232    "bookmarkStart",
233    "bookmarkEnd",
234    "commentRangeStart",
235    "commentRangeEnd",
236    "commentReference",
237    "comment",
238    "footnoteReference",
239    "endnoteReference",
240    "footnote",
241    "endnote",
242    "permStart",
243    "permEnd",
244];
245
246/// On/off properties: `w:val="1"` is the bare element.
247const TOGGLES: [&str; 48] = [
248    "b",
249    "bCs",
250    "i",
251    "iCs",
252    "caps",
253    "smallCaps",
254    "strike",
255    "dstrike",
256    "outline",
257    "shadow",
258    "emboss",
259    "imprint",
260    "noProof",
261    "snapToGrid",
262    "vanish",
263    "webHidden",
264    "specVanish",
265    "rtl",
266    "cs",
267    "oMath",
268    "keepNext",
269    "keepLines",
270    "pageBreakBefore",
271    "widowControl",
272    "suppressLineNumbers",
273    "suppressAutoHyphens",
274    "kinsoku",
275    "wordWrap",
276    "overflowPunct",
277    "topLinePunct",
278    "autoSpaceDE",
279    "autoSpaceDN",
280    "bidi",
281    "adjustRightInd",
282    "contextualSpacing",
283    "mirrorIndents",
284    "suppressOverlap",
285    "qFormat",
286    "semiHidden",
287    "unhideWhenUsed",
288    "hidden",
289    "locked",
290    "cantSplit",
291    "tblHeader",
292    "noWrap",
293    "titlePg",
294    "bidiVisual",
295    "hideMark",
296];
297
298/// Values naming a style by id: shown by the style's name.
299const STYLE_REFS: [&str; 6] = ["pStyle", "rStyle", "tblStyle", "basedOn", "next", "link"];
300
301/// Each part of `pkg` the options select, keyed by role (headers and
302/// footers) or name, as a tree.
303fn package_tree(pkg: &Package, opts: &DiffOptions, filter: &Filter) -> Vec<(String, N)> {
304    let roles = story_roles_all(pkg);
305    let parse = |data: &[u8]| -> Option<(Dom, NodeId)> {
306        let xml = decode_xml(data)?;
307        std::panic::catch_unwind(|| {
308            let mut dom = Dom::new();
309            let doc = dom.parse_xdocument(&xml);
310            let root = dom.root(doc);
311            (dom, root)
312        })
313        .ok()
314        .and_then(|(dom, root)| root.map(|r| (dom, r)))
315    };
316    let style_names: HashMap<String, String> = pkg
317        .entries
318        .iter()
319        .find(|e| e.name == "word/styles.xml")
320        .and_then(|e| parse(&e.data))
321        .map(|(dom, root)| {
322            dom.elements(root, Some(&XNamespace::get(W_NS).name("style")))
323                .into_iter()
324                .map(|s| {
325                    let id = attr(&dom, s, "styleId");
326                    let name = dom
327                        .element(s, &XNamespace::get(W_NS).name("name"))
328                        .map(|n| attr(&dom, n, "val"))
329                        .unwrap_or_else(|| id.clone());
330                    (id, name)
331                })
332                .collect()
333        })
334        .unwrap_or_default();
335    let mut out = Vec::new();
336    for e in &pkg.entries {
337        if e.name.ends_with('/') {
338            continue;
339        }
340        // A part several sections show pairs under each of their roles.
341        let keys = roles
342            .get(&e.name)
343            .cloned()
344            .unwrap_or_else(|| vec![e.name.clone()]);
345        let xml = e.name.ends_with(".xml") || e.name.ends_with(".rels");
346        let targets = if xml {
347            rel_targets(pkg, &e.name)
348        } else {
349            HashMap::new()
350        };
351        for key in keys {
352            if opts
353                .part
354                .as_ref()
355                .is_some_and(|p| !e.name.contains(p.as_str()) && !key.contains(p.as_str()))
356            {
357                continue;
358            }
359            // The permissive parser forgives what Word rejects (a
360            // mismatched end tag): such a part is reported, not compared.
361            let mut malformed = None;
362            let parsed = if xml {
363                match decode_xml(&e.data).map(|x| crate::xmllinq::parse::validate_xml(&x)) {
364                    Some(Err(err)) => {
365                        malformed = Some(err);
366                        None
367                    }
368                    _ => parse(&e.data),
369                }
370            } else {
371                None
372            };
373            let tree = match parsed {
374                Some((dom, root)) => {
375                    let mut b = Build {
376                        dom: &dom,
377                        raw: opts.raw,
378                        filter,
379                        style_names: &style_names,
380                        targets: &targets,
381                        paras: 0,
382                        tables: 0,
383                    };
384                    let mut n = b.generic(root);
385                    n.key = key.clone();
386                    n.label = key.clone();
387                    n
388                }
389                None => {
390                    let mut n = N::new("bytes", key.clone(), key.clone());
391                    n.lines
392                        .extend(malformed.map(|err| format!("malformed XML: {err}")));
393                    n.lines
394                        .push(format!("{} bytes, fnv {:016x}", e.data.len(), fnv(&e.data)));
395                    n
396                }
397            };
398            out.push((key, tree));
399        }
400    }
401    out
402}
403
404/// What each relationship of `part` points to: an external target as
405/// written, an XML part by name, any other part by a hash of its bytes (so
406/// a renamed copy of the same image is the same target).
407fn rel_targets(pkg: &Package, part: &str) -> HashMap<String, String> {
408    let (dir, file) = part.rsplit_once('/').unwrap_or(("", part));
409    let rels = if dir.is_empty() {
410        format!("_rels/{file}.rels")
411    } else {
412        format!("{dir}/_rels/{file}.rels")
413    };
414    let Some(xml) = pkg
415        .entries
416        .iter()
417        .find(|e| e.name == rels)
418        .and_then(|e| decode_xml(&e.data))
419    else {
420        return HashMap::new();
421    };
422    let mut dom = Dom::new();
423    let doc = dom.parse_xdocument(&xml);
424    let Some(root) = dom.root(doc) else {
425        return HashMap::new();
426    };
427    dom.elements(root, None)
428        .into_iter()
429        .map(|r| {
430            let target = attr(&dom, r, "Target");
431            let shown = if attr(&dom, r, "TargetMode") == "External" {
432                target
433            } else {
434                let joined = match target.strip_prefix('/') {
435                    Some(absolute) => absolute.to_string(),
436                    None if dir.is_empty() => target.clone(),
437                    None => format!("{dir}/{target}"),
438                };
439                let mut segments: Vec<&str> = Vec::new();
440                for s in joined.split('/') {
441                    match s {
442                        ".." => {
443                            segments.pop();
444                        }
445                        "." | "" => {}
446                        _ => segments.push(s),
447                    }
448                }
449                let name = segments.join("/");
450                match pkg.entries.iter().find(|e| e.name == name) {
451                    Some(t) if !name.ends_with(".xml") => format!("#{:016x}", fnv(&t.data)),
452                    _ => name,
453                }
454            };
455            (attr(&dom, r, "Id"), shown)
456        })
457        .collect()
458}
459
460/// FNV-1a: tells binary parts apart.
461fn fnv(data: &[u8]) -> u64 {
462    data.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| {
463        (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
464    })
465}
466
467/// `n`'s attribute with this local name, or "".
468fn attr(dom: &Dom, n: NodeId, name: &str) -> String {
469    dom.attributes(n)
470        .into_iter()
471        .find(|(k, _)| k.local_name() == name && !dom.is_namespace_declaration(k))
472        .map(|(_, v)| v)
473        .unwrap_or_default()
474}
475
476/// Builds one part's tree.
477struct Build<'a> {
478    dom: &'a Dom,
479    raw: bool,
480    filter: &'a Filter,
481    /// Style id → name, from the package's stylesheet.
482    style_names: &'a HashMap<String, String>,
483    /// Relationship id → what it points to, from the part's rels.
484    targets: &'a HashMap<String, String>,
485    /// Paragraphs and tables seen so far: their ordinal in labels.
486    paras: usize,
487    tables: usize,
488}
489
490impl Build<'_> {
491    fn local(&self, n: NodeId) -> String {
492        local(self.dom, n)
493    }
494
495    fn elements(&self, n: NodeId) -> Vec<NodeId> {
496        self.dom
497            .nodes(n)
498            .into_iter()
499            .filter(|&c| self.dom.is_element(c))
500            .collect()
501    }
502
503    /// An attribute the diff drops by default.
504    fn noise(&self, elem: &str, a: &XName) -> bool {
505        if self.dom.is_namespace_declaration(a) {
506            return true;
507        }
508        if self.raw {
509            return false;
510        }
511        let ln = a.local_name();
512        let ns = a.namespace().namespace_name();
513        ln.starts_with("rsid")
514            || (ns == MC_NS && ln == "Ignorable")
515            || (ns != W_NS
516                && matches!(
517                    ln,
518                    "paraId" | "textId" | "durableId" | "dateUtc" | "anchorId" | "editId"
519                ))
520            || (ln == "id"
521                && (REVISION_MARKS.contains(&elem)
522                    || CHANGES.contains(&elem)
523                    || LINK_IDS.contains(&elem)
524                    || matches!(elem, "docPr" | "cNvPr")))
525            || (matches!(ln, "author" | "date")
526                && (REVISION_MARKS.contains(&elem) || CHANGES.contains(&elem)))
527            || (elem == "comment" && matches!(ln, "date" | "initials"))
528            || (elem == "Relationship" && ln == "Id")
529    }
530
531    /// An element the diff drops by default.
532    fn noise_element(&self, parent: &str, name: &str) -> bool {
533        !self.raw
534            && (matches!(
535                name,
536                "nsid" | "tmpl" | "rsid" | "proofErr" | "lastRenderedPageBreak"
537            ) || (parent == "sdtPr" && name == "id")
538                // What every save restamps or recounts in docProps.
539                || (parent == "coreProperties"
540                    && matches!(
541                        name,
542                        "created" | "modified" | "lastModifiedBy" | "revision" | "lastPrinted"
543                    ))
544                || (parent == "Properties"
545                    && matches!(
546                        name,
547                        "Application"
548                            | "AppVersion"
549                            | "TotalTime"
550                            | "Pages"
551                            | "Words"
552                            | "Characters"
553                            | "CharactersWithSpaces"
554                            | "Lines"
555                            | "Paragraphs"
556                            | "HeadingPairs"
557                            | "TitlesOfParts"
558                    )))
559    }
560
561    /// `n`'s namespace when it differs from its parent's and says
562    /// something: any namespace under --raw, else one outside the Office
563    /// vocabularies (Strict and Transitional names compare alike).
564    fn namespace_note(&self, n: NodeId) -> Option<String> {
565        let ns = |id: NodeId| {
566            self.dom
567                .name(id)
568                .map(|x| x.namespace().namespace_name().to_string())
569                .unwrap_or_default()
570        };
571        let own = ns(n);
572        let parent = self
573            .dom
574            .parent(n)
575            .filter(|&p| self.dom.is_element(p))
576            .map(ns)
577            .unwrap_or_default();
578        let office = [
579            "http://schemas.openxmlformats.org/",
580            "http://purl.oclc.org/ooxml/",
581            "http://schemas.microsoft.com/office/",
582            "urn:schemas-microsoft-com:",
583            "http://www.w3.org/",
584            "http://purl.org/dc/",
585        ];
586        (!own.is_empty()
587            && own != parent
588            && (self.raw || !office.iter().any(|o| own.starts_with(o))))
589        .then_some(own)
590    }
591
592    /// The element's attributes, noise dropped, sorted: `k=v`.
593    fn attrs(&self, n: NodeId) -> Vec<(String, String)> {
594        let elem = self.local(n);
595        let mut v: Vec<(String, String)> = self
596            .dom
597            .attributes(n)
598            .into_iter()
599            .filter(|(k, _)| !self.noise(&elem, k))
600            .filter_map(|(k, v)| {
601                if k.namespace().namespace_name() == R_NS {
602                    // A relationship id says where it points; the id
603                    // itself is renumbered by every save. Header and
604                    // footer references pair by section role instead.
605                    let target = self.targets.get(&v);
606                    let v = match (self.raw, target) {
607                        (true, Some(t)) => format!("{v}→{t}"),
608                        (true, None) => v,
609                        (false, Some(t))
610                            if !matches!(elem.as_str(), "headerReference" | "footerReference") =>
611                        {
612                            format!("→{t}")
613                        }
614                        (false, _) => return None,
615                    };
616                    return Some((k.local_name().to_string(), v));
617                }
618                let v = if !self.raw && elem == "Relationship" && k.local_name() == "Type" {
619                    v.rsplit('/').next().unwrap_or(&v).to_string()
620                } else if !self.raw
621                    && k.local_name() == "val"
622                    && STYLE_REFS.contains(&elem.as_str())
623                {
624                    format!("\"{}\"", self.style_names.get(&v).unwrap_or(&v))
625                } else {
626                    v
627                };
628                Some((k.local_name().to_string(), v))
629            })
630            .collect();
631        v.sort();
632        v
633    }
634
635    /// The element's own attributes as one line, `@(k=v,…)`.
636    fn attr_line(&self, n: NodeId) -> Option<String> {
637        let attrs = self.attrs(n);
638        let a: Vec<String> = attrs.iter().map(|(k, v)| format!("{k}={v}")).collect();
639        (!a.is_empty()).then(|| format!("@({})", a.join(",")))
640    }
641
642    /// One element as an item: `name`, `name=val`, `name(k=v,…)`, its own
643    /// children in braces, its text quoted.
644    fn item(&self, c: NodeId) -> String {
645        let local = self.local(c);
646        let name = match self.namespace_note(c) {
647            Some(ns) => format!("{local}<{ns}>"),
648            None => local.clone(),
649        };
650        let attrs = self.attrs(c);
651        let mut s = match attrs.as_slice() {
652            [] => name.clone(),
653            [(k, v)] if k == "val" => match v.as_str() {
654                "true" | "on" if !self.raw => name.clone(),
655                "1" if !self.raw && TOGGLES.contains(&local.as_str()) => name.clone(),
656                "false" | "off" if !self.raw => format!("{name}=0"),
657                _ => format!("{name}={v}"),
658            },
659            _ => {
660                let a: Vec<String> = attrs.iter().map(|(k, v)| format!("{k}={v}")).collect();
661                format!("{name}({})", a.join(","))
662            }
663        };
664        let kids: Vec<String> = self
665            .elements(c)
666            .into_iter()
667            .filter(|&k| !self.noise_element(&local, &self.local(k)))
668            // A text box story is compared as its own node.
669            .map(|k| {
670                if self.local(k) == "txbxContent" {
671                    "txbxContent".to_string()
672                } else {
673                    self.item(k)
674                }
675            })
676            .collect();
677        if !kids.is_empty() {
678            s.push('{');
679            s.push_str(&kids.join(" "));
680            s.push('}');
681        } else {
682            let text: String = self
683                .dom
684                .nodes(c)
685                .into_iter()
686                .filter_map(|t| self.dom.text_value(t))
687                .collect();
688            if !text.trim().is_empty() {
689                let _ = write!(s, " \"{}\"", text.trim());
690            }
691        }
692        s
693    }
694
695    /// A child that becomes a node of its own rather than a line.
696    fn is_node(&self, c: NodeId) -> bool {
697        let l = self.local(c);
698        matches!(
699            l.as_str(),
700            "p" | "tbl"
701                | "sdt"
702                | "style"
703                | "footnote"
704                | "endnote"
705                | "comment"
706                | "body"
707                | "txbxContent"
708        ) || BLOCKS.contains(&l.as_str())
709            || CHANGES.contains(&l.as_str())
710            || !self.elements(c).is_empty()
711    }
712
713    /// Dispatch on the element's kind.
714    fn node(&mut self, e: NodeId) -> Option<N> {
715        let l = self.local(e);
716        match l.as_str() {
717            "style" => Some(self.style(e)),
718            "p" => Some(self.paragraph(e)),
719            "tbl" => Some(self.table(e)),
720            "sdt" => Some(self.sdt(e)),
721            "footnote" | "endnote" | "comment" => Some(self.note(e)),
722            _ if CHANGES.contains(&l.as_str()) => self.change(e),
723            _ if BLOCKS.contains(&l.as_str()) => self.block(e),
724            _ => Some(self.generic(e)),
725        }
726    }
727
728    /// Children as nodes, in order.
729    fn content(&mut self, parent: NodeId) -> Vec<N> {
730        let pl = self.local(parent);
731        let kids: Vec<NodeId> = self
732            .elements(parent)
733            .into_iter()
734            .filter(|&c| !self.noise_element(&pl, &self.local(c)))
735            .collect();
736        kids.into_iter().filter_map(|c| self.node(c)).collect()
737    }
738
739    /// Any element: its attributes and leaf children as lines, the rest as
740    /// nodes. Keyed by name and the first identifying attribute.
741    fn generic(&mut self, e: NodeId) -> N {
742        let name = self.local(e);
743        let attrs = self.attrs(e);
744        let ident = [
745            "abstractNumId",
746            "numId",
747            "ilvl",
748            "type",
749            "name",
750            "PartName",
751            "Extension",
752            "uri",
753        ]
754        .iter()
755        .find_map(|k| attrs.iter().find(|(a, _)| a == k))
756        .map(|(_, v)| v.clone());
757        let label = match &ident {
758            Some(v) => format!("{name} {v}"),
759            None => name.clone(),
760        };
761        let mut n = N::new(&name, label.clone(), label);
762        n.lines
763            .extend(self.namespace_note(e).map(|ns| format!("xmlns={ns}")));
764        n.lines.extend(self.attr_line(e));
765        let text: String = self
766            .dom
767            .nodes(e)
768            .into_iter()
769            .filter_map(|t| self.dom.text_value(t))
770            .collect();
771        if !text.trim().is_empty() {
772            n.lines.push(format!("\"{}\"", text.trim()));
773        }
774        let mut kids = Vec::new();
775        for c in self.elements(e) {
776            if self.noise_element(&name, &self.local(c)) {
777                continue;
778            }
779            if self.is_node(c) {
780                kids.extend(self.node(c));
781            } else {
782                n.lines.push(self.item(c));
783            }
784        }
785        n.with_kids(kids)
786    }
787
788    /// A property block: each child an item, nested blocks and change
789    /// records as nodes. None when empty.
790    fn block(&mut self, e: NodeId) -> Option<N> {
791        let name = self.local(e);
792        let mut n = N::new(&name, name.clone(), name.clone());
793        n.block = true;
794        n.lines.extend(self.attr_line(e));
795        let mut kids = Vec::new();
796        for c in self.elements(e) {
797            let cl = self.local(c);
798            if self.noise_element(&name, &cl) {
799                continue;
800            }
801            let nested = CHANGES.contains(&cl.as_str())
802                || (cl != name && matches!(cl.as_str(), "rPr" | "sectPr" | "pPr"));
803            if nested {
804                kids.extend(self.node(c));
805            } else {
806                n.lines.push(self.item(c));
807            }
808        }
809        n.lines.sort();
810        if n.lines.is_empty() && kids.is_empty() && !self.raw {
811            return None;
812        }
813        Some(n.with_kids(kids))
814    }
815
816    /// A change record: the recorded old block's items.
817    fn change(&mut self, e: NodeId) -> Option<N> {
818        let name = self.local(e);
819        let mut n = N::new(&name, name.clone(), name.clone());
820        n.block = true;
821        n.lines.extend(self.attr_line(e));
822        for old in self.elements(e) {
823            for c in self.elements(old) {
824                n.lines.push(self.item(c));
825            }
826        }
827        n.lines.sort();
828        if n.lines.is_empty() {
829            n.lines.push("(empty)".to_string());
830        }
831        Some(n)
832    }
833
834    fn style(&mut self, s: NodeId) -> N {
835        // An omitted w:type is a paragraph style.
836        let ty = match attr(self.dom, s, "type") {
837            t if t.is_empty() => "paragraph".to_string(),
838            t => t,
839        };
840        let id = attr(self.dom, s, "styleId");
841        let name = self
842            .elements(s)
843            .into_iter()
844            .find(|&c| self.local(c) == "name")
845            .map(|c| attr(self.dom, c, "val"))
846            .unwrap_or_else(|| id.clone());
847        let mut n = N::new(
848            "style",
849            format!("style {ty} \"{}\"", name.to_lowercase()),
850            format!("style {ty} \"{name}\""),
851        );
852        if matches!(attr(self.dom, s, "default").as_str(), "1" | "true") {
853            n.lines.push("default".to_string());
854        }
855        if matches!(attr(self.dom, s, "customStyle").as_str(), "1" | "true") {
856            n.lines.push("customStyle".to_string());
857        }
858        if self.raw {
859            n.lines.push(format!("styleId={id}"));
860        }
861        let mut kids = Vec::new();
862        for c in self.elements(s) {
863            let cl = self.local(c);
864            match cl.as_str() {
865                "name" => {}
866                "tblStylePr" => {
867                    let t = attr(self.dom, c, "type");
868                    let mut k = N::new(
869                        "tblStylePr",
870                        format!("tblStylePr {t}"),
871                        format!("tblStylePr {t}"),
872                    );
873                    let blocks = self.content(c);
874                    k = k.with_kids(blocks);
875                    kids.push(k);
876                }
877                _ if BLOCKS.contains(&cl.as_str()) => kids.extend(self.block(c)),
878                _ if !self.noise_element("style", &cl) => n.lines.push(self.item(c)),
879                _ => {}
880            }
881        }
882        n.hit = self
883            .filter
884            .style
885            .as_ref()
886            .is_some_and(|f| *f == name.to_lowercase() || *f == id.to_lowercase());
887        n.with_kids(kids)
888    }
889
890    fn paragraph(&mut self, p: NodeId) -> N {
891        self.paras += 1;
892        let ord = self.paras;
893        let mut segs: Vec<Seg> = Vec::new();
894        let mut boxes: Vec<NodeId> = Vec::new();
895        self.segments(p, "", &mut segs, &mut boxes);
896        let text: String = segs
897            .iter()
898            .filter(|s| s.text_run)
899            .map(|s| s.text.as_str())
900            .collect();
901        let mut n = N::new(
902            "p",
903            format!("p {text}"),
904            format!("p#{ord} \"{}\"", clip(&text, 40)),
905        );
906        n.lines.extend(self.attr_line(p));
907        n.lines.extend(segs.iter().map(Seg::line));
908        let mut kids = Vec::new();
909        if let Some(ppr) = self
910            .elements(p)
911            .into_iter()
912            .find(|&c| self.local(c) == "pPr")
913        {
914            kids.extend(self.block(ppr));
915        }
916        for (i, b) in boxes.into_iter().enumerate() {
917            let label = format!("txbx {}", i + 1);
918            let content = self.content(b);
919            kids.push(N::new("txbx", label.clone(), label).with_kids(content));
920        }
921        n.hit = self
922            .filter
923            .para
924            .as_ref()
925            .is_some_and(|f| text.contains(f.as_str()));
926        n.with_kids(kids)
927    }
928
929    /// The paragraph content under `n` as run segments, `rev` the revision
930    /// mark around it; text box stories go to `boxes`.
931    fn segments(&self, n: NodeId, rev: &str, segs: &mut Vec<Seg>, boxes: &mut Vec<NodeId>) {
932        for c in self.elements(n) {
933            let l = self.local(c);
934            match l.as_str() {
935                "pPr" => {}
936                "r" => self.run(c, rev, segs, boxes),
937                "ins" | "del" | "moveFrom" | "moveTo" => {
938                    // --raw keeps the mark's id, author and date.
939                    let mark = match self.attr_line(c) {
940                        Some(a) if self.raw => format!("{l}{a}"),
941                        _ => l.clone(),
942                    };
943                    self.segments(c, &mark, segs, boxes);
944                }
945                "hyperlink" => {
946                    // Where the link leads: its anchor or relationship
947                    // target, around the text it covers.
948                    let link = match self.attr_line(c) {
949                        Some(a) => format!("⟨hyperlink{a}⟩"),
950                        None => "⟨hyperlink⟩".to_string(),
951                    };
952                    segs.push(Seg::marker(rev, link));
953                    self.segments(c, rev, segs, boxes);
954                    segs.push(Seg::marker(rev, "⟨/hyperlink⟩".to_string()));
955                }
956                "smartTag" | "customXml" | "sdtContent" | "dir" | "bdo" => {
957                    self.segments(c, rev, segs, boxes);
958                }
959                "sdt" => {
960                    for k in self.elements(c) {
961                        if self.local(k) == "sdtContent" {
962                            self.segments(k, rev, segs, boxes);
963                        }
964                    }
965                }
966                "fldSimple" => {
967                    Seg::push(
968                        segs,
969                        rev,
970                        "",
971                        &format!("{{{}|", attr(self.dom, c, "instr").trim()),
972                        true,
973                    );
974                    self.segments(c, rev, segs, boxes);
975                    Seg::push(segs, rev, "", "}", true);
976                }
977                "oMath" | "oMathPara" => {
978                    let t: String = self
979                        .dom
980                        .descendants(c, None)
981                        .into_iter()
982                        .filter(|&d| self.local(d) == "t")
983                        .map(|d| self.dom.value(d))
984                        .collect();
985                    Seg::push(segs, rev, "", &format!("[math {t}]"), true);
986                }
987                "bookmarkStart" => segs.push(Seg::marker(
988                    rev,
989                    format!("⟨bookmark {}⟩", attr(self.dom, c, "name")),
990                )),
991                "bookmarkEnd" | "commentRangeStart" | "commentRangeEnd" | "proofErr"
992                | "permStart" | "permEnd" | "moveFromRangeStart" | "moveFromRangeEnd"
993                | "moveToRangeStart" | "moveToRangeEnd"
994                    if !self.raw => {}
995                _ => segs.push(Seg::marker(rev, format!("⟨{}⟩", self.item(c)))),
996            }
997        }
998    }
999
1000    fn run(&self, r: NodeId, rev: &str, segs: &mut Vec<Seg>, boxes: &mut Vec<NodeId>) {
1001        let mut fmt = String::new();
1002        let mut text = String::new();
1003        for c in self.elements(r) {
1004            let l = self.local(c);
1005            match l.as_str() {
1006                "rPr" => {
1007                    let mut items = Vec::new();
1008                    let mut was = None;
1009                    for k in self.elements(c) {
1010                        let kl = self.local(k);
1011                        if kl == "rPrChange" {
1012                            let old: Vec<String> = self
1013                                .elements(k)
1014                                .into_iter()
1015                                .flat_map(|o| self.elements(o))
1016                                .map(|o| self.item(o))
1017                                .collect();
1018                            was = Some(old.join(" "));
1019                        } else if !self.noise_element("rPr", &kl) {
1020                            items.push(self.item(k));
1021                        }
1022                    }
1023                    items.sort();
1024                    fmt = items.join(" ");
1025                    if let Some(w) = was {
1026                        let _ = write!(fmt, "{}was{{{w}}}", if fmt.is_empty() { "" } else { " " });
1027                    }
1028                }
1029                "t" | "delText" => text.push_str(&self.dom.value(c)),
1030                "instrText" | "delInstrText" => text.push_str(&self.dom.value(c)),
1031                "fldChar" => text.push_str(match attr(self.dom, c, "fldCharType").as_str() {
1032                    "begin" => "{",
1033                    "separate" => "|",
1034                    "end" => "}",
1035                    _ => "",
1036                }),
1037                "tab" | "ptab" => text.push('⇥'),
1038                "br" if attr(self.dom, c, "type") == "page" => text.push('⤓'),
1039                "br" | "cr" => text.push('↵'),
1040                "noBreakHyphen" => text.push('‑'),
1041                "softHyphen" => text.push('¬'),
1042                "lastRenderedPageBreak" if !self.raw => {}
1043                "drawing" | "pict" | "object" | "AlternateContent" => {
1044                    // Placement, extent, crop and target are the drawing's
1045                    // items; its text box stories are nodes of their own.
1046                    Seg::push(segs, rev, &fmt, &std::mem::take(&mut text), true);
1047                    segs.push(Seg {
1048                        rev: rev.to_string(),
1049                        fmt: fmt.clone(),
1050                        text: format!("[{}]", self.item(c)),
1051                        text_run: false,
1052                    });
1053                    for d in self.dom.descendants(c, None) {
1054                        if self.local(d) == "txbxContent"
1055                            && !self
1056                                .dom
1057                                .ancestors(d, None)
1058                                .into_iter()
1059                                .take_while(|&a| a != c)
1060                                .any(|a| {
1061                                    self.local(a) == "Fallback" || self.local(a) == "txbxContent"
1062                                })
1063                        {
1064                            boxes.push(d);
1065                        }
1066                    }
1067                }
1068                _ => {
1069                    let _ = write!(text, "[{}]", self.item(c));
1070                }
1071            }
1072        }
1073        Seg::push(segs, rev, &fmt, &text, true);
1074    }
1075
1076    fn table(&mut self, t: NodeId) -> N {
1077        self.tables += 1;
1078        let ord = self.tables;
1079        let first: String = self
1080            .dom
1081            .descendants(t, None)
1082            .into_iter()
1083            .filter(|&d| self.local(d) == "t")
1084            .map(|d| self.dom.value(d))
1085            .take(8)
1086            .collect();
1087        let mut n = N::new(
1088            "tbl",
1089            format!("tbl {}", clip(&first, 60)),
1090            format!("tbl#{ord} \"{}\"", clip(&first, 30)),
1091        );
1092        let mut kids = Vec::new();
1093        let mut row = 0;
1094        for c in self.elements(t) {
1095            match self.local(c).as_str() {
1096                "tr" => {
1097                    row += 1;
1098                    kids.push(self.row(c, row));
1099                }
1100                _ => kids.extend(self.node(c)),
1101            }
1102        }
1103        n.lines.clear();
1104        n.with_kids(kids)
1105    }
1106
1107    fn row(&mut self, tr: NodeId, i: usize) -> N {
1108        let text: String = self
1109            .dom
1110            .descendants(tr, None)
1111            .into_iter()
1112            .filter(|&d| matches!(self.local(d).as_str(), "t" | "delText"))
1113            .map(|d| self.dom.value(d))
1114            .collect();
1115        let n = N::new(
1116            "tr",
1117            format!("tr {text}"),
1118            format!("tr {i} \"{}\"", clip(&text, 30)),
1119        );
1120        let mut kids = Vec::new();
1121        let mut cell = 0;
1122        for c in self.elements(tr) {
1123            match self.local(c).as_str() {
1124                "tc" => {
1125                    cell += 1;
1126                    let label = format!("tc {cell}");
1127                    let content = self.content(c);
1128                    kids.push(N::new("tc", label.clone(), label).with_kids(content));
1129                }
1130                _ => kids.extend(self.node(c)),
1131            }
1132        }
1133        n.with_kids(kids)
1134    }
1135
1136    fn sdt(&mut self, s: NodeId) -> N {
1137        let find = |b: &Self, name: &str| -> String {
1138            b.dom
1139                .descendants(s, None)
1140                .into_iter()
1141                .find(|&d| b.local(d) == name)
1142                .map(|d| attr(b.dom, d, "val"))
1143                .unwrap_or_default()
1144        };
1145        let tag = find(self, "tag");
1146        let tag = if tag.is_empty() {
1147            find(self, "alias")
1148        } else {
1149            tag
1150        };
1151        let label = format!("sdt \"{tag}\"");
1152        let n = N::new("sdt", label.clone(), label);
1153        let mut kids = Vec::new();
1154        for c in self.elements(s) {
1155            if self.local(c) == "sdtContent" {
1156                kids.extend(self.content(c));
1157            } else {
1158                kids.extend(self.node(c));
1159            }
1160        }
1161        n.with_kids(kids)
1162    }
1163
1164    /// A footnote, endnote or comment, keyed by its text.
1165    fn note(&mut self, e: NodeId) -> N {
1166        let name = self.local(e);
1167        let text: String = self
1168            .dom
1169            .descendants(e, None)
1170            .into_iter()
1171            .filter(|&d| matches!(self.local(d).as_str(), "t" | "delText"))
1172            .map(|d| self.dom.value(d))
1173            .collect();
1174        let ty = attr(self.dom, e, "type");
1175        let label = if ty.is_empty() || ty == "normal" {
1176            format!("{name} \"{}\"", clip(&text, 30))
1177        } else {
1178            format!("{name} {ty}")
1179        };
1180        let mut n = N::new(&name, format!("{name} {ty} {text}"), label);
1181        n.lines.extend(self.attr_line(e));
1182        let content = self.content(e);
1183        n.with_kids(content)
1184    }
1185}
1186
1187/// A run of paragraph content: its revision mark, formatting and text.
1188struct Seg {
1189    rev: String,
1190    fmt: String,
1191    text: String,
1192    /// Text that joins its neighbours formatted alike (a marker does not).
1193    text_run: bool,
1194}
1195
1196impl Seg {
1197    fn push(segs: &mut Vec<Seg>, rev: &str, fmt: &str, text: &str, text_run: bool) {
1198        if text.is_empty() {
1199            return;
1200        }
1201        if let Some(last) = segs.last_mut()
1202            && last.text_run
1203            && last.rev == rev
1204            && last.fmt == fmt
1205        {
1206            last.text.push_str(text);
1207            return;
1208        }
1209        segs.push(Seg {
1210            rev: rev.to_string(),
1211            fmt: fmt.to_string(),
1212            text: text.to_string(),
1213            text_run,
1214        });
1215    }
1216
1217    fn marker(rev: &str, text: String) -> Seg {
1218        Seg {
1219            rev: rev.to_string(),
1220            fmt: String::new(),
1221            text,
1222            text_run: false,
1223        }
1224    }
1225
1226    fn line(&self) -> String {
1227        let mut s = String::new();
1228        if !self.rev.is_empty() {
1229            let _ = write!(s, "{}: ", self.rev);
1230        }
1231        if self.text_run {
1232            let _ = write!(s, "\"{}\"", self.text);
1233        } else {
1234            s.push_str(&self.text);
1235        }
1236        if !self.fmt.is_empty() {
1237            let _ = write!(s, " [{}]", self.fmt);
1238        }
1239        s
1240    }
1241}
1242
1243/// Walks aligned trees and writes hunks.
1244struct Walker<'a> {
1245    labels: &'a [&'a str],
1246    filtered: bool,
1247    full: bool,
1248}
1249
1250impl Walker<'_> {
1251    /// `nodes`: one element per file (None: absent); `parents`: whether each
1252    /// file holds the parent (a file without it says nothing here).
1253    fn walk(
1254        &self,
1255        nodes: &[Option<&N>],
1256        parents: &[bool],
1257        path: &mut Vec<String>,
1258        in_scope: bool,
1259        hunks: &mut Vec<(String, bool)>,
1260    ) {
1261        let hit = nodes.iter().flatten().any(|n| n.hit);
1262        let sub = nodes.iter().flatten().any(|n| n.sub_hit);
1263        if self.filtered && !in_scope && !hit && !sub {
1264            return;
1265        }
1266        let scope = !self.filtered || in_scope || hit;
1267        let Some(first) = nodes.iter().flatten().next() else {
1268            return;
1269        };
1270        let pushed = !first.label.is_empty();
1271        if pushed {
1272            path.push(first.label.clone());
1273        }
1274        if scope && let Some(h) = self.hunk(nodes, parents, path) {
1275            hunks.push(h);
1276        }
1277        let present: Vec<bool> = nodes.iter().map(Option::is_some).collect();
1278        let lists: Vec<&[N]> = nodes
1279            .iter()
1280            .map(|n| n.map_or(&[][..], |n| n.kids.as_slice()))
1281            .collect();
1282        for slot in align(&lists) {
1283            self.walk(&slot, &present, path, scope && self.filtered, hunks);
1284        }
1285        if pushed {
1286            path.pop();
1287        }
1288    }
1289
1290    /// The hunk for one aligned element and whether the files disagree on
1291    /// it, or None when every file holding its parent agrees on it and
1292    /// --full is off.
1293    fn hunk(
1294        &self,
1295        nodes: &[Option<&N>],
1296        parents: &[bool],
1297        path: &[String],
1298    ) -> Option<(String, bool)> {
1299        let block = nodes.iter().flatten().any(|n| n.block);
1300        let absent: Vec<usize> = (0..nodes.len())
1301            .filter(|&i| parents[i] && nodes[i].is_none())
1302            .collect();
1303        let mut order: Vec<&str> = Vec::new();
1304        let mut counts: Vec<HashMap<&str, usize>> = vec![HashMap::new(); nodes.len()];
1305        for (i, n) in nodes.iter().enumerate() {
1306            for l in n.iter().flat_map(|n| n.lines.iter()) {
1307                *counts[i].entry(l.as_str()).or_default() += 1;
1308                if !order.contains(&l.as_str()) {
1309                    order.push(l);
1310                }
1311            }
1312        }
1313        // A file without the element holds none of its lines.
1314        let active: Vec<usize> = (0..nodes.len()).collect();
1315        let count = |i: usize, l: &str| counts[i].get(l).copied().unwrap_or(0);
1316        let differs = |l: &str| {
1317            let c0 = count(active[0], l);
1318            active.iter().any(|&i| count(i, l) != c0)
1319        };
1320        let diff_lines: Vec<&str> = order.iter().copied().filter(|l| differs(l)).collect();
1321        let show_absent = !block && !absent.is_empty();
1322        if diff_lines.is_empty() && !show_absent && (!self.full || order.is_empty()) {
1323            return None;
1324        }
1325        let mut out = format!("{}\n", path.join(" › "));
1326        if show_absent {
1327            let names: Vec<&str> = absent.iter().map(|&i| self.labels[i]).collect();
1328            let _ = writeln!(out, "  (absent) [{}]", names.join(" "));
1329        }
1330        let rows: Vec<(char, &str)> = order
1331            .iter()
1332            .copied()
1333            .filter(|l| self.full || differs(l))
1334            .map(|l| {
1335                let mark = if !differs(l) {
1336                    ' '
1337                } else if count(0, l) > 0 {
1338                    '-'
1339                } else {
1340                    '+'
1341                };
1342                (mark, l)
1343            })
1344            .collect();
1345        let shown: Vec<String> = rows
1346            .iter()
1347            .map(|(m, l)| {
1348                if *m == ' ' {
1349                    return clip_line(l);
1350                }
1351                // Past the width, show where this line parts from the others.
1352                let common = diff_lines
1353                    .iter()
1354                    .filter(|o| **o != *l)
1355                    .map(|o| l.chars().zip(o.chars()).take_while(|(a, b)| a == b).count())
1356                    .max()
1357                    .unwrap_or(0);
1358                if common > WIDTH.saturating_sub(60) {
1359                    clip_line(&clip_from(l, common.saturating_sub(40)))
1360                } else {
1361                    clip_line(l)
1362                }
1363            })
1364            .collect();
1365        let tagged = self.labels.len() > 2;
1366        let pad = shown
1367            .iter()
1368            .map(|s| s.chars().count())
1369            .max()
1370            .unwrap_or(0)
1371            .min(70);
1372        for ((mark, l), s) in rows.iter().zip(&shown) {
1373            if tagged && *mark != ' ' {
1374                let tags: Vec<String> = active
1375                    .iter()
1376                    .filter(|&&i| count(i, l) > 0)
1377                    .map(|&i| match count(i, l) {
1378                        1 => self.labels[i].to_string(),
1379                        n => format!("{}×{n}", self.labels[i]),
1380                    })
1381                    .collect();
1382                let w = s.chars().count();
1383                let _ = writeln!(
1384                    out,
1385                    "  {mark} {s}{}  [{}]",
1386                    " ".repeat(pad.saturating_sub(w)),
1387                    tags.join(" ")
1388                );
1389            } else {
1390                let _ = writeln!(out, "  {mark} {s}");
1391            }
1392        }
1393        Some((out, !diff_lines.is_empty() || show_absent))
1394    }
1395}
1396
1397/// Content kinds: they align in document order, and within a gap an
1398/// unmatched one pairs with an unmatched one of its kind (a rewritten
1399/// paragraph meets the one it replaced). Every other kind is named by its
1400/// key alone and matches it wherever it stands.
1401const SEQUENCE: [&str; 9] = [
1402    "p", "tbl", "tr", "sdt", "footnote", "endnote", "comment", "txbx", "bytes",
1403];
1404
1405/// Align each file's children: slots of one element per file.
1406fn align<'n>(lists: &[&'n [N]]) -> Vec<Vec<Option<&'n N>>> {
1407    let k = lists.len();
1408    let is_seq = |n: &N| SEQUENCE.contains(&n.kind.as_str());
1409    let mut slots: Vec<Vec<Option<&'n N>>> = Vec::new();
1410    for (f, list) in lists.iter().enumerate() {
1411        let rep = |s: &Vec<Option<&'n N>>| -> &'n N {
1412            s.iter()
1413                .flatten()
1414                .next()
1415                .copied()
1416                .expect("a slot holds an element")
1417        };
1418        let fresh = |n: &'n N| {
1419            let mut s = vec![None; k];
1420            s[f] = Some(n);
1421            s
1422        };
1423        // Content: an LCS over the content slots, gaps paired by kind.
1424        let seq_slots: Vec<usize> = (0..slots.len())
1425            .filter(|&i| is_seq(rep(&slots[i])))
1426            .collect();
1427        let seq_items: Vec<&'n N> = list.iter().filter(|n| is_seq(n)).collect();
1428        let skeys: Vec<&str> = seq_slots
1429            .iter()
1430            .map(|&i| rep(&slots[i]).key.as_str())
1431            .collect();
1432        let fkeys: Vec<&str> = seq_items.iter().map(|n| n.key.as_str()).collect();
1433        // New content slots, by the content slot they follow (None: first).
1434        let mut after: HashMap<Option<usize>, Vec<&'n N>> = HashMap::new();
1435        let mut last: Option<usize> = None;
1436        let (mut gap_s, mut gap_f): (Vec<usize>, Vec<&'n N>) = (Vec::new(), Vec::new());
1437        let mut flush = |gap_s: &mut Vec<usize>,
1438                         gap_f: &mut Vec<&'n N>,
1439                         slots: &mut Vec<Vec<Option<&'n N>>>,
1440                         last: Option<usize>| {
1441            let mut used = vec![false; gap_f.len()];
1442            let mut next = 0;
1443            for &si in gap_s.iter() {
1444                let kind = rep(&slots[si]).kind.clone();
1445                if let Some(j) = (next..gap_f.len()).find(|&j| gap_f[j].kind == kind) {
1446                    slots[si][f] = Some(gap_f[j]);
1447                    used[j] = true;
1448                    next = j + 1;
1449                }
1450            }
1451            let tail = gap_s.last().copied().or(last);
1452            for (j, n) in gap_f.iter().enumerate() {
1453                if !used[j] {
1454                    after.entry(tail).or_default().push(n);
1455                }
1456            }
1457            gap_s.clear();
1458            gap_f.clear();
1459        };
1460        for op in lcs_ops(&skeys, &fkeys) {
1461            match op {
1462                (Some(i), Some(j)) => {
1463                    flush(&mut gap_s, &mut gap_f, &mut slots, last);
1464                    slots[seq_slots[i]][f] = Some(seq_items[j]);
1465                    last = Some(seq_slots[i]);
1466                }
1467                (Some(i), None) => gap_s.push(seq_slots[i]),
1468                (None, Some(j)) => gap_f.push(seq_items[j]),
1469                (None, None) => {}
1470            }
1471        }
1472        flush(&mut gap_s, &mut gap_f, &mut slots, last);
1473        // Everything else: by key, the n-th of a key with the n-th.
1474        let mut by_key: HashMap<&str, Vec<usize>> = HashMap::new();
1475        for i in (0..slots.len()).rev() {
1476            if !is_seq(rep(&slots[i])) && slots[i][f].is_none() {
1477                by_key
1478                    .entry(rep(&slots[i]).key.as_str())
1479                    .or_default()
1480                    .push(i);
1481            }
1482        }
1483        let mut unmatched = Vec::new();
1484        for n in list.iter().filter(|n| !is_seq(n)) {
1485            match by_key.get_mut(n.key.as_str()).and_then(Vec::pop) {
1486                Some(i) => slots[i][f] = Some(n),
1487                None => unmatched.push(n),
1488            }
1489        }
1490        let old = std::mem::take(&mut slots);
1491        slots.extend(
1492            after
1493                .remove(&None)
1494                .unwrap_or_default()
1495                .into_iter()
1496                .map(fresh),
1497        );
1498        for (i, s) in old.into_iter().enumerate() {
1499            slots.push(s);
1500            slots.extend(
1501                after
1502                    .remove(&Some(i))
1503                    .unwrap_or_default()
1504                    .into_iter()
1505                    .map(fresh),
1506            );
1507        }
1508        slots.extend(unmatched.into_iter().map(fresh));
1509    }
1510    slots
1511}
1512
1513/// An edit script between `a` and `b`: `(Some(i), Some(j))` a match,
1514/// `(Some(i), None)` only in `a`, `(None, Some(j))` only in `b`. A longest
1515/// common subsequence; past the size an LCS affords, a greedy in-order
1516/// match by key.
1517fn lcs_ops(a: &[&str], b: &[&str]) -> Vec<(Option<usize>, Option<usize>)> {
1518    let pre = a.iter().zip(b).take_while(|(x, y)| x == y).count();
1519    let suf = a[pre..]
1520        .iter()
1521        .rev()
1522        .zip(b[pre..].iter().rev())
1523        .take_while(|(x, y)| x == y)
1524        .count();
1525    let (n, m) = (a.len() - pre - suf, b.len() - pre - suf);
1526    let mut ops: Vec<(Option<usize>, Option<usize>)> =
1527        (0..pre).map(|i| (Some(i), Some(i))).collect();
1528    if n.saturating_mul(m) > 4_000_000 {
1529        let mut by_key: HashMap<&str, Vec<usize>> = HashMap::new();
1530        for j in (pre..pre + m).rev() {
1531            by_key.entry(b[j]).or_default().push(j);
1532        }
1533        let mut next_j = pre;
1534        for (i, key) in a.iter().enumerate().skip(pre).take(n) {
1535            let hit = by_key.get_mut(key).and_then(|v| {
1536                while v.last().is_some_and(|&j| j < next_j) {
1537                    v.pop();
1538                }
1539                v.pop()
1540            });
1541            match hit {
1542                Some(j) => {
1543                    ops.extend((next_j..j).map(|x| (None, Some(x))));
1544                    ops.push((Some(i), Some(j)));
1545                    next_j = j + 1;
1546                }
1547                None => ops.push((Some(i), None)),
1548            }
1549        }
1550        ops.extend((next_j..pre + m).map(|x| (None, Some(x))));
1551    } else {
1552        let w = m + 1;
1553        let mut lcs = vec![0u32; (n + 1) * w];
1554        for i in (0..n).rev() {
1555            for j in (0..m).rev() {
1556                lcs[i * w + j] = if a[pre + i] == b[pre + j] {
1557                    lcs[(i + 1) * w + j + 1] + 1
1558                } else {
1559                    lcs[(i + 1) * w + j].max(lcs[i * w + j + 1])
1560                };
1561            }
1562        }
1563        let (mut i, mut j) = (0, 0);
1564        while i < n || j < m {
1565            if i < n && j < m && a[pre + i] == b[pre + j] {
1566                ops.push((Some(pre + i), Some(pre + j)));
1567                i += 1;
1568                j += 1;
1569            } else if j == m || (i < n && lcs[(i + 1) * w + j] >= lcs[i * w + j + 1]) {
1570                ops.push((Some(pre + i), None));
1571                i += 1;
1572            } else {
1573                ops.push((None, Some(pre + j)));
1574                j += 1;
1575            }
1576        }
1577    }
1578    let (sa, sb) = (a.len() - suf, b.len() - suf);
1579    ops.extend((0..suf).map(|x| (Some(sa + x), Some(sb + x))));
1580    ops
1581}
1582
1583#[cfg(test)]
1584#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1585mod tests {
1586    use super::*;
1587    use std::io::{Cursor, Write};
1588
1589    const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
1590    const TYPES: &str = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/></Types>"#;
1591    const ROOT_RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
1592
1593    /// A package with `body` (inside `w:body`), a stylesheet holding `styles`
1594    /// and, when given, a default header part `header` named `hdr_name`.
1595    fn docx(body: &str, styles: &str, header: Option<(&str, &str)>) -> Vec<u8> {
1596        let mut rels = String::from(
1597            r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>"#,
1598        );
1599        let mut sect = String::new();
1600        if let Some((name, _)) = header {
1601            rels.push_str(&format!(
1602                r#"<Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="{name}"/>"#
1603            ));
1604            sect = r#"<w:sectPr><w:headerReference w:type="default" r:id="rId9"/></w:sectPr>"#
1605                .to_string();
1606        }
1607        rels.push_str("</Relationships>");
1608        let document = format!(
1609            r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="{W}" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml"><w:body>{body}{sect}</w:body></w:document>"#
1610        );
1611        let styles = format!(r#"<w:styles xmlns:w="{W}">{styles}</w:styles>"#);
1612        let mut entries: Vec<(String, String)> = vec![
1613            ("[Content_Types].xml".into(), TYPES.into()),
1614            ("_rels/.rels".into(), ROOT_RELS.into()),
1615            ("word/document.xml".into(), document),
1616            ("word/_rels/document.xml.rels".into(), rels),
1617            ("word/styles.xml".into(), styles),
1618        ];
1619        if let Some((name, xml)) = header {
1620            entries.push((
1621                format!("word/{name}"),
1622                format!(r#"<w:hdr xmlns:w="{W}">{xml}</w:hdr>"#),
1623            ));
1624        }
1625        let mut buf = Cursor::new(Vec::new());
1626        {
1627            let mut z = zip::ZipWriter::new(&mut buf);
1628            let opt = zip::write::SimpleFileOptions::default();
1629            for (name, data) in &entries {
1630                z.start_file(name.as_str(), opt).unwrap();
1631                z.write_all(data.as_bytes()).unwrap();
1632            }
1633            z.finish().unwrap();
1634        }
1635        buf.into_inner()
1636    }
1637
1638    fn body_text(id: &str, name: &str, rpr: &str) -> String {
1639        format!(
1640            r#"<w:style w:type="paragraph" w:styleId="{id}"><w:name w:val="{name}"/><w:basedOn w:val="Normal"/><w:rPr>{rpr}</w:rPr></w:style><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>"#
1641        )
1642    }
1643
1644    fn run(files: &[(&str, &[u8])], opts: &DiffOptions) -> String {
1645        diff(files, opts).unwrap()
1646    }
1647
1648    /// Styles pair by type and name, not by id; each hunk names the style
1649    /// and the block, and prints only the items that differ.
1650    #[test]
1651    fn styles_pair_by_name_and_print_only_their_differing_items() {
1652        let a = docx(
1653            "",
1654            &body_text(
1655                "BodyText",
1656                "Body Text",
1657                r#"<w:rFonts w:ascii="Arial"/><w:b/>"#,
1658            ),
1659            None,
1660        );
1661        let b = docx(
1662            "",
1663            &body_text(
1664                "Textoindependiente",
1665                "Body Text",
1666                r#"<w:b/><w:sz w:val="20"/>"#,
1667            ),
1668            None,
1669        );
1670        let out = run(&[("A", &a), ("B", &b)], &DiffOptions::default());
1671        assert!(
1672            out.contains("word/styles.xml › style paragraph \"Body Text\" › rPr\n"),
1673            "{out}"
1674        );
1675        assert!(out.contains("\n  - rFonts(ascii=Arial)\n"), "{out}");
1676        assert!(out.contains("\n  + sz=20\n"), "{out}");
1677        assert!(
1678            !out.contains("  - b\n") && !out.contains("  + b\n"),
1679            "{out}"
1680        );
1681        assert!(!out.contains("Textoindependiente"), "ids are noise: {out}");
1682    }
1683
1684    /// rsids, paragraph ids, revision ids/authors/dates, attribute order, an
1685    /// explicit on/off `w:val="1"`/`"true"` and empty property shells are
1686    /// noise; `raw` keeps them.
1687    #[test]
1688    fn noise_is_dropped_unless_raw() {
1689        let a = docx(
1690            r#"<w:p w14:paraId="11111111" w:rsidR="00AB"><w:pPr/><w:r><w:rPr><w:b/><w:lang w:val="en-US" w:eastAsia="en-US"/></w:rPr><w:t>kept</w:t></w:r><w:ins w:id="3" w:author="X" w:date="2026-01-01T00:00:00Z"><w:r><w:t> more</w:t></w:r></w:ins></w:p>"#,
1691            "",
1692            None,
1693        );
1694        let b = docx(
1695            r#"<w:p w14:paraId="22222222" w:rsidR="00CD"><w:r><w:rPr><w:b w:val="1"/><w:lang w:eastAsia="en-US" w:val="en-US"/></w:rPr><w:t>kept</w:t></w:r><w:ins w:id="9" w:author="Y" w:date="2026-02-02T00:00:00Z"><w:r><w:rPr><w:bCs w:val="true"/></w:rPr><w:t> more</w:t></w:r></w:ins></w:p>"#,
1696            "",
1697            None,
1698        );
1699        let out = run(&[("A", &a), ("B", &b)], &DiffOptions::default());
1700        assert!(out.contains("\n  + ins: \" more\" [bCs]\n"), "{out}");
1701        assert!(out.contains("\n  - ins: \" more\"\n"), "{out}");
1702        assert!(
1703            !out.contains("  \"kept\""),
1704            "the first run is identical: {out}"
1705        );
1706        assert!(!out.contains("paraId") && !out.contains("rsid"), "{out}");
1707        assert!(out.ends_with("1 difference\n"), "{out}");
1708
1709        let same = docx(
1710            r#"<w:p w14:paraId="33333333"><w:r><w:rPr><w:b w:val="true"/><w:lang w:eastAsia="en-US" w:val="en-US"/></w:rPr><w:t>kept</w:t></w:r><w:ins w:id="1" w:author="Z"><w:r><w:t> more</w:t></w:r></w:ins></w:p>"#,
1711            "",
1712            None,
1713        );
1714        let out = run(&[("A", &a), ("B", &same)], &DiffOptions::default());
1715        assert!(out.ends_with("no differences\n"), "{out}");
1716
1717        let raw = DiffOptions {
1718            raw: true,
1719            ..Default::default()
1720        };
1721        let out = run(&[("A", &a), ("B", &same)], &raw);
1722        assert!(out.contains("paraId"), "{out}");
1723    }
1724
1725    /// Paragraphs pair by their text: a paragraph inserted before them does
1726    /// not shift the comparison, and it shows as absent from A.
1727    #[test]
1728    fn paragraphs_pair_by_text_not_position() {
1729        let a = docx(
1730            r#"<w:p><w:r><w:t>Alpha</w:t></w:r></w:p><w:p><w:pPr><w:jc w:val="left"/></w:pPr><w:r><w:t>Beta</w:t></w:r></w:p>"#,
1731            "",
1732            None,
1733        );
1734        let b = docx(
1735            r#"<w:p><w:r><w:t>New</w:t></w:r></w:p><w:p><w:r><w:t>Alpha</w:t></w:r></w:p><w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>Beta</w:t></w:r></w:p>"#,
1736            "",
1737            None,
1738        );
1739        let out = run(&[("A", &a), ("B", &b)], &DiffOptions::default());
1740        assert!(
1741            out.contains(
1742                "word/document.xml › body › p#2 \"Beta\" › pPr\n  - jc=left\n  + jc=center\n"
1743            ),
1744            "{out}"
1745        );
1746        assert!(
1747            out.contains("word/document.xml › body › p#1 \"New\"\n  (absent) [A]\n  + \"New\"\n"),
1748            "{out}"
1749        );
1750        assert!(!out.contains("\"Alpha\""), "Alpha is identical: {out}");
1751    }
1752
1753    /// A paragraph whose text changed in place still pairs with its
1754    /// counterpart and shows the text that differs.
1755    #[test]
1756    fn a_rewritten_paragraph_pairs_with_the_one_it_replaced() {
1757        let a = docx(
1758            r#"<w:p><w:r><w:t>Start</w:t></w:r></w:p><w:p><w:r><w:t>old words</w:t></w:r></w:p><w:p><w:r><w:t>End</w:t></w:r></w:p>"#,
1759            "",
1760            None,
1761        );
1762        let b = docx(
1763            r#"<w:p><w:r><w:t>Start</w:t></w:r></w:p><w:p><w:r><w:t>new words</w:t></w:r></w:p><w:p><w:r><w:t>End</w:t></w:r></w:p>"#,
1764            "",
1765            None,
1766        );
1767        let out = run(&[("A", &a), ("B", &b)], &DiffOptions::default());
1768        assert!(
1769            out.contains("› p#2 \"old words\"\n  - \"old words\"\n  + \"new words\"\n"),
1770            "{out}"
1771        );
1772        assert!(!out.contains("(absent)"), "{out}");
1773    }
1774
1775    /// With three files each differing line carries the files that hold it.
1776    #[test]
1777    fn three_files_tag_each_line_with_the_files_holding_it() {
1778        let a = docx(
1779            "",
1780            &body_text("BodyText", "Body Text", r#"<w:rFonts w:ascii="Arial"/>"#),
1781            None,
1782        );
1783        let b = docx("", &body_text("BodyText", "Body Text", ""), None);
1784        let c = docx(
1785            "",
1786            &body_text("BT", "Body Text", r#"<w:sz w:val="20"/>"#),
1787            None,
1788        );
1789        let out = run(
1790            &[("A", &a), ("ours_rej", &b), ("word_rej", &c)],
1791            &DiffOptions::default(),
1792        );
1793        assert!(out.starts_with("files: A · ours_rej · word_rej\n"), "{out}");
1794        let hunk = out
1795            .split("style paragraph \"Body Text\" › rPr\n")
1796            .nth(1)
1797            .expect("rPr hunk");
1798        let mut lines = hunk.lines();
1799        let first = lines.next().unwrap();
1800        assert!(
1801            first.starts_with("  - rFonts(ascii=Arial)") && first.ends_with("[A]"),
1802            "{out}"
1803        );
1804        let second = lines.next().unwrap();
1805        assert!(
1806            second.starts_with("  + sz=20") && second.ends_with("[word_rej]"),
1807            "{out}"
1808        );
1809    }
1810
1811    /// `style` and `para_text` narrow the report to one element, and `full`
1812    /// prints its common lines too.
1813    #[test]
1814    fn filters_narrow_to_one_element() {
1815        let styles_a = format!(
1816            "{}{}",
1817            body_text("BodyText", "Body Text", r#"<w:b/><w:i/>"#),
1818            r#"<w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:rPr><w:sz w:val="56"/></w:rPr></w:style>"#
1819        );
1820        let styles_b = format!(
1821            "{}{}",
1822            body_text("BodyText", "Body Text", r#"<w:b/>"#),
1823            r#"<w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:rPr><w:sz w:val="48"/></w:rPr></w:style>"#
1824        );
1825        let a = docx(
1826            r#"<w:p><w:r><w:t>one</w:t></w:r></w:p><w:p><w:r><w:t>two</w:t></w:r></w:p>"#,
1827            &styles_a,
1828            None,
1829        );
1830        let b = docx(
1831            r#"<w:p><w:r><w:rPr><w:b/></w:rPr><w:t>one</w:t></w:r></w:p><w:p><w:r><w:rPr><w:b/></w:rPr><w:t>two</w:t></w:r></w:p>"#,
1832            &styles_b,
1833            None,
1834        );
1835        let files: [(&str, &[u8]); 2] = [("A", &a), ("B", &b)];
1836        let style = DiffOptions {
1837            style: Some("body text".into()),
1838            ..Default::default()
1839        };
1840        let out = run(&files, &style);
1841        assert!(out.contains("\"Body Text\" › rPr\n  - i\n"), "{out}");
1842        assert!(
1843            !out.contains("Title") && !out.contains("document.xml"),
1844            "{out}"
1845        );
1846
1847        let para = DiffOptions {
1848            para_text: Some("two".into()),
1849            ..Default::default()
1850        };
1851        let out = run(&files, &para);
1852        assert!(out.contains("p#2 \"two\""), "{out}");
1853        assert!(
1854            !out.contains("\"one\"") && !out.contains("styles.xml"),
1855            "{out}"
1856        );
1857
1858        let full = DiffOptions {
1859            style: Some("Body Text".into()),
1860            full: true,
1861            ..Default::default()
1862        };
1863        let out = run(&files, &full);
1864        assert!(out.contains("\n    b\n"), "common lines under full: {out}");
1865    }
1866
1867    /// Styles match by key whatever their order, and a style one file lacks
1868    /// never pairs with another style.
1869    #[test]
1870    fn styles_match_by_name_in_any_order_and_never_cross_pair() {
1871        let style = |id: &str, rpr: &str| {
1872            format!(
1873                r#"<w:style w:type="paragraph" w:styleId="{id}"><w:name w:val="{id}"/><w:rPr>{rpr}</w:rPr></w:style>"#
1874            )
1875        };
1876        let a = docx(
1877            "",
1878            &format!(
1879                "{}{}",
1880                style("Title", r#"<w:sz w:val="56"/>"#),
1881                style("Quote", "<w:i/>")
1882            ),
1883            None,
1884        );
1885        let b = docx(
1886            "",
1887            &format!(
1888                "{}{}{}",
1889                style("Heading", r#"<w:sz w:val="32"/>"#),
1890                style("Quote", "<w:i/>"),
1891                style("Title", r#"<w:sz w:val="56"/>"#)
1892            ),
1893            None,
1894        );
1895        let out = run(&[("A", &a), ("B", &b)], &DiffOptions::default());
1896        assert!(
1897            out.contains("style paragraph \"Heading\"\n  (absent) [A]\n"),
1898            "{out}"
1899        );
1900        assert!(
1901            out.contains("style paragraph \"Heading\" › rPr\n  + sz=32\n"),
1902            "{out}"
1903        );
1904        assert!(!out.contains("Title") && !out.contains("Quote"), "{out}");
1905        assert!(out.ends_with("2 differences\n"), "{out}");
1906    }
1907
1908    /// Cells compare by their position in the row, and a field shows as
1909    /// `{code|result}` in its run segments.
1910    #[test]
1911    fn table_cells_pair_by_position_and_fields_show_their_code() {
1912        let table = |second: &str, w: &str| {
1913            format!(
1914                r#"<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/></w:tblPr><w:tr><w:tc><w:tcPr><w:tcW w:w="{w}" w:type="dxa"/></w:tcPr><w:p><w:r><w:t>Name</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>{second}</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> PAGE </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>1</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>"#
1915            )
1916        };
1917        let a = docx(&table("Old", "2000"), "", None);
1918        let b = docx(&table("New", "2400"), "", None);
1919        let out = run(&[("A", &a), ("B", &b)], &DiffOptions::default());
1920        assert!(
1921            out.contains("› tbl#1 \"NameOld\" › tr 1 \"NameOld\" › tc 1 › tcPr\n  - tcW(type=dxa,w=2000)\n  + tcW(type=dxa,w=2400)\n"),
1922            "{out}"
1923        );
1924        assert!(
1925            out.contains("› tc 2 › p#2 \"Old\"\n  - \"Old\"\n  + \"New\"\n"),
1926            "{out}"
1927        );
1928        assert!(!out.contains("PAGE"), "the field is identical: {out}");
1929        let c = docx(
1930            &table("Old", "2000").replace(" PAGE ", " NUMPAGES "),
1931            "",
1932            None,
1933        );
1934        let out = run(&[("A", &a), ("C", &c)], &DiffOptions::default());
1935        assert!(
1936            out.contains("  - \"{ PAGE |1}\"\n  + \"{ NUMPAGES |1}\"\n"),
1937            "{out}"
1938        );
1939    }
1940
1941    /// Headers pair by the section role that shows them, whatever their
1942    /// part names.
1943    #[test]
1944    fn headers_pair_by_role() {
1945        let a = docx(
1946            "",
1947            "",
1948            Some(("header1.xml", r#"<w:p><w:r><w:t>Head A</w:t></w:r></w:p>"#)),
1949        );
1950        let b = docx(
1951            "",
1952            "",
1953            Some(("header3.xml", r#"<w:p><w:r><w:t>Head B</w:t></w:r></w:p>"#)),
1954        );
1955        let out = run(&[("A", &a), ("B", &b)], &DiffOptions::default());
1956        assert!(
1957            out.contains("section 1 default header › p#1 \"Head A\"\n"),
1958            "{out}"
1959        );
1960        assert!(!out.contains("(absent)"), "{out}");
1961    }
1962
1963    const REL_NS: &str = "http://schemas.openxmlformats.org/package/2006/relationships";
1964
1965    /// A package of exactly these parts, the content types and root rels
1966    /// added.
1967    fn package(parts: &[(&str, &str)]) -> Vec<u8> {
1968        let mut entries: Vec<(&str, &str)> =
1969            vec![("[Content_Types].xml", TYPES), ("_rels/.rels", ROOT_RELS)];
1970        entries.extend_from_slice(parts);
1971        let mut buf = Cursor::new(Vec::new());
1972        {
1973            let mut z = zip::ZipWriter::new(&mut buf);
1974            let opt = zip::write::SimpleFileOptions::default();
1975            for (name, data) in &entries {
1976                z.start_file(*name, opt).unwrap();
1977                z.write_all(data.as_bytes()).unwrap();
1978            }
1979            z.finish().unwrap();
1980        }
1981        buf.into_inner()
1982    }
1983
1984    fn document(body: &str) -> String {
1985        format!(
1986            r#"<w:document xmlns:w="{W}" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><w:body>{body}</w:body></w:document>"#
1987        )
1988    }
1989
1990    fn rels(items: &str) -> String {
1991        format!(r#"<Relationships xmlns="{REL_NS}">{items}</Relationships>"#)
1992    }
1993
1994    /// A link that leads elsewhere is a difference, by its anchor or by
1995    /// the target its relationship names.
1996    #[test]
1997    fn hyperlink_destinations_are_compared() {
1998        let link =
1999            r#"<w:p><w:hyperlink r:id="rId5"><w:r><w:t>Site</w:t></w:r></w:hyperlink></w:p>"#;
2000        let to = |url: &str| {
2001            rels(&format!(
2002                r#"<Relationship Id="rId5" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="{url}" TargetMode="External"/>"#
2003            ))
2004        };
2005        let (doc, ra, rb) = (
2006            document(link),
2007            to("https://a.example/"),
2008            to("https://b.example/"),
2009        );
2010        let a = package(&[
2011            ("word/document.xml", &doc),
2012            ("word/_rels/document.xml.rels", &ra),
2013        ]);
2014        let b = package(&[
2015            ("word/document.xml", &doc),
2016            ("word/_rels/document.xml.rels", &rb),
2017        ]);
2018        let out = run(&[("A", &a), ("B", &b)], &DiffOptions::default());
2019        assert!(
2020            out.contains("b.example") && out.contains("p#1 \"Site\""),
2021            "{out}"
2022        );
2023
2024        let anchored = |name: &str| {
2025            document(&format!(
2026                r#"<w:p><w:hyperlink w:anchor="{name}"><w:r><w:t>Site</w:t></w:r></w:hyperlink></w:p>"#
2027            ))
2028        };
2029        let (da, db) = (anchored("One"), anchored("Two"));
2030        let a = package(&[("word/document.xml", &da)]);
2031        let b = package(&[("word/document.xml", &db)]);
2032        let out = run(&[("A", &a), ("B", &b)], &DiffOptions::default());
2033        assert!(out.contains("anchor=Two"), "{out}");
2034    }
2035
2036    /// A drawing is its items: a new extent or an embed that now points
2037    /// at other bytes is a difference.
2038    #[test]
2039    fn drawings_compare_their_placement_and_target() {
2040        let drawing = |cx: &str| {
2041            document(&format!(
2042                r#"<w:p><w:r><w:drawing><wp:inline><wp:extent cx="{cx}" cy="100"/><wp:docPr id="1" name="P"/><a:graphic><a:graphicData><a:blip r:embed="rId7"/></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>"#
2043            ))
2044        };
2045        let image = |target: &str| {
2046            rels(&format!(
2047                r#"<Relationship Id="rId7" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="{target}"/>"#
2048            ))
2049        };
2050        let (d100, d200) = (drawing("100"), drawing("200"));
2051        let (one, two) = (image("media/one.png"), image("media/two.png"));
2052        let parts = |doc: &str, rels: &str| {
2053            package(&[
2054                ("word/document.xml", doc),
2055                ("word/_rels/document.xml.rels", rels),
2056                ("word/media/one.png", "AAA"),
2057                ("word/media/two.png", "BBB"),
2058            ])
2059        };
2060        let a = parts(&d100, &one);
2061        let out = run(
2062            &[("A", &a), ("B", &parts(&d200, &one))],
2063            &DiffOptions::default(),
2064        );
2065        assert!(out.contains("cx=200"), "{out}");
2066        let out = run(
2067            &[("A", &a), ("B", &parts(&d100, &two))],
2068            &DiffOptions::default(),
2069        );
2070        assert!(out.contains("p#1 \"\"\n  - [drawing{"), "{out}");
2071        assert!(out.contains("embed=→#"), "{out}");
2072        let out = run(
2073            &[("A", &a), ("B", &parts(&d100, &one))],
2074            &DiffOptions::default(),
2075        );
2076        assert!(out.ends_with("no differences\n"), "{out}");
2077        // The drawing's run keeps its formatting.
2078        let lang = d100.replace(
2079            "<w:r><w:drawing>",
2080            r#"<w:r><w:rPr><w:lang w:val="en-US"/></w:rPr><w:drawing>"#,
2081        );
2082        let out = run(
2083            &[("A", &a), ("B", &parts(&lang, &one))],
2084            &DiffOptions::default(),
2085        );
2086        assert!(out.contains(" [lang=en-US]\n"), "{out}");
2087    }
2088
2089    /// A style without w:type is a paragraph style.
2090    #[test]
2091    fn an_omitted_style_type_is_paragraph() {
2092        let a = docx(
2093            "",
2094            r#"<w:style w:styleId="X"><w:name w:val="X"/></w:style>"#,
2095            None,
2096        );
2097        let b = docx(
2098            "",
2099            r#"<w:style w:type="paragraph" w:styleId="X"><w:name w:val="X"/></w:style>"#,
2100            None,
2101        );
2102        let out = run(&[("A", &a), ("B", &b)], &DiffOptions::default());
2103        assert!(out.ends_with("no differences\n"), "{out}");
2104    }
2105
2106    /// --full prints agreeing elements without counting them.
2107    #[test]
2108    fn full_context_is_not_a_difference() {
2109        let a = docx(
2110            r#"<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>Same</w:t></w:r></w:p>"#,
2111            &body_text("BodyText", "Body Text", "<w:b/>"),
2112            None,
2113        );
2114        let full = DiffOptions {
2115            full: true,
2116            ..DiffOptions::default()
2117        };
2118        let out = run(&[("A", &a), ("B", &a)], &full);
2119        assert!(
2120            out.contains("\"Same\""),
2121            "--full prints the common lines: {out}"
2122        );
2123        assert!(out.ends_with("no differences\n"), "{out}");
2124    }
2125
2126    /// docProps compare their meaningful fields; the save stamps do not.
2127    #[test]
2128    fn document_properties_compare_all_but_save_stamps() {
2129        let core = |title: &str, modified: &str| {
2130            format!(
2131                r#"<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/"><dc:title>{title}</dc:title><dcterms:modified>{modified}</dcterms:modified></cp:coreProperties>"#
2132            )
2133        };
2134        let doc = document("<w:p/>");
2135        let with =
2136            |core: &str| package(&[("word/document.xml", &doc), ("docProps/core.xml", core)]);
2137        let a = with(&core("Lease", "2026-01-01T00:00:00Z"));
2138        let restamped = with(&core("Lease", "2026-02-02T00:00:00Z"));
2139        let out = run(&[("A", &a), ("B", &restamped)], &DiffOptions::default());
2140        assert!(out.ends_with("no differences\n"), "{out}");
2141        let retitled = with(&core("Sublease", "2026-01-01T00:00:00Z"));
2142        let out = run(&[("A", &a), ("B", &retitled)], &DiffOptions::default());
2143        assert!(out.contains("+ title \"Sublease\""), "{out}");
2144    }
2145
2146    /// An element that moves to another namespace is a difference.
2147    #[test]
2148    fn a_custom_namespace_is_compared() {
2149        let item = |ns: &str| format!(r#"<root xmlns="{ns}"><v>1</v></root>"#);
2150        let doc = document("<w:p/>");
2151        let (ia, ib) = (item("urn:a"), item("urn:b"));
2152        let a = package(&[("word/document.xml", &doc), ("customXml/item1.xml", &ia)]);
2153        let b = package(&[("word/document.xml", &doc), ("customXml/item1.xml", &ib)]);
2154        let out = run(&[("A", &a), ("B", &b)], &DiffOptions::default());
2155        assert!(out.contains("+ xmlns=urn:b"), "{out}");
2156        // Office vocabularies say nothing by default.
2157        let out = run(&[("A", &a), ("B", &a)], &DiffOptions::default());
2158        assert!(out.ends_with("no differences\n"), "{out}");
2159    }
2160
2161    /// A part Word rejects (a mismatched end tag) is reported, not read
2162    /// as the well-formed part it resembles.
2163    #[test]
2164    fn malformed_xml_is_not_compared_as_a_tree() {
2165        let doc = document("<w:p/>");
2166        let a = package(&[
2167            ("word/document.xml", &doc),
2168            ("customXml/item1.xml", "<root><a>1</a></root>"),
2169        ]);
2170        let b = package(&[
2171            ("word/document.xml", &doc),
2172            ("customXml/item1.xml", "<root><a>1</b></root>"),
2173        ]);
2174        let out = run(&[("A", &a), ("B", &b)], &DiffOptions::default());
2175        assert!(out.contains("+ malformed XML"), "{out}");
2176    }
2177
2178    /// --raw keeps a revision mark's author, date and id.
2179    #[test]
2180    fn raw_keeps_revision_metadata() {
2181        let ins = |author: &str| {
2182            docx(
2183                &format!(
2184                    r#"<w:p><w:ins w:id="1" w:author="{author}" w:date="2026-01-01T00:00:00Z"><w:r><w:t>x</w:t></w:r></w:ins></w:p>"#
2185                ),
2186                "",
2187                None,
2188            )
2189        };
2190        let (a, b) = (ins("Ann"), ins("Bob"));
2191        let out = run(&[("A", &a), ("B", &b)], &DiffOptions::default());
2192        assert!(out.ends_with("no differences\n"), "{out}");
2193        let raw = DiffOptions {
2194            raw: true,
2195            ..DiffOptions::default()
2196        };
2197        let out = run(&[("A", &a), ("B", &b)], &raw);
2198        assert!(out.contains("author=Bob"), "{out}");
2199    }
2200
2201    /// A header part two sections share pairs under both roles.
2202    #[test]
2203    fn a_shared_header_pairs_under_every_role() {
2204        let head = format!(r#"<w:hdr xmlns:w="{W}"><w:p><w:r><w:t>Head</w:t></w:r></w:p></w:hdr>"#);
2205        let rel = |id: &str, target: &str| {
2206            format!(
2207                r#"<Relationship Id="{id}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="{target}"/>"#
2208            )
2209        };
2210        let body = |last: &str| {
2211            document(&format!(
2212                r#"<w:p><w:pPr><w:sectPr><w:headerReference w:type="default" r:id="rId9"/></w:sectPr></w:pPr></w:p><w:sectPr><w:headerReference w:type="default" r:id="{last}"/></w:sectPr>"#
2213            ))
2214        };
2215        let (da, ra) = (body("rId9"), rels(&rel("rId9", "header1.xml")));
2216        let a = package(&[
2217            ("word/document.xml", &da),
2218            ("word/_rels/document.xml.rels", &ra),
2219            ("word/header1.xml", &head),
2220        ]);
2221        let (db, rb) = (
2222            body("rId10"),
2223            rels(&format!(
2224                "{}{}",
2225                rel("rId9", "header1.xml"),
2226                rel("rId10", "header2.xml")
2227            )),
2228        );
2229        let b = package(&[
2230            ("word/document.xml", &db),
2231            ("word/_rels/document.xml.rels", &rb),
2232            ("word/header1.xml", &head),
2233            ("word/header2.xml", &head),
2234        ]);
2235        let out = run(&[("A", &a), ("B", &b)], &DiffOptions::default());
2236        assert!(!out.contains("section 2 default header"), "{out}");
2237    }
2238}
2239
2240#[cfg(test)]
2241#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2242mod boundary_coverage_tests {
2243    use super::*;
2244
2245    fn with_build(fragment: &str, raw: bool, f: impl FnOnce(&mut Build<'_>, NodeId)) {
2246        let mut dom = Dom::new();
2247        let doc = dom.parse_xdocument(&format!(r#"<root xmlns:w="{W_NS}" xmlns:r="{R_NS}" xmlns:mc="{MC_NS}" xmlns:x="urn:custom">{fragment}</root>"#));
2248        let root = dom.root(doc).unwrap();
2249        let filter = Filter {
2250            style: None,
2251            para: None,
2252        };
2253        let names = HashMap::from([("Heading1".into(), "Heading 1".into())]);
2254        let targets = HashMap::from([("rId1".into(), "https://example.test/".into())]);
2255        let mut build = Build {
2256            dom: &dom,
2257            raw,
2258            filter: &filter,
2259            style_names: &names,
2260            targets: &targets,
2261            paras: 0,
2262            tables: 0,
2263        };
2264        let node = dom.elements(root, None)[0];
2265        f(&mut build, node);
2266    }
2267
2268    #[test]
2269    fn toggle_normalization_distinguishes_boolean_values_from_numeric_properties() {
2270        for (property, value, normalized) in [
2271            ("b", "true", "b"),
2272            ("b", "on", "b"),
2273            ("b", "1", "b"),
2274            ("b", "false", "b=0"),
2275            ("b", "off", "b=0"),
2276            ("sz", "1", "sz=1"),
2277            ("sz", "12", "sz=12"),
2278        ] {
2279            let fragment = format!("<w:{property} w:val=\"{value}\"/>");
2280            with_build(&fragment, false, |build, node| {
2281                assert_eq!(build.item(node), normalized);
2282            });
2283            with_build(&fragment, true, |build, node| {
2284                assert_eq!(build.item(node), format!("{property}<{W_NS}>={value}"));
2285            });
2286        }
2287        with_build(
2288            "<x:custom x:kind=\"1\">text</x:custom>",
2289            false,
2290            |build, node| {
2291                assert_eq!(build.item(node), "custom<urn:custom>(kind=1) \"text\"");
2292            },
2293        );
2294        with_build("<w:b><w:proofErr/></w:b>", false, |build, node| {
2295            assert_eq!(build.item(node), "b");
2296        });
2297    }
2298
2299    #[test]
2300    fn relationship_attributes_resolve_targets_without_inventing_missing_targets() {
2301        for (raw, expected) in [
2302            (false, "→https://example.test/"),
2303            (true, "rId1→https://example.test/"),
2304        ] {
2305            with_build("<w:hyperlink r:id=\"rId1\"/>", raw, |build, node| {
2306                assert_eq!(build.attrs(node), [("id".into(), expected.into())]);
2307            });
2308        }
2309        with_build("<w:hyperlink r:id=\"missing\"/>", true, |build, node| {
2310            assert_eq!(build.attrs(node), [("id".into(), "missing".into())]);
2311        });
2312        with_build("<w:hyperlink r:id=\"missing\"/>", false, |build, node| {
2313            assert!(build.attrs(node).is_empty());
2314        });
2315        with_build(
2316            "<w:headerReference r:id=\"rId1\"/>",
2317            false,
2318            |build, node| assert!(build.attrs(node).is_empty()),
2319        );
2320        with_build("<w:pStyle w:val=\"Heading1\"/>", false, |build, node| {
2321            assert_eq!(build.item(node), "pStyle=\"Heading 1\"");
2322        });
2323    }
2324
2325    #[test]
2326    fn noisy_metadata_drops_only_save_artifacts_and_raw_keeps_it() {
2327        for (element, namespace, attribute, expected_noise) in [
2328            ("p", W_NS, "rsidR", true),
2329            ("p", MC_NS, "Ignorable", true),
2330            ("p", "urn:custom", "paraId", true),
2331            ("p", W_NS, "paraId", false),
2332            ("ins", W_NS, "id", true),
2333            ("pPrChange", W_NS, "id", true),
2334            ("bookmarkStart", W_NS, "id", true),
2335            ("docPr", "", "id", true),
2336            ("cNvPr", "", "id", true),
2337            ("ins", W_NS, "author", true),
2338            ("rPrChange", W_NS, "date", true),
2339            ("comment", W_NS, "initials", true),
2340            ("Relationship", "", "Id", true),
2341            ("p", W_NS, "val", false),
2342        ] {
2343            with_build("<w:p/>", false, |build, _| {
2344                assert_eq!(
2345                    build.noise(element, &XName::get(attribute, namespace)),
2346                    expected_noise
2347                );
2348            });
2349            with_build("<w:p/>", true, |build, _| {
2350                assert!(!build.noise(element, &XName::get(attribute, namespace)));
2351            });
2352        }
2353        for (parent, name, expected) in [
2354            ("p", "proofErr", true),
2355            ("sdtPr", "id", true),
2356            ("pPr", "id", false),
2357            ("coreProperties", "modified", true),
2358            ("coreProperties", "title", false),
2359            ("Properties", "Words", true),
2360            ("Properties", "custom", false),
2361        ] {
2362            with_build("<w:p/>", false, |build, _| {
2363                assert_eq!(build.noise_element(parent, name), expected);
2364            });
2365            with_build("<w:p/>", true, |build, _| {
2366                assert!(!build.noise_element(parent, name));
2367            });
2368        }
2369    }
2370
2371    #[test]
2372    fn run_projection_preserves_field_delimiters_breaks_and_old_formatting() {
2373        let fragment = "<w:r><w:rPr><w:b/><w:rPrChange><w:rPr><w:i/></w:rPr></w:rPrChange></w:rPr><w:fldChar w:fldCharType=\"begin\"/><w:instrText>CODE</w:instrText><w:fldChar w:fldCharType=\"separate\"/><w:t>result</w:t><w:fldChar w:fldCharType=\"end\"/><w:fldChar w:fldCharType=\"unknown\"/><w:tab/><w:ptab/><w:br w:type=\"page\"/><w:br/><w:cr/><w:noBreakHyphen/><w:softHyphen/><w:annotationRef/></w:r>";
2374        with_build(fragment, false, |build, node| {
2375            let mut segments = Vec::new();
2376            build.run(node, "del", &mut segments, &mut Vec::new());
2377            assert_eq!(segments.len(), 1);
2378            assert_eq!(segments[0].rev, "del");
2379            assert_eq!(segments[0].fmt, "b was{i}");
2380            assert_eq!(segments[0].text, "{CODE|result}⇥⇥⤓↵↵‑¬[annotationRef]");
2381        });
2382    }
2383
2384    #[test]
2385    fn empty_property_blocks_and_change_records_are_distinct() {
2386        for raw in [false, true] {
2387            with_build("<w:pPr/>", raw, |build, node| {
2388                assert_eq!(build.block(node).is_some(), raw);
2389            });
2390            with_build("<w:pPrChange/>", raw, |build, node| {
2391                assert_eq!(build.change(node).unwrap().lines, ["(empty)"]);
2392            });
2393        }
2394        with_build(
2395            "<w:sdt><w:sdtPr><w:alias w:val=\"Alias\"/></w:sdtPr><w:sdtContent><w:p/></w:sdtContent></w:sdt>",
2396            false,
2397            |build, node| assert_eq!(build.sdt(node).label, "sdt \"Alias\""),
2398        );
2399        with_build(
2400            "<w:footnote w:type=\"separator\"><w:p/></w:footnote>",
2401            false,
2402            |build, node| assert_eq!(build.note(node).label, "footnote separator"),
2403        );
2404        with_build(
2405            "<w:comment w:type=\"normal\"><w:p><w:r><w:t>note</w:t></w:r></w:p></w:comment>",
2406            false,
2407            |build, node| assert_eq!(build.note(node).label, "comment \"note\""),
2408        );
2409    }
2410
2411    #[test]
2412    fn hunk_distinguishes_empty_blocks_absence_and_multiplicity() {
2413        let mut a = N::new("p", "a".into(), "paragraph".into());
2414        a.lines = vec!["same".into()];
2415        let mut b = N::new("p", "a".into(), "paragraph".into());
2416        b.lines = vec!["same".into(), "same".into()];
2417        let walker = Walker {
2418            labels: &["A", "B", "C"],
2419            filtered: false,
2420            full: false,
2421        };
2422        let (output, differs) = walker
2423            .hunk(
2424                &[Some(&a), Some(&b), None],
2425                &[true; 3],
2426                &["paragraph".into()],
2427            )
2428            .unwrap();
2429        assert!(differs);
2430        assert!(output.contains("(absent) [C]"));
2431        assert!(output.contains("B×2"));
2432        assert!(
2433            walker
2434                .hunk(&[Some(&a), Some(&a)], &[true; 2], &[])
2435                .is_none()
2436        );
2437        a.lines.clear();
2438        a.block = true;
2439        assert!(walker.hunk(&[Some(&a), None], &[true; 2], &[]).is_none());
2440        let full = Walker {
2441            labels: &["A", "B"],
2442            filtered: false,
2443            full: true,
2444        };
2445        b.lines = vec!["same".into()];
2446        assert!(!full.hunk(&[Some(&b), Some(&b)], &[true; 2], &[]).unwrap().1);
2447        let filtered = Walker {
2448            labels: &["A", "B"],
2449            filtered: true,
2450            full: false,
2451        };
2452        let mut hunks = Vec::new();
2453        filtered.walk(
2454            &[Some(&b), None],
2455            &[true; 2],
2456            &mut Vec::new(),
2457            false,
2458            &mut hunks,
2459        );
2460        assert!(hunks.is_empty());
2461        b.hit = true;
2462        filtered.walk(
2463            &[Some(&b), None],
2464            &[true; 2],
2465            &mut Vec::new(),
2466            false,
2467            &mut hunks,
2468        );
2469        assert_eq!(hunks.len(), 1);
2470    }
2471
2472    #[test]
2473    fn large_greedy_alignment_preserves_every_source_position_and_only_matches_equal_keys() {
2474        let a = (0..2003)
2475            .map(|i| if i % 2 == 0 { "left" } else { "shared" })
2476            .collect::<Vec<_>>();
2477        let b = (0..2002)
2478            .map(|i| if i % 2 == 0 { "shared" } else { "right" })
2479            .collect::<Vec<_>>();
2480        let operations = lcs_ops(&a, &b);
2481        assert_eq!(
2482            operations
2483                .iter()
2484                .filter_map(|(i, _)| *i)
2485                .collect::<Vec<_>>(),
2486            (0..a.len()).collect::<Vec<_>>()
2487        );
2488        assert_eq!(
2489            operations
2490                .iter()
2491                .filter_map(|(_, j)| *j)
2492                .collect::<Vec<_>>(),
2493            (0..b.len()).collect::<Vec<_>>()
2494        );
2495        let matched = operations
2496            .iter()
2497            .filter_map(|(i, j)| Some((*i.as_ref()?, *j.as_ref()?)))
2498            .collect::<Vec<_>>();
2499        assert_eq!(matched.len(), 1001);
2500        assert!(matched.iter().all(|&(i, j)| a[i] == b[j]));
2501    }
2502}
2503
2504#[cfg(test)]
2505#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2506mod raw_source_projection_contract_tests {
2507    use super::*;
2508
2509    fn with_source(source: &str, raw: bool, check: impl FnOnce(&mut Build<'_>, NodeId)) {
2510        let mut dom = Dom::new();
2511        let doc = dom.parse_xdocument(&format!(
2512            r#"<w:document xmlns:w="{W_NS}"><w:body>{source}</w:body></w:document>"#
2513        ));
2514        let before = dom.serialize_document(doc);
2515        let root = dom.root(doc).unwrap();
2516        let body = dom.elements(root, None)[0];
2517        let node = dom.elements(body, None)[0];
2518        let filter = Filter {
2519            style: None,
2520            para: None,
2521        };
2522        let names = HashMap::new();
2523        let targets = HashMap::new();
2524        let mut build = Build {
2525            dom: &dom,
2526            raw,
2527            filter: &filter,
2528            style_names: &names,
2529            targets: &targets,
2530            paras: 0,
2531            tables: 0,
2532        };
2533        check(&mut build, node);
2534        assert_eq!(dom.serialize_document(doc), before);
2535    }
2536
2537    #[test]
2538    fn recorded_run_properties_and_saved_page_breaks_keep_exact_raw_source_projection() {
2539        let source = r#"<w:p><w:r><w:rPr><w:rPrChange w:id="51" w:author="Owner" w:date="2026-10-09T00:00:00Z"><w:rPr><w:i/></w:rPr></w:rPrChange></w:rPr><w:t>ação</w:t><w:lastRenderedPageBreak/><w:t>τέλος</w:t></w:r></w:p>"#;
2540        for raw in [false, true] {
2541            with_source(source, raw, |build, node| {
2542                let mut segments = Vec::new();
2543                let mut boxes = Vec::new();
2544                let run = build.dom.elements(node, Some(&XName::get("r", W_NS)))[0];
2545                build.run(run, "del", &mut segments, &mut boxes);
2546                let actual = segments
2547                    .into_iter()
2548                    .map(|s| (s.rev, s.fmt, s.text, s.text_run))
2549                    .collect::<Vec<_>>();
2550                let text = if raw {
2551                    "ação[lastRenderedPageBreak]τέλος"
2552                } else {
2553                    "açãoτέλος"
2554                };
2555                assert_eq!(
2556                    actual,
2557                    vec![("del".into(), "was{i}".into(), text.into(), true)]
2558                );
2559                assert!(boxes.is_empty());
2560            });
2561        }
2562    }
2563
2564    #[test]
2565    fn inline_content_controls_preserve_each_source_run_format_and_range_marker() {
2566        let source = r#"<w:p><w:pPr><w:spacing w:after="80"/></w:pPr><w:bookmarkStart w:id="7" w:name="owned"/><w:sdt><w:sdtPr><w:alias w:val="Review"/><w:tag w:val="owner"/></w:sdtPr><w:sdtContent><w:r><w:rPr><w:b/></w:rPr><w:t>ação</w:t></w:r><w:r><w:rPr><w:i/></w:rPr><w:t>τέλος</w:t></w:r></w:sdtContent></w:sdt><w:bookmarkEnd w:id="7"/></w:p>"#;
2567        for raw in [false, true] {
2568            with_source(source, raw, |build, node| {
2569                let mut segments = Vec::new();
2570                let mut boxes = Vec::new();
2571                build.segments(node, "", &mut segments, &mut boxes);
2572                let actual = segments
2573                    .into_iter()
2574                    .map(|s| (s.rev, s.fmt, s.text, s.text_run))
2575                    .collect::<Vec<_>>();
2576                let mut expected = vec![
2577                    ("".into(), "".into(), "⟨bookmark owned⟩".into(), false),
2578                    ("".into(), "b".into(), "ação".into(), true),
2579                    ("".into(), "i".into(), "τέλος".into(), true),
2580                ];
2581                if raw {
2582                    expected.push(("".into(), "".into(), "⟨bookmarkEnd(id=7)⟩".into(), false));
2583                }
2584                assert_eq!(actual, expected);
2585                assert!(boxes.is_empty());
2586            });
2587        }
2588    }
2589
2590    #[test]
2591    fn large_reordered_key_alignment_discards_only_positions_already_crossed() {
2592        let mut a = vec!["x", "y", "x"];
2593        let mut b = vec!["y", "x", "x"];
2594        a.extend(std::iter::repeat_n("left", 2001));
2595        b.extend(std::iter::repeat_n("right", 2001));
2596        let mut expected = vec![
2597            (None, Some(0)),
2598            (Some(0), Some(1)),
2599            (Some(1), None),
2600            (Some(2), Some(2)),
2601        ];
2602        expected.extend((3..a.len()).map(|i| (Some(i), None)));
2603        expected.extend((3..b.len()).map(|j| (None, Some(j))));
2604        assert_eq!(lcs_ops(&a, &b), expected);
2605    }
2606}