Skip to main content

jubarte_doc/
debug.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! `jubarte debug`: triage a `.docx` that Word refuses, or compare two builds of
6//! one. Every report is short on purpose. It counts findings by kind, shows a
7//! few examples of each (`limit`), and with two files prints only what differs.
8//!
9//! The checks are the Word-validity shapes the OpenXmlValidator does not see
10//! (see `AGENTS.md`, "When Word cannot open a jubarte file"):
11//!
12//! - `orphans`: `w:delText`/`w:delInstrText` with no `w:del`/`w:moveFrom` in
13//!   its own story, `w:t`/`w:instrText` under a `w:del`, and bare runs in a
14//!   text box whose anchor is deleted. `w:txbxContent` is a story of its own:
15//!   the deletion around its anchor does not reach into it.
16//! - `fields`: `begin`/`separate`/`end` nesting per story, and fields whose
17//!   parts disagree on being deleted.
18//! - `bookmarks`: duplicate or unpaired names and ids, an end before its start,
19//!   a start and end in different `w:sdt`, `w:tc`, `w:txbxContent` or
20//!   revision containers, and a bookmark in a single-value content control
21//!   (plain text, list, date, picture, checkbox).
22//! - `package`: parts without a content type, overrides without a part,
23//!   duplicate relationship ids, relationship targets and `r:` ids that name
24//!   nothing, dangling note and comment references, unpaired comment ranges,
25//!   undeclared `mc:Ignorable` prefixes.
26//! - `structure`: empty field codes, cells that do not end in a paragraph,
27//!   rows without cells, a revision nested in one of its own kind, a body
28//!   `w:sectPr` that is not last, and unequal source/destination range counts
29//!   for a move name (Word opens it but misreads Reject All).
30//! - `ids`: revision and `wp:docPr` ids used twice in the package. Word opens
31//!   files that repeat them, so they are leads, not causes.
32//! - `styles`: `basedOn`/`next`/`link` and `pStyle`/`rStyle`/`tblStyle`
33//!   values naming no style, and two styles of one type whose names match
34//!   case-insensitively (Word pairs styles by type and name, not by id).
35//! - `chains`: where bookmark starts and ends sit (parent chains, tallied).
36//! - `elements`: element counts (with two files, only the ones that differ).
37//! - `textbox`: the XML of each text box story (namespace declarations
38//!   dropped), filtered by `grep`.
39//! - `render` (a listing, like `text`): what each story part should put on
40//!   the page, for diagnosing a low score against Word's PDF. Every story
41//!   part is read, not only the body: sections, tables (size, style, float,
42//!   direct, cell and style shading, first row), frames, anchored drawings,
43//!   fields, paragraph styles and shading, text colour, highlight, run
44//!   shading, hidden text, requested fonts, and the order of deleted and
45//!   inserted runs. `(layout)` adds jubarte's page count (Word revision
46//!   style) and the face each requested font resolved to.
47
48use std::collections::{BTreeMap, HashMap, HashSet};
49use std::fmt::Write as _;
50use std::io::{Cursor, Read};
51
52use crate::xmllinq::{Dom, NodeId};
53
54pub mod diff;
55#[cfg(feature = "render")]
56mod render;
57
58/// Which reports to print.
59#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
60pub enum Check {
61    /// Deleted text outside its story's deletion, live text inside one.
62    /// Triage check.
63    Orphans,
64    /// Field structure and deletion state. Triage check.
65    Fields,
66    /// Bookmark integrity and crossings. Triage check.
67    Bookmarks,
68    /// Content types, relationships, cross-part references. Triage check.
69    Package,
70    /// Cell, row, revision and section shapes Word rejects. Triage check.
71    Structure,
72    /// Revision and drawing ids used twice.
73    Ids,
74    /// Style links and references naming no style; two styles with one type
75    /// and name.
76    Styles,
77    /// Bookmark parent chains, tallied.
78    Chains,
79    /// Element counts.
80    Elements,
81    /// Text box stories as XML.
82    Textbox,
83    /// Paragraph text per story with revision marks (`{+ins+}`, `[-del-]`,
84    /// a deleted or inserted paragraph mark as `¶-` / `¶+`).
85    Text,
86    /// Part XML without namespace declarations, rsids and paragraph ids, one
87    /// element per line.
88    Xml,
89    /// `Text` with each paragraph's direct properties and each run's direct
90    /// formatting, revision marks left out; adjacent runs formatted alike
91    /// merge.
92    Runs,
93    /// Property-change records (`pPrChange`, `tcPrChange`, `sectPrChange`,
94    /// …): where each sits and what the live properties add and drop
95    /// against the recorded ones.
96    Changes,
97    /// Tables per story part: the grid (and the old one a `tblGridChange`
98    /// records), each row's mark, `gridBefore`/`gridAfter` and
99    /// `trPrChange`, each cell's mark (`cellIns`, `cellDel`, `cellMerge`),
100    /// span, width and `vMerge` with the old ones a `tcPrChange` records,
101    /// and its paragraphs as `Text` shows them.
102    Tables,
103    /// Style definitions by type and name (ids name nothing across
104    /// documents): docDefaults, then each style's default flag, basedOn and
105    /// link by name, and its pPr/rPr/tblPr/trPr/tcPr items.
106    StyleDefs,
107    /// List levels by `numId` and level, as paragraphs see them: the
108    /// abstract definition with the list's overrides applied.
109    Numbering,
110    /// What each story part should put on the page: sections, tables (size,
111    /// style, float, direct, cell and style shading, first row), frames,
112    /// anchored drawings, fields, paragraph styles and shading, text colour,
113    /// highlight, run shading, hidden text, requested fonts and the order of
114    /// deleted and inserted runs; `(layout)` adds jubarte's page count and
115    /// the face each font resolved to.
116    #[cfg(feature = "render")]
117    Render,
118}
119
120/// The checks a bare `jubarte debug FILE` runs.
121pub const TRIAGE: [Check; 5] = [
122    Check::Orphans,
123    Check::Fields,
124    Check::Bookmarks,
125    Check::Package,
126    Check::Structure,
127];
128
129/// Report options.
130#[derive(Clone, Debug)]
131pub struct Options {
132    /// Reports to print.
133    pub checks: Vec<Check>,
134    /// Only parts whose name contains this.
135    pub part: Option<String>,
136    /// `textbox`: only stories whose text contains this; `text`, `runs`,
137    /// `xml`, `changes`, `tables`, `styledefs`, `numbering`: only lines that
138    /// hold it, a `runs` line read as plain text, printed whole.
139    pub grep: Option<String>,
140    /// Examples per finding kind, lines per listing.
141    pub limit: usize,
142    /// `text`/`xml`/`runs` of two files: common lines shown around each
143    /// change.
144    pub context: usize,
145    /// `text`, `xml`, `runs`, `changes`, `styledefs`, `numbering`, `render`:
146    /// each line whole, not clipped at 200 characters.
147    pub full_lines: bool,
148}
149
150impl Default for Options {
151    fn default() -> Self {
152        Options {
153            checks: TRIAGE.to_vec(),
154            part: None,
155            grep: None,
156            limit: 5,
157            context: 0,
158            full_lines: false,
159        }
160    }
161}
162
163/// Longest line a report prints.
164const WIDTH: usize = 200;
165/// Longest text box XML a report prints.
166const TEXTBOX_XML: usize = 1500;
167
168/// One zip entry.
169struct Entry {
170    name: String,
171    size: u64,
172    packed: u64,
173    data: Vec<u8>,
174}
175
176/// A package's zip entries, in archive order.
177struct Package {
178    entries: Vec<Entry>,
179    /// The package's bytes, for the render check's layout pass.
180    #[cfg(feature = "render")]
181    raw: Vec<u8>,
182    /// The package's structural zip defects: a package every reader
183    /// refuses is still a package a maintainer must triage, so `debug`
184    /// opens it unchecked and reports each defect as a finding.
185    defects: Vec<crate::opc::ZipDefect>,
186}
187
188impl Package {
189    fn open(bytes: &[u8]) -> Result<Self, String> {
190        Self::open_within(bytes, crate::admission::InputLimits::compare())
191    }
192
193    /// [`Package::open`] under an explicit budget, so the caps are provable
194    /// with budgets small enough for a test (#645). The compressed size and
195    /// the declared entry count run before the archive is indexed, each
196    /// entry inflates through a capped reader with a checked cumulative
197    /// total, and no allocation is sized from the central directory's
198    /// declared sizes: the initial capacity follows the Markdown reader's
199    /// `min(size, 16 MiB)` rule (`markdown::from_docx::ooxml`).
200    fn open_within(bytes: &[u8], limits: crate::admission::InputLimits) -> Result<Self, String> {
201        // Preserve the diagnostic reader's malformed-ZIP prefix while keeping
202        // budget refusals identical to admission's INPUT_LIMIT wording.
203        let budget_error = |error: crate::admission::AdmissionError| {
204            if error.kind == crate::admission::AdmissionErrorKind::InputLimit {
205                error.to_string()
206            } else {
207                format!("not a zip: {error}")
208            }
209        };
210        crate::admission::preindex_budget(bytes, limits).map_err(budget_error)?;
211        // Read Strict packages as the Transitional the checks describe, as
212        // the comparer does at load. The rewrite touches namespace
213        // declarations and relationship types alone and hands a package
214        // with none of them back byte-identical, so a Transitional file
215        // that merely quotes a Strict URI in its text is reported as the
216        // bytes it carries (#531), while a package whose subparts alone
217        // are Strict is translated too, as before the main-part gate
218        // (#561).
219        // A ZIP32 plan refusal keeps the original bytes: triage reports on
220        // the package as found rather than refusing its one openable file.
221        let translated =
222            crate::strict_translation::strict_to_transitional_docx_within(bytes, limits)
223                .unwrap_or_else(|_| bytes.to_vec());
224        let bytes = translated.as_slice();
225        crate::admission::preindex_budget(bytes, limits).map_err(budget_error)?;
226        let mut zip = crate::opc::open_archive_unchecked(Cursor::new(bytes))
227            .map_err(|e| format!("not a zip: {e}"))?;
228        let mut defects = crate::opc::zip_defects(&zip, &mut Cursor::new(bytes));
229        let mut entries = Vec::with_capacity(zip.len());
230        let mut total = 0u64;
231        let mut elements = 0u64;
232        for i in 0..zip.len() {
233            // Every read failure is a finding named for the entry: where
234            // a reading route refuses, triage keeps going so the
235            // structural findings collected above still reach the
236            // report (#644). `by_index` borrows `zip` mutably while its
237            // result lives, so the central name is resolved first.
238            let shown = zip.name_for_index(i).and_then(Result::ok).map_or_else(
239                || "unnamed".to_string(),
240                |name| format!("'{}'", crate::admission::shown(&name)),
241            );
242            let mut f = match zip.by_index(i) {
243                Ok(f) => f,
244                Err(error) => {
245                    defects.push(crate::opc::ZipDefect {
246                        kind: crate::opc::ZipDefectKind::EntryRead,
247                        detail: format!("entry {i} ({shown}) cannot be opened: {error}"),
248                    });
249                    continue;
250                }
251            };
252            // Names reach every finding and the report: decode escapes
253            // control characters so a crafted name cannot write terminal
254            // sequences when the report is displayed.
255            let name = match f.name() {
256                Ok(name) => crate::admission::shown(&name).into_owned(),
257                Err(error) => {
258                    defects.push(crate::opc::ZipDefect {
259                        kind: crate::opc::ZipDefectKind::EntryRead,
260                        detail: format!("entry {i} ({shown}) has an unreadable name: {error}"),
261                    });
262                    continue;
263                }
264            };
265            if f.size() > limits.max_part_bytes {
266                return Err(
267                    crate::admission::part_declared_over(&name, f.size(), &limits).to_string(),
268                );
269            }
270            let cap = limits
271                .max_part_bytes
272                .min(limits.max_uncompressed_bytes.saturating_sub(total));
273            let mut data = Vec::with_capacity(
274                usize::try_from(f.size().min(cap).min(16 * 1024 * 1024)).unwrap_or(0),
275            );
276            let read = match (&mut f).take(cap.saturating_add(1)).read_to_end(&mut data) {
277                Ok(read) => read,
278                Err(error) if f.is_dir() => {
279                    defects.push(crate::opc::ZipDefect {
280                        kind: crate::opc::ZipDefectKind::DirectoryPayload,
281                        detail: format!(
282                            "directory entry '{name}' has an unreadable payload: {error}"
283                        ),
284                    });
285                    // A read that fails after producing bytes still owes
286                    // the budget what `data` holds: uncharged failures
287                    // would hand the next entry a fresh allowance.
288                    crate::admission::tally_inflated(
289                        &mut total,
290                        data.len() as u64,
291                        &name,
292                        cap,
293                        &limits,
294                    )
295                    .map_err(|e| e.to_string())?;
296                    continue;
297                }
298                Err(error) => {
299                    defects.push(crate::opc::ZipDefect {
300                        kind: crate::opc::ZipDefectKind::EntryRead,
301                        detail: format!("entry '{name}' has an unreadable payload: {error}"),
302                    });
303                    crate::admission::tally_inflated(
304                        &mut total,
305                        data.len() as u64,
306                        &name,
307                        cap,
308                        &limits,
309                    )
310                    .map_err(|e| e.to_string())?;
311                    continue;
312                }
313            };
314            crate::admission::tally_inflated(&mut total, read as u64, &name, cap, &limits)
315                .map_err(|e| e.to_string())?;
316            // The element budget holds here too (#2014): `xml_parts`
317            // parses every XML part into a tree.
318            crate::admission::count_xml_elements(&mut elements, &name, &data, &limits)
319                .map_err(|e| e.to_string())?;
320            entries.push(Entry {
321                name,
322                size: f.size(),
323                packed: f.compressed_size(),
324                data,
325            });
326        }
327        Ok(Package {
328            entries,
329            #[cfg(feature = "render")]
330            raw: bytes.to_vec(),
331            defects,
332        })
333    }
334
335    /// XML parts selected by `part`, parsed. A part that does not parse is
336    /// reported as a finding instead.
337    fn xml_parts(&self, part: Option<&str>, findings: &mut Findings) -> Vec<(String, Dom, NodeId)> {
338        let mut out = Vec::new();
339        for e in &self.entries {
340            if !(e.name.ends_with(".xml") || e.name.ends_with(".rels")) {
341                continue;
342            }
343            if part.is_some_and(|p| !e.name.contains(p)) {
344                continue;
345            }
346            let Some(xml) = decode_xml(&e.data) else {
347                findings.add("xml-undecodable", &e.name, String::new());
348                continue;
349            };
350            let parsed = std::panic::catch_unwind(|| {
351                let mut dom = Dom::new();
352                let doc = dom.parse_xdocument(&xml);
353                let root = dom.root(doc);
354                (dom, root)
355            });
356            match parsed {
357                Ok((dom, Some(root))) => out.push((e.name.clone(), dom, root)),
358                _ => findings.add("xml-unparsable", &e.name, String::new()),
359            }
360        }
361        out
362    }
363}
364
365/// A part's XML text: UTF-8, or UTF-16 behind its byte order mark (custom
366/// XML parts are often UTF-16).
367fn decode_xml(data: &[u8]) -> Option<String> {
368    let utf16 = |be: bool| {
369        let (chunks, _) = data[2..].as_chunks::<2>();
370        let units: Vec<u16> = chunks
371            .iter()
372            .map(|c| {
373                if be {
374                    u16::from_be_bytes(*c)
375                } else {
376                    u16::from_le_bytes(*c)
377                }
378            })
379            .collect();
380        String::from_utf16(&units).ok()
381    };
382    match data {
383        [0xFF, 0xFE, ..] => utf16(false),
384        [0xFE, 0xFF, ..] => utf16(true),
385        [0xEF, 0xBB, 0xBF, rest @ ..] => std::str::from_utf8(rest).ok().map(str::to_string),
386        _ => std::str::from_utf8(data).ok().map(str::to_string),
387    }
388}
389
390/// Findings by kind, each with its examples in document order.
391#[derive(Default)]
392struct Findings {
393    by_kind: BTreeMap<String, Vec<(String, String)>>,
394    /// In step with `by_kind`: where each example sits, as `validate`'s
395    /// element chain ([`crate::validate::element_path`]), or empty.
396    places: BTreeMap<String, Vec<String>>,
397}
398
399impl Findings {
400    fn add(&mut self, kind: &str, part: &str, detail: String) {
401        self.push(kind, part, detail, String::new());
402    }
403
404    /// [`Findings::add`] for an example at element `n`.
405    fn add_at(&mut self, kind: &str, part: &str, detail: String, dom: &Dom, n: NodeId) {
406        self.push(kind, part, detail, crate::validate::element_path(dom, n));
407    }
408
409    fn push(&mut self, kind: &str, part: &str, detail: String, place: String) {
410        self.by_kind
411            .entry(kind.to_string())
412            .or_default()
413            .push((part.to_string(), detail));
414        self.places.entry(kind.to_string()).or_default().push(place);
415    }
416}
417
418fn local(dom: &Dom, n: NodeId) -> String {
419    dom.name(n)
420        .map(|x| x.local_name().to_string())
421        .unwrap_or_default()
422}
423
424/// Whether a table cell's content ends in a paragraph. A cell-level content
425/// control counts by what its content ends in: Word writes and opens a cell
426/// whose last child is a `w:sdt` (nested or not) ending in a `w:p`. Each level
427/// skips only its own properties (`w:tcPr`; a control's `w:sdtContent` comes
428/// after its `w:sdtPr` and `w:sdtEndPr`).
429pub(crate) fn cell_ends_in_paragraph(dom: &Dom, tc: NodeId) -> bool {
430    let mut node = tc;
431    let mut properties = Some("tcPr");
432    loop {
433        let last = dom
434            .elements(node, None)
435            .into_iter()
436            .map(|c| (c, local(dom, c)))
437            .rfind(|(_, name)| Some(name.as_str()) != properties);
438        match last {
439            Some((_, name)) if name == "p" => return true,
440            Some((sdt, name)) if name == "sdt" => {
441                match dom.elements(sdt, None).last().map(|&c| (c, local(dom, c))) {
442                    Some((content, name)) if name == "sdtContent" => node = content,
443                    _ => return false,
444                }
445                properties = None;
446            }
447            _ => return false,
448        }
449    }
450}
451
452/// Story boundaries: a text box is a story inside the story that anchors it.
453const STORIES: [&str; 7] = [
454    "txbxContent",
455    "body",
456    "hdr",
457    "ftr",
458    "footnote",
459    "endnote",
460    "comment",
461];
462const REVISIONS: [&str; 4] = ["ins", "del", "moveFrom", "moveTo"];
463
464/// `n`'s last few ancestors and itself, outermost first: `p/del/r/delText`.
465fn path(dom: &Dom, n: NodeId) -> String {
466    let mut names: Vec<String> = dom
467        .ancestors(n, None)
468        .iter()
469        .take(5)
470        .map(|&a| local(dom, a))
471        .collect();
472    names.reverse();
473    names.push(local(dom, n));
474    names.join("/")
475}
476
477fn clip(s: &str, max: usize) -> String {
478    let s = crate::util::collapse_whitespace(s);
479    if s.chars().count() <= max {
480        s
481    } else {
482        format!("{}…", s.chars().take(max).collect::<String>())
483    }
484}
485
486/// The nearest story boundary above `n`.
487fn story_of(dom: &Dom, n: NodeId) -> Option<NodeId> {
488    dom.ancestors(n, None)
489        .into_iter()
490        .find(|&a| STORIES.contains(&local(dom, a).as_str()))
491}
492
493/// `D` (deleted), `I` (inserted) or `-`. A deletion in `n`'s own story wins,
494/// even through an insertion or a move destination, as validate's repair
495/// (`under_deletion`) reads it. Otherwise an insertion or move destination
496/// counts.
497fn state(dom: &Dom, n: NodeId) -> char {
498    let mut inserted = false;
499    for a in dom.ancestors(n, None) {
500        match local(dom, a).as_str() {
501            "del" | "moveFrom" => return 'D',
502            "ins" | "moveTo" => inserted = true,
503            s if STORIES.contains(&s) => break,
504            _ => {}
505        }
506    }
507    if inserted { 'I' } else { '-' }
508}
509
510/// The deletion around a text box's anchor, in the story that holds it.
511fn anchor_deleted(dom: &Dom, tb: NodeId) -> bool {
512    for a in dom.ancestors(tb, None) {
513        match local(dom, a).as_str() {
514            "del" => return true,
515            "txbxContent" => return false,
516            _ => {}
517        }
518    }
519    false
520}
521
522fn check_orphans(dom: &Dom, root: NodeId, part: &str, f: &mut Findings) {
523    for n in dom.descendants(root, None) {
524        let name = local(dom, n);
525        match name.as_str() {
526            "delText" | "delInstrText" if state(dom, n) != 'D' => f.add_at(
527                &format!("orphan-{name}"),
528                part,
529                format!("{} \"{}\"", path(dom, n), clip(&dom.value(n), 40)),
530                dom,
531                n,
532            ),
533            "t" | "instrText"
534                if state(dom, n) == 'D'
535                    && dom
536                        .ancestors(n, None)
537                        .iter()
538                        .any(|&a| local(dom, a) == "del") =>
539            {
540                f.add_at(
541                    &format!("{name}-under-del"),
542                    part,
543                    format!("{} \"{}\"", path(dom, n), clip(&dom.value(n), 40)),
544                    dom,
545                    n,
546                );
547            }
548            "r" => {
549                // A bare run in a text box whose anchor is deleted.
550                let mut tb = None;
551                for a in dom.ancestors(n, None) {
552                    let an = local(dom, a);
553                    if REVISIONS.contains(&an.as_str()) {
554                        break;
555                    }
556                    if an == "txbxContent" {
557                        tb = Some(a);
558                        break;
559                    }
560                }
561                if let Some(tb) = tb
562                    && anchor_deleted(dom, tb)
563                {
564                    let kids: Vec<String> = dom
565                        .elements(n, None)
566                        .into_iter()
567                        .map(|c| local(dom, c))
568                        .filter(|c| c != "rPr")
569                        .collect();
570                    f.add_at(
571                        "bare-run-in-deleted-textbox",
572                        part,
573                        format!(
574                            "{} [{}] \"{}\"",
575                            path(dom, n),
576                            kids.join(","),
577                            clip(&dom.value(n), 30)
578                        ),
579                        dom,
580                        n,
581                    );
582                }
583            }
584            _ => {}
585        }
586    }
587}
588
589struct OpenField {
590    begin: char,
591    separate: Option<char>,
592    instr: Vec<(bool, char)>,
593    code: String,
594    at: String,
595    node: NodeId,
596}
597
598fn check_fields(dom: &Dom, root: NodeId, part: &str, f: &mut Findings) {
599    let mut stacks: HashMap<Option<NodeId>, Vec<OpenField>> = HashMap::new();
600    for n in dom.descendants(root, None) {
601        let name = local(dom, n);
602        let is_instr = name == "instrText" || name == "delInstrText";
603        if name != "fldChar" && !is_instr {
604            continue;
605        }
606        let stack = stacks.entry(story_of(dom, n)).or_default();
607        let st = state(dom, n);
608        if is_instr {
609            match stack.last_mut() {
610                Some(open) => {
611                    open.instr.push((name == "delInstrText", st));
612                    open.code.push_str(&dom.value(n));
613                }
614                None => f.add_at("field-code-outside-field", part, path(dom, n), dom, n),
615            }
616            continue;
617        }
618        let kind = dom
619            .attributes(n)
620            .into_iter()
621            .find(|(k, _)| k.local_name() == "fldCharType")
622            .map(|(_, v)| v)
623            .unwrap_or_default();
624        match kind.as_str() {
625            "begin" => stack.push(OpenField {
626                begin: st,
627                separate: None,
628                instr: Vec::new(),
629                code: String::new(),
630                at: path(dom, n),
631                node: n,
632            }),
633            "separate" => match stack.last_mut() {
634                Some(open) => open.separate = Some(st),
635                None => f.add_at("field-separate-without-begin", part, path(dom, n), dom, n),
636            },
637            "end" => {
638                let Some(open) = stack.pop() else {
639                    f.add_at("field-end-without-begin", part, path(dom, n), dom, n);
640                    continue;
641                };
642                let states: String = std::iter::once(open.begin)
643                    .chain(open.instr.iter().map(|&(_, s)| s))
644                    .chain(open.separate)
645                    .chain(std::iter::once(st))
646                    .collect();
647                let code = clip(&open.code, 40);
648                if states.contains('D') && states.chars().any(|c| c != 'D') {
649                    f.add_at(
650                        "field-partly-deleted",
651                        part,
652                        format!("begin/code/separate/end={states} \"{code}\" at {}", open.at),
653                        dom,
654                        open.node,
655                    );
656                }
657                if open.instr.iter().any(|&(del, s)| del != (s == 'D')) {
658                    f.add_at(
659                        "field-code-kind-vs-state",
660                        part,
661                        format!("states={states} \"{code}\" at {}", open.at),
662                        dom,
663                        open.node,
664                    );
665                }
666            }
667            _ => {}
668        }
669    }
670    for open in stacks.into_values().flatten() {
671        f.add_at(
672            "field-unclosed",
673            part,
674            format!("\"{}\" at {}", clip(&open.code, 40), open.at),
675            dom,
676            open.node,
677        );
678    }
679}
680
681fn attr(dom: &Dom, n: NodeId, name: &str) -> String {
682    dom.attributes(n)
683        .into_iter()
684        .find(|(k, _)| k.local_name() == name)
685        .map(|(_, v)| v)
686        .unwrap_or_default()
687}
688
689fn check_bookmarks(
690    dom: &Dom,
691    root: NodeId,
692    part: &str,
693    f: &mut Findings,
694    chains: Option<&mut BTreeMap<String, usize>>,
695) {
696    let marks: Vec<NodeId> = dom
697        .descendants(root, None)
698        .into_iter()
699        .filter(|&n| matches!(local(dom, n).as_str(), "bookmarkStart" | "bookmarkEnd"))
700        .collect();
701    let mut starts: HashMap<String, NodeId> = HashMap::new();
702    let mut names: HashSet<String> = HashSet::new();
703    let mut ended: HashSet<String> = HashSet::new();
704    for &m in &marks {
705        let id = attr(dom, m, "id");
706        if local(dom, m) == "bookmarkStart" {
707            let name = attr(dom, m, "name");
708            if !names.insert(name.clone()) {
709                f.add("bookmark-duplicate-name", part, name.clone());
710            }
711            if starts.insert(id.clone(), m).is_some() {
712                f.add("bookmark-duplicate-id", part, format!("id {id} ({name})"));
713            }
714            if ended.contains(&id) {
715                f.add(
716                    "bookmark-end-before-start",
717                    part,
718                    format!("id {id} ({name})"),
719                );
720            }
721        } else if !ended.insert(id.clone()) {
722            f.add("bookmark-duplicate-end", part, format!("id {id}"));
723        }
724    }
725    for (id, &s) in &starts {
726        if !ended.contains(id) {
727            f.add(
728                "bookmark-start-without-end",
729                part,
730                format!("id {id} ({})", attr(dom, s, "name")),
731            );
732        }
733    }
734    for id in &ended {
735        if !starts.contains_key(id) {
736            f.add("bookmark-end-without-start", part, format!("id {id}"));
737        }
738    }
739    let within = |n: NodeId, set: &[&str]| -> Vec<NodeId> {
740        dom.ancestors(n, None)
741            .into_iter()
742            .filter(|&a| set.contains(&local(dom, a).as_str()))
743            .collect()
744    };
745    for &e in marks.iter().filter(|&&m| local(dom, m) == "bookmarkEnd") {
746        let Some(&s) = starts.get(&attr(dom, e, "id")) else {
747            continue;
748        };
749        for (label, set) in [
750            ("sdt", &["sdtContent"][..]),
751            ("cell", &["tc"][..]),
752            ("textbox", &["txbxContent"][..]),
753            // Deleted and moved-away text can hold a source endpoint:
754            // Accept hoists it; Reject restores it (#1176, #1195).
755            // Insertions and move destinations remain placement guards
756            // for #827, though Word tolerates these crossings (#1195).
757            ("revision", &["ins", "moveTo"][..]),
758        ] {
759            if within(s, set) != within(e, set) {
760                f.add(
761                    &format!("bookmark-crosses-{label}"),
762                    part,
763                    format!(
764                        "{}: start {} and end {} sit in different {label} containers",
765                        attr(dom, s, "name"),
766                        path(dom, s),
767                        path(dom, e)
768                    ),
769                );
770            }
771        }
772    }
773    for &m in &marks {
774        let control = dom
775            .ancestors(m, None)
776            .into_iter()
777            .filter(|&a| local(dom, a) == "sdt")
778            .find_map(|sdt| single_value_control(dom, sdt));
779        if let Some(control) = control {
780            let id = attr(dom, m, "id");
781            let name = starts
782                .get(&id)
783                .map_or(String::new(), |&s| attr(dom, s, "name"));
784            f.add(
785                &format!("bookmark-in-{control}-control"),
786                part,
787                format!("{name} (id {id}) {}", path(dom, m)),
788            );
789        }
790    }
791    if let Some(chains) = chains {
792        for &m in &marks {
793            let mut names: Vec<String> = dom
794                .ancestors(m, None)
795                .into_iter()
796                .map(|a| local(dom, a))
797                .take_while(|a| !STORIES.contains(&a.as_str()))
798                .collect();
799            names.reverse();
800            let kind = if local(dom, m) == "bookmarkStart" {
801                "start"
802            } else {
803                "end"
804            };
805            *chains
806                .entry(format!("{part} {kind} {}", names.join("/")))
807                .or_default() += 1;
808        }
809    }
810}
811
812/// Content controls that hold one value. Word keeps no bookmark in one: it
813/// refused en 7b649361 and 57c181da until those bookmarks were dropped.
814const SINGLE_VALUE_CONTROLS: [&str; 6] = [
815    "text",
816    "dropDownList",
817    "comboBox",
818    "date",
819    "picture",
820    "checkbox",
821];
822
823/// The single-value kind `sdt` declares in its `w:sdtPr`, if any.
824fn single_value_control(dom: &Dom, sdt: NodeId) -> Option<String> {
825    let pr = dom
826        .elements(sdt, None)
827        .into_iter()
828        .find(|&c| local(dom, c) == "sdtPr")?;
829    dom.elements(pr, None)
830        .into_iter()
831        .map(|c| local(dom, c))
832        .find(|k| SINGLE_VALUE_CONTROLS.contains(&k.as_str()))
833}
834
835const RELATIONSHIPS_NS: &str =
836    "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
837
838/// `%XX` escapes decoded, so a rel target and a zip entry name compare as the
839/// part names they are.
840fn percent_decode(s: &str) -> String {
841    let b = s.as_bytes();
842    let mut out = Vec::with_capacity(b.len());
843    let mut i = 0;
844    while i < b.len() {
845        let hex = |c: u8| (c as char).to_digit(16);
846        if b[i] == b'%'
847            && i + 2 < b.len()
848            && let (Some(h), Some(l)) = (hex(b[i + 1]), hex(b[i + 2]))
849        {
850            out.push((h * 16 + l) as u8);
851            i += 3;
852        } else {
853            out.push(b[i]);
854            i += 1;
855        }
856    }
857    String::from_utf8_lossy(&out).into_owned()
858}
859
860/// The part a rel target names: relative to the folder of the rels file's
861/// source part, `.`/`..` resolved, no leading slash.
862fn resolve_target(rels: &str, target: &str) -> String {
863    let source_dir = rels
864        .rsplit_once("_rels/")
865        .map_or("", |(dir, _)| dir.trim_end_matches('/'));
866    let joined = match target.strip_prefix('/') {
867        Some(abs) => abs.to_string(),
868        None if source_dir.is_empty() => target.to_string(),
869        None => format!("{source_dir}/{target}"),
870    };
871    let mut segments: Vec<&str> = Vec::new();
872    for seg in joined.split('/') {
873        match seg {
874            "" | "." => {}
875            ".." => {
876                segments.pop();
877            }
878            s => segments.push(s),
879        }
880    }
881    segments.join("/")
882}
883
884/// The rels file that holds `part`'s relationships.
885fn rels_of(part: &str) -> String {
886    match part.rsplit_once('/') {
887        Some((dir, name)) => format!("{dir}/_rels/{name}.rels"),
888        None => format!("_rels/{part}.rels"),
889    }
890}
891
892fn elements_named<'a>(
893    dom: &'a Dom,
894    root: NodeId,
895    name: &'a str,
896) -> impl Iterator<Item = NodeId> + 'a {
897    dom.descendants(root, None)
898        .into_iter()
899        .filter(move |&n| local(dom, n) == name)
900}
901
902/// Office's legacy `[trash]/` folder: its entries are no parts and need no
903/// content type; Word ignores them.
904pub(crate) const OFFICE_TRASH: &str = "[trash]/";
905
906fn check_package(pkg: &Package, parts: &[(String, Dom, NodeId)], f: &mut Findings) {
907    const CT: &str = "[Content_Types].xml";
908    let names: HashSet<String> = pkg
909        .entries
910        .iter()
911        .filter(|e| !e.name.ends_with('/') && !e.name.starts_with(OFFICE_TRASH))
912        .map(|e| percent_decode(&e.name))
913        .collect();
914    let by_name: HashMap<&str, (&Dom, NodeId)> = parts
915        .iter()
916        .map(|(n, d, r)| (n.as_str(), (d, *r)))
917        .collect();
918
919    if let Some(&(dom, root)) = by_name.get(CT) {
920        let mut defaults = HashSet::new();
921        let mut overrides = HashSet::new();
922        for n in dom.elements(root, None) {
923            match local(dom, n).as_str() {
924                "Default" => {
925                    defaults.insert(attr(dom, n, "Extension").to_ascii_lowercase());
926                }
927                "Override" => {
928                    overrides.insert(percent_decode(
929                        attr(dom, n, "PartName").trim_start_matches('/'),
930                    ));
931                }
932                _ => {}
933            }
934        }
935        for name in names.iter().filter(|n| n.as_str() != CT) {
936            let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase());
937            if !overrides.contains(name) && !ext.is_some_and(|e| defaults.contains(&e)) {
938                f.add("part-without-content-type", name, String::new());
939            }
940        }
941        for o in overrides.iter().filter(|o| !names.contains(*o)) {
942            f.add("override-without-part", CT, o.clone());
943        }
944    } else {
945        f.add("content-types-missing", CT, String::new());
946    }
947
948    // Relationship ids per rels file, and targets that name no part.
949    let mut rel_ids: HashMap<&str, HashSet<String>> = HashMap::new();
950    for (name, dom, root) in parts.iter().filter(|(n, ..)| n.ends_with(".rels")) {
951        let ids = rel_ids.entry(name.as_str()).or_default();
952        for r in dom.elements(*root, None) {
953            let id = attr(dom, r, "Id");
954            if !ids.insert(id.clone()) {
955                f.add("rel-duplicate-id", name, id.clone());
956            }
957            if attr(dom, r, "TargetMode") == "External" {
958                continue;
959            }
960            let target = attr(dom, r, "Target");
961            if !names.contains(&percent_decode(&resolve_target(name, &target))) {
962                f.add("rel-target-missing", name, format!("{id} → {target}"));
963            }
964        }
965    }
966
967    // Ids a note or comment reference can name.
968    let ids_in = |part: &str, tag: &str| -> Option<HashSet<String>> {
969        by_name.get(part).map(|&(dom, root)| {
970            elements_named(dom, root, tag)
971                .map(|n| attr(dom, n, "id"))
972                .collect()
973        })
974    };
975    let targets = [
976        (
977            "footnoteReference",
978            ids_in("word/footnotes.xml", "footnote"),
979        ),
980        ("endnoteReference", ids_in("word/endnotes.xml", "endnote")),
981        ("commentReference", ids_in("word/comments.xml", "comment")),
982    ];
983    for (name, dom, root) in parts
984        .iter()
985        .filter(|(n, ..)| !n.ends_with(".rels") && n.as_str() != CT)
986    {
987        let rels = rel_ids.get(rels_of(name).as_str());
988        let (mut range_starts, mut range_ends) = (HashSet::new(), HashSet::new());
989        for n in dom.descendants(*root, None) {
990            for (k, v) in dom.attributes(n) {
991                // Diagram layouts write empty `r:blip=""` placeholders.
992                if k.namespace_name() == RELATIONSHIPS_NS
993                    && !v.is_empty()
994                    && !rels.is_some_and(|ids| ids.contains(&v))
995                {
996                    f.add(
997                        "rid-not-in-rels",
998                        name,
999                        format!("{} r:{}=\"{v}\"", path(dom, n), k.local_name()),
1000                    );
1001                }
1002            }
1003            let tag = local(dom, n);
1004            match tag.as_str() {
1005                "commentRangeStart" => {
1006                    range_starts.insert(attr(dom, n, "id"));
1007                }
1008                "commentRangeEnd" => {
1009                    range_ends.insert(attr(dom, n, "id"));
1010                }
1011                _ => {}
1012            }
1013            if let Some((_, ids)) = targets.iter().find(|(t, _)| *t == tag) {
1014                let id = attr(dom, n, "id");
1015                if !ids.as_ref().is_some_and(|ids| ids.contains(&id)) {
1016                    f.add(&format!("{tag}-dangling"), name, format!("id {id}"));
1017                }
1018            }
1019        }
1020        for id in range_starts.symmetric_difference(&range_ends) {
1021            f.add("comment-range-unpaired", name, format!("id {id}"));
1022        }
1023        if let Some(e) = pkg.entries.iter().find(|e| &e.name == name) {
1024            let xml = decode_xml(&e.data).unwrap_or_default();
1025            for prefix in undeclared_ignorable_prefixes(&xml) {
1026                f.add("ignorable-prefix-undeclared", name, prefix);
1027            }
1028        }
1029    }
1030}
1031
1032/// `mc:Ignorable` prefixes that the element carrying the attribute does not
1033/// declare.
1034fn undeclared_ignorable_prefixes(xml: &str) -> Vec<String> {
1035    let Some(at) = xml.find("mc:Ignorable=\"") else {
1036        return Vec::new();
1037    };
1038    let tag_start = xml[..at].rfind('<').unwrap_or(0);
1039    let tag_end = xml[at..].find('>').map_or(xml.len(), |e| at + e);
1040    let tag = &xml[tag_start..tag_end];
1041    let value_start = at + "mc:Ignorable=\"".len();
1042    let value = xml[value_start..].split('"').next().unwrap_or_default();
1043    value
1044        .split_whitespace()
1045        .filter(|p| !tag.contains(&format!("xmlns:{p}=")))
1046        .map(str::to_string)
1047        .collect()
1048}
1049
1050fn check_structure(dom: &Dom, root: NodeId, part: &str, f: &mut Findings) {
1051    let mut moves: BTreeMap<String, (usize, usize)> = BTreeMap::new();
1052    for n in dom.descendants(root, None) {
1053        let name = local(dom, n);
1054        match name.as_str() {
1055            "moveFromRangeStart" | "moveToRangeStart" => {
1056                let move_name = attr(dom, n, "name");
1057                if !move_name.is_empty() {
1058                    let counts = moves.entry(move_name).or_default();
1059                    if name == "moveFromRangeStart" {
1060                        counts.0 += 1;
1061                    } else {
1062                        counts.1 += 1;
1063                    }
1064                }
1065            }
1066            "instrText" | "delInstrText" if dom.value(n).is_empty() => {
1067                f.add_at(&format!("{name}-empty"), part, path(dom, n), dom, n);
1068            }
1069            "tc" if !cell_ends_in_paragraph(dom, n) => {
1070                let last = dom
1071                    .elements(n, None)
1072                    .into_iter()
1073                    .map(|c| local(dom, c))
1074                    .rfind(|c| c.as_str() != "tcPr");
1075                f.add_at(
1076                    "cell-not-ending-in-p",
1077                    part,
1078                    format!("{} last={}", path(dom, n), last.unwrap_or_default()),
1079                    dom,
1080                    n,
1081                );
1082            }
1083            "tr" if !dom
1084                .descendants(n, None)
1085                .iter()
1086                .any(|&c| local(dom, c) == "tc") =>
1087            {
1088                f.add_at("row-without-cell", part, path(dom, n), dom, n);
1089            }
1090            // Only `ins`/`del` count as interleaving: Word's measured
1091            // reject-all misreading (#1134, 2026-10-17) alternates the two. A
1092            // move between two same-kind revisions is its own `move-nested`
1093            // kind: Word opens it (#1395), but its reading is unmeasured.
1094            "ins" | "del"
1095                if dom
1096                    .ancestors(n, None)
1097                    .into_iter()
1098                    .take_while(|&a| !STORIES.contains(&local(dom, a).as_str()))
1099                    .any(|a| local(dom, a) == name) =>
1100            {
1101                // One walk up to the outer same-kind revision (or the story).
1102                let (mut interleaved, mut moved) = (false, false);
1103                let mut current = dom.parent(n);
1104                while let Some(a) = current {
1105                    let a_local = local(dom, a);
1106                    if STORIES.contains(&a_local.as_str()) || a_local == name {
1107                        break;
1108                    }
1109                    match a_local.as_str() {
1110                        "ins" | "del" => interleaved = true,
1111                        "moveFrom" | "moveTo" => moved = true,
1112                        _ => {}
1113                    }
1114                    current = dom.parent(a);
1115                }
1116                let relation = if interleaved {
1117                    "interleaved"
1118                } else if moved {
1119                    "move-nested"
1120                } else {
1121                    "nested"
1122                };
1123                f.add_at(
1124                    &format!("{name}-{relation}-in-{name}"),
1125                    part,
1126                    path(dom, n),
1127                    dom,
1128                    n,
1129                );
1130            }
1131            "body" => {
1132                let kids = dom.elements(n, None);
1133                if let Some(i) = kids.iter().position(|&k| local(dom, k) == "sectPr")
1134                    && i + 1 != kids.len()
1135                {
1136                    f.add(
1137                        "body-sectPr-not-last",
1138                        part,
1139                        format!("at {i} of {}", kids.len()),
1140                    );
1141                }
1142            }
1143            _ => {}
1144        }
1145    }
1146    for (name, (source, destination)) in moves {
1147        if source != destination {
1148            f.add(
1149                "move-range-count-mismatch",
1150                part,
1151                format!("{name}: {source} source ranges, {destination} destination ranges; Word opens it but Reject All can duplicate moved text (#1214)"),
1152            );
1153        }
1154    }
1155}
1156
1157/// Revision elements: they share one id space across the package.
1158const REVISION_IDS: [&str; 18] = [
1159    "ins",
1160    "del",
1161    "rPrChange",
1162    "pPrChange",
1163    "sectPrChange",
1164    "tblPrChange",
1165    "trPrChange",
1166    "tcPrChange",
1167    "tblGridChange",
1168    "numberingChange",
1169    "moveFrom",
1170    "moveTo",
1171    "moveFromRangeStart",
1172    "moveToRangeStart",
1173    "cellIns",
1174    "cellDel",
1175    "cellMerge",
1176    "tblPrExChange",
1177];
1178
1179/// Ids one package should hold once: revision ids and drawing `wp:docPr`
1180/// ids. Word opens files that repeat either, so these are leads, not causes.
1181#[derive(Default)]
1182struct IdUses {
1183    revisions: BTreeMap<String, Vec<String>>,
1184    drawings: BTreeMap<String, usize>,
1185}
1186
1187fn collect_ids(dom: &Dom, root: NodeId, part: &str, seen: &mut IdUses) {
1188    for n in dom.descendants(root, None) {
1189        let name = local(dom, n);
1190        if name == "docPr" {
1191            *seen.drawings.entry(attr(dom, n, "id")).or_default() += 1;
1192        } else if REVISION_IDS.contains(&name.as_str()) {
1193            let id = attr(dom, n, "id");
1194            if !id.is_empty() {
1195                seen.revisions
1196                    .entry(id)
1197                    .or_default()
1198                    .push(format!("{part}:{name}"));
1199            }
1200        }
1201    }
1202}
1203
1204const STYLES_PART: &str = "word/styles.xml";
1205
1206/// Style links in `styles.xml` and style references in every part that name
1207/// no defined style, and styles of one type whose names match
1208/// case-insensitively. Word resolves a dangling reference to the default
1209/// style and pairs stylesheets by type and name, so twins merge in Word's
1210/// compare while jubarte keeps both.
1211fn check_styles(parts: &[(String, Dom, NodeId)], f: &mut Findings) {
1212    let Some((_, sd, sr)) = parts.iter().find(|(p, _, _)| p == STYLES_PART) else {
1213        return;
1214    };
1215    let styles: Vec<NodeId> = sd
1216        .descendants(*sr, None)
1217        .into_iter()
1218        .filter(|&n| local(sd, n) == "style")
1219        .collect();
1220    let ids: HashSet<String> = styles.iter().map(|&s| attr(sd, s, "styleId")).collect();
1221    let mut twins: BTreeMap<(String, String), Vec<String>> = BTreeMap::new();
1222    for &s in &styles {
1223        let id = attr(sd, s, "styleId");
1224        let mut ty = attr(sd, s, "type");
1225        if ty.is_empty() {
1226            ty = "paragraph".to_string();
1227        }
1228        let mut name = String::new();
1229        for c in sd.elements(s, None) {
1230            let what = local(sd, c);
1231            let val = attr(sd, c, "val");
1232            match what.as_str() {
1233                "name" => name = val.to_lowercase(),
1234                "basedOn" | "next" | "link" if !ids.contains(&val) => {
1235                    f.add(
1236                        "style-link-dangling",
1237                        STYLES_PART,
1238                        format!("{id} {what} {val}"),
1239                    );
1240                }
1241                _ => {}
1242            }
1243        }
1244        twins.entry((ty, name)).or_default().push(id);
1245    }
1246    for ((ty, name), ids) in twins.into_iter().filter(|(_, v)| v.len() > 1) {
1247        f.add(
1248            "style-name-twin",
1249            STYLES_PART,
1250            format!("{ty} {name:?}: {}", ids.join(", ")),
1251        );
1252    }
1253    for (part, dom, root) in parts {
1254        for n in dom.descendants(*root, None) {
1255            let what = local(dom, n);
1256            if matches!(what.as_str(), "pStyle" | "rStyle" | "tblStyle") {
1257                let val = attr(dom, n, "val");
1258                if !ids.contains(&val) {
1259                    f.add("style-ref-dangling", part, format!("{what} {val}"));
1260                }
1261            }
1262        }
1263    }
1264}
1265
1266/// Everything one package yields for the selected checks.
1267struct Analysis {
1268    findings: Findings,
1269    elements: BTreeMap<String, usize>,
1270    chains: BTreeMap<String, usize>,
1271    textboxes: Vec<String>,
1272}
1273
1274fn analyze(pkg: &Package, opts: &Options) -> Analysis {
1275    let mut a = Analysis {
1276        findings: Findings::default(),
1277        elements: BTreeMap::new(),
1278        chains: BTreeMap::new(),
1279        textboxes: Vec::new(),
1280    };
1281    let on = |c: Check| opts.checks.contains(&c);
1282    for defect in &pkg.defects {
1283        a.findings.add(
1284            defect.finding_kind(),
1285            "package",
1286            defect.refusal().to_string(),
1287        );
1288    }
1289    let parts = pkg.xml_parts(opts.part.as_deref(), &mut a.findings);
1290    if on(Check::Package) {
1291        // Cross-part references need every part, whatever `part` selects.
1292        match opts.part {
1293            None => check_package(pkg, &parts, &mut a.findings),
1294            Some(_) => {
1295                let all = pkg.xml_parts(None, &mut Findings::default());
1296                check_package(pkg, &all, &mut a.findings);
1297            }
1298        }
1299    }
1300    if on(Check::Styles) {
1301        // References need the stylesheet, whatever `part` selects.
1302        match opts.part {
1303            None => check_styles(&parts, &mut a.findings),
1304            Some(_) => {
1305                let all = pkg.xml_parts(None, &mut Findings::default());
1306                check_styles(&all, &mut a.findings);
1307            }
1308        }
1309    }
1310    let mut ids = IdUses::default();
1311    for (part, dom, root) in &parts {
1312        let (part, dom, root) = (part.as_str(), dom, *root);
1313        if on(Check::Orphans) {
1314            check_orphans(dom, root, part, &mut a.findings);
1315        }
1316        if on(Check::Fields) {
1317            check_fields(dom, root, part, &mut a.findings);
1318        }
1319        if on(Check::Structure) {
1320            check_structure(dom, root, part, &mut a.findings);
1321        }
1322        if on(Check::Ids) {
1323            collect_ids(dom, root, part, &mut ids);
1324        }
1325        if on(Check::Bookmarks) || on(Check::Chains) {
1326            let chains = on(Check::Chains).then_some(&mut a.chains);
1327            let mut scratch = Findings::default();
1328            let sink = if on(Check::Bookmarks) {
1329                &mut a.findings
1330            } else {
1331                &mut scratch
1332            };
1333            check_bookmarks(dom, root, part, sink, chains);
1334        }
1335        if on(Check::Elements) {
1336            for n in dom.descendants(root, None) {
1337                *a.elements.entry(local(dom, n)).or_default() += 1;
1338            }
1339        }
1340        if on(Check::Textbox) {
1341            for tb in dom
1342                .descendants(root, None)
1343                .into_iter()
1344                .filter(|&n| local(dom, n) == "txbxContent")
1345            {
1346                if opts
1347                    .grep
1348                    .as_deref()
1349                    .is_some_and(|g| !dom.value(tb).contains(g))
1350                {
1351                    continue;
1352                }
1353                let deleted = if anchor_deleted(dom, tb) {
1354                    " (anchor deleted)"
1355                } else {
1356                    ""
1357                };
1358                let xml = strip_namespace_declarations(&dom.serialize_element(tb));
1359                let shown = if xml.chars().count() > TEXTBOX_XML {
1360                    format!(
1361                        "{}… ({} chars; narrow with --grep)",
1362                        xml.chars().take(TEXTBOX_XML).collect::<String>(),
1363                        xml.chars().count()
1364                    )
1365                } else {
1366                    xml
1367                };
1368                a.textboxes
1369                    .push(format!("{part} {}{deleted}\n  {shown}", path(dom, tb)));
1370            }
1371        }
1372    }
1373    for (id, uses) in ids.revisions.into_iter().filter(|(_, u)| u.len() > 1) {
1374        a.findings.add(
1375            "revision-duplicate-id",
1376            "package",
1377            format!("id {id} ×{}: {}", uses.len(), uses.join(", ")),
1378        );
1379    }
1380    for (id, n) in ids.drawings.into_iter().filter(|&(_, n)| n > 1) {
1381        a.findings
1382            .add("docpr-duplicate-id", "package", format!("id {id} ×{n}"));
1383    }
1384    a
1385}
1386
1387/// Drop every ` xmlns…="…"` so the XML shows only content.
1388fn strip_namespace_declarations(xml: &str) -> String {
1389    let mut out = String::with_capacity(xml.len());
1390    let mut rest = xml;
1391    while let Some(i) = rest.find(" xmlns") {
1392        out.push_str(&rest[..i]);
1393        let tail = &rest[i..];
1394        let Some(q) = tail.find('"') else {
1395            rest = tail;
1396            break;
1397        };
1398        match tail[q + 1..].find('"') {
1399            Some(e) => rest = &tail[q + 1 + e + 1..],
1400            None => {
1401                rest = tail;
1402                break;
1403            }
1404        }
1405    }
1406    out.push_str(rest);
1407    out
1408}
1409
1410/// Root elements of the parts `text` walks.
1411const TEXT_PARTS: [&str; 6] = [
1412    "document",
1413    "hdr",
1414    "ftr",
1415    "footnotes",
1416    "endnotes",
1417    "comments",
1418];
1419
1420/// Direct properties of `pr` (a `pPr` or `rPr`) on one line: children sorted,
1421/// `name`, `name=val` or `name(attr=value,…)`; revision records, the mark's
1422/// `rPr` and `sectPr` left out.
1423fn props_line(dom: &Dom, pr: NodeId) -> String {
1424    let mut items: Vec<String> = dom
1425        .nodes(pr)
1426        .into_iter()
1427        .filter(|&c| dom.is_element(c))
1428        .filter(|&c| {
1429            !matches!(
1430                local(dom, c).as_str(),
1431                "ins"
1432                    | "del"
1433                    | "moveFrom"
1434                    | "moveTo"
1435                    | "rPrChange"
1436                    | "pPrChange"
1437                    | "rPr"
1438                    | "sectPr"
1439            )
1440        })
1441        .map(|c| {
1442            let name = local(dom, c);
1443            let mut attrs: Vec<(String, String)> = dom
1444                .attributes(c)
1445                .into_iter()
1446                .filter(|(n, _)| !n.local_name().starts_with("rsid"))
1447                .map(|(n, v)| (n.local_name().to_string(), v))
1448                .collect();
1449            attrs.sort();
1450            match attrs.as_slice() {
1451                [] => name,
1452                [(k, v)] if k == "val" => format!("{name}={v}"),
1453                _ => {
1454                    let a: Vec<String> = attrs.iter().map(|(k, v)| format!("{k}={v}")).collect();
1455                    format!("{name}({})", a.join(","))
1456                }
1457            }
1458        })
1459        .collect();
1460    items.sort();
1461    items.join(" ")
1462}
1463
1464/// The property-change records `changes` lists.
1465const CHANGE_RECORDS: [&str; 8] = [
1466    "pPrChange",
1467    "rPrChange",
1468    "tblPrChange",
1469    "tblPrExChange",
1470    "trPrChange",
1471    "tcPrChange",
1472    "sectPrChange",
1473    "tblGridChange",
1474];
1475
1476/// Each child of the property block `pr` as one item: `name`, `name=val`
1477/// or `name(attr=value,…)`, its own children in braces; revision records,
1478/// the mark's `rPr` and `sectPr` left out. Sorted.
1479fn prop_items(dom: &Dom, pr: NodeId) -> Vec<String> {
1480    fn item(dom: &Dom, c: NodeId) -> String {
1481        let name = local(dom, c);
1482        let mut attrs: Vec<(String, String)> = dom
1483            .attributes(c)
1484            .into_iter()
1485            .filter(|(n, _)| {
1486                !n.local_name().starts_with("rsid") && !dom.is_namespace_declaration(n)
1487            })
1488            .map(|(n, v)| (n.local_name().to_string(), v))
1489            .collect();
1490        attrs.sort();
1491        let mut s = match attrs.as_slice() {
1492            [] => name,
1493            [(k, v)] if k == "val" => format!("{name}={v}"),
1494            _ => {
1495                let a: Vec<String> = attrs.iter().map(|(k, v)| format!("{k}={v}")).collect();
1496                format!("{name}({})", a.join(","))
1497            }
1498        };
1499        let kids: Vec<String> = dom
1500            .nodes(c)
1501            .into_iter()
1502            .filter(|&k| dom.is_element(k))
1503            .map(|k| item(dom, k))
1504            .collect();
1505        if !kids.is_empty() {
1506            s.push('{');
1507            s.push_str(&kids.join(" "));
1508            s.push('}');
1509        }
1510        s
1511    }
1512    let mut items: Vec<String> = dom
1513        .nodes(pr)
1514        .into_iter()
1515        .filter(|&c| dom.is_element(c))
1516        .filter(|&c| {
1517            let n = local(dom, c);
1518            !CHANGE_RECORDS.contains(&n.as_str())
1519                && !matches!(
1520                    n.as_str(),
1521                    "ins" | "del" | "moveFrom" | "moveTo" | "rPr" | "sectPr"
1522                )
1523        })
1524        .map(|c| item(dom, c))
1525        .collect();
1526    items.sort();
1527    items
1528}
1529
1530/// `changes`: one line per property-change record of a part — its kind,
1531/// where it sits (style id, or the start of the cell, row, table or
1532/// paragraph text) and what the live properties add (`+`) and drop (`-`)
1533/// against the recorded old ones. Returns the lines and the record count.
1534fn change_lines(dom: &Dom, root: NodeId) -> (Vec<String>, usize) {
1535    let text_of = |n: NodeId| -> String {
1536        let t: String = dom
1537            .descendants(n, None)
1538            .into_iter()
1539            .filter(|&d| matches!(local(dom, d).as_str(), "t" | "delText"))
1540            .map(|d| dom.value(d))
1541            .collect();
1542        t.chars().take(30).collect()
1543    };
1544    let mut lines = Vec::new();
1545    for rec in dom.descendants(root, None) {
1546        let kind = local(dom, rec);
1547        if !CHANGE_RECORDS.contains(&kind.as_str()) {
1548            continue;
1549        }
1550        let Some(live) = dom.parent(rec) else {
1551            continue;
1552        };
1553        let old = dom.nodes(rec).into_iter().find(|&c| dom.is_element(c));
1554        let place = dom
1555            .ancestors(rec, None)
1556            .into_iter()
1557            .find_map(|a| match local(dom, a).as_str() {
1558                "style" => Some(format!("style={}", attr(dom, a, "styleId"))),
1559                "p" | "tc" | "tr" | "tbl" => Some(format!("{} \"{}\"", local(dom, a), text_of(a))),
1560                _ => None,
1561            })
1562            .unwrap_or_default();
1563        let l = prop_items(dom, live);
1564        let o = old.map(|o| prop_items(dom, o)).unwrap_or_default();
1565        let mut diff: Vec<String> = l
1566            .iter()
1567            .filter(|x| !o.contains(x))
1568            .map(|x| format!("+{x}"))
1569            .collect();
1570        diff.extend(o.iter().filter(|x| !l.contains(x)).map(|x| format!("-{x}")));
1571        if diff.is_empty() {
1572            diff.push("(no difference)".to_string());
1573        }
1574        lines.push(format!("  {kind} {place}: {}", diff.join(" ")));
1575    }
1576    let n = lines.len();
1577    (lines, n)
1578}
1579
1580/// `styledefs`: the docDefaults' blocks, then each style of a stylesheet
1581/// as lines that name it by type and name: one with `default` and
1582/// `basedOn`/`link` by the name they point at, one per property block
1583/// (pPr and rPr always, tblPr/trPr/tcPr when present) and per conditional
1584/// `tblStylePr` block. Sorted, so a style's lines stay together. Returns
1585/// the lines and the style count.
1586fn style_lines(dom: &Dom, root: NodeId) -> (Vec<String>, usize) {
1587    let child = |n: NodeId, name: &str| {
1588        dom.nodes(n)
1589            .into_iter()
1590            .find(|&c| dom.is_element(c) && local(dom, c) == name)
1591    };
1592    let items = |n: Option<NodeId>| n.map(|b| prop_items(dom, b).join(" ")).unwrap_or_default();
1593    let styles: Vec<NodeId> = dom
1594        .nodes(root)
1595        .into_iter()
1596        .filter(|&c| dom.is_element(c) && local(dom, c) == "style")
1597        .collect();
1598    let name_of = |s: NodeId| -> String {
1599        child(s, "name")
1600            .map(|n| attr(dom, n, "val"))
1601            .unwrap_or_else(|| attr(dom, s, "styleId"))
1602    };
1603    let name_for_id = |id: &str| -> String {
1604        styles
1605            .iter()
1606            .find(|&&s| attr(dom, s, "styleId") == id)
1607            .map(|&s| name_of(s))
1608            .unwrap_or_else(|| id.to_string())
1609    };
1610    // One line per property block of a style or conditional block.
1611    let blocks = |head: &str, s: NodeId, out: &mut Vec<String>| {
1612        for k in ["pPr", "rPr", "tblPr", "trPr", "tcPr"] {
1613            let b = child(s, k);
1614            if b.is_some() || matches!(k, "pPr" | "rPr") {
1615                out.push(format!("{head} {k}[{}]", items(b)));
1616            }
1617        }
1618    };
1619    let mut lines = Vec::new();
1620    if let Some(dd) = child(root, "docDefaults") {
1621        let p = child(dd, "pPrDefault").and_then(|x| child(x, "pPr"));
1622        let r = child(dd, "rPrDefault").and_then(|x| child(x, "rPr"));
1623        lines.push(format!("  docDefaults pPr[{}]", items(p)));
1624        lines.push(format!("  docDefaults rPr[{}]", items(r)));
1625    }
1626    let mut rows: Vec<String> = Vec::new();
1627    for &s in &styles {
1628        let head = format!("  {} \"{}\"", attr(dom, s, "type"), name_of(s));
1629        let mut l = head.clone();
1630        if matches!(attr(dom, s, "default").as_str(), "1" | "true") {
1631            l.push_str(" default");
1632        }
1633        for k in ["basedOn", "link"] {
1634            if let Some(b) = child(s, k) {
1635                l.push_str(&format!(" {k}=\"{}\"", name_for_id(&attr(dom, b, "val"))));
1636            }
1637        }
1638        rows.push(l);
1639        blocks(&head, s, &mut rows);
1640        for c in dom.nodes(s) {
1641            if dom.is_element(c) && local(dom, c) == "tblStylePr" {
1642                blocks(&format!("{head} {}", attr(dom, c, "type")), c, &mut rows);
1643            }
1644        }
1645    }
1646    rows.sort();
1647    lines.extend(rows);
1648    (lines, styles.len())
1649}
1650
1651/// `numbering`: one line per level of each list (`w:num`), keyed by the
1652/// `numId` paragraphs point at: the abstract definition's level, or the
1653/// list's `lvlOverride` level when it brings one, with a `startOverride`
1654/// applied. The abstract's id is left out: Word renumbers it on save.
1655/// Returns the lines and the list count.
1656fn numbering_lines(dom: &Dom, root: NodeId) -> (Vec<String>, usize) {
1657    let kids = |n: NodeId, name: &str| -> Vec<NodeId> {
1658        dom.nodes(n)
1659            .into_iter()
1660            .filter(|&c| dom.is_element(c) && local(dom, c) == name)
1661            .collect()
1662    };
1663    let child = |n: NodeId, name: &str| kids(n, name).into_iter().next();
1664    let val = |n: NodeId, name: &str| child(n, name).map(|c| attr(dom, c, "val"));
1665    let items = |n: Option<NodeId>| n.map(|b| prop_items(dom, b).join(" ")).unwrap_or_default();
1666    let abstracts = kids(root, "abstractNum");
1667    let nums = kids(root, "num");
1668    let mut rows = Vec::new();
1669    for &num in &nums {
1670        let id = attr(dom, num, "numId");
1671        let abs_id = val(num, "abstractNumId").unwrap_or_default();
1672        let Some(abs) = abstracts
1673            .iter()
1674            .copied()
1675            .find(|&a| attr(dom, a, "abstractNumId") == abs_id)
1676        else {
1677            rows.push(format!("  num {id} abstract {abs_id} missing"));
1678            continue;
1679        };
1680        let overrides = kids(num, "lvlOverride");
1681        for lvl in kids(abs, "lvl") {
1682            let ilvl = attr(dom, lvl, "ilvl");
1683            let ov = overrides
1684                .iter()
1685                .copied()
1686                .find(|&o| attr(dom, o, "ilvl") == ilvl);
1687            let lvl = ov.and_then(|o| child(o, "lvl")).unwrap_or(lvl);
1688            let start = ov
1689                .and_then(|o| val(o, "startOverride"))
1690                .or_else(|| val(lvl, "start"))
1691                .unwrap_or_default();
1692            rows.push(format!(
1693                "  num {id} lvl {ilvl} start={start} {} \"{}\" jc={} pPr[{}] rPr[{}]",
1694                val(lvl, "numFmt").unwrap_or_default(),
1695                val(lvl, "lvlText").unwrap_or_default(),
1696                val(lvl, "lvlJc").unwrap_or_default(),
1697                items(child(lvl, "pPr")),
1698                items(child(lvl, "rPr")),
1699            ));
1700        }
1701    }
1702    // Numerically by list, then level.
1703    let key = |l: &String| -> (u32, u32) {
1704        let mut w = l.split_whitespace().skip(1);
1705        let n = w.next().and_then(|x| x.parse().ok()).unwrap_or(u32::MAX);
1706        let v = w.nth(1).and_then(|x| x.parse().ok()).unwrap_or(0);
1707        (n, v)
1708    };
1709    rows.sort_by_key(key);
1710    (rows, nums.len())
1711}
1712
1713/// `text`: one line per paragraph, table and row of a story part, indented
1714/// by table and text box depth; with `props`, the `runs` view. Returns the
1715/// lines and the paragraph count.
1716/// Escapes CriticMarkup delimiters in literal text (the markdown layer's
1717/// `critic_literal`, passed in by callers above it; this crate cannot
1718/// name markdown - plan A5 seam).
1719pub type CriticEscape = fn(&str) -> String;
1720
1721fn text_lines(
1722    dom: &Dom,
1723    root: NodeId,
1724    props: bool,
1725    critic: bool,
1726    escape: CriticEscape,
1727) -> (Vec<String>, usize) {
1728    fn mark(dom: &Dom, n: NodeId, props: &str) -> &'static str {
1729        let Some(pr) = dom.nodes(n).into_iter().find(|&c| local(dom, c) == props) else {
1730            return " ";
1731        };
1732        let holder = if props == "pPr" {
1733            match dom.nodes(pr).into_iter().find(|&c| local(dom, c) == "rPr") {
1734                Some(r) => r,
1735                None => return " ",
1736            }
1737        } else {
1738            pr
1739        };
1740        for c in dom.nodes(holder) {
1741            match local(dom, c).as_str() {
1742                "del" | "moveFrom" => return "-",
1743                "ins" | "moveTo" => return "+",
1744                _ => {}
1745            }
1746        }
1747        " "
1748    }
1749    /// A stretch of text: revision kind (0 plain, 1 inserted, 2 deleted),
1750    /// the run's direct formatting (`runs` view only), the text.
1751    type Seg = (u8, Option<String>, String);
1752    /// Text of `n`'s subtree, nested paragraphs left out.
1753    fn runs(dom: &Dom, n: NodeId, kind: u8, fmt: &Option<String>, props: bool, out: &mut Vec<Seg>) {
1754        let push = |t: &str, out: &mut Vec<Seg>| match out.last_mut() {
1755            Some((lk, lf, lt)) if *lk == kind && lf == fmt => lt.push_str(t),
1756            _ => out.push((kind, fmt.clone(), t.to_string())),
1757        };
1758        for c in dom.nodes(n) {
1759            if dom.is_text(c) {
1760                continue;
1761            }
1762            match local(dom, c).as_str() {
1763                "p" | "txbxContent" | "pPr" | "rPr" | "instrText" | "delInstrText" => {}
1764                "t" | "delText" => push(&dom.value(c), out),
1765                "tab" => push("→", out),
1766                "br" | "cr" => push("↵", out),
1767                "commentReference" => push(&format!("[c{}]", attr(dom, c, "id")), out),
1768                "footnoteReference" => push(&format!("[f{}]", attr(dom, c, "id")), out),
1769                "endnoteReference" => push(&format!("[e{}]", attr(dom, c, "id")), out),
1770                "ins" | "moveTo" => runs(dom, c, 1, fmt, props, out),
1771                "del" | "moveFrom" => runs(dom, c, 2, fmt, props, out),
1772                "r" if props => {
1773                    let rpr = dom.nodes(c).into_iter().find(|&x| local(dom, x) == "rPr");
1774                    let f = Some(rpr.map(|r| props_line(dom, r)).unwrap_or_default());
1775                    runs(dom, c, kind, &f, props, out);
1776                }
1777                _ => runs(dom, c, kind, fmt, props, out),
1778            }
1779        }
1780    }
1781    /// `[pPr] ¶«mark rPr» ` for the `runs` view.
1782    fn para_props(dom: &Dom, p: NodeId) -> String {
1783        let Some(ppr) = dom.nodes(p).into_iter().find(|&c| local(dom, c) == "pPr") else {
1784            return "[] ¶«» ".to_string();
1785        };
1786        let mark = dom
1787            .nodes(ppr)
1788            .into_iter()
1789            .find(|&c| local(dom, c) == "rPr")
1790            .map(|r| props_line(dom, r))
1791            .unwrap_or_default();
1792        format!("[{}] ¶«{mark}» ", props_line(dom, ppr))
1793    }
1794    /// Walk state: the lines, the paragraph count, the `runs` view flag.
1795    struct Walk {
1796        out: Vec<String>,
1797        paras: usize,
1798        props: bool,
1799        critic: bool,
1800        escape: CriticEscape,
1801    }
1802    fn nested(dom: &Dom, n: NodeId, depth: usize, w: &mut Walk) {
1803        for c in dom.nodes(n) {
1804            match local(dom, c).as_str() {
1805                "p" => {}
1806                "txbxContent" => walk(dom, c, depth + 1, w),
1807                _ => nested(dom, c, depth, w),
1808            }
1809        }
1810    }
1811    fn walk(dom: &Dom, n: NodeId, depth: usize, w: &mut Walk) {
1812        let pad = " ".repeat(2 + 2 * depth);
1813        for c in dom.nodes(n) {
1814            match local(dom, c).as_str() {
1815                "p" => {
1816                    w.paras += 1;
1817                    let mut segs = Vec::new();
1818                    runs(dom, c, 0, &None, w.props, &mut segs);
1819                    let text: String = segs
1820                        .iter()
1821                        .map(|(k, f, t)| {
1822                            let f = f.as_ref().map(|f| format!("«{f}»")).unwrap_or_default();
1823                            if w.critic {
1824                                let t = (w.escape)(t);
1825                                return match k {
1826                                    1 => format!("{{++{t}++}}"),
1827                                    2 => format!("{{--{t}--}}"),
1828                                    _ => t,
1829                                };
1830                            }
1831                            match k {
1832                                1 => format!("{{+{f}{t}+}}"),
1833                                2 => format!("[-{f}{t}-]"),
1834                                _ => format!("{f}{t}"),
1835                            }
1836                        })
1837                        .collect();
1838                    let pp = if w.props {
1839                        para_props(dom, c)
1840                    } else {
1841                        String::new()
1842                    };
1843                    w.out
1844                        .push(format!("{pad}¶{} {pp}{text}", mark(dom, c, "pPr")));
1845                    nested(dom, c, depth, w);
1846                }
1847                "tbl" => {
1848                    w.out.push(format!("{pad}table"));
1849                    for tr in dom.nodes(c).into_iter().filter(|&r| local(dom, r) == "tr") {
1850                        w.out
1851                            .push(format!("{pad} row{}", mark(dom, tr, "trPr").trim()));
1852                        for tc in dom.nodes(tr).into_iter().filter(|&t| local(dom, t) == "tc") {
1853                            walk(dom, tc, depth + 1, w);
1854                        }
1855                    }
1856                }
1857                _ if dom.is_element(c) => walk(dom, c, depth, w),
1858                _ => {}
1859            }
1860        }
1861    }
1862    let mut w = Walk {
1863        out: Vec::new(),
1864        paras: 0,
1865        props,
1866        critic,
1867        escape,
1868    };
1869    walk(dom, root, 0, &mut w);
1870    (w.out, w.paras)
1871}
1872
1873/// `tables`: each table of a story part, a nested one under its cell: the
1874/// grid and the old grid a `tblGridChange` records; each row's mark,
1875/// `gridBefore`/`gridAfter` and `trPrChange`; each cell's mark (`cellIns`
1876/// `+`, `cellDel` `-`, `cellMerge` `~`), span, width, `vMerge`, the old
1877/// span, width and `vMerge` a `tcPrChange` records, and its paragraphs as
1878/// `text` shows them. The count is the number of tables.
1879fn table_lines(dom: &Dom, root: NodeId) -> (Vec<String>, usize) {
1880    /// `n`'s children named `name`, through content controls and custom XML.
1881    fn kids(dom: &Dom, n: NodeId, name: &str) -> Vec<NodeId> {
1882        let mut out = Vec::new();
1883        for c in dom.nodes(n) {
1884            match local(dom, c).as_str() {
1885                l if l == name => out.push(c),
1886                "sdt" | "sdtContent" | "customXml" => out.extend(kids(dom, c, name)),
1887                _ => {}
1888            }
1889        }
1890        out
1891    }
1892    fn child(dom: &Dom, n: NodeId, name: &str) -> Option<NodeId> {
1893        dom.nodes(n).into_iter().find(|&c| local(dom, c) == name)
1894    }
1895    /// ` key=val` for `pr`'s child `name` (` key` when it has no `w:val`).
1896    fn val(dom: &Dom, pr: Option<NodeId>, name: &str, key: &str) -> String {
1897        let Some(c) = pr.and_then(|pr| child(dom, pr, name)) else {
1898            return String::new();
1899        };
1900        match attr(dom, c, "val") {
1901            v if v.is_empty() => format!(" {key}"),
1902            v => format!(" {key}={v}"),
1903        }
1904    }
1905    /// A cell's span, width and `vMerge` as ` span=2 w=3120 vMerge=restart`.
1906    fn cell_props(dom: &Dom, pr: Option<NodeId>) -> String {
1907        let mut s = val(dom, pr, "gridSpan", "span");
1908        if let Some(w) = pr.and_then(|pr| child(dom, pr, "tcW")) {
1909            let ty = attr(dom, w, "type");
1910            let unit = if ty.is_empty() || ty == "dxa" {
1911                String::new()
1912            } else {
1913                ty
1914            };
1915            s.push_str(&format!(" w={}{unit}", attr(dom, w, "w")));
1916        }
1917        s + &val(dom, pr, "vMerge", "vMerge")
1918    }
1919    fn grid(dom: &Dom, g: NodeId) -> String {
1920        let mut cols = String::new();
1921        for (i, c) in kids(dom, g, "gridCol").into_iter().enumerate() {
1922            if i > 0 {
1923                cols.push(',');
1924            }
1925            cols.push_str(&attr(dom, c, "w"));
1926        }
1927        cols
1928    }
1929    /// The first of `marks` among `pr`'s children, as its sign.
1930    fn sign(dom: &Dom, pr: Option<NodeId>, marks: &[(&str, &'static str)]) -> &'static str {
1931        let Some(pr) = pr else { return "" };
1932        dom.nodes(pr)
1933            .into_iter()
1934            .find_map(|c| {
1935                let l = local(dom, c);
1936                marks.iter().find(|(m, _)| *m == l).map(|(_, s)| *s)
1937            })
1938            .unwrap_or("")
1939    }
1940    fn table(dom: &Dom, tbl: NodeId, pad: &str, n: &mut usize, out: &mut Vec<String>) {
1941        *n += 1;
1942        let mut head = format!("{pad}table");
1943        if let Some(g) = child(dom, tbl, "tblGrid") {
1944            head.push_str(&format!(" grid={}", grid(dom, g)));
1945            let old = child(dom, g, "tblGridChange").and_then(|c| child(dom, c, "tblGrid"));
1946            if let Some(old) = old {
1947                head.push_str(&format!(" (old grid={})", grid(dom, old)));
1948            }
1949        }
1950        let tblpr = child(dom, tbl, "tblPr");
1951        if tblpr.and_then(|p| child(dom, p, "tblPrChange")).is_some() {
1952            head.push_str(" tblPrChange");
1953        }
1954        out.push(head);
1955        for tr in kids(dom, tbl, "tr") {
1956            let trpr = child(dom, tr, "trPr");
1957            let mut row = format!(
1958                "{pad} row{}",
1959                sign(dom, trpr, &[("ins", "+"), ("del", "-")])
1960            );
1961            row.push_str(&val(dom, trpr, "gridBefore", "before"));
1962            row.push_str(&val(dom, trpr, "gridAfter", "after"));
1963            if trpr.and_then(|p| child(dom, p, "trPrChange")).is_some() {
1964                row.push_str(" trPrChange");
1965            }
1966            out.push(row);
1967            for tc in kids(dom, tr, "tc") {
1968                let tcpr = child(dom, tc, "tcPr");
1969                let marks = [("cellIns", "+"), ("cellDel", "-"), ("cellMerge", "~")];
1970                let mut cell = format!(
1971                    "{pad}  cell{}{}",
1972                    sign(dom, tcpr, &marks),
1973                    cell_props(dom, tcpr)
1974                );
1975                let old = tcpr
1976                    .and_then(|p| child(dom, p, "tcPrChange"))
1977                    .and_then(|c| child(dom, c, "tcPr"));
1978                if let Some(old) = old {
1979                    cell.push_str(&format!(" (old{})", cell_props(dom, Some(old))));
1980                }
1981                // The cell's own paragraphs: `text` lines at depth 0.
1982                cell.push_str(": ");
1983                let lines = text_lines(dom, tc, false, false, |_| String::new()).0;
1984                for (i, l) in lines.iter().filter(|l| l.starts_with("  ¶")).enumerate() {
1985                    if i > 0 {
1986                        cell.push_str(" | ");
1987                    }
1988                    cell.push_str(&l[2..]);
1989                }
1990                out.push(cell);
1991                // Its tables: nested ones and those in its text boxes.
1992                find(dom, tc, &format!("{pad}    "), n, out);
1993            }
1994        }
1995    }
1996    /// A WordprocessingML table, Transitional or Strict: a DrawingML
1997    /// `a:tbl` in a picture is not one.
1998    fn is_table(dom: &Dom, n: NodeId) -> bool {
1999        const STRICT: &str = "http://purl.oclc.org/ooxml/wordprocessingml/main";
2000        dom.name(n).is_some_and(|x| {
2001            x.local_name() == "tbl"
2002                && matches!(x.namespace_name(), crate::namespaces::W::URI | STRICT)
2003        })
2004    }
2005    fn find(dom: &Dom, n: NodeId, pad: &str, count: &mut usize, out: &mut Vec<String>) {
2006        for c in dom.nodes(n) {
2007            if is_table(dom, c) {
2008                table(dom, c, pad, count, out);
2009            } else if dom.is_element(c) {
2010                find(dom, c, pad, count, out);
2011            }
2012        }
2013    }
2014    let mut out = Vec::new();
2015    let mut count = 0;
2016    find(dom, root, "  ", &mut count, &mut out);
2017    (out, count)
2018}
2019
2020/// `xml`: `xml` without its declaration, namespace declarations,
2021/// `mc:Ignorable`, rsids and paragraph ids; attributes sorted, one element
2022/// per line indented by depth, an element holding only text on one line.
2023fn xml_lines(xml: &str) -> Vec<String> {
2024    enum Tok {
2025        Open(String, bool),
2026        Close(String),
2027        Text(String),
2028    }
2029    fn noise(name: &str) -> bool {
2030        let local = name.rsplit(':').next().unwrap_or(name);
2031        name.starts_with("xmlns")
2032            || name == "mc:Ignorable"
2033            || local.starts_with("rsid")
2034            || name == "w14:paraId"
2035            || name == "w14:textId"
2036    }
2037    /// A rebuilt open tag of an element whose content is text.
2038    fn holds_text(tag: &str) -> bool {
2039        let name = tag.trim_start_matches('<').split(' ').next().unwrap_or("");
2040        let local = name.rsplit(':').next().unwrap_or(name);
2041        matches!(local, "t" | "delText" | "instrText" | "delInstrText")
2042    }
2043    /// `<name a="1" b='2'/>` → the rebuilt tag text and whether it closes itself.
2044    fn open_tag(inner: &str) -> (String, bool) {
2045        let (inner, closed) = match inner.strip_suffix('/') {
2046            Some(i) => (i, true),
2047            None => (inner, false),
2048        };
2049        let inner = inner.trim();
2050        let name_end = inner.find(char::is_whitespace).unwrap_or(inner.len());
2051        let name = &inner[..name_end];
2052        let mut attrs = Vec::new();
2053        let mut rest = inner[name_end..].trim_start();
2054        while let Some(eq) = rest.find('=') {
2055            let key = rest[..eq].trim();
2056            let after = rest[eq + 1..].trim_start();
2057            let Some(q) = after.chars().next() else { break };
2058            let Some(end) = after[1..].find(q) else { break };
2059            let value = &after[1..1 + end];
2060            if !noise(key) {
2061                attrs.push(format!("{key}=\"{value}\""));
2062            }
2063            rest = after[1 + end + 1..].trim_start();
2064        }
2065        attrs.sort();
2066        let mut tag = format!("<{name}");
2067        for a in attrs {
2068            tag.push(' ');
2069            tag.push_str(&a);
2070        }
2071        (tag, closed)
2072    }
2073    let mut toks = Vec::new();
2074    let mut rest = xml;
2075    while let Some(lt) = rest.find('<') {
2076        let text = &rest[..lt];
2077        // Whitespace between a text element's open and close tags is its
2078        // text (`<w:t> </w:t>`); elsewhere, even inside `<w:p>\n</w:p>`,
2079        // it is pretty-print.
2080        let content = !text.is_empty()
2081            && rest[lt..].starts_with("</")
2082            && matches!(toks.last(), Some(Tok::Open(tag, false)) if holds_text(tag));
2083        if !text.trim().is_empty() || content {
2084            toks.push(Tok::Text(text.to_string()));
2085        }
2086        // The tag ends at the first `>` outside quotes.
2087        let bytes = rest.as_bytes();
2088        let (mut i, mut quote) = (lt + 1, 0u8);
2089        while i < bytes.len() {
2090            match bytes[i] {
2091                b'"' | b'\'' if quote == 0 => quote = bytes[i],
2092                c if c == quote => quote = 0,
2093                b'>' if quote == 0 => break,
2094                _ => {}
2095            }
2096            i += 1;
2097        }
2098        let inner = &rest[lt + 1..i.min(rest.len())];
2099        rest = &rest[(i + 1).min(rest.len())..];
2100        if inner.starts_with('?') || inner.starts_with('!') {
2101            continue;
2102        }
2103        match inner.strip_prefix('/') {
2104            Some(name) => toks.push(Tok::Close(name.trim().to_string())),
2105            None => {
2106                let (tag, closed) = open_tag(inner);
2107                toks.push(Tok::Open(tag, closed));
2108            }
2109        }
2110    }
2111    let mut out = Vec::new();
2112    let mut depth = 0usize;
2113    let mut i = 0;
2114    while i < toks.len() {
2115        let pad = "  ".repeat(depth);
2116        match &toks[i] {
2117            Tok::Open(tag, true) => out.push(format!("{pad}{tag}/>")),
2118            Tok::Open(tag, false) => match (toks.get(i + 1), toks.get(i + 2)) {
2119                (Some(Tok::Close(_)), _) => {
2120                    out.push(format!("{pad}{tag}/>"));
2121                    i += 1;
2122                }
2123                (Some(Tok::Text(t)), Some(Tok::Close(c))) => {
2124                    out.push(format!("{pad}{tag}>{t}</{c}>"));
2125                    i += 2;
2126                }
2127                _ => {
2128                    out.push(format!("{pad}{tag}>"));
2129                    depth += 1;
2130                }
2131            },
2132            Tok::Close(name) => {
2133                depth = depth.saturating_sub(1);
2134                out.push(format!("{}</{name}>", "  ".repeat(depth)));
2135            }
2136            Tok::Text(t) => out.push(format!("{pad}{}", t.trim())),
2137        }
2138        i += 1;
2139    }
2140    out
2141}
2142
2143/// One change hunk: where it starts in A, the lines only in A, then the
2144/// lines only in B.
2145type Hunk<'a> = (usize, Vec<&'a str>, Vec<&'a str>);
2146
2147/// Line diff: common prefix and suffix trimmed, LCS on the rest (a middle
2148/// too large for LCS is one replaced block).
2149fn diff_lines<'a>(a: &'a [String], b: &'a [String]) -> Vec<Hunk<'a>> {
2150    let pre = a.iter().zip(b).take_while(|(x, y)| x == y).count();
2151    let suf = a[pre..]
2152        .iter()
2153        .rev()
2154        .zip(b[pre..].iter().rev())
2155        .take_while(|(x, y)| x == y)
2156        .count();
2157    let (am, bm) = (&a[pre..a.len() - suf], &b[pre..b.len() - suf]);
2158    if am.is_empty() && bm.is_empty() {
2159        return Vec::new();
2160    }
2161    let (n, m) = (am.len(), bm.len());
2162    if n.saturating_mul(m) > 4_000_000 {
2163        return vec![(
2164            pre,
2165            am.iter().map(String::as_str).collect(),
2166            bm.iter().map(String::as_str).collect(),
2167        )];
2168    }
2169    // lcs[i][j]: LCS length of am[i..] and bm[j..].
2170    let mut lcs = vec![0u32; (n + 1) * (m + 1)];
2171    for i in (0..n).rev() {
2172        for j in (0..m).rev() {
2173            lcs[i * (m + 1) + j] = if am[i] == bm[j] {
2174                lcs[(i + 1) * (m + 1) + j + 1] + 1
2175            } else {
2176                lcs[(i + 1) * (m + 1) + j].max(lcs[i * (m + 1) + j + 1])
2177            };
2178        }
2179    }
2180    let (mut hunks, mut cur): (Vec<Hunk>, Hunk) = (Vec::new(), (pre, Vec::new(), Vec::new()));
2181    let (mut i, mut j) = (0, 0);
2182    while i < n || j < m {
2183        if i < n && j < m && am[i] == bm[j] {
2184            if !cur.1.is_empty() || !cur.2.is_empty() {
2185                hunks.push(std::mem::take(&mut cur));
2186            }
2187            i += 1;
2188            j += 1;
2189            continue;
2190        }
2191        if cur.1.is_empty() && cur.2.is_empty() {
2192            cur.0 = pre + i;
2193        }
2194        if j == m || (i < n && lcs[(i + 1) * (m + 1) + j] >= lcs[i * (m + 1) + j + 1]) {
2195            cur.1.push(&am[i]);
2196            i += 1;
2197        } else {
2198            cur.2.push(&bm[j]);
2199            j += 1;
2200        }
2201    }
2202    if !cur.1.is_empty() || !cur.2.is_empty() {
2203        hunks.push(cur);
2204    }
2205    hunks
2206}
2207
2208type PartLines = BTreeMap<String, (Vec<String>, usize)>;
2209
2210/// Rekey both packages' header and footer parts by their role (the first
2211/// section reference that shows them); a pair whose part names differ shows
2212/// both.
2213fn pair_by_role(a: PartLines, pa: &Package, b: PartLines, pb: &Package) -> (PartLines, PartLines) {
2214    let (ra, rb) = (story_roles(pa), story_roles(pb));
2215    let name_of = |roles: &HashMap<String, String>, role: &str| {
2216        roles
2217            .iter()
2218            .find(|(_, r)| r.as_str() == role)
2219            .map(|(n, _)| n.clone())
2220    };
2221    let rekey = |lines: PartLines, roles: &HashMap<String, String>| -> PartLines {
2222        lines
2223            .into_iter()
2224            .map(|(name, v)| {
2225                let Some(role) = roles.get(&name) else {
2226                    return (name, v);
2227                };
2228                let (na, nb) = (name_of(&ra, role), name_of(&rb, role));
2229                let key = match (na, nb) {
2230                    (Some(x), Some(y)) if x != y => format!("{role} (A {x}, B {y})"),
2231                    _ => name,
2232                };
2233                (key, v)
2234            })
2235            .collect()
2236    };
2237    (rekey(a, &ra), rekey(b, &rb))
2238}
2239
2240/// Header and footer part name → "section N TYPE header|footer", from the
2241/// first section reference that shows it.
2242fn story_roles(pkg: &Package) -> HashMap<String, String> {
2243    story_roles_all(pkg)
2244        .into_iter()
2245        .filter_map(|(part, roles)| roles.into_iter().next().map(|r| (part, r)))
2246        .collect()
2247}
2248
2249/// Header and footer part name → every "section N TYPE header|footer" that
2250/// shows it, in section order.
2251fn story_roles_all(pkg: &Package) -> HashMap<String, Vec<String>> {
2252    let parse = |name: &str| -> Option<(Dom, NodeId)> {
2253        let e = pkg.entries.iter().find(|e| e.name == name)?;
2254        let xml = decode_xml(&e.data)?;
2255        let mut dom = Dom::new();
2256        let doc = dom.parse_xdocument(&xml);
2257        let root = dom.root(doc)?;
2258        Some((dom, root))
2259    };
2260    let rel_targets = |rels: &str| -> Vec<(String, String, String)> {
2261        let Some((dom, root)) = parse(rels) else {
2262            return Vec::new();
2263        };
2264        dom.elements(root, None)
2265            .into_iter()
2266            .map(|r| {
2267                (
2268                    attr(&dom, r, "Id"),
2269                    attr(&dom, r, "Type"),
2270                    attr(&dom, r, "Target"),
2271                )
2272            })
2273            .collect()
2274    };
2275    let mut roles = HashMap::new();
2276    let Some(main) = rel_targets("_rels/.rels")
2277        .into_iter()
2278        .find(|(_, t, _)| t.ends_with("/officeDocument"))
2279        .map(|(_, _, target)| crate::opc::resolve_rel_target("", &target))
2280    else {
2281        return roles;
2282    };
2283    let (dir, file) = main.rsplit_once('/').unwrap_or(("", main.as_str()));
2284    let targets: HashMap<String, String> = rel_targets(&format!("{dir}/_rels/{file}.rels"))
2285        .into_iter()
2286        .map(|(id, _, target)| {
2287            let part = crate::opc::resolve_rel_target(&main, &target);
2288            (id, part)
2289        })
2290        .collect();
2291    let Some((dom, root)) = parse(&main) else {
2292        return roles;
2293    };
2294    let sections = dom
2295        .descendants(root, None)
2296        .into_iter()
2297        .filter(|&e| local(&dom, e) == "sectPr");
2298    for (i, sect) in sections.enumerate() {
2299        for r in dom.elements(sect, None) {
2300            let kind = match local(&dom, r).as_str() {
2301                "headerReference" => "header",
2302                "footerReference" => "footer",
2303                _ => continue,
2304            };
2305            // w:type and r:id share no local name, so `attr` tells them apart.
2306            let ty = attr(&dom, r, "type");
2307            let ty = if ty.is_empty() {
2308                "default".to_string()
2309            } else {
2310                ty
2311            };
2312            if let Some(part) = targets.get(&attr(&dom, r, "id")) {
2313                roles
2314                    .entry(part.clone())
2315                    .or_insert_with(Vec::new)
2316                    .push(format!("section {} {ty} {kind}", i + 1));
2317            }
2318        }
2319    }
2320    roles
2321}
2322
2323/// Ordered, complete lines underlying every debug listing.
2324fn listing_lines(pkg: &Package, check: Check, opts: &Options) -> PartLines {
2325    // `render` reads the package as a whole; the others part by part.
2326    #[cfg(feature = "render")]
2327    let (mut map, entries) = if check == Check::Render {
2328        (render::render_parts(pkg, opts.part.as_deref()), &[][..])
2329    } else {
2330        (BTreeMap::new(), &pkg.entries[..])
2331    };
2332    #[cfg(not(feature = "render"))]
2333    let (mut map, entries) = (BTreeMap::new(), &pkg.entries[..]);
2334    for e in entries {
2335        if opts.part.as_deref().is_some_and(|p| !e.name.contains(p)) {
2336            continue;
2337        }
2338        if !(e.name.ends_with(".xml") || e.name.ends_with(".rels")) {
2339            continue;
2340        }
2341        let Some(xml) = decode_xml(&e.data) else {
2342            continue;
2343        };
2344        if check == Check::Xml {
2345            map.insert(e.name.clone(), (xml_lines(&xml), 0));
2346            continue;
2347        }
2348        let mut dom = Dom::new();
2349        let doc = dom.parse_xdocument(&xml);
2350        let Some(root) = dom.root(doc) else { continue };
2351        if check == Check::Changes {
2352            let (lines, n) = change_lines(&dom, root);
2353            if n > 0 {
2354                map.insert(e.name.clone(), (lines, n));
2355            }
2356            continue;
2357        }
2358        if check == Check::Tables {
2359            if TEXT_PARTS.contains(&local(&dom, root).as_str()) {
2360                let (lines, n) = table_lines(&dom, root);
2361                if n > 0 {
2362                    map.insert(e.name.clone(), (lines, n));
2363                }
2364            }
2365            continue;
2366        }
2367        if check == Check::StyleDefs {
2368            if local(&dom, root) == "styles" {
2369                map.insert(e.name.clone(), style_lines(&dom, root));
2370            }
2371            continue;
2372        }
2373        if check == Check::Numbering {
2374            if local(&dom, root) == "numbering" {
2375                map.insert(e.name.clone(), numbering_lines(&dom, root));
2376            }
2377            continue;
2378        }
2379        if TEXT_PARTS.contains(&local(&dom, root).as_str()) {
2380            map.insert(
2381                e.name.clone(),
2382                text_lines(&dom, root, check == Check::Runs, false, |_| String::new()),
2383            );
2384        }
2385    }
2386    if let Some(g) = opts.grep.as_deref() {
2387        for (lines, _) in map.values_mut() {
2388            lines.retain(|l| line_has(l, g));
2389        }
2390        map.retain(|_, (lines, _)| !lines.is_empty());
2391    }
2392    map
2393}
2394
2395/// A complete text snapshot for unified diffs, with no report clipping.
2396/// Header/footer roles are stable when Word renumbers their ZIP parts.
2397#[doc(hidden)]
2398pub fn document_text(bytes: &[u8]) -> Result<String, String> {
2399    document_text_with_critic(bytes, false, |_| String::new())
2400}
2401
2402/// The complete snapshot with revision spans rendered at their XML source.
2403#[doc(hidden)]
2404pub fn document_text_with_critic(
2405    bytes: &[u8],
2406    critic: bool,
2407    escape: CriticEscape,
2408) -> Result<String, String> {
2409    document_text_view(bytes, critic, false, escape)
2410}
2411
2412/// Validated document snapshot with an explicit revision policy.
2413#[doc(hidden)]
2414pub fn document_text_view(
2415    bytes: &[u8],
2416    critic: bool,
2417    accept: bool,
2418    escape: CriticEscape,
2419) -> Result<String, String> {
2420    let admitted = crate::admission::admit(bytes, crate::admission::InputLimits::default())
2421        .map_err(|e| e.to_string())?;
2422    let pkg = Package::open(bytes)?;
2423    let parse = |entry: &Entry| -> Result<(Dom, NodeId), String> {
2424        let xml = decode_xml(&entry.data)
2425            .ok_or_else(|| format!("{}: unsupported XML encoding", entry.name))?;
2426        crate::xmllinq::parse::validate_xml(&xml).map_err(|e| format!("{}: {e}", entry.name))?;
2427        let mut dom = Dom::new();
2428        let doc = dom.parse_xdocument(&xml);
2429        let root = dom
2430            .root(doc)
2431            .ok_or_else(|| format!("{}: missing XML root", entry.name))?;
2432        Ok((dom, root))
2433    };
2434    let types_entry = pkg
2435        .entries
2436        .iter()
2437        .find(|e| e.name == "[Content_Types].xml")
2438        .ok_or("missing content types")?;
2439    let (types, root) = parse(types_entry)?;
2440    let mut overrides = HashMap::new();
2441    let mut defaults = HashMap::new();
2442    for node in types.elements(root, None) {
2443        let kind = attr(&types, node, "ContentType");
2444        if local(&types, node) == "Override" {
2445            overrides.insert(
2446                attr(&types, node, "PartName")
2447                    .trim_start_matches('/')
2448                    .to_string(),
2449                kind,
2450            );
2451        } else if local(&types, node) == "Default" {
2452            defaults.insert(attr(&types, node, "Extension").to_ascii_lowercase(), kind);
2453        }
2454    }
2455    let word_name = |dom: &Dom, node: NodeId, name: &str| {
2456        dom.name(node).is_some_and(|n| {
2457            n.local_name() == name
2458                && matches!(
2459                    n.namespace_name(),
2460                    "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
2461                        | "http://purl.oclc.org/ooxml/wordprocessingml/main"
2462                )
2463        })
2464    };
2465    let roles = story_roles(&pkg);
2466    let mut parts = BTreeMap::new();
2467    for entry in &pkg.entries {
2468        let kind = overrides
2469            .get(&entry.name)
2470            .or_else(|| {
2471                entry
2472                    .name
2473                    .rsplit_once('.')
2474                    .and_then(|(_, ext)| defaults.get(&ext.to_ascii_lowercase()))
2475            })
2476            .map(String::as_str)
2477            .unwrap_or("");
2478        let main = entry.name == admitted.main_part;
2479        let xml = main
2480            || entry.name.ends_with(".xml")
2481            || entry.name.ends_with(".rels")
2482            || kind.ends_with("+xml")
2483            || matches!(kind, "application/xml" | "text/xml");
2484        if !xml {
2485            continue;
2486        }
2487        let (mut dom, mut root) = parse(entry)?;
2488        if main
2489            && (!word_name(&dom, root, "document")
2490                || !dom
2491                    .elements(root, None)
2492                    .into_iter()
2493                    .any(|n| word_name(&dom, n, "body")))
2494        {
2495            return Err(format!(
2496                "{}: expected a Word document root and body",
2497                entry.name
2498            ));
2499        }
2500        let expected = kind
2501            .strip_prefix("application/vnd.openxmlformats-officedocument.wordprocessingml.")
2502            .and_then(|k| match k {
2503                "header+xml" => Some("hdr"),
2504                "footer+xml" => Some("ftr"),
2505                "footnotes+xml" => Some("footnotes"),
2506                "endnotes+xml" => Some("endnotes"),
2507                "comments+xml" => Some("comments"),
2508                _ => None,
2509            });
2510        if expected.is_some_and(|name| !word_name(&dom, root, name)) {
2511            return Err(format!("{}: expected a Word story root", entry.name));
2512        }
2513        // Main parts are resolved by admission; unrelated document-shaped
2514        // custom XML is not a second body. Other Word stories keep debug's view.
2515        if !main
2516            && (local(&dom, root) == "document"
2517                || !TEXT_PARTS.iter().any(|name| word_name(&dom, root, name)))
2518        {
2519            continue;
2520        }
2521        let name = if main {
2522            "body".to_string()
2523        } else {
2524            roles
2525                .get(&entry.name)
2526                .cloned()
2527                .unwrap_or_else(|| entry.name.clone())
2528        };
2529        if accept {
2530            // Revision transforms use Transitional Word names. Normalize
2531            // element and attribute names only, preserving literal URI text.
2532            const STRICT: &str = "http://purl.oclc.org/ooxml/wordprocessingml/main";
2533            const WORD: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
2534            let mut nodes = dom.descendants(root, None);
2535            nodes.push(root);
2536            for node in nodes {
2537                if let Some(n) = dom.name(node).filter(|n| n.namespace_name() == STRICT) {
2538                    dom.set_name(node, crate::xmllinq::XName::get(n.local_name(), WORD));
2539                }
2540                for (n, value) in dom.attributes(node) {
2541                    if n.namespace_name() == STRICT {
2542                        dom.set_attribute_value(node, &n, None);
2543                        dom.set_attribute_value(
2544                            node,
2545                            &crate::xmllinq::XName::get(n.local_name(), WORD),
2546                            Some(&value),
2547                        );
2548                    }
2549                }
2550            }
2551            root = crate::revision_processor::accept_revisions_for_part_content(&mut dom, root);
2552        }
2553        parts.insert(name, text_lines(&dom, root, false, critic, escape).0);
2554    }
2555    let mut out = String::new();
2556    for (part, lines) in parts {
2557        let _ = writeln!(out, "[{part}]");
2558        for line in lines {
2559            let _ = writeln!(out, "{line}");
2560        }
2561    }
2562    Ok(out)
2563}
2564
2565/// `text` / `xml` for one package, or their per-part differences between two.
2566fn text_or_xml(pa: &Package, pb: Option<&Package>, check: Check, opts: &Options) -> String {
2567    let label = match check {
2568        Check::Xml => "xml",
2569        Check::Runs => "runs",
2570        Check::Changes => "changes",
2571        Check::Tables => "tables",
2572        Check::StyleDefs => "styledefs",
2573        Check::Numbering => "numbering",
2574        #[cfg(feature = "render")]
2575        Check::Render => "render",
2576        _ => "text",
2577    };
2578    let mut out = String::new();
2579    let a = listing_lines(pa, check, opts);
2580    let Some(pb) = pb else {
2581        for (part, (lines, paras)) in &a {
2582            if check == Check::Xml {
2583                line(&mut out, part);
2584            } else if check == Check::Changes {
2585                line(&mut out, &format!("{part}: {paras} property changes"));
2586            } else if check == Check::Tables {
2587                line(&mut out, &format!("{part}: {paras} tables"));
2588            } else if check == Check::StyleDefs {
2589                line(&mut out, &format!("{part}: {paras} styles"));
2590            } else if check == Check::Numbering {
2591                line(&mut out, &format!("{part}: {paras} lists"));
2592            } else if is_render_layout(&check, part) {
2593                line(&mut out, &format!("{part}: {paras} pages"));
2594            } else {
2595                line(&mut out, &format!("{part}: {paras} paragraphs"));
2596            }
2597            for l in lines {
2598                // Asked for by name (`--grep`) or `--full-lines`: the whole
2599                // paragraph.
2600                whole_or_clipped(&mut out, l, opts.grep.is_some() || opts.full_lines);
2601            }
2602        }
2603        return out;
2604    };
2605    let b = listing_lines(pb, check, opts);
2606    // Header and footer parts pair by the section that shows them (Word
2607    // renumbers them on save); XML stays by part name.
2608    let (a, b) = if check == Check::Xml {
2609        (a, b)
2610    } else {
2611        pair_by_role(a, pa, b, pb)
2612    };
2613    let names: std::collections::BTreeSet<&String> = a.keys().chain(b.keys()).collect();
2614    for name in names {
2615        let (la, lb) = match (a.get(name), b.get(name)) {
2616            (Some(x), Some(y)) => (&x.0, &y.0),
2617            (Some(_), None) => {
2618                line(&mut out, &format!("{name}: only in A"));
2619                continue;
2620            }
2621            (None, _) => {
2622                line(&mut out, &format!("{name}: only in B"));
2623                continue;
2624            }
2625        };
2626        let hunks = diff_lines(la, lb);
2627        if hunks.is_empty() {
2628            continue;
2629        }
2630        let dels: usize = hunks.iter().map(|h| h.1.len()).sum();
2631        let adds: usize = hunks.iter().map(|h| h.2.len()).sum();
2632        let n = dels.max(adds);
2633        line(
2634            &mut out,
2635            &format!(
2636                "{name}: {n} line{} differ{}",
2637                if n == 1 { "" } else { "s" },
2638                if n == 1 { "s" } else { "" }
2639            ),
2640        );
2641        for (k, (at, del, add)) in hunks.iter().enumerate() {
2642            if k == opts.limit {
2643                line(
2644                    &mut out,
2645                    &format!("  … {} more hunks (raise --limit)", hunks.len() - k),
2646                );
2647                break;
2648            }
2649            if k > 0 {
2650                line(&mut out, "  ~");
2651            }
2652            // A line paired with its counterpart is clipped from a little
2653            // before their first difference, so the change stays visible.
2654            let from = |i: usize| match (del.get(i), add.get(i)) {
2655                _ if opts.full_lines => 0,
2656                (Some(x), Some(y)) => x
2657                    .chars()
2658                    .zip(y.chars())
2659                    .take_while(|(c, d)| c == d)
2660                    .count()
2661                    .saturating_sub(WIDTH / 3),
2662                _ => 0,
2663            };
2664            let whole = opts.full_lines;
2665            for l in &la[at.saturating_sub(opts.context)..*at] {
2666                whole_or_clipped(&mut out, &format!("   {l}"), whole);
2667            }
2668            for (i, l) in del.iter().enumerate() {
2669                whole_or_clipped(&mut out, &format!("-A {}", clip_from(l, from(i))), whole);
2670            }
2671            for (i, l) in add.iter().enumerate() {
2672                whole_or_clipped(&mut out, &format!("+B {}", clip_from(l, from(i))), whole);
2673            }
2674            let after = at + del.len();
2675            for l in &la[after..(after + opts.context).min(la.len())] {
2676                whole_or_clipped(&mut out, &format!("   {l}"), whole);
2677            }
2678        }
2679    }
2680    if out.is_empty() {
2681        line(&mut out, &format!("{label} identical"));
2682    }
2683    out
2684}
2685
2686/// `l` holds `g`, read as plain text when `l` is a `runs` line: run
2687/// properties (`«…»`) and revision marks (`{+ +}`, `[- -]`) dropped, so a
2688/// phrase split over runs still matches.
2689fn line_has(l: &str, g: &str) -> bool {
2690    if l.contains(g) {
2691        return true;
2692    }
2693    let mut plain = String::with_capacity(l.len());
2694    let mut depth = 0usize;
2695    for c in l.chars() {
2696        match c {
2697            '«' => depth += 1,
2698            '»' => depth = depth.saturating_sub(1),
2699            _ if depth == 0 => plain.push(c),
2700            _ => {}
2701        }
2702    }
2703    ["{+", "+}", "[-", "-]"]
2704        .iter()
2705        .fold(plain, |t, m| t.replace(m, ""))
2706        .contains(g)
2707}
2708
2709fn line(out: &mut String, s: &str) {
2710    let _ = writeln!(out, "{}", clip_line(s));
2711}
2712
2713/// `s` as a report line: whole when `whole`, else clipped at `WIDTH`.
2714fn whole_or_clipped(out: &mut String, s: &str, whole: bool) {
2715    if whole {
2716        let _ = writeln!(out, "{s}");
2717    } else {
2718        line(out, s);
2719    }
2720}
2721
2722/// `s` from its `from`-th character, the dropped head marked `…`.
2723fn clip_from(s: &str, from: usize) -> String {
2724    if from == 0 || s.chars().count() <= WIDTH {
2725        s.to_string()
2726    } else {
2727        format!("…{}", s.chars().skip(from).collect::<String>())
2728    }
2729}
2730
2731fn clip_line(s: &str) -> String {
2732    if s.chars().count() <= WIDTH {
2733        s.to_string()
2734    } else {
2735        format!("{}…", s.chars().take(WIDTH).collect::<String>())
2736    }
2737}
2738
2739/// `--list`: the package's entries (archive order, sizes). With a second
2740/// package, every entry by name with its state: `=` identical, `~` changed,
2741/// `A`/`B` only in one.
2742///
2743/// # Errors
2744///
2745/// A message naming which package is not a readable zip, or which zip
2746/// entry failed to read.
2747pub fn list(a: &[u8], b: Option<&[u8]>, opts: &Options) -> Result<String, String> {
2748    let pa = Package::open(a)?;
2749    let mut out = String::new();
2750    let Some(b) = b else {
2751        let total: u64 = pa.entries.iter().map(|e| e.size).sum();
2752        line(
2753            &mut out,
2754            &format!("{} entries, {total} bytes unpacked", pa.entries.len()),
2755        );
2756        for e in &pa.entries {
2757            if opts.part.as_deref().is_some_and(|p| !e.name.contains(p)) {
2758                continue;
2759            }
2760            line(
2761                &mut out,
2762                &format!("{:>10} {:>9} {}", e.size, e.packed, e.name),
2763            );
2764        }
2765        return Ok(out);
2766    };
2767    let pb = Package::open(b)?;
2768    let bm: HashMap<&str, &Entry> = pb.entries.iter().map(|e| (e.name.as_str(), e)).collect();
2769    let am: HashSet<&str> = pa.entries.iter().map(|e| e.name.as_str()).collect();
2770    let mut rows = Vec::new();
2771    let (mut same, mut changed, mut only_a, mut only_b) = (0, 0, 0, 0);
2772    for e in &pa.entries {
2773        match bm.get(e.name.as_str()) {
2774            Some(o) if o.data == e.data => {
2775                same += 1;
2776                rows.push(format!("= {:>10} {}", e.size, e.name));
2777            }
2778            Some(o) => {
2779                changed += 1;
2780                rows.push(format!("~ {:>10} → {:<10} {}", e.size, o.size, e.name));
2781            }
2782            None => {
2783                only_a += 1;
2784                rows.push(format!("A {:>10} {}", e.size, e.name));
2785            }
2786        }
2787    }
2788    for e in pb.entries.iter().filter(|e| !am.contains(e.name.as_str())) {
2789        only_b += 1;
2790        rows.push(format!("B {:>10} {}", e.size, e.name));
2791    }
2792    line(
2793        &mut out,
2794        &format!("{same} identical, {changed} changed, {only_a} only in A, {only_b} only in B"),
2795    );
2796    for r in rows {
2797        if r.starts_with('=') || opts.part.as_deref().is_some_and(|p| !r.contains(p)) {
2798            continue;
2799        }
2800        line(&mut out, &r);
2801    }
2802    Ok(out)
2803}
2804
2805/// The five [`TRIAGE`] checks as [`crate::validate::Finding`]s: one per
2806/// example, with the triage kind and its detail in the message. The code
2807/// table is the one `jubarte validate` prints; kinds the Ring-1 checks
2808/// also cover map to the Ring-1 code.
2809///
2810/// # Errors
2811///
2812/// A package that is not a readable zip.
2813pub fn findings(docx: &[u8]) -> Result<Vec<crate::validate::Finding>, String> {
2814    let pkg = Package::open(docx)?;
2815    let analysis = analyze(&pkg, &Options::default());
2816    let mut out = Vec::new();
2817    for (kind, items) in &analysis.findings.by_kind {
2818        let code = finding_code(kind);
2819        // An example with no place listed has none, as `Findings::add`
2820        // writes it: no example is dropped, and none panics.
2821        let places = analysis.findings.places.get(kind);
2822        for (i, (part, detail)) in items.iter().enumerate() {
2823            let place = places.and_then(|p| p.get(i)).map_or("", String::as_str);
2824            let message = if detail.is_empty() {
2825                format!("{kind} in '{part}'")
2826            } else {
2827                format!("{kind} in '{part}': {detail}")
2828            };
2829            let mut finding = crate::validate::Finding::new(&code, part, place, message);
2830            if kind.contains("move-nested") {
2831                finding.message.push_str("; Word opens it");
2832            }
2833            if code == "NESTED_SAME_REVISION" && !kind.contains("move-nested") {
2834                if matches!(kind.as_str(), "ins-nested-in-ins" | "del-nested-in-del") {
2835                    finding.severity = "info".to_string();
2836                    finding
2837                        .message
2838                        .push_str("; Word opens it and reads it faithfully (#1134, 2026-10-17)");
2839                } else {
2840                    finding
2841                        .message
2842                        .push_str("; Word opens it but misreads reject-all (#1134, 2026-10-17)");
2843                }
2844            }
2845            out.push(finding);
2846        }
2847    }
2848    Ok(out)
2849}
2850
2851/// The stable code for a triage finding kind.
2852fn finding_code(kind: &str) -> String {
2853    let code = match kind {
2854        "orphan-delText" | "orphan-delInstrText" => "DELTEXT_OUTSIDE_DELETION",
2855        "t-under-del" => "TEXT_INSIDE_DELETION",
2856        "instrText-under-del" => "INSTR_TEXT_INSIDE_DELETION",
2857        "bare-run-in-deleted-textbox" => "BARE_RUN_IN_DELETED_TEXTBOX",
2858        "field-code-outside-field"
2859        | "field-separate-without-begin"
2860        | "field-end-without-begin"
2861        | "field-unclosed" => "FIELD_UNBALANCED",
2862        "field-partly-deleted" => "FIELD_SPLIT_DELETION",
2863        "field-code-kind-vs-state" => "FIELD_CODE_STATE",
2864        "part-without-content-type" | "content-types-missing" => "MISSING_CONTENT_TYPE",
2865        "override-without-part" => "OVERRIDE_WITHOUT_PART",
2866        "rel-duplicate-id" => "DUPLICATE_RID",
2867        "rel-target-missing" => "MISSING_REL_TARGET",
2868        "rid-not-in-rels" => "DANGLING_RELATIONSHIP",
2869        "footnoteReference-dangling" | "endnoteReference-dangling" => "NOTE_REFERENCE_DANGLING",
2870        "commentReference-dangling" => "COMMENT_ANCHOR_ORPHAN",
2871        "comment-range-unpaired" => "COMMENT_RANGE_UNPAIRED",
2872        "ignorable-prefix-undeclared" => "MC_UNBOUND_PREFIX",
2873        "xml-undecodable" | "xml-unparsable" => "MALFORMED_XML",
2874        "instrText-empty" | "delInstrText-empty" => "EMPTY_FIELD_CODE",
2875        "cell-not-ending-in-p" => "CELL_WITHOUT_PARAGRAPH",
2876        "row-without-cell" => "ROW_WITHOUT_CELL",
2877        "ins-nested-in-ins"
2878        | "del-nested-in-del"
2879        | "ins-interleaved-in-ins"
2880        | "del-interleaved-in-del"
2881        | "ins-move-nested-in-ins"
2882        | "del-move-nested-in-del" => "NESTED_SAME_REVISION",
2883        "body-sectPr-not-last" => "SECTPR_NOT_LAST",
2884        k if k.starts_with("bookmark-in-") && k.ends_with("-control") => {
2885            "BOOKMARK_IN_SINGLE_VALUE_CONTROL"
2886        }
2887        k => return k.to_ascii_uppercase().replace('-', "_"),
2888    };
2889    code.to_string()
2890}
2891
2892/// Whether this part line is the render check's whole-package layout
2893/// summary (the feature-gated variant names it).
2894#[cfg(feature = "render")]
2895fn is_render_layout(check: &Check, part: &str) -> bool {
2896    *check == Check::Render && part == "(layout)"
2897}
2898
2899/// Without the renderer there is no render check, so no layout summary.
2900#[cfg(not(feature = "render"))]
2901fn is_render_layout(_: &Check, _: &str) -> bool {
2902    false
2903}
2904
2905/// Whether a check lists the package part by part (render reads it whole).
2906fn is_listing_check(c: &Check) -> bool {
2907    match c {
2908        Check::Text
2909        | Check::Xml
2910        | Check::Runs
2911        | Check::Changes
2912        | Check::Tables
2913        | Check::StyleDefs
2914        | Check::Numbering => true,
2915        #[cfg(feature = "render")]
2916        Check::Render => true,
2917        _ => false,
2918    }
2919}
2920
2921/// The report for one package, or the differences between two.
2922///
2923/// # Errors
2924///
2925/// A message naming which package is not a readable zip, or which zip
2926/// entry failed to read.
2927pub fn report(a: &[u8], b: Option<&[u8]>, opts: &Options) -> Result<String, String> {
2928    let is_listing = |c: &Check| is_listing_check(c);
2929    if opts.checks.iter().any(is_listing) {
2930        let pa = Package::open(a)?;
2931        let pb = match b {
2932            Some(b) => Some(Package::open(b)?),
2933            None => None,
2934        };
2935        let mut out = String::new();
2936        for c in opts.checks.iter().filter(|c| is_listing(c)) {
2937            out.push_str(&text_or_xml(&pa, pb.as_ref(), *c, opts));
2938        }
2939        let rest: Vec<Check> = opts
2940            .checks
2941            .iter()
2942            .copied()
2943            .filter(|c| !is_listing(c))
2944            .collect();
2945        if !rest.is_empty() {
2946            let more = Options {
2947                checks: rest,
2948                ..opts.clone()
2949            };
2950            out.push_str(&report(a, b, &more)?);
2951        }
2952        return Ok(out);
2953    }
2954    let ra = analyze(&Package::open(a)?, opts);
2955    let rb = match b {
2956        Some(b) => Some(analyze(&Package::open(b)?, opts)),
2957        None => None,
2958    };
2959    let mut out = String::new();
2960    let limit = opts.limit;
2961    match &rb {
2962        None => {
2963            if ra.findings.by_kind.is_empty()
2964                && !opts
2965                    .checks
2966                    .iter()
2967                    .all(|c| matches!(c, Check::Elements | Check::Chains | Check::Textbox))
2968            {
2969                line(&mut out, "no findings");
2970            }
2971            for (kind, items) in &ra.findings.by_kind {
2972                line(&mut out, &format!("{kind}: {}", items.len()));
2973                for (part, d) in items.iter().take(limit) {
2974                    line(&mut out, &format!("  {part} {d}"));
2975                }
2976            }
2977            if opts.checks.contains(&Check::Elements) {
2978                let mut v: Vec<_> = ra.elements.iter().collect();
2979                v.sort_by(|x, y| y.1.cmp(x.1).then(x.0.cmp(y.0)));
2980                let top: Vec<String> = v
2981                    .iter()
2982                    .take(limit.max(20))
2983                    .map(|(k, n)| format!("{k} {n}"))
2984                    .collect();
2985                line(&mut out, &format!("elements: {}", top.join(", ")));
2986            }
2987            print_counts(&mut out, "chains", &ra.chains, None, limit.max(20));
2988        }
2989        Some(rb) => {
2990            let kinds: std::collections::BTreeSet<&String> = ra
2991                .findings
2992                .by_kind
2993                .keys()
2994                .chain(rb.findings.by_kind.keys())
2995                .collect();
2996            let mut any = false;
2997            for kind in kinds {
2998                let (xa, xb) = (
2999                    ra.findings.by_kind.get(kind).map_or(&[][..], |v| &v[..]),
3000                    rb.findings.by_kind.get(kind).map_or(&[][..], |v| &v[..]),
3001                );
3002                if xa == xb {
3003                    continue;
3004                }
3005                any = true;
3006                line(&mut out, &format!("{kind}: {} → {}", xa.len(), xb.len()));
3007                // Examples that are new in B, else gone from A.
3008                let new: Vec<_> = xb.iter().filter(|x| !xa.contains(x)).collect();
3009                let gone: Vec<_> = xa.iter().filter(|x| !xb.contains(x)).collect();
3010                for (part, d) in new.iter().take(limit) {
3011                    line(&mut out, &format!("  +B {part} {d}"));
3012                }
3013                for (part, d) in gone.iter().take(limit) {
3014                    line(&mut out, &format!("  -A {part} {d}"));
3015                }
3016            }
3017            if !any
3018                && !opts
3019                    .checks
3020                    .iter()
3021                    .all(|c| matches!(c, Check::Elements | Check::Chains | Check::Textbox))
3022            {
3023                line(&mut out, "findings identical");
3024            }
3025            print_counts(
3026                &mut out,
3027                "elements",
3028                &ra.elements,
3029                Some(&rb.elements),
3030                usize::MAX,
3031            );
3032            print_counts(&mut out, "chains", &ra.chains, Some(&rb.chains), usize::MAX);
3033            if opts.checks.contains(&Check::Textbox) {
3034                let only_b: Vec<_> = rb
3035                    .textboxes
3036                    .iter()
3037                    .filter(|t| !ra.textboxes.contains(t))
3038                    .collect();
3039                let only_a: Vec<_> = ra
3040                    .textboxes
3041                    .iter()
3042                    .filter(|t| !rb.textboxes.contains(t))
3043                    .collect();
3044                line(
3045                    &mut out,
3046                    &format!("textbox: {} differ", only_a.len().max(only_b.len())),
3047                );
3048                for t in only_a.iter().take(limit) {
3049                    let _ = writeln!(out, "-A {t}");
3050                }
3051                for t in only_b.iter().take(limit) {
3052                    let _ = writeln!(out, "+B {t}");
3053                }
3054            }
3055            return Ok(out);
3056        }
3057    }
3058    if opts.checks.contains(&Check::Textbox) {
3059        line(&mut out, &format!("textbox: {}", ra.textboxes.len()));
3060        for t in ra.textboxes.iter().take(limit) {
3061            let _ = writeln!(out, "{t}");
3062        }
3063    }
3064    Ok(out)
3065}
3066
3067/// Counts; with a second map, only the keys whose counts differ (`a → b`).
3068fn print_counts(
3069    out: &mut String,
3070    label: &str,
3071    a: &BTreeMap<String, usize>,
3072    b: Option<&BTreeMap<String, usize>>,
3073    limit: usize,
3074) {
3075    match b {
3076        None => {
3077            if a.is_empty() {
3078                return;
3079            }
3080            let mut v: Vec<_> = a.iter().collect();
3081            v.sort_by(|x, y| y.1.cmp(x.1).then(x.0.cmp(y.0)));
3082            line(out, &format!("{label}:"));
3083            for (k, n) in v.into_iter().take(limit) {
3084                line(out, &format!("  {n:>6} {k}"));
3085            }
3086        }
3087        Some(b) => {
3088            let keys: std::collections::BTreeSet<&String> = a.keys().chain(b.keys()).collect();
3089            let rows: Vec<String> = keys
3090                .into_iter()
3091                .filter_map(|k| {
3092                    let (x, y) = (
3093                        a.get(k).copied().unwrap_or(0),
3094                        b.get(k).copied().unwrap_or(0),
3095                    );
3096                    (x != y).then(|| format!("  {k} {x} → {y}"))
3097                })
3098                .collect();
3099            if a.is_empty() && b.is_empty() {
3100                return;
3101            }
3102            line(out, &format!("{label}: {} differ", rows.len()));
3103            for r in rows.into_iter().take(limit) {
3104                line(out, &r);
3105            }
3106        }
3107    }
3108}
3109
3110#[cfg(test)]
3111#[cfg_attr(all(coverage_nightly, test), coverage(off))]
3112mod tests {
3113    use super::*;
3114    use std::io::Write;
3115
3116    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"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#;
3117    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>"#;
3118
3119    fn zip_of(entries: &[(&str, &str)]) -> Vec<u8> {
3120        let mut buf = Cursor::new(Vec::new());
3121        {
3122            let mut z = zip::ZipWriter::new(&mut buf);
3123            let opt = zip::write::SimpleFileOptions::default();
3124            for (name, data) in entries {
3125                z.start_file(*name, opt).unwrap();
3126                z.write_all(data.as_bytes()).unwrap();
3127            }
3128            z.finish().unwrap();
3129        }
3130        buf.into_inner()
3131    }
3132
3133    #[test]
3134    fn a_cell_ends_in_a_paragraph_through_its_content_controls_only() {
3135        const W_NS: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
3136        let cases = [
3137            ("<w:tcPr/><w:p/>", true),
3138            ("<w:tcPr/>", false),
3139            (
3140                "<w:sdt><w:sdtPr/><w:sdtContent><w:p/></w:sdtContent></w:sdt>",
3141                true,
3142            ),
3143            (
3144                "<w:sdt><w:sdtPr/><w:sdtEndPr/><w:sdtContent><w:sdt><w:sdtContent><w:sdt>\
3145                 <w:sdtContent><w:p/></w:sdtContent></w:sdt></w:sdtContent></w:sdt>\
3146                 </w:sdtContent></w:sdt>",
3147                true,
3148            ),
3149            ("<w:sdt><w:sdtPr/><w:sdtContent/></w:sdt>", false),
3150            ("<w:sdt><w:sdtPr/></w:sdt>", false),
3151            (
3152                "<w:sdt><w:sdtContent><w:tbl/></w:sdtContent></w:sdt>",
3153                false,
3154            ),
3155            // Only the level's own properties are skipped.
3156            (
3157                "<w:sdt><w:sdtContent><w:p/><w:tcPr/></w:sdtContent></w:sdt>",
3158                false,
3159            ),
3160            (
3161                "<w:sdt><w:sdtContent><w:p/></w:sdtContent><w:sdtPr/></w:sdt>",
3162                false,
3163            ),
3164            ("<w:p/><w:sdtEndPr/>", false),
3165            ("<w:sdtContent><w:p/></w:sdtContent>", false),
3166        ];
3167        for (cell, expected) in cases {
3168            let mut dom = Dom::new();
3169            let doc = dom.parse_xdocument(&format!(r#"<w:tc xmlns:w="{W_NS}">{cell}</w:tc>"#));
3170            let tc = dom.root(doc).unwrap();
3171            assert_eq!(cell_ends_in_paragraph(&dom, tc), expected, "{cell}");
3172        }
3173    }
3174
3175    fn document(body: &str) -> String {
3176        format!(
3177            r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"><w:body>{body}</w:body></w:document>"#
3178        )
3179    }
3180
3181    fn docx(body: &str) -> Vec<u8> {
3182        zip_of(&[
3183            ("[Content_Types].xml", TYPES),
3184            ("_rels/.rels", ROOT_RELS),
3185            ("word/document.xml", &document(body)),
3186        ])
3187    }
3188
3189    const CLEAN: &str = r#"<w:p><w:r><w:t>kept</w:t></w:r><w:del w:id="1" w:author="A"><w:r><w:delText>gone</w:delText></w:r></w:del></w:p>"#;
3190
3191    /// en bb113e88's deleted FILENAME text box: the field code is
3192    /// delInstrText in a run no deletion of the text box's story wraps.
3193    const ORPHAN: &str = r#"<w:p><w:del w:id="1" w:author="A"><w:r><w:pict><v:shape><v:textbox><w:txbxContent><w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:delInstrText> FILENAME </w:delInstrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:del w:id="2" w:author="A"><w:r><w:delText>AG</w:delText></w:r></w:del><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p></w:txbxContent></v:textbox></v:shape></w:pict></w:r></w:del></w:p>"#;
3194
3195    #[test]
3196    fn a_clean_package_has_no_findings() {
3197        let out = report(&docx(CLEAN), None, &Options::default()).unwrap();
3198        assert_eq!(out, "no findings\n");
3199    }
3200
3201    /// Change only the local name, locating the header through the
3202    /// central record rather than searching payload bytes.
3203    fn rename_local_header(bytes: &mut [u8], from: &[u8], to: &[u8]) {
3204        assert_eq!(from.len(), to.len());
3205        let at = {
3206            let mut archive = zip::ZipArchive::new(Cursor::new(&*bytes)).unwrap();
3207            archive
3208                .by_name(std::str::from_utf8(from).unwrap())
3209                .unwrap()
3210                .header_start() as usize
3211        };
3212        assert_eq!(&bytes[at..at + 4], b"PK\x03\x04");
3213        assert_eq!(&bytes[at + 30..at + 30 + from.len()], from);
3214        bytes[at + 30..at + 30 + from.len()].copy_from_slice(to);
3215    }
3216
3217    /// GHSA-m665-v7pm-7grj: every reader refuses a package whose local
3218    /// header disagrees with its central directory — except `debug`, the
3219    /// triage tool, which opens it anyway and reports the disagreement as
3220    /// a finding so a maintainer can inspect what was refused.
3221    #[test]
3222    fn a_dual_header_package_reports_a_finding_instead_of_refusing() {
3223        let mut pkg = docx(CLEAN);
3224        rename_local_header(&mut pkg, b"word/document.xml", b"w0rd/document.xml");
3225        let out = report(&pkg, None, &Options::default()).unwrap();
3226        assert!(out.contains("zip-header-mismatch: 1\n"), "{out}");
3227        assert!(
3228            out.contains(
3229                "'word/document.xml' in the central directory but 'w0rd/document.xml' in its local header"
3230            ),
3231            "{out}"
3232        );
3233        let found = findings(&pkg).unwrap();
3234        assert!(
3235            found.iter().any(|f| f.code == "ZIP_HEADER_MISMATCH"),
3236            "{found:?}"
3237        );
3238    }
3239
3240    /// The fixture builders for structural packages, shared with the
3241    /// admission tests.
3242    use crate::admission::zip_names;
3243
3244    /// An entry's local-header offset, located through the reader.
3245    fn local_header_at(bytes: &[u8], name: &str) -> usize {
3246        let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
3247        usize::try_from(archive.by_name(name).unwrap().header_start()).unwrap()
3248    }
3249
3250    /// ZIP-17 (#644): a content field that disagrees between the two
3251    /// headers is a `zip-header-mismatch` finding, not a refusal.
3252    #[test]
3253    fn a_header_field_mismatch_reports_a_finding_instead_of_refusing() {
3254        let mut pkg = docx(CLEAN);
3255        let at = local_header_at(&pkg, "word/document.xml");
3256        pkg[at + 8] ^= 0x08; // the local method no longer matches the record's
3257        let out = report(&pkg, None, &Options::default()).unwrap();
3258        assert!(out.contains("zip-header-mismatch: 1\n"), "{out}");
3259        assert!(
3260            out.contains("compression method 8 in the central directory but 0"),
3261            "{out}"
3262        );
3263        let found = findings(&pkg).unwrap();
3264        assert!(
3265            found.iter().any(|f| f.code == "ZIP_HEADER_MISMATCH"),
3266            "{found:?}"
3267        );
3268    }
3269
3270    /// ZIP-17 (#644): an entry nested inside another entry's payload is
3271    /// a `zip-extent` finding, not a refusal.
3272    #[test]
3273    fn an_overlapping_entry_reports_a_finding_instead_of_refusing() {
3274        let mut embedded = zip_names::local_header(b"b.bin", 0, zip_names::crc32(b"x"), 1, 1, &[]);
3275        embedded.push(b'x');
3276        let mut pkg = zip_names::docx_package(
3277            "",
3278            &[
3279                zip_names::RawEntry::raw(b"a.bin", &embedded),
3280                zip_names::RawEntry::raw(b"b.bin", b"x"),
3281            ],
3282        );
3283        let embedded_at = local_header_at(&pkg, "a.bin") + 30 + b"a.bin".len();
3284        let b_central = {
3285            let mut archive = zip::ZipArchive::new(Cursor::new(&*pkg)).unwrap();
3286            usize::try_from(archive.by_name("b.bin").unwrap().central_header_start()).unwrap()
3287        };
3288        pkg[b_central + 42..b_central + 46]
3289            .copy_from_slice(&u32::try_from(embedded_at).unwrap().to_le_bytes());
3290        let out = report(&pkg, None, &Options::default()).unwrap();
3291        assert!(out.contains("zip-extent: 1\n"), "{out}");
3292        let found = findings(&pkg).unwrap();
3293        assert!(found.iter().any(|f| f.code == "ZIP_EXTENT"), "{found:?}");
3294    }
3295
3296    /// ZIP-17 (#644): a descriptor that disagrees with the central
3297    /// record is a `zip-descriptor` finding, not a refusal.
3298    #[test]
3299    fn a_descriptor_disagreement_reports_a_finding_instead_of_refusing() {
3300        let mut pkg = zip_names::assembled(
3301            b"",
3302            &[
3303                zip_names::AssembledEntry::plain(b"[Content_Types].xml", b"<Types/>"),
3304                zip_names::AssembledEntry::plain(b"_rels/.rels", b"<Relationships/>"),
3305                zip_names::AssembledEntry::plain(b"word/document.xml", b"<w:document/>"),
3306                zip_names::AssembledEntry::plain(b"x.bin", b"payload")
3307                    .with_descriptor(zip_names::Descriptor::Signed),
3308            ],
3309            None,
3310            b"",
3311        );
3312        let signature = pkg
3313            .windows(4)
3314            .position(|w| w == b"PK\x07\x08")
3315            .expect("signed descriptor");
3316        pkg[signature + 4] ^= 0xff;
3317        let out = report(&pkg, None, &Options::default()).unwrap();
3318        assert!(out.contains("zip-descriptor: 1\n"), "{out}");
3319        let found = findings(&pkg).unwrap();
3320        assert!(
3321            found.iter().any(|f| f.code == "ZIP_DESCRIPTOR"),
3322            "{found:?}"
3323        );
3324    }
3325
3326    /// ZIP-17 (#644): a directory entry whose payload fails its CRC is a
3327    /// `zip-directory-payload` finding, not a refusal.
3328    #[test]
3329    fn a_corrupt_directory_payload_reports_a_finding_instead_of_refusing() {
3330        let mut pkg =
3331            zip_names::docx_package("", &[zip_names::RawEntry::raw(b"word/media/", b"x")]);
3332        let at = local_header_at(&pkg, "word/media/") + 30 + b"word/media/".len();
3333        pkg[at] = b'y';
3334        let out = report(&pkg, None, &Options::default()).unwrap();
3335        assert!(out.contains("zip-directory-payload: 1\n"), "{out}");
3336        let found = findings(&pkg).unwrap();
3337        assert!(
3338            found.iter().any(|f| f.code == "ZIP_DIRECTORY_PAYLOAD"),
3339            "{found:?}"
3340        );
3341    }
3342
3343    /// A failed read still owes the budget the bytes it inflated: an
3344    /// entry whose payload errors after producing bytes must charge them,
3345    /// or every unreadable entry hands the next one a fresh allowance and
3346    /// `debug` inflates past `max_uncompressed_bytes` (#645).
3347    #[test]
3348    fn failed_entry_reads_still_consume_the_inflate_budget() {
3349        let payload = vec![b'x'; 2048];
3350        let mut pkg = zip_names::docx_package(
3351            "",
3352            &[
3353                zip_names::RawEntry::raw(b"word/a/", &payload),
3354                zip_names::RawEntry::raw(b"word/b.bin", &payload),
3355            ],
3356        );
3357        // Corrupt both payloads so each entry's read fails at its CRC
3358        // after inflating its full stored size.
3359        for name in ["word/a/", "word/b.bin"] {
3360            let at = local_header_at(&pkg, name) + 30 + name.len();
3361            pkg[at] = b'y';
3362        }
3363        let limits = crate::admission::InputLimits {
3364            max_part_bytes: 8192,
3365            max_uncompressed_bytes: 4096,
3366            ..crate::admission::InputLimits::compare()
3367        };
3368        let err = Package::open_within(&pkg, limits)
3369            .err()
3370            .expect("two failed 2048-byte reads must exhaust the 4096-byte budget");
3371        assert!(err.contains("INPUT_LIMIT"), "{err}");
3372    }
3373
3374    /// The report or its refusal message, so a package `debug` cannot
3375    /// open fails the finding assertion instead of panicking (#644).
3376    fn debug_output(pkg: &[u8]) -> String {
3377        report(pkg, None, &Options::default()).unwrap_or_else(|e| e)
3378    }
3379
3380    /// A minimal package whose one binary entry is easy to corrupt:
3381    /// stored, no extra fields, so extents are plain arithmetic.
3382    fn bin_package() -> Vec<u8> {
3383        zip_names::docx_package("", &[zip_names::RawEntry::raw(b"z.bin", b"payload")])
3384    }
3385
3386    /// The offset of `name`'s central record, located through the reader.
3387    fn central_header_at(bytes: &[u8], name: &str) -> usize {
3388        let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
3389        usize::try_from(archive.by_name(name).unwrap().central_header_start()).unwrap()
3390    }
3391
3392    /// Set `name`'s central-record compressed size (the field at +20),
3393    /// which both the extent pass and the payload read follow.
3394    fn set_central_compressed_size(bytes: &mut [u8], name: &str, size: u32) {
3395        assert_ne!(size, u32::MAX, "0xFFFFFFFF is the ZIP64 placeholder");
3396        let at = central_header_at(bytes, name);
3397        bytes[at + 20..at + 24].copy_from_slice(&size.to_le_bytes());
3398    }
3399
3400    /// ZIP-17 (#644): an entry whose extent reaches past the central
3401    /// directory fails its read on every route — `debug` still reports
3402    /// the structural finding, and the failed read is a finding of its
3403    /// own rather than the end of the report.
3404    #[test]
3405    fn an_extent_past_the_directory_reports_a_finding_instead_of_refusing() {
3406        let mut pkg = bin_package();
3407        let reach = {
3408            let mut archive = zip::ZipArchive::new(Cursor::new(&*pkg)).unwrap();
3409            let start = archive.by_name("z.bin").unwrap().header_start();
3410            archive.central_directory_start() - start + 1
3411        };
3412        set_central_compressed_size(&mut pkg, "z.bin", u32::try_from(reach).unwrap());
3413        let out = debug_output(&pkg);
3414        assert!(out.contains("zip-extent: 1\n"), "{out}");
3415        assert!(out.contains("reaches past the central directory"), "{out}");
3416        assert!(out.contains("zip-entry-read: 1\n"), "{out}");
3417        let found = findings(&pkg).unwrap();
3418        assert!(found.iter().any(|f| f.code == "ZIP_EXTENT"), "{found:?}");
3419    }
3420
3421    /// ZIP-17 (#644): the same defect one byte into the central
3422    /// directory, the smallest overlapping extent.
3423    #[test]
3424    fn an_extent_one_byte_into_the_directory_reports_a_finding() {
3425        let mut pkg = bin_package();
3426        let reach = {
3427            let mut archive = zip::ZipArchive::new(Cursor::new(&*pkg)).unwrap();
3428            let start = archive.by_name("z.bin").unwrap().data_start().unwrap();
3429            archive.central_directory_start() - start + 1
3430        };
3431        set_central_compressed_size(&mut pkg, "z.bin", u32::try_from(reach).unwrap());
3432        let out = debug_output(&pkg);
3433        assert!(out.contains("zip-extent: 1\n"), "{out}");
3434        assert!(out.contains("reaches past the central directory"), "{out}");
3435        assert!(out.contains("zip-entry-read: 1\n"), "{out}");
3436    }
3437
3438    /// ZIP-17 (#644): the first entry's extent ends inside the second
3439    /// entry's local record — an overlap finding, even though reading
3440    /// the first entry fails.
3441    #[test]
3442    fn an_extent_over_the_next_entry_reports_a_finding_instead_of_refusing() {
3443        let mut pkg = zip_names::docx_package("", &[]);
3444        let reach = {
3445            let mut archive = zip::ZipArchive::new(Cursor::new(&*pkg)).unwrap();
3446            let next = archive.by_name("_rels/.rels").unwrap().header_start();
3447            let start = archive
3448                .by_name("[Content_Types].xml")
3449                .unwrap()
3450                .data_start()
3451                .unwrap();
3452            next - start + 1
3453        };
3454        set_central_compressed_size(
3455            &mut pkg,
3456            "[Content_Types].xml",
3457            u32::try_from(reach).unwrap(),
3458        );
3459        let out = debug_output(&pkg);
3460        assert!(out.contains("zip-extent: 1\n"), "{out}");
3461        assert!(out.contains("inside entry '_rels/.rels'"), "{out}");
3462        assert!(out.contains("zip-entry-read: 1\n"), "{out}");
3463        let found = findings(&pkg).unwrap();
3464        assert!(found.iter().any(|f| f.code == "ZIP_EXTENT"), "{found:?}");
3465    }
3466
3467    /// ZIP-17 (#644): a central record that points inside another
3468    /// entry's payload has no local header there — a header-mismatch
3469    /// finding, and the failed open of the entry is a finding too.
3470    #[test]
3471    fn a_central_record_inside_a_payload_reports_a_finding_instead_of_refusing() {
3472        let mut pkg = bin_package();
3473        let inside =
3474            local_header_at(&pkg, "word/document.xml") + 30 + b"word/document.xml".len() + 1;
3475        let at = central_header_at(&pkg, "z.bin");
3476        pkg[at + 42..at + 46].copy_from_slice(&u32::try_from(inside).unwrap().to_le_bytes());
3477        let out = debug_output(&pkg);
3478        assert!(out.contains("zip-header-mismatch: 1\n"), "{out}");
3479        assert!(out.contains("has no local header"), "{out}");
3480        assert!(out.contains("zip-entry-read: 1\n"), "{out}");
3481        let found = findings(&pkg).unwrap();
3482        assert!(
3483            found.iter().any(|f| f.code == "ZIP_HEADER_MISMATCH"),
3484            "{found:?}"
3485        );
3486    }
3487
3488    /// ZIP-17 (#644): an entry whose payload fails its CRC, with no
3489    /// structural defect behind it, is a `zip-entry-read` finding — the
3490    /// same triage a directory's payload already gets.
3491    #[test]
3492    fn a_corrupt_entry_payload_reports_a_finding_instead_of_refusing() {
3493        let mut pkg = bin_package();
3494        let at = local_header_at(&pkg, "z.bin") + 30 + b"z.bin".len();
3495        pkg[at] = b'X';
3496        let out = debug_output(&pkg);
3497        assert!(out.contains("zip-entry-read: 1\n"), "{out}");
3498        assert!(out.contains("'z.bin'"), "{out}");
3499        let found = findings(&pkg).unwrap();
3500        assert!(
3501            found.iter().any(|f| f.code == "ZIP_ENTRY_READ"),
3502            "{found:?}"
3503        );
3504    }
3505
3506    /// ZIP-16 (#639): an entry recorded as a non-regular Unix type — a
3507    /// symlink here — is a `zip-special-entry` finding, not a refusal.
3508    #[test]
3509    fn a_special_entry_reports_a_finding_instead_of_refusing() {
3510        let mut pkg = docx(CLEAN);
3511        let at = {
3512            let mut archive = zip::ZipArchive::new(Cursor::new(&*pkg)).unwrap();
3513            usize::try_from(
3514                archive
3515                    .by_name("word/document.xml")
3516                    .unwrap()
3517                    .central_header_start(),
3518            )
3519            .unwrap()
3520        };
3521        assert_eq!(&pkg[at..at + 4], b"PK\x01\x02");
3522        // version_made_by = Unix host, S_IFLNK mode in the high 16 bits
3523        // of the external attributes.
3524        pkg[at + 4..at + 6].copy_from_slice(&0x0314u16.to_le_bytes());
3525        pkg[at + 38..at + 42].copy_from_slice(&(0o120777u32 << 16).to_le_bytes());
3526        let out = report(&pkg, None, &Options::default()).unwrap();
3527        assert!(out.contains("zip-special-entry: 1\n"), "{out}");
3528        let found = findings(&pkg).unwrap();
3529        assert!(
3530            found.iter().any(|f| f.code == "ZIP_SPECIAL_ENTRY"),
3531            "{found:?}"
3532        );
3533    }
3534
3535    #[test]
3536    fn a_deleted_text_box_field_left_bare_is_reported() {
3537        let out = report(&docx(ORPHAN), None, &Options::default()).unwrap();
3538        assert!(out.contains("orphan-delInstrText: 1\n"), "{out}");
3539        assert!(out.contains("bare-run-in-deleted-textbox: 4\n"), "{out}");
3540        assert!(out.contains("field-code-kind-vs-state: 1\n"), "{out}");
3541        assert!(
3542            out.contains("txbxContent/p/r/delInstrText \"FILENAME\""),
3543            "{out}"
3544        );
3545    }
3546
3547    #[test]
3548    fn two_files_print_only_what_differs() {
3549        let (a, b) = (docx(CLEAN), docx(ORPHAN));
3550        let out = report(&a, Some(&b), &Options::default()).unwrap();
3551        assert!(
3552            out.starts_with("bare-run-in-deleted-textbox: 0 → 4\n"),
3553            "{out}"
3554        );
3555        assert!(out.contains("  +B word/document.xml "), "{out}");
3556        assert_eq!(
3557            report(&a, Some(&a), &Options::default()).unwrap(),
3558            "findings identical\n"
3559        );
3560        let opts = Options {
3561            checks: vec![Check::Elements],
3562            ..Default::default()
3563        };
3564        let out = report(&a, Some(&b), &opts).unwrap();
3565        assert!(out.contains("  delInstrText 0 → 1\n"), "{out}");
3566        assert!(!out.contains("  body "), "unchanged counts stay out: {out}");
3567    }
3568
3569    #[test]
3570    fn list_shows_entries_and_with_two_files_only_changed_ones() {
3571        let (a, b) = (docx(CLEAN), docx(ORPHAN));
3572        let one = list(&a, None, &Options::default()).unwrap();
3573        assert!(one.starts_with("3 entries, "), "{one}");
3574        assert!(one.contains(" word/document.xml\n"), "{one}");
3575        let two = list(&a, Some(&b), &Options::default()).unwrap();
3576        assert!(
3577            two.starts_with("2 identical, 1 changed, 0 only in A, 0 only in B\n"),
3578            "{two}"
3579        );
3580        assert!(
3581            two.contains("~ ") && two.contains("word/document.xml"),
3582            "{two}"
3583        );
3584        assert!(
3585            !two.contains("[Content_Types]"),
3586            "identical entries stay out: {two}"
3587        );
3588    }
3589
3590    #[test]
3591    fn a_partly_deleted_field_is_reported() {
3592        let body = r#"<w:p><w:del w:id="1" w:author="A"><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:delInstrText> PAGE </w:delInstrText></w:r></w:del><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>"#;
3593        let out = report(&docx(body), None, &Options::default()).unwrap();
3594        assert!(out.contains("field-partly-deleted: 1\n"), "{out}");
3595        assert!(out.contains("begin/code/separate/end=DD-"), "{out}");
3596    }
3597
3598    #[test]
3599    fn broken_bookmarks_are_reported() {
3600        let body = r#"<w:p><w:bookmarkStart w:id="1" w:name="x"/><w:r><w:t>a</w:t></w:r><w:bookmarkEnd w:id="1"/><w:bookmarkStart w:id="2" w:name="x"/><w:bookmarkEnd w:id="2"/><w:bookmarkEnd w:id="9"/></w:p>"#;
3601        let out = report(&docx(body), None, &Options::default()).unwrap();
3602        assert!(out.contains("bookmark-duplicate-name: 1\n"), "{out}");
3603        assert!(out.contains("bookmark-end-without-start: 1\n"), "{out}");
3604    }
3605
3606    #[test]
3607    fn textbox_prints_the_story_without_namespace_declarations() {
3608        let opts = Options {
3609            checks: vec![Check::Textbox],
3610            grep: Some("AG".into()),
3611            ..Default::default()
3612        };
3613        let out = report(&docx(ORPHAN), None, &opts).unwrap();
3614        assert!(out.starts_with("textbox: 1\n"), "{out}");
3615        assert!(out.contains("(anchor deleted)"), "{out}");
3616        assert!(out.contains("<w:txbxContent><w:p>"), "{out}");
3617        assert!(!out.contains("xmlns"), "{out}");
3618        let none = Options {
3619            grep: Some("absent".into()),
3620            ..opts
3621        };
3622        assert_eq!(report(&docx(ORPHAN), None, &none).unwrap(), "textbox: 0\n");
3623    }
3624
3625    #[test]
3626    fn package_references_that_name_nothing_are_reported() {
3627        let body = r#"<w:p><w:r><w:footnoteReference w:id="7"/></w:r><w:r><w:drawing><wp:inline><wp:docPr id="1" name="a"/></wp:inline></w:drawing></w:r><w:r><w:drawing><wp:inline><wp:docPr id="1" name="b"/></wp:inline></w:drawing></w:r><w:hyperlink r:id="rId9"><w:r><w:t>x</w:t></w:r></w:hyperlink><w:commentRangeStart w:id="3"/></w:p>"#;
3628        let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="t" Target="media/image%201.png"/><Relationship Id="rId1" Type="t" Target="../customXml/item1.xml"/><Relationship Id="rId2" Type="t" Target="https://x" TargetMode="External"/></Relationships>"#;
3629        let pkg = zip_of(&[
3630            ("[Content_Types].xml", TYPES),
3631            ("_rels/.rels", ROOT_RELS),
3632            ("word/document.xml", &document(body)),
3633            ("word/_rels/document.xml.rels", rels),
3634            ("word/media/image 1.png", "png"),
3635        ]);
3636        let out = report(&pkg, None, &Options::default()).unwrap();
3637        for expected in [
3638            "footnoteReference-dangling: 1\n",
3639            "rid-not-in-rels: 1\n",
3640            "  word/document.xml document/body/p/hyperlink r:id=\"rId9\"",
3641            "comment-range-unpaired: 1\n",
3642            "rel-duplicate-id: 1\n",
3643            "rel-target-missing: 1\n",
3644            "rId1 → ../customXml/item1.xml",
3645            "part-without-content-type: 1\n  word/media/image 1.png",
3646        ] {
3647            assert!(out.contains(expected), "{expected:?} in {out}");
3648        }
3649        // Word opens 66 of the English outputs that repeat a docPr id.
3650        assert!(!out.contains("docpr-duplicate-id"), "{out}");
3651    }
3652
3653    #[test]
3654    fn what_word_ignores_is_not_reported() {
3655        // Office's `[trash]/` folder, a diagram's empty `r:embed=""`.
3656        let body = r#"<w:p><w:r><w:drawing><wp:inline><a:blip xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" r:embed=""/></wp:inline></w:drawing></w:r></w:p>"#;
3657        let pkg = zip_of(&[
3658            ("[Content_Types].xml", TYPES),
3659            ("_rels/.rels", ROOT_RELS),
3660            ("word/document.xml", &document(body)),
3661            ("[trash]/0001.dat", "junk"),
3662        ]);
3663        let out = report(&pkg, None, &Options::default()).unwrap();
3664        assert_eq!(out, "no findings\n");
3665    }
3666
3667    #[test]
3668    fn utf16_parts_are_decoded_behind_their_byte_order_mark() {
3669        let xml = r#"<?xml version="1.0" encoding="UTF-16"?><r/>"#;
3670        let le: Vec<u8> = [0xFF, 0xFE]
3671            .into_iter()
3672            .chain(xml.encode_utf16().flat_map(u16::to_le_bytes))
3673            .collect();
3674        let be: Vec<u8> = [0xFE, 0xFF]
3675            .into_iter()
3676            .chain(xml.encode_utf16().flat_map(u16::to_be_bytes))
3677            .collect();
3678        let bom8: Vec<u8> = [0xEF, 0xBB, 0xBF].into_iter().chain(xml.bytes()).collect();
3679        for data in [le, be, bom8] {
3680            assert_eq!(decode_xml(&data).as_deref(), Some(xml));
3681        }
3682        assert_eq!(decode_xml(&[0xFF, 0xFE, 0x00, 0xD8]), None);
3683    }
3684
3685    #[test]
3686    fn a_bookmark_in_a_single_value_control_is_reported() {
3687        // Word keeps no bookmark in a plain-text or list control (en
3688        // 7b649361, 57c181da); a rich-text control may hold one.
3689        let control = |kind: &str, id: u32| {
3690            format!(
3691                r#"<w:sdt><w:sdtPr>{kind}</w:sdtPr><w:sdtContent><w:p><w:bookmarkStart w:id="{id}" w:name="b{id}"/><w:r><w:t>x</w:t></w:r><w:bookmarkEnd w:id="{id}"/></w:p></w:sdtContent></w:sdt>"#
3692            )
3693        };
3694        let body = [
3695            control("<w:text/>", 1),
3696            control(
3697                r#"<w:dropDownList><w:listItem w:value="a"/></w:dropDownList>"#,
3698                2,
3699            ),
3700            control(r#"<w:alias w:val="rich"/>"#, 3),
3701        ]
3702        .concat();
3703        let out = report(&docx(&body), None, &Options::default()).unwrap();
3704        assert!(out.contains("bookmark-in-text-control: 2\n"), "{out}");
3705        assert!(
3706            out.contains("bookmark-in-dropDownList-control: 2\n"),
3707            "{out}"
3708        );
3709        assert!(!out.contains("b3"), "{out}");
3710    }
3711
3712    #[test]
3713    fn undeclared_ignorable_prefixes_are_found_on_the_carrying_element() {
3714        let xml = r#"<w:document xmlns:mc="m" xmlns:w14="x" mc:Ignorable="w14 wp14"><w:body/></w:document>"#;
3715        assert_eq!(undeclared_ignorable_prefixes(xml), vec!["wp14".to_string()]);
3716    }
3717
3718    #[test]
3719    fn structures_word_rejects_are_reported() {
3720        let body = r#"<w:tbl><w:tr><w:tc><w:tcPr/><w:tbl/></w:tc></w:tr><w:tr/></w:tbl><w:p><w:r><w:instrText/></w:r><w:r><w:instrText xml:space="preserve"> </w:instrText></w:r><w:ins w:id="1" w:author="A"><w:ins w:id="2" w:author="A"><w:r><w:t>x</w:t></w:r></w:ins></w:ins></w:p><w:sectPr/><w:p/>"#;
3721        let out = report(&docx(body), None, &Options::default()).unwrap();
3722        for expected in [
3723            "cell-not-ending-in-p: 1\n",
3724            "row-without-cell: 1\n",
3725            // Word writes " " codes itself; only a code with no text is blank.
3726            "instrText-empty: 1\n",
3727            "ins-nested-in-ins: 1\n",
3728            "body-sectPr-not-last: 1\n",
3729        ] {
3730            assert!(out.contains(expected), "{expected:?} in {out}");
3731        }
3732    }
3733
3734    #[test]
3735    fn duplicate_revision_ids_are_reported_only_when_asked() {
3736        let body = r#"<w:p><w:ins w:id="4" w:author="A"><w:r><w:t>a</w:t></w:r></w:ins><w:del w:id="4" w:author="A"><w:r><w:delText>b</w:delText></w:r></w:del><w:r><w:drawing><wp:inline><wp:docPr id="1" name="a"/></wp:inline></w:drawing></w:r><w:r><w:drawing><wp:inline><wp:docPr id="1" name="b"/></wp:inline></w:drawing></w:r></w:p>"#;
3737        assert_eq!(
3738            report(&docx(body), None, &Options::default()).unwrap(),
3739            "no findings\n"
3740        );
3741        let opts = Options {
3742            checks: vec![Check::Ids],
3743            ..Default::default()
3744        };
3745        let out = report(&docx(body), None, &opts).unwrap();
3746        assert!(out.contains("revision-duplicate-id: 1\n"), "{out}");
3747        assert!(
3748            out.contains("id 4 ×2: word/document.xml:ins, word/document.xml:del"),
3749            "{out}"
3750        );
3751        assert!(
3752            out.contains("docpr-duplicate-id: 1\n  package id 1 ×2"),
3753            "{out}"
3754        );
3755    }
3756
3757    #[test]
3758    fn dangling_style_links_and_twin_names_are_reported_only_when_asked() {
3759        let styles = r#"<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:style w:type="paragraph" w:styleId="Normal"><w:name w:val="Normal"/></w:style><w:style w:type="paragraph" w:styleId="a"><w:name w:val="normal"/></w:style><w:style w:type="paragraph" w:styleId="Quote"><w:name w:val="Quote"/><w:basedOn w:val="a0"/><w:next w:val="Normal"/></w:style><w:style w:type="character" w:styleId="Normal0"><w:name w:val="Normal"/></w:style></w:styles>"#;
3760        let body = r#"<w:p><w:pPr><w:pStyle w:val="Missing"/></w:pPr><w:r><w:rPr><w:rStyle w:val="Normal0"/></w:rPr><w:t>x</w:t></w:r></w:p>"#;
3761        let pkg = zip_of(&[
3762            ("[Content_Types].xml", TYPES),
3763            ("_rels/.rels", ROOT_RELS),
3764            ("word/document.xml", &document(body)),
3765            ("word/styles.xml", styles),
3766        ]);
3767        let out = report(&pkg, None, &opts_for(Check::Styles)).unwrap();
3768        assert!(
3769            out.contains("style-link-dangling: 1\n  word/styles.xml Quote basedOn a0"),
3770            "{out}"
3771        );
3772        assert!(
3773            out.contains("style-ref-dangling: 1\n  word/document.xml pStyle Missing"),
3774            "{out}"
3775        );
3776        // Word pairs styles by type and name, case-insensitively; a character
3777        // style may share a paragraph style's name.
3778        assert!(
3779            out.contains("style-name-twin: 1\n  word/styles.xml paragraph \"normal\": Normal, a"),
3780            "{out}"
3781        );
3782        let triage = report(&pkg, None, &Options::default()).unwrap();
3783        assert!(!triage.contains("style-"), "{triage}");
3784    }
3785
3786    fn opts_for(check: Check) -> Options {
3787        Options {
3788            checks: vec![check],
3789            ..Default::default()
3790        }
3791    }
3792
3793    /// A deleted paragraph mark, inserted and deleted text, a comment
3794    /// reference and a table whose one row is deleted.
3795    const TRACKED: &str = r#"<w:p><w:r><w:t>Plain</w:t></w:r></w:p><w:p><w:pPr><w:rPr><w:del w:id="1" w:author="A"/></w:rPr></w:pPr><w:ins w:id="2" w:author="A"><w:r><w:t>Track</w:t></w:r></w:ins><w:del w:id="3" w:author="A"><w:r><w:delText>old</w:delText></w:r></w:del><w:r><w:commentReference w:id="7"/></w:r></w:p><w:tbl><w:tr><w:trPr><w:del w:id="4" w:author="A"/></w:trPr><w:tc><w:p><w:r><w:t>cell</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p/>"#;
3796
3797    #[test]
3798    fn text_lists_paragraphs_with_their_revision_marks() {
3799        let out = report(&docx(TRACKED), None, &opts_for(Check::Text)).unwrap();
3800        for expected in [
3801            "word/document.xml: 4 paragraphs\n",
3802            "  ¶  Plain\n",
3803            "  ¶- {+Track+}[-old-][c7]\n",
3804            "  table\n",
3805            "   row-\n",
3806            "    ¶  cell\n",
3807            "  ¶  \n",
3808        ] {
3809            assert!(out.contains(expected), "{expected:?} in\n{out}");
3810        }
3811    }
3812
3813    #[test]
3814    fn tables_list_grids_rows_and_cells_with_their_marks() {
3815        let body = concat!(
3816            r#"<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/><w:tblPrChange w:id="1" w:author="A"><w:tblPr/></w:tblPrChange></w:tblPr>"#,
3817            r#"<w:tblGrid><w:gridCol w:w="3120"/><w:gridCol w:w="6240"/><w:tblGridChange w:id="2"><w:tblGrid><w:gridCol w:w="9360"/></w:tblGrid></w:tblGridChange></w:tblGrid>"#,
3818            r#"<w:tr><w:tc><w:tcPr><w:tcW w:w="3120" w:type="dxa"/><w:tcPrChange w:id="3" w:author="A"><w:tcPr><w:tcW w:w="9360" w:type="dxa"/><w:gridSpan w:val="2"/></w:tcPr></w:tcPrChange></w:tcPr>"#,
3819            r#"<w:p><w:r><w:t>Name</w:t></w:r></w:p></w:tc>"#,
3820            r#"<w:tc><w:tcPr><w:tcW w:w="50" w:type="pct"/><w:vMerge w:val="restart"/><w:cellIns w:id="4" w:author="A"/></w:tcPr>"#,
3821            r#"<w:p><w:ins w:id="5" w:author="A"><w:r><w:t>Role</w:t></w:r></w:ins></w:p>"#,
3822            r#"<w:tbl><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid><w:tr><w:tc><w:p><w:r><w:t>Inner</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p/></w:tc></w:tr>"#,
3823            r#"<w:sdt><w:sdtContent><w:tr><w:trPr><w:gridBefore w:val="1"/><w:del w:id="6" w:author="A"/></w:trPr>"#,
3824            r#"<w:tc><w:tcPr><w:vMerge/><w:cellDel w:id="7" w:author="A"/></w:tcPr><w:p><w:del w:id="8" w:author="A"><w:r><w:delText>Old</w:delText></w:r></w:del></w:p></w:tc></w:tr></w:sdtContent></w:sdt>"#,
3825            r#"</w:tbl><w:p/>"#,
3826        );
3827        let out = report(&docx(body), None, &opts_for(Check::Tables)).unwrap();
3828        let expected = concat!(
3829            "word/document.xml: 2 tables\n",
3830            "  table grid=3120,6240 (old grid=9360) tblPrChange\n",
3831            "   row\n",
3832            "    cell w=3120 (old span=2 w=9360): ¶  Name\n",
3833            "    cell+ w=50pct vMerge=restart: ¶  {+Role+} | ¶  \n",
3834            "      table grid=2000\n",
3835            "       row\n",
3836            "        cell: ¶  Inner\n",
3837            "   row- before=1\n",
3838            "    cell- vMerge: ¶  [-Old-]\n",
3839        );
3840        assert!(out.contains(expected), "{expected}\nin\n{out}");
3841        let same = report(&docx(body), Some(&docx(body)), &opts_for(Check::Tables)).unwrap();
3842        assert!(!same.contains("cell"), "{same}");
3843        let plain = report(&docx("<w:p/>"), None, &opts_for(Check::Tables)).unwrap();
3844        assert!(!plain.contains("tables"), "{plain}");
3845    }
3846
3847    /// A table in a text box inside a cell is listed under the cell
3848    /// (#4372490724); a DrawingML `a:tbl` is no document table
3849    /// (#4372490734).
3850    #[test]
3851    fn tables_reach_text_boxes_in_cells_and_skip_drawing_tables() {
3852        let text_box = concat!(
3853            r#"<w:p><w:r><w:pict><v:shape xmlns:v="urn:schemas-microsoft-com:vml"><v:textbox><w:txbxContent>"#,
3854            r#"<w:tbl><w:tblGrid><w:gridCol w:w="1000"/></w:tblGrid><w:tr><w:tc><w:p><w:r><w:t>Boxed</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p/>"#,
3855            r#"</w:txbxContent></v:textbox></v:shape></w:pict></w:r></w:p>"#,
3856        );
3857        let drawing_table = concat!(
3858            r#"<w:p><w:r><w:drawing><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData>"#,
3859            r#"<a:tbl><a:tblGrid><a:gridCol w="100"/></a:tblGrid><a:tr h="1"><a:tc><a:txBody/></a:tc></a:tr></a:tbl>"#,
3860            r#"</a:graphicData></a:graphic></w:drawing></w:r></w:p>"#,
3861        );
3862        let body = format!(
3863            r#"<w:tbl><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid><w:tr><w:tc>{text_box}</w:tc></w:tr></w:tbl>{drawing_table}<w:p/>"#
3864        );
3865        let out = report(&docx(&body), None, &opts_for(Check::Tables)).unwrap();
3866        for expected in [
3867            "word/document.xml: 2 tables\n",
3868            "  table grid=4000\n   row\n    cell",
3869            "\n      table grid=1000\n       row\n        cell: ¶  Boxed\n",
3870        ] {
3871            assert!(out.contains(expected), "{expected:?} in\n{out}");
3872        }
3873        assert!(!out.contains("grid=100\n"), "{out}");
3874    }
3875
3876    #[test]
3877    fn runs_show_each_paragraph_with_its_direct_formatting() {
3878        let body = r#"<w:p><w:pPr><w:pStyle w:val="Body"/><w:jc w:val="both"/><w:rPr><w:del w:id="1" w:author="A"/><w:sz w:val="20"/></w:rPr></w:pPr><w:r><w:rPr><w:b/><w:rFonts w:cs="Arial" w:ascii="Arial"/><w:sz w:val="24"/></w:rPr><w:t>Bold</w:t></w:r><w:r><w:rPr><w:sz w:val="24"/><w:b/><w:rFonts w:ascii="Arial" w:cs="Arial"/><w:rPrChange w:id="2" w:author="A"><w:rPr/></w:rPrChange></w:rPr><w:t> too</w:t></w:r><w:r><w:t>plain</w:t></w:r><w:r><w:rPr/><w:t> end</w:t></w:r></w:p>"#;
3879        let out = report(&docx(body), None, &opts_for(Check::Runs)).unwrap();
3880        let expected = "  ¶- [jc=both pStyle=Body] ¶«sz=20» «b rFonts(ascii=Arial,cs=Arial) sz=24»Bold too«»plain end\n";
3881        assert!(out.contains(expected), "{expected:?} in\n{out}");
3882    }
3883
3884    #[test]
3885    fn changes_list_what_each_property_record_changed() {
3886        let body = r#"<w:tbl><w:tr><w:tc><w:tcPr><w:tcW w:w="3120" w:type="dxa"/><w:tcPrChange w:id="1" w:author="A"><w:tcPr><w:tcW w:w="3120" w:type="dxa"/><w:shd w:val="clear" w:fill="F8FAFC"/></w:tcPr></w:tcPrChange></w:tcPr><w:p><w:r><w:t>Name</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p><w:pPr><w:jc w:val="center"/><w:pPrChange w:id="2" w:author="A"><w:pPr/></w:pPrChange></w:pPr><w:r><w:t>Title</w:t></w:r></w:p>"#;
3887        let out = report(&docx(body), None, &opts_for(Check::Changes)).unwrap();
3888        for expected in [
3889            "word/document.xml: 2 property changes\n",
3890            "  tcPrChange tc \"Name\": -shd(fill=F8FAFC,val=clear)\n",
3891            "  pPrChange p \"Title\": +jc=center\n",
3892        ] {
3893            assert!(out.contains(expected), "{expected:?} in\n{out}");
3894        }
3895        let same = report(&docx(body), Some(&docx(body)), &opts_for(Check::Changes)).unwrap();
3896        assert!(!same.contains("Change"), "{same}");
3897    }
3898
3899    /// A package whose stylesheet is `styles` (the `w:styles` children).
3900    fn docx_with_styles(styles: &str) -> Vec<u8> {
3901        zip_of(&[
3902            ("[Content_Types].xml", TYPES),
3903            ("_rels/.rels", ROOT_RELS),
3904            ("word/document.xml", &document(CLEAN)),
3905            (
3906                "word/styles.xml",
3907                &format!(
3908                    r#"<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{styles}</w:styles>"#
3909                ),
3910            ),
3911        ])
3912    }
3913
3914    /// Styles list by type and name, whatever their ids: a localized
3915    /// stylesheet (`Norml`, `Listaszerbekezds`) and an English one compare
3916    /// on what each style defines.
3917    #[test]
3918    fn styledefs_list_each_style_by_name() {
3919        let hu = r#"<w:docDefaults><w:pPrDefault><w:pPr><w:spacing w:after="200" w:line="276" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Norml"><w:name w:val="Normal"/></w:style><w:style w:type="paragraph" w:styleId="Listaszerbekezds"><w:name w:val="List Paragraph"/><w:basedOn w:val="Norml"/><w:pPr><w:ind w:left="720"/></w:pPr><w:rPr><w:b/></w:rPr></w:style>"#;
3920        let out = report(&docx_with_styles(hu), None, &opts_for(Check::StyleDefs)).unwrap();
3921        for expected in [
3922            "word/styles.xml: 2 styles\n",
3923            "  docDefaults pPr[spacing(after=200,line=276,lineRule=auto)]\n",
3924            "  docDefaults rPr[]\n",
3925            "  paragraph \"Normal\" default\n",
3926            "  paragraph \"Normal\" pPr[]\n",
3927            "  paragraph \"List Paragraph\" basedOn=\"Normal\"\n",
3928            "  paragraph \"List Paragraph\" pPr[ind(left=720)]\n",
3929            "  paragraph \"List Paragraph\" rPr[b]\n",
3930        ] {
3931            assert!(out.contains(expected), "{expected:?} in\n{out}");
3932        }
3933        let en = hu
3934            .replace("Norml", "Normal")
3935            .replace("Listaszerbekezds", "ListParagraph");
3936        let same = report(
3937            &docx_with_styles(hu),
3938            Some(&docx_with_styles(&en)),
3939            &opts_for(Check::StyleDefs),
3940        )
3941        .unwrap();
3942        assert_eq!(same, "styledefs identical\n");
3943        let bolder = en.replace("<w:b/>", "<w:b/><w:i/>");
3944        let out = report(
3945            &docx_with_styles(hu),
3946            Some(&docx_with_styles(&bolder)),
3947            &opts_for(Check::StyleDefs),
3948        )
3949        .unwrap();
3950        assert!(
3951            out.contains("+B   paragraph \"List Paragraph\" rPr[b i]\n"),
3952            "{out}"
3953        );
3954    }
3955
3956    fn docx_with_numbering(numbering: &str) -> Vec<u8> {
3957        zip_of(&[
3958            ("[Content_Types].xml", TYPES),
3959            ("_rels/.rels", ROOT_RELS),
3960            ("word/document.xml", &document(CLEAN)),
3961            (
3962                "word/numbering.xml",
3963                &format!(
3964                    r#"<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{numbering}</w:numbering>"#
3965                ),
3966            ),
3967        ])
3968    }
3969
3970    /// Each list level as the paragraphs naming the list see it: the
3971    /// abstract definition with the list's overrides applied, by `numId`
3972    /// (what paragraphs point at), never by the abstract's id, which Word
3973    /// renumbers.
3974    #[test]
3975    fn numbering_lists_each_level_a_list_resolves_to() {
3976        let abs = |id: &str, left: &str| {
3977            format!(
3978                r#"<w:abstractNum w:abstractNumId="{id}"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1)"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="{left}" w:hanging="360"/></w:pPr></w:lvl><w:lvl w:ilvl="1"><w:start w:val="1"/><w:numFmt w:val="lowerLetter"/><w:lvlText w:val="%2."/><w:lvlJc w:val="left"/><w:rPr><w:b/></w:rPr></w:lvl></w:abstractNum>"#
3979            )
3980        };
3981        let num = r#"<w:num w:numId="20"><w:abstractNumId w:val="9"/><w:lvlOverride w:ilvl="0"><w:startOverride w:val="3"/></w:lvlOverride></w:num>"#;
3982        let a = docx_with_numbering(&format!("{}{num}", abs("9", "1069")));
3983        let out = report(&a, None, &opts_for(Check::Numbering)).unwrap();
3984        for expected in [
3985            "word/numbering.xml: 1 lists\n",
3986            "  num 20 lvl 0 start=3 decimal \"%1)\" jc=left pPr[ind(hanging=360,left=1069)] rPr[]\n",
3987            "  num 20 lvl 1 start=1 lowerLetter \"%2.\" jc=left pPr[] rPr[b]\n",
3988        ] {
3989            assert!(out.contains(expected), "{expected:?} in\n{out}");
3990        }
3991        // The same list under another abstract id reads the same.
3992        let renumbered = docx_with_numbering(&format!(
3993            "{}{}",
3994            abs("4", "1069"),
3995            num.replace(r#"w:val="9""#, r#"w:val="4""#)
3996        ));
3997        let same = report(&a, Some(&renumbered), &opts_for(Check::Numbering)).unwrap();
3998        assert_eq!(same, "numbering identical\n");
3999        let wider = docx_with_numbering(&format!("{}{num}", abs("9", "1800")));
4000        let out = report(&a, Some(&wider), &opts_for(Check::Numbering)).unwrap();
4001        assert!(
4002            out.contains("+B   num 20 lvl 0 start=3 decimal \"%1)\" jc=left pPr[ind(hanging=360,left=1800)] rPr[]\n"),
4003            "{out}"
4004        );
4005    }
4006
4007    #[test]
4008    fn grep_narrows_runs_to_the_paragraphs_whose_text_has_it() {
4009        let long = "x".repeat(300);
4010        let body = format!(
4011            r#"<w:p><w:r><w:rPr><w:sz w:val="24"/></w:rPr><w:t xml:space="preserve">{long} Q: Can you do PT/</w:t></w:r><w:r><w:rPr><w:b/><w:sz w:val="24"/></w:rPr><w:t>INRs?</w:t></w:r></w:p><w:p><w:r><w:t>Q: Other</w:t></w:r></w:p>"#
4012        );
4013        let opts = Options {
4014            grep: Some("PT/INRs".into()),
4015            ..opts_for(Check::Runs)
4016        };
4017        let out = report(&docx(&body), None, &opts).unwrap();
4018        assert!(out.contains("«b sz=24»INRs?"), "{out}");
4019        assert!(out.contains(&long), "printed whole: {out}");
4020        assert!(!out.contains("Other"), "{out}");
4021    }
4022
4023    /// A package whose one section shows `header_text` from the header part
4024    /// `part`, related as `rid`.
4025    fn docx_with_header(part: &str, rid: &str, header_text: &str) -> Vec<u8> {
4026        let body = format!(
4027            r#"<w:p><w:r><w:t>Body</w:t></w:r></w:p><w:sectPr><w:headerReference w:type="first" r:id="{rid}"/></w:sectPr>"#
4028        );
4029        let rels = format!(
4030            r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="{rid}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="{}"/></Relationships>"#,
4031            part.trim_start_matches("word/")
4032        );
4033        let header = format!(
4034            r#"<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:p><w:r><w:t>{header_text}</w:t></w:r></w:p></w:hdr>"#
4035        );
4036        zip_of(&[
4037            ("[Content_Types].xml", TYPES),
4038            ("_rels/.rels", ROOT_RELS),
4039            ("word/document.xml", &document(&body)),
4040            ("word/_rels/document.xml.rels", &rels),
4041            (part, &header),
4042        ])
4043    }
4044
4045    /// Word renumbers header and footer parts on save: two packages pair
4046    /// them by the section reference that shows them, not by part name.
4047    #[test]
4048    fn text_pairs_headers_by_the_section_that_shows_them() {
4049        let a = docx_with_header("word/header1.xml", "rId7", "Top");
4050        let b = docx_with_header("word/header3.xml", "rId10", "Top");
4051        let same = report(&a, Some(&b), &opts_for(Check::Text)).unwrap();
4052        assert_eq!(same, "text identical\n");
4053        let c = docx_with_header("word/header3.xml", "rId10", "Topper");
4054        let out = report(&a, Some(&c), &opts_for(Check::Text)).unwrap();
4055        assert!(
4056            out.starts_with(
4057                "section 1 first header (A word/header1.xml, B word/header3.xml): 1 line differs\n"
4058            ),
4059            "{out}"
4060        );
4061    }
4062
4063    /// A header with a PAGE field in a shaded table cell, and a body with a
4064    /// styled floating table, shaded and highlighted text, a hidden run and
4065    /// a replacement laid out as the deletion first.
4066    #[cfg(feature = "render")]
4067    fn docx_for_render() -> Vec<u8> {
4068        let w = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#;
4069        let body = r#"<w:p><w:pPr><w:pStyle w:val="Title"/></w:pPr><w:r><w:t>Heading</w:t></w:r></w:p><w:tbl><w:tblPr><w:tblStyle w:val="GridTable4"/><w:tblpPr w:vertAnchor="text" w:tblpX="100" w:tblpY="200"/><w:shd w:val="clear" w:color="auto" w:fill="FFFF00"/></w:tblPr><w:tblGrid><w:gridCol w:w="2000"/><w:gridCol w:w="2000"/></w:tblGrid><w:tr><w:tc><w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="D9E2F3"/></w:tcPr><w:p><w:r><w:t>A1</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>B1</w:t></w:r></w:p></w:tc></w:tr><w:tr><w:tc><w:p/></w:tc><w:tc><w:p/></w:tc></w:tr></w:tbl><w:p><w:pPr><w:shd w:val="clear" w:color="auto" w:fill="FFC000"/></w:pPr><w:r><w:rPr><w:rFonts w:ascii="Arial" w:hAnsi="Arial"/><w:highlight w:val="yellow"/></w:rPr><w:t>marked</w:t></w:r><w:r><w:rPr><w:color w:val="FF0000"/></w:rPr><w:t>red</w:t></w:r><w:r><w:rPr><w:vanish/></w:rPr><w:t>hidden</w:t></w:r><w:r><w:rPr><w:rStyle w:val="Hidden"/></w:rPr><w:t>styled</w:t></w:r></w:p><w:p><w:del w:id="1" w:author="A"><w:r><w:delText>old</w:delText></w:r></w:del><w:ins w:id="2" w:author="A"><w:r><w:t>new</w:t></w:r></w:ins></w:p><w:sectPr><w:headerReference w:type="default" r:id="rId7"/><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1800" w:bottom="1440" w:left="1800" w:header="720" w:footer="720" w:gutter="0"/><w:titlePg/></w:sectPr>"#;
4070        let styles = format!(
4071            r#"<w:styles {w}><w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri"/></w:rPr></w:rPrDefault></w:docDefaults><w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:pPr><w:shd w:val="clear" w:color="auto" w:fill="E7E6E6"/></w:pPr><w:rPr><w:color w:val="2F5496"/></w:rPr></w:style><w:style w:type="character" w:styleId="Hidden"><w:name w:val="Hidden Text"/><w:rPr><w:vanish/></w:rPr></w:style><w:style w:type="table" w:styleId="GridTable4"><w:name w:val="Grid Table 4"/><w:tblStylePr w:type="firstRow"><w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="4472C4"/></w:tcPr></w:tblStylePr></w:style></w:styles>"#
4072        );
4073        let header = format!(
4074            r#"<w:hdr {w}><w:tbl><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid><w:tr><w:tc><w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="1F3864"/></w:tcPr><w:p><w:r><w:t xml:space="preserve">Page </w:t></w:r><w:fldSimple w:instr=" PAGE \* MERGEFORMAT "><w:r><w:t>1</w:t></w:r></w:fldSimple></w:p></w:tc></w:tr></w:tbl></w:hdr>"#
4075        );
4076        let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId7" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/><Relationship Id="rId8" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
4077        zip_of(&[
4078            ("[Content_Types].xml", TYPES),
4079            ("_rels/.rels", ROOT_RELS),
4080            ("word/document.xml", &document(body)),
4081            ("word/_rels/document.xml.rels", rels),
4082            ("word/styles.xml", &styles),
4083            ("word/header1.xml", &header),
4084        ])
4085    }
4086
4087    #[cfg(feature = "render")]
4088    /// `render` lists, for every story part and not only the body, what
4089    /// should reach the page: tables with their style, float and shading
4090    /// (direct, per cell, and from the table style), shaded, highlighted,
4091    /// coloured and hidden text, fields, the order of deleted and inserted
4092    /// runs, and the sections; `(layout)` adds the page count and the face
4093    /// each requested font resolved to.
4094    #[test]
4095    fn render_lists_what_each_part_puts_on_the_page() {
4096        let out = report(&docx_for_render(), None, &opts_for(Check::Render)).unwrap();
4097        for expected in [
4098            "word/document.xml: 7 paragraphs\n",
4099            "  section 1 page=12240x15840 margins=1440,1800,1440,1800 header=720 footer=720 titlePg default-header=word/header1.xml\n",
4100            "  table 1 2x2 style=\"Grid Table 4\" float(tblpX=100,tblpY=200,vertAnchor=text) shd=FFFF00 cells-shd[D9E2F3×1] style-shd[firstRow=4472C4] \"A1 | B1\"\n",
4101            "  pstyle \"Title\" ×1\n",
4102            "  para-shd E7E6E6 via \"Title\" ×1 \"Heading\"\n",
4103            "  para-shd FFC000 ×1 \"markedredhiddenstyled\"\n",
4104            "  color 2F5496 via \"Title\" ×1 \"Heading\"\n",
4105            "  color FF0000 ×1 \"red\"\n",
4106            "  highlight yellow ×1 \"marked\"\n",
4107            "  vanish ×1 \"hidden\"\n",
4108            "  vanish via \"Hidden Text\" ×1 \"styled\"\n",
4109            "  rfonts \"Arial\" ×1\n",
4110            "  revisions del→ins ×1 \"oldnew\"\n",
4111            "word/header1.xml: 1 paragraphs\n",
4112            "  shown as section 1 default header\n",
4113            "  table 1 1x1 cells-shd[1F3864×1] \"Page 1\"\n",
4114            "  field PAGE ×1\n",
4115            "(layout): 1 pages\n",
4116            "  docDefaults rfonts ascii=Calibri hAnsi=Calibri\n",
4117        ] {
4118            assert!(out.contains(expected), "{expected:?} in\n{out}");
4119        }
4120        assert!(out.contains("  font \"Arial\" regular → "), "{out}");
4121        // Two files: only what differs.
4122        let same = report(
4123            &docx_for_render(),
4124            Some(&docx_for_render()),
4125            &opts_for(Check::Render),
4126        )
4127        .unwrap();
4128        assert_eq!(same, "render identical\n");
4129        let pick = |fill: &str| {
4130            let pkg = docx_for_render();
4131            let mut z = zip::ZipArchive::new(Cursor::new(pkg)).unwrap();
4132            let mut parts: Vec<(String, String)> = Vec::new();
4133            for i in 0..z.len() {
4134                let mut f = z.by_index(i).unwrap();
4135                let mut s = String::new();
4136                f.read_to_string(&mut s).unwrap();
4137                parts.push((
4138                    f.name().expect("decode ZIP fixture name").to_string(),
4139                    s.replace("1F3864", fill),
4140                ));
4141            }
4142            let refs: Vec<(&str, &str)> = parts
4143                .iter()
4144                .map(|(n, s)| (n.as_str(), s.as_str()))
4145                .collect();
4146            zip_of(&refs)
4147        };
4148        let out = report(
4149            &docx_for_render(),
4150            Some(&pick("FFFFFF")),
4151            &opts_for(Check::Render),
4152        )
4153        .unwrap();
4154        assert!(
4155            out.contains("-A   table 1 1x1 cells-shd[1F3864×1] \"Page 1\"\n")
4156                && out.contains("+B   table 1 1x1 cells-shd[FFFFFF×1] \"Page 1\"\n"),
4157            "{out}"
4158        );
4159    }
4160
4161    #[cfg(feature = "render")]
4162    /// PR #247 review: `color auto`, `highlight none` and a nil `shd` are
4163    /// resets, not absences. Direct on a run, or in a style over its base,
4164    /// they stop the style's value from reaching the page, so `render`
4165    /// must not report it.
4166    #[test]
4167    fn render_honours_formatting_resets() {
4168        let w = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#;
4169        let loud = r#"<w:color w:val="FF0000"/><w:highlight w:val="yellow"/><w:shd w:val="clear" w:color="auto" w:fill="00FF00"/>"#;
4170        let reset = r#"<w:color w:val="auto"/><w:highlight w:val="none"/><w:shd w:val="nil"/>"#;
4171        let body = format!(
4172            r#"<w:p><w:r><w:rPr><w:rStyle w:val="Loud"/></w:rPr><w:t>shout</w:t></w:r><w:r><w:rPr><w:rStyle w:val="Loud"/>{reset}</w:rPr><w:t>hush</w:t></w:r><w:r><w:rPr><w:rStyle w:val="Quiet"/></w:rPr><w:t>calm</w:t></w:r></w:p>"#
4173        );
4174        let styles = format!(
4175            r#"<w:styles {w}><w:style w:type="character" w:styleId="Loud"><w:name w:val="Loud"/><w:rPr>{loud}</w:rPr></w:style><w:style w:type="character" w:styleId="Quiet"><w:name w:val="Quiet"/><w:basedOn w:val="Loud"/><w:rPr>{reset}</w:rPr></w:style></w:styles>"#
4176        );
4177        let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId8" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
4178        let pkg = zip_of(&[
4179            ("[Content_Types].xml", TYPES),
4180            ("_rels/.rels", ROOT_RELS),
4181            ("word/document.xml", &document(&body)),
4182            ("word/_rels/document.xml.rels", rels),
4183            ("word/styles.xml", &styles),
4184        ]);
4185        let out = report(&pkg, None, &opts_for(Check::Render)).unwrap();
4186        for expected in [
4187            "  color FF0000 via \"Loud\" ×1 \"shout\"\n",
4188            "  highlight yellow via \"Loud\" ×1 \"shout\"\n",
4189            "  run-shd 00FF00 via \"Loud\" ×1 \"shout\"\n",
4190        ] {
4191            assert!(out.contains(expected), "{expected:?} in\n{out}");
4192        }
4193        assert!(
4194            !out.contains("\"hush\"") && !out.contains("\"calm\""),
4195            "reset runs report no inherited formatting:\n{out}"
4196        );
4197    }
4198
4199    #[cfg(feature = "render")]
4200    /// `render` over a body and a styles part (PR #247 review probes).
4201    fn render_of(body: &str, styles: &str) -> String {
4202        let w = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#;
4203        let styles = format!(r#"<w:styles {w}>{styles}</w:styles>"#);
4204        let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId8" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
4205        let pkg = zip_of(&[
4206            ("[Content_Types].xml", TYPES),
4207            ("_rels/.rels", ROOT_RELS),
4208            ("word/document.xml", &document(body)),
4209            ("word/_rels/document.xml.rels", rels),
4210            ("word/styles.xml", &styles),
4211        ]);
4212        report(&pkg, None, &opts_for(Check::Render)).unwrap()
4213    }
4214
4215    #[cfg(feature = "render")]
4216    const ONE_CELL: &str = r#"<w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid><w:tr><w:tc><w:p><w:r><w:t>A1</w:t></w:r></w:p></w:tc></w:tr>"#;
4217
4218    #[cfg(feature = "render")]
4219    /// PR #247 review: a derived table style keeps its base's conditions
4220    /// (the base's whole-table fill under the derived first row).
4221    #[test]
4222    fn render_merges_table_style_shading_down_the_chain() {
4223        let styles = r#"<w:style w:type="table" w:styleId="Base"><w:name w:val="Base"/><w:tblPr><w:shd w:val="clear" w:color="auto" w:fill="FFFF00"/></w:tblPr></w:style><w:style w:type="table" w:styleId="Derived"><w:name w:val="Derived"/><w:basedOn w:val="Base"/><w:tblStylePr w:type="firstRow"><w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="4472C4"/></w:tcPr></w:tblStylePr></w:style>"#;
4224        let body = format!(
4225            r#"<w:tbl><w:tblPr><w:tblStyle w:val="Derived"/></w:tblPr>{ONE_CELL}</w:tbl><w:p/>"#
4226        );
4227        let out = render_of(&body, styles);
4228        assert!(
4229            out.contains(" style-shd[whole=FFFF00,firstRow=4472C4] "),
4230            "{out}"
4231        );
4232    }
4233
4234    #[cfg(feature = "render")]
4235    /// PR #247 review: a replacement inside a hyperlink, smart tag or
4236    /// content control still reports its order.
4237    #[test]
4238    fn render_reports_revision_order_inside_run_containers() {
4239        let pair = r#"<w:del w:id="1" w:author="A"><w:r><w:delText>old</w:delText></w:r></w:del><w:ins w:id="2" w:author="A"><w:r><w:t>new</w:t></w:r></w:ins>"#;
4240        for wrap in [
4241            format!("<w:hyperlink>{pair}</w:hyperlink>"),
4242            format!("<w:smartTag>{pair}</w:smartTag>"),
4243            format!("<w:sdt><w:sdtContent>{pair}</w:sdtContent></w:sdt>"),
4244        ] {
4245            let out = render_of(&format!("<w:p>{wrap}</w:p>"), "");
4246            assert!(
4247                out.contains("  revisions del→ins ×1 \"oldnew\"\n"),
4248                "{wrap}:\n{out}"
4249            );
4250        }
4251        // A plain run between them still breaks the pair.
4252        let split = r#"<w:p><w:hyperlink><w:del w:id="1" w:author="A"><w:r><w:delText>old</w:delText></w:r></w:del><w:r><w:t>mid</w:t></w:r><w:ins w:id="2" w:author="A"><w:r><w:t>new</w:t></w:r></w:ins></w:hyperlink></w:p>"#;
4253        assert!(!render_of(split, "").contains("revisions"));
4254    }
4255
4256    #[cfg(feature = "render")]
4257    /// PR #247 review: the old `w:sectPr` a `w:sectPrChange` records is
4258    /// history, not a live section.
4259    #[test]
4260    fn render_lists_only_live_sections() {
4261        let body = r#"<w:p/><w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:sectPrChange w:id="1" w:author="A"><w:sectPr><w:pgSz w:w="11906" w:h="16838"/></w:sectPr></w:sectPrChange></w:sectPr>"#;
4262        let out = render_of(body, "");
4263        assert!(out.contains("  section 1 page=12240x15840"), "{out}");
4264        assert!(
4265            !out.contains("section 2") && !out.contains("11906"),
4266            "{out}"
4267        );
4268    }
4269
4270    #[cfg(feature = "render")]
4271    /// PR #247 review: a derived paragraph style's nil `shd` stops its
4272    /// base's fill.
4273    #[test]
4274    fn render_honours_a_paragraph_style_shading_reset() {
4275        let styles = r#"<w:style w:type="paragraph" w:styleId="Loud"><w:name w:val="Loud"/><w:pPr><w:shd w:val="clear" w:color="auto" w:fill="00FF00"/></w:pPr></w:style><w:style w:type="paragraph" w:styleId="Quiet"><w:name w:val="Quiet"/><w:basedOn w:val="Loud"/><w:pPr><w:shd w:val="nil"/></w:pPr></w:style>"#;
4276        let body = r#"<w:p><w:pPr><w:pStyle w:val="Loud"/></w:pPr><w:r><w:t>shout</w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val="Quiet"/></w:pPr><w:r><w:t>calm</w:t></w:r></w:p>"#;
4277        let out = render_of(body, styles);
4278        assert!(
4279            out.contains("  para-shd 00FF00 via \"Loud\" ×1 \"shout\"\n"),
4280            "{out}"
4281        );
4282        assert!(!out.contains("\"calm\""), "{out}");
4283    }
4284
4285    #[cfg(feature = "render")]
4286    /// PR #247 review: a `w:customXml` row is a row of its table, as the
4287    /// converter lays it out.
4288    #[test]
4289    fn render_counts_rows_wrapped_in_custom_xml() {
4290        let body = r#"<w:tbl><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid><w:customXml w:element="row"><w:tr><w:tc><w:p><w:r><w:t>A1</w:t></w:r></w:p></w:tc></w:tr></w:customXml><w:tr><w:tc><w:p><w:r><w:t>A2</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p/>"#;
4291        let out = render_of(body, "");
4292        assert!(out.contains("  table 1 2x1 \"A1\"\n"), "{out}");
4293    }
4294
4295    #[cfg(feature = "render")]
4296    /// A `w:sdt` row and a `w:sdt` cell's paragraphs are the table's own,
4297    /// as Strict files and content controls spell them.
4298    #[test]
4299    fn render_counts_rows_and_cells_through_sdt_wrappers() {
4300        let body = r#"<w:tbl><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid><w:sdt><w:sdtPr/><w:sdtContent><w:tr><w:tc><w:sdt><w:sdtPr/><w:sdtContent><w:p><w:r><w:t>A1</w:t></w:r></w:p></w:sdtContent></w:sdt></w:tc></w:tr></w:sdtContent></w:sdt><w:tr><w:tc><w:p><w:r><w:t>A2</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p/>"#;
4301        let out = render_of(body, "");
4302        assert!(out.contains("  table 1 2x1 \"A1\"\n"), "{out}");
4303    }
4304
4305    #[cfg(feature = "render")]
4306    /// Strict parts reach the checks translated: the package the SDK's
4307    /// strict→transitional load writes is what `render` describes, so a
4308    /// Strict `w:tbl` and `w:pgSz` list like Transitional ones.
4309    #[test]
4310    fn render_reads_strict_packages() {
4311        let w = r#"xmlns:w="http://purl.oclc.org/ooxml/wordprocessingml/main""#;
4312        let body = format!(
4313            r#"<w:tbl><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid>{ONE_CELL}</w:tbl><w:p/><w:sectPr><w:pgSz w:w="612pt" w:h="792pt"/></w:sectPr>"#,
4314        );
4315        let doc_xml = format!("<w:document {w}><w:body>{body}</w:body></w:document>");
4316        let pkg = zip_of(&[
4317            ("[Content_Types].xml", TYPES),
4318            ("_rels/.rels", ROOT_RELS),
4319            ("word/document.xml", doc_xml.as_str()),
4320        ]);
4321        let out = report(&pkg, None, &opts_for(Check::Render)).unwrap();
4322        assert!(out.contains("  table 1 1x1 \"A1\"\n"), "{out}");
4323        assert!(out.contains("  section 1 page=12240x15840"), "{out}");
4324    }
4325
4326    /// A *Transitional* document whose text quotes a Strict URI reports its
4327    /// text verbatim (#531 review defect 2): debug describes the file's own
4328    /// bytes, so only a package whose main part IS Strict (detected by its
4329    /// namespace) is read through the strict→transitional translation —
4330    /// not any package that merely mentions the URI in prose.
4331    #[test]
4332    fn text_quoting_a_strict_uri_stays_verbatim() {
4333        let body = r#"<w:p><w:r><w:t>See http://purl.oclc.org/ooxml/wordprocessingml/main for the strict namespace.</w:t></w:r></w:p><w:p/>"#;
4334        for check in [Check::Text, Check::Runs] {
4335            let out = report(&docx(body), None, &opts_for(check)).unwrap();
4336            assert!(
4337                out.contains("See http://purl.oclc.org/ooxml/wordprocessingml/main"),
4338                "{check:?}: the run's text is the file's own content: {out}"
4339            );
4340            assert!(
4341                !out.contains("See http://schemas.openxmlformats.org/wordprocessingml/2006/main"),
4342                "{check:?}: the report rewrote the file's prose: {out}"
4343            );
4344        }
4345    }
4346
4347    /// A hybrid package — a Transitional main part with Strict subparts —
4348    /// is read through the translation too, as before the main-part gate:
4349    /// the checks describe the Transitional twin of every part that
4350    /// carries Strict namespaces, not only of packages whose main part
4351    /// does (#561 review defect 3).
4352    #[test]
4353    fn hybrid_packages_translate_their_strict_subparts() {
4354        let pkg = zip_of(&[
4355            ("[Content_Types].xml", TYPES),
4356            ("_rels/.rels", ROOT_RELS),
4357            ("word/document.xml", &document(CLEAN)),
4358            (
4359                "customXml/item1.xml",
4360                r#"<b:data xmlns:b="http://purl.oclc.org/ooxml/wordprocessingml/main"/>"#,
4361            ),
4362        ]);
4363        let package = Package::open(&pkg).unwrap();
4364        let item = package
4365            .entries
4366            .iter()
4367            .find(|e| e.name == "customXml/item1.xml")
4368            .unwrap();
4369        let text = String::from_utf8_lossy(&item.data);
4370        assert!(
4371            text.contains("http://schemas.openxmlformats.org/wordprocessingml/2006/main"),
4372            "the Strict subpart reaches the checks translated: {text}"
4373        );
4374        assert!(!text.contains("purl.oclc.org"), "{text}");
4375    }
4376
4377    #[cfg(feature = "render")]
4378    /// PR #247 review: `behindDoc="true"` is behind the text, like `"1"`.
4379    #[test]
4380    fn render_marks_a_true_behind_doc_anchor() {
4381        let anchor = |v: &str| {
4382            format!(
4383                r#"<w:p><w:r><w:drawing><wp:anchor behindDoc="{v}" distT="0" distB="0" distL="0" distR="0" simplePos="0" relativeHeight="1" locked="0" layoutInCell="1" allowOverlap="1"><wp:simplePos x="0" y="0"/><wp:positionH relativeFrom="column"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV><wp:extent cx="100" cy="100"/><wp:wrapNone/><wp:docPr id="1" name="Pic"/></wp:anchor></w:drawing></w:r></w:p>"#
4384            )
4385        };
4386        for v in ["1", "true"] {
4387            let out = render_of(&anchor(v), "");
4388            assert!(out.contains(" behind \"Pic\""), "{v}:\n{out}");
4389        }
4390        assert!(!render_of(&anchor("false"), "").contains(" behind "));
4391    }
4392
4393    #[cfg(feature = "render")]
4394    /// PR #247 review: each font slot a run asks for is reported, explicit
4395    /// or theme, not only the first.
4396    #[test]
4397    fn render_reports_every_requested_font_slot() {
4398        let body = r#"<w:p><w:r><w:rPr><w:rFonts w:ascii="Arial" w:hAnsi="Arial" w:eastAsia="MS Mincho" w:cstheme="minorBidi"/></w:rPr><w:t>mixed</w:t></w:r></w:p>"#;
4399        let out = render_of(body, "");
4400        for expected in [
4401            "  rfonts \"Arial\" ×1\n",
4402            "  rfonts \"MS Mincho\" ×1\n",
4403            "  rfonts \"theme:minorBidi\" ×1\n",
4404        ] {
4405            assert!(out.contains(expected), "{expected:?} in\n{out}");
4406        }
4407    }
4408
4409    #[cfg(feature = "render")]
4410    /// PR #247 review: unequal columns report their widths and gaps, so
4411    /// two builds that move them differ.
4412    #[test]
4413    fn render_reports_custom_column_geometry() {
4414        let sect = |a: &str, b: &str| {
4415            format!(
4416                r#"<w:p/><w:sectPr><w:cols w:equalWidth="0"><w:col w:w="{a}" w:space="720"/><w:col w:w="{b}"/></w:cols></w:sectPr>"#
4417            )
4418        };
4419        let out = render_of(&sect("3000", "5000"), "");
4420        assert!(out.contains(" cols=2[3000+720,5000]"), "{out}");
4421        assert!(!render_of(&sect("4000", "4000"), "").contains("3000"));
4422    }
4423
4424    #[cfg(feature = "render")]
4425    /// PR #247 review: only the branch Word renders counts; a DrawingML
4426    /// `mc:Choice` and its VML `mc:Fallback` are one picture.
4427    #[test]
4428    fn render_skips_the_fallback_of_an_alternate_content() {
4429        let body = r#"<w:p><w:r><mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"><mc:Choice Requires="wps"><w:drawing><wp:inline><wp:extent cx="100" cy="100"/><wp:docPr id="1" name="Box"/></wp:inline></w:drawing></mc:Choice><mc:Fallback><w:pict><v:rect/></w:pict></mc:Fallback></mc:AlternateContent></w:r></w:p>"#;
4430        let out = render_of(body, "");
4431        assert!(out.contains("  inline ×1\n"), "{out}");
4432        assert!(!out.contains("vml pict"), "{out}");
4433    }
4434
4435    #[cfg(feature = "render")]
4436    /// PR #247 review: an unstyled paragraph takes the default paragraph
4437    /// style's shading and run colour, as the converter paints them.
4438    #[test]
4439    fn render_applies_the_default_paragraph_style() {
4440        let styles = r#"<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:pPr><w:shd w:val="clear" w:color="auto" w:fill="EEEEEE"/></w:pPr><w:rPr><w:color w:val="C00000"/></w:rPr></w:style>"#;
4441        let out = render_of(r#"<w:p><w:r><w:t>plain</w:t></w:r></w:p>"#, styles);
4442        assert!(out.contains("para-shd EEEEEE via \"Normal\""), "{out}");
4443        assert!(out.contains("color C00000 via \"Normal\""), "{out}");
4444    }
4445
4446    #[cfg(feature = "render")]
4447    /// PR #247 review: a frame from the paragraph style's chain is the
4448    /// paragraph's frame; direct attributes override the style's.
4449    #[test]
4450    fn render_reports_a_frame_from_the_style_chain() {
4451        let styles = r#"<w:style w:type="paragraph" w:styleId="Boxed"><w:name w:val="Boxed"/><w:pPr><w:framePr w:w="3000" w:hAnchor="page" w:x="1000"/></w:pPr></w:style><w:style w:type="paragraph" w:styleId="Side"><w:name w:val="Side"/><w:basedOn w:val="Boxed"/></w:style>"#;
4452        let body = r#"<w:p><w:pPr><w:pStyle w:val="Side"/><w:framePr w:x="2000"/></w:pPr><w:r><w:t>framed</w:t></w:r></w:p>"#;
4453        let out = render_of(body, styles);
4454        assert!(
4455            out.contains("  frame(hAnchor=page,w=3000,x=2000) \"framed\""),
4456            "{out}"
4457        );
4458    }
4459
4460    #[cfg(feature = "render")]
4461    /// PR #247 review: a theme colour's tint and shade change the ink, so
4462    /// they are part of the colour.
4463    #[test]
4464    fn render_keeps_a_theme_colours_tint_and_shade() {
4465        let body = r#"<w:p><w:r><w:rPr><w:color w:val="4472C4" w:themeColor="accent1" w:themeShade="BF"/></w:rPr><w:t>dark</w:t></w:r><w:r><w:rPr><w:color w:val="4472C4" w:themeColor="accent1" w:themeTint="99"/></w:rPr><w:t>light</w:t></w:r></w:p>"#;
4466        let out = render_of(body, "");
4467        assert!(out.contains("color theme:accent1/shade:BF ×1"), "{out}");
4468        assert!(out.contains("color theme:accent1/tint:99 ×1"), "{out}");
4469    }
4470
4471    #[cfg(feature = "render")]
4472    /// PR #247 review: fonts a run takes from its character or paragraph
4473    /// style are the fonts it paints in.
4474    #[test]
4475    fn render_reports_fonts_from_run_and_paragraph_styles() {
4476        let styles = r#"<w:style w:type="paragraph" w:styleId="Code"><w:name w:val="Code"/><w:rPr><w:rFonts w:ascii="Consolas" w:hAnsi="Consolas"/></w:rPr></w:style><w:style w:type="character" w:styleId="Quote"><w:name w:val="Quote"/><w:rPr><w:rFonts w:ascii="Georgia" w:hAnsi="Georgia"/></w:rPr></w:style>"#;
4477        let body = r#"<w:p><w:pPr><w:pStyle w:val="Code"/></w:pPr><w:r><w:t>code</w:t></w:r><w:r><w:rPr><w:rStyle w:val="Quote"/></w:rPr><w:t>quote</w:t></w:r></w:p>"#;
4478        let out = render_of(body, styles);
4479        assert!(out.contains("rfonts \"Consolas\" via \"Code\""), "{out}");
4480        assert!(out.contains("rfonts \"Georgia\" via \"Quote\""), "{out}");
4481    }
4482
4483    #[cfg(feature = "render")]
4484    /// PR #247 review: a run's leading `w:rPr` blocks apply in order, as
4485    /// the converter folds them; an `rPr` after the run's content does not.
4486    #[test]
4487    fn render_folds_every_leading_rpr() {
4488        let body = r#"<w:p><w:r><w:rPr><w:color w:val="FF0000"/><w:vanish/></w:rPr><w:rPr><w:color w:val="0000FF"/><w:vanish w:val="0"/></w:rPr><w:t>two</w:t></w:r><w:r><w:t>tail</w:t><w:rPr><w:color w:val="00FF00"/></w:rPr></w:r></w:p>"#;
4489        let out = render_of(body, "");
4490        assert!(out.contains("  color 0000FF ×1 \"two\"\n"), "{out}");
4491        assert!(
4492            !out.contains("FF0000") && !out.contains("00FF00") && !out.contains("vanish"),
4493            "{out}"
4494        );
4495    }
4496
4497    #[cfg(feature = "render")]
4498    /// PR #247 review: a direct `w:rFonts` overrides only the slots it
4499    /// names; the style's other slots still reach the page.
4500    #[test]
4501    fn render_merges_partial_rfonts_by_slot() {
4502        let styles = r#"<w:style w:type="character" w:styleId="Asian"><w:name w:val="Asian"/><w:rPr><w:rFonts w:ascii="Georgia" w:eastAsia="MS Mincho"/></w:rPr></w:style>"#;
4503        let body = r#"<w:p><w:r><w:rPr><w:rStyle w:val="Asian"/><w:rFonts w:ascii="Arial"/></w:rPr><w:t>mixed</w:t></w:r></w:p>"#;
4504        let out = render_of(body, styles);
4505        assert!(out.contains("  rfonts \"Arial\" ×1\n"), "{out}");
4506        assert!(
4507            out.contains("  rfonts \"MS Mincho\" via \"Asian\" ×1\n"),
4508            "{out}"
4509        );
4510        assert!(!out.contains("Georgia"), "{out}");
4511    }
4512
4513    #[cfg(feature = "render")]
4514    /// PR #247 review: a run that paints nothing does not separate a
4515    /// deletion from the insertion after it.
4516    #[test]
4517    fn render_pairs_revisions_across_an_empty_run() {
4518        let body = r#"<w:p><w:del w:id="1" w:author="A"><w:r><w:delText>old</w:delText></w:r></w:del><w:r><w:rPr><w:b/></w:rPr></w:r><w:r><w:t></w:t></w:r><w:ins w:id="2" w:author="A"><w:r><w:t>new</w:t></w:r></w:ins></w:p>"#;
4519        let out = render_of(body, "");
4520        assert!(out.contains("  revisions del→ins ×1 \"oldnew\"\n"), "{out}");
4521    }
4522
4523    #[cfg(feature = "render")]
4524    /// PR #247 review: `docDefaults` paint the unstyled text, so their
4525    /// colour, highlight and shading are reported as the last layer.
4526    #[test]
4527    fn render_applies_doc_defaults_paint() {
4528        let styles = r#"<w:docDefaults><w:rPrDefault><w:rPr><w:color w:val="112233"/><w:highlight w:val="cyan"/><w:shd w:val="clear" w:color="auto" w:fill="DDDDDD"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:shd w:val="clear" w:color="auto" w:fill="ABCDEF"/></w:pPr></w:pPrDefault></w:docDefaults>"#;
4529        let out = render_of(r#"<w:p><w:r><w:t>plain</w:t></w:r></w:p>"#, styles);
4530        for expected in [
4531            "  color 112233 via \"docDefaults\" ×1 \"plain\"\n",
4532            "  highlight cyan via \"docDefaults\" ×1 \"plain\"\n",
4533            "  run-shd DDDDDD via \"docDefaults\" ×1 \"plain\"\n",
4534            "  para-shd ABCDEF via \"docDefaults\" ×1 \"plain\"\n",
4535        ] {
4536            assert!(out.contains(expected), "{expected:?} in\n{out}");
4537        }
4538        // A style's own value still wins over the defaults.
4539        let styled = format!(
4540            r#"{styles}<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:rPr><w:color w:val="C00000"/></w:rPr></w:style>"#
4541        );
4542        let out = render_of(r#"<w:p><w:r><w:t>plain</w:t></w:r></w:p>"#, &styled);
4543        assert!(out.contains("color C00000 via \"Normal\""), "{out}");
4544        assert!(!out.contains("112233"), "{out}");
4545    }
4546
4547    #[cfg(feature = "render")]
4548    /// PR #247 review: a derived table style's nil `shd` resets the
4549    /// condition its base fills.
4550    #[test]
4551    fn render_keeps_a_table_style_shading_reset() {
4552        let styles = r#"<w:style w:type="table" w:styleId="Base"><w:name w:val="Base"/><w:tblStylePr w:type="firstRow"><w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="4472C4"/></w:tcPr></w:tblStylePr></w:style><w:style w:type="table" w:styleId="Derived"><w:name w:val="Derived"/><w:basedOn w:val="Base"/><w:tblStylePr w:type="firstRow"><w:tcPr><w:shd w:val="nil"/></w:tcPr></w:tblStylePr></w:style>"#;
4553        let table = |style: &str| {
4554            format!(
4555                r#"<w:tbl><w:tblPr><w:tblStyle w:val="{style}"/></w:tblPr>{ONE_CELL}</w:tbl><w:p/>"#
4556            )
4557        };
4558        assert!(render_of(&table("Base"), styles).contains(" style-shd[firstRow=4472C4] "));
4559        let out = render_of(&table("Derived"), styles);
4560        assert!(!out.contains("style-shd"), "{out}");
4561    }
4562
4563    #[cfg(feature = "render")]
4564    /// PR #247 review: first-row cells inside a content control or
4565    /// customXml are the row's cells, as the converter lays them out.
4566    #[test]
4567    fn render_reads_first_row_cells_through_wrappers() {
4568        let body = r#"<w:tbl><w:tblGrid><w:gridCol w:w="2000"/><w:gridCol w:w="2000"/></w:tblGrid><w:tr><w:sdt><w:sdtContent><w:tc><w:p><w:r><w:t>A1</w:t></w:r></w:p></w:tc></w:sdtContent></w:sdt><w:customXml w:element="cell"><w:tc><w:p><w:r><w:t>B1</w:t></w:r></w:p></w:tc></w:customXml></w:tr></w:tbl><w:p/>"#;
4569        let out = render_of(body, "");
4570        assert!(out.contains("  table 1 1x2 \"A1 | B1\"\n"), "{out}");
4571    }
4572
4573    #[cfg(feature = "render")]
4574    /// PR #247 review: the conditions a table's `w:tblLook` turns off
4575    /// paint nothing, so they are not reported.
4576    #[test]
4577    fn render_filters_table_style_shading_by_look() {
4578        let styles = r#"<w:style w:type="table" w:styleId="Banded"><w:name w:val="Banded"/><w:tblStylePr w:type="firstRow"><w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="4472C4"/></w:tcPr></w:tblStylePr><w:tblStylePr w:type="firstCol"><w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="FF0000"/></w:tcPr></w:tblStylePr><w:tblStylePr w:type="band1Horz"><w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="D9E2F3"/></w:tcPr></w:tblStylePr></w:style>"#;
4579        let table = |look: &str| {
4580            format!(
4581                r#"<w:tbl><w:tblPr><w:tblStyle w:val="Banded"/>{look}</w:tblPr>{ONE_CELL}</w:tbl><w:p/>"#
4582            )
4583        };
4584        // No tblLook: the converter's default look, first row on, first
4585        // column off, horizontal bands on.
4586        let out = render_of(&table(""), styles);
4587        assert!(
4588            out.contains(" style-shd[firstRow=4472C4,band1Horz=D9E2F3] "),
4589            "{out}"
4590        );
4591        let out = render_of(
4592            &table(r#"<w:tblLook w:firstRow="0" w:firstColumn="1" w:noHBand="1"/>"#),
4593            styles,
4594        );
4595        assert!(out.contains(" style-shd[firstCol=FF0000] "), "{out}");
4596    }
4597
4598    #[cfg(feature = "render")]
4599    /// PR #247 review: a row with a live `w:cellDel` gains the "Deleted
4600    /// Cells" column the converter paints.
4601    #[test]
4602    fn render_counts_the_deleted_cells_column() {
4603        let body = r#"<w:tbl><w:tblGrid><w:gridCol w:w="2000"/><w:gridCol w:w="2000"/></w:tblGrid><w:tr><w:tc><w:p><w:r><w:t>A1</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:cellDel w:id="1" w:author="A"/></w:tcPr><w:p><w:r><w:t>B1</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p/>"#;
4604        let out = render_of(body, "");
4605        assert!(out.contains("  table 1 1x3 "), "{out}");
4606        assert!(
4607            render_of(
4608                &body.replace(r#"<w:tcPr><w:cellDel w:id="1" w:author="A"/></w:tcPr>"#, ""),
4609                ""
4610            )
4611            .contains("  table 1 1x2 ")
4612        );
4613    }
4614
4615    /// PR #247 review: pretty-print inside an element with no text is not
4616    /// its text; `<w:p>\n  </w:p>` prints as `<w:p></w:p>` does.
4617    #[test]
4618    fn xml_drops_pretty_print_inside_a_textless_element() {
4619        let pretty = report(&docx("<w:p>\n  </w:p>"), None, &opts_for(Check::Xml)).unwrap();
4620        let tight = report(&docx("<w:p></w:p>"), None, &opts_for(Check::Xml)).unwrap();
4621        assert_eq!(pretty, tight);
4622        // A text element keeps its whitespace.
4623        let space = report(
4624            &docx(r#"<w:p><w:r><w:t xml:space="preserve"> </w:t></w:r></w:p>"#),
4625            None,
4626            &opts_for(Check::Xml),
4627        )
4628        .unwrap();
4629        assert!(
4630            space.contains("<w:t xml:space=\"preserve\"> </w:t>"),
4631            "{space}"
4632        );
4633    }
4634
4635    #[test]
4636    fn text_of_two_packages_shows_only_the_changed_lines() {
4637        let a = docx(TRACKED);
4638        let b = docx(&TRACKED.replace("cell", "cellar"));
4639        let out = report(&a, Some(&b), &opts_for(Check::Text)).unwrap();
4640        assert!(out.contains("word/document.xml: 1 line differs\n"), "{out}");
4641        assert!(out.contains("-A     ¶  cell\n"), "{out}");
4642        assert!(out.contains("+B     ¶  cellar\n"), "{out}");
4643        assert!(!out.contains("Plain"), "unchanged lines stay out: {out}");
4644        let same = report(&a, Some(&a), &opts_for(Check::Text)).unwrap();
4645        assert_eq!(same, "text identical\n");
4646    }
4647
4648    #[test]
4649    fn context_shows_the_common_lines_around_a_change() {
4650        let body = |x: &str| {
4651            ["one", "two", x, "four", "five"]
4652                .map(|t| format!("<w:p><w:r><w:t>{t}</w:t></w:r></w:p>"))
4653                .concat()
4654        };
4655        let opts = Options {
4656            context: 1,
4657            ..opts_for(Check::Text)
4658        };
4659        let out = report(&docx(&body("three")), Some(&docx(&body("3"))), &opts).unwrap();
4660        assert!(
4661            out.contains("     ¶  two\n-A   ¶  three\n+B   ¶  3\n     ¶  four\n"),
4662            "{out}"
4663        );
4664        assert!(!out.contains("one") && !out.contains("five"), "{out}");
4665    }
4666
4667    #[test]
4668    fn a_long_changed_line_is_clipped_around_its_first_difference() {
4669        let long = "word ".repeat(80);
4670        let body = |tail: &str| format!(r#"<w:p><w:r><w:t>{long}{tail}</w:t></w:r></w:p>"#);
4671        let out = report(
4672            &docx(&body("apples")),
4673            Some(&docx(&body("pears"))),
4674            &opts_for(Check::Text),
4675        )
4676        .unwrap();
4677        assert!(out.contains("apples"), "{out}");
4678        assert!(out.contains("pears"), "{out}");
4679        assert!(out.contains("-A …"), "the clipped head is marked: {out}");
4680    }
4681
4682    #[test]
4683    fn xml_prints_one_element_per_line_without_noise() {
4684        let body = r#"<w:p w:rsidR="00AB12CD" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" w14:paraId="1A2B3C4D" w14:textId="77777777"><w:pPr><w:jc w:val="center"/></w:pPr><w:r w:rsidRPr="00FF00FF"><w:t xml:space="preserve">Hi </w:t></w:r><w:r><w:delText xml:space="preserve"> </w:delText></w:r></w:p>"#;
4685        let out = report(&docx(body), None, &opts_for(Check::Xml)).unwrap();
4686        for expected in [
4687            "word/document.xml\n",
4688            "<w:document>\n",
4689            "  <w:body>\n",
4690            "    <w:p>\n",
4691            "      <w:pPr>\n",
4692            "        <w:jc w:val=\"center\"/>\n",
4693            "        <w:t xml:space=\"preserve\">Hi </w:t>\n",
4694            // A space-only text is content (246c7fcf50's footer), not
4695            // the pretty-print between elements.
4696            "        <w:delText xml:space=\"preserve\"> </w:delText>\n",
4697            "    </w:p>\n",
4698        ] {
4699            assert!(out.contains(expected), "{expected:?} in\n{out}");
4700        }
4701        for noise in ["xmlns", "rsid", "paraId", "textId"] {
4702            assert!(!out.contains(noise), "{noise} in\n{out}");
4703        }
4704    }
4705
4706    #[test]
4707    fn xml_of_two_packages_diffs_only_what_changed() {
4708        let a = docx(
4709            r#"<w:p><w:pPr><w:pStyle w:val="X"/><w:rPr/></w:pPr><w:r><w:t>same</w:t></w:r></w:p>"#,
4710        );
4711        let b = docx(r#"<w:p w:rsidR="00000001"><w:r><w:t>same</w:t></w:r></w:p>"#);
4712        let out = report(&a, Some(&b), &opts_for(Check::Xml)).unwrap();
4713        assert!(out.contains("word/document.xml: 4 lines differ\n"), "{out}");
4714        let pad = " ".repeat(8);
4715        assert!(
4716            out.contains(&format!("-A {pad}<w:pStyle w:val=\"X\"/>\n")),
4717            "{out}"
4718        );
4719        assert!(out.contains(&format!("-A {pad}<w:rPr/>\n")), "{out}");
4720        assert!(!out.contains("+B"), "{out}");
4721        assert!(!out.contains("same"), "{out}");
4722        let same = report(&b, Some(&b), &opts_for(Check::Xml)).unwrap();
4723        assert_eq!(same, "xml identical\n");
4724    }
4725}
4726
4727#[cfg(test)]
4728#[cfg_attr(all(coverage_nightly, test), coverage(off))]
4729mod residual_byte_diagnostic_contract_tests {
4730    use super::*;
4731    use std::io::Write;
4732
4733    const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
4734    const TYPES: &[u8] = br#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/xml"/><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#;
4735    const ROOT_RELS: &[u8] = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="main" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
4736
4737    fn zip_bytes(entries: &[(&str, &[u8])]) -> Vec<u8> {
4738        let mut bytes = Cursor::new(Vec::new());
4739        {
4740            let mut zip = zip::ZipWriter::new(&mut bytes);
4741            for (name, data) in entries {
4742                zip.start_file(*name, zip::write::SimpleFileOptions::default())
4743                    .unwrap();
4744                zip.write_all(data).unwrap();
4745            }
4746            zip.finish().unwrap();
4747        }
4748        bytes.into_inner()
4749    }
4750
4751    fn document(body: &str) -> String {
4752        format!(r#"<w:document xmlns:w="{W}"><w:body>{body}</w:body></w:document>"#)
4753    }
4754
4755    fn source(body: &str) -> Vec<u8> {
4756        let xml = document(body);
4757        zip_bytes(&[
4758            ("[Content_Types].xml", TYPES),
4759            ("_rels/.rels", ROOT_RELS),
4760            ("word/document.xml", xml.as_bytes()),
4761        ])
4762    }
4763
4764    fn dom(xml: &str) -> (Dom, NodeId) {
4765        let mut d = Dom::new();
4766        let doc = d.parse_xdocument(xml);
4767        let root = d.root(doc).unwrap();
4768        (d, root)
4769    }
4770
4771    #[test]
4772    fn malformed_xml_byte_parts_report_exact_findings_and_selected_filter_is_respected() {
4773        // Intentional undecodable XML and an empty XML document alongside
4774        // valid Word XML, a binary part, and non-XML ZIP directory entries.
4775        let xml = document("<w:p/>");
4776        let bytes = zip_bytes(&[
4777            ("[Content_Types].xml", TYPES),
4778            ("_rels/.rels", ROOT_RELS),
4779            ("word/document.xml", xml.as_bytes()),
4780            ("word/bad.xml", &[0xFF]),
4781            ("word/empty.xml", b""),
4782            ("word/image.bin", &[0xFF]),
4783            ("word/", b""),
4784        ]);
4785        let before = bytes.clone();
4786        let pkg = Package::open(&bytes).unwrap();
4787        let mut f = Findings::default();
4788        let parts = pkg.xml_parts(Some("word/"), &mut f);
4789        assert_eq!(
4790            parts.iter().map(|x| x.0.as_str()).collect::<Vec<_>>(),
4791            vec!["word/document.xml"]
4792        );
4793        assert_eq!(
4794            f.by_kind,
4795            BTreeMap::from([
4796                (
4797                    "xml-undecodable".into(),
4798                    vec![("word/bad.xml".into(), String::new())]
4799                ),
4800                (
4801                    "xml-unparsable".into(),
4802                    vec![("word/empty.xml".into(), String::new())]
4803                ),
4804            ])
4805        );
4806        let mut filtered = Findings::default();
4807        assert_eq!(pkg.xml_parts(Some("document"), &mut filtered).len(), 1);
4808        assert!(filtered.by_kind.is_empty());
4809        assert_eq!(bytes, before);
4810        #[cfg(feature = "render")]
4811        assert_eq!(pkg.raw, before);
4812        assert!(
4813            Package::open(b"not a ZIP")
4814                .err()
4815                .unwrap()
4816                .starts_with("not a zip: ")
4817        );
4818    }
4819
4820    #[test]
4821    fn utf_byte_order_marks_and_malformed_escape_sequences_have_literal_decoding() {
4822        let text = "<t>漢😀</t>";
4823        let mut utf8 = vec![0xEF, 0xBB, 0xBF];
4824        utf8.extend_from_slice(text.as_bytes());
4825        assert_eq!(decode_xml(&utf8).as_deref(), Some(text));
4826        for big_endian in [false, true] {
4827            let mut bytes = if big_endian {
4828                vec![0xFE, 0xFF]
4829            } else {
4830                vec![0xFF, 0xFE]
4831            };
4832            for unit in text.encode_utf16() {
4833                bytes.extend_from_slice(&if big_endian {
4834                    unit.to_be_bytes()
4835                } else {
4836                    unit.to_le_bytes()
4837                });
4838            }
4839            assert_eq!(decode_xml(&bytes).as_deref(), Some(text));
4840            let invalid = if big_endian {
4841                [0xFE, 0xFF, 0xD8, 0x00]
4842            } else {
4843                [0xFF, 0xFE, 0x00, 0xD8]
4844            };
4845            assert!(decode_xml(&invalid).is_none()); // unpaired surrogate diagnostic
4846        }
4847        assert!(decode_xml(&[0xEF, 0xBB, 0xBF, 0xFF]).is_none());
4848        for (input, expected) in [
4849            ("header%20one.xml", "header one.xml"),
4850            ("%E6%BC%A2", "漢"),
4851            ("%", "%"),
4852            ("%2", "%2"),
4853            ("%GG", "%GG"),
4854            ("%2G", "%2G"),
4855            ("%FF", "�"),
4856        ] {
4857            assert_eq!(percent_decode(input), expected);
4858        }
4859    }
4860
4861    #[test]
4862    fn property_histories_compare_complete_nested_values_and_keep_no_difference_records() {
4863        let xml = document(
4864            r#"<w:p><w:pPr><w:spacing w:before="120" w:after="80"/><w:pPrChange w:id="1" w:author="A"><w:pPr><w:spacing w:before="120" w:after="80"/></w:pPr></w:pPrChange></w:pPr><w:r><w:rPr><w:rFonts w:ascii="New" w:hAnsi="New"/><w:rPrChange w:id="2" w:author="A"><w:rPr><w:rFonts w:ascii="Old" w:hAnsi="Old"/></w:rPr></w:rPrChange></w:rPr><w:t>Label</w:t></w:r></w:p>"#,
4865        );
4866        let (d, root) = dom(&xml);
4867        let before = d.serialize_element(root);
4868        assert_eq!(change_lines(&d, root), (vec![
4869            "  pPrChange p \"Label\": (no difference)".into(),
4870            "  rPrChange p \"Label\": +rFonts(ascii=New,hAnsi=New) -rFonts(ascii=Old,hAnsi=Old)".into(),
4871        ], 2));
4872        let (p, r) = dom(&format!(
4873            r#"<w:pPr xmlns:w="{W}"><w:tabs><w:tab w:pos="720" w:val="left"/></w:tabs><w:jc w:val="right"/><w:keepNext/><!--source comment--><w:rPr><w:b/></w:rPr></w:pPr>"#
4874        ));
4875        assert_eq!(
4876            prop_items(&p, r),
4877            vec!["jc=right", "keepNext", "tabs{tab(pos=720,val=left)}"]
4878        );
4879        assert_eq!(d.serialize_element(root), before);
4880    }
4881
4882    #[test]
4883    fn bookmark_duplicate_end_and_early_end_have_complete_diagnostics_and_chains() {
4884        // Intentional malformed range pairing; diagnose every distinct error.
4885        let (d, root) = dom(&document(
4886            r#"<w:p><w:bookmarkEnd w:id="7"/><w:bookmarkStart w:id="7" w:name="same"/><w:bookmarkStart w:id="7" w:name="same"/><w:bookmarkEnd w:id="7"/></w:p>"#,
4887        ));
4888        let before = d.serialize_element(root);
4889        let mut f = Findings::default();
4890        let mut chains = BTreeMap::new();
4891        check_bookmarks(&d, root, "word/document.xml", &mut f, Some(&mut chains));
4892        assert_eq!(
4893            f.by_kind,
4894            BTreeMap::from([
4895                (
4896                    "bookmark-duplicate-end".into(),
4897                    vec![("word/document.xml".into(), "id 7".into())]
4898                ),
4899                (
4900                    "bookmark-duplicate-id".into(),
4901                    vec![("word/document.xml".into(), "id 7 (same)".into())]
4902                ),
4903                (
4904                    "bookmark-duplicate-name".into(),
4905                    vec![("word/document.xml".into(), "same".into())]
4906                ),
4907                (
4908                    "bookmark-end-before-start".into(),
4909                    vec![
4910                        ("word/document.xml".into(), "id 7 (same)".into()),
4911                        ("word/document.xml".into(), "id 7 (same)".into())
4912                    ]
4913                ),
4914            ])
4915        );
4916        assert_eq!(
4917            chains,
4918            BTreeMap::from([
4919                ("word/document.xml end p".into(), 2),
4920                ("word/document.xml start p".into(), 2)
4921            ])
4922        );
4923        assert_eq!(d.serialize_element(root), before);
4924    }
4925
4926    #[test]
4927    fn line_diff_handles_identical_large_replacements_and_separated_hunks_exactly() {
4928        let strings = |x: &[&str]| x.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>();
4929        let a = strings(&["prefix", "old", "middle", "removed", "suffix"]);
4930        let b = strings(&["prefix", "new", "middle", "added", "suffix"]);
4931        assert_eq!(diff_lines(&a, &a), Vec::<Hunk>::new());
4932        assert_eq!(
4933            diff_lines(&a, &b),
4934            vec![
4935                (1, vec!["old"], vec!["new"]),
4936                (3, vec!["removed"], vec!["added"])
4937            ]
4938        );
4939        assert_eq!(
4940            diff_lines(&[], &strings(&["new"])),
4941            vec![(0, vec![], vec!["new"])]
4942        );
4943        let mut large_a = vec!["old".to_owned(); 2001];
4944        let mut large_b = vec!["new".to_owned(); 2000];
4945        large_a.insert(0, "prefix".into());
4946        large_b.insert(0, "prefix".into());
4947        large_a.push("suffix".into());
4948        large_b.push("suffix".into());
4949        let h = diff_lines(&large_a, &large_b);
4950        assert_eq!(h, vec![(1, vec!["old"; 2001], vec!["new"; 2000])]);
4951    }
4952
4953    #[test]
4954    fn diff_report_context_hunk_limit_and_one_sided_parts_keep_exact_source_lines() {
4955        let a = source(
4956            "<w:p><w:r><w:t>prefix</w:t></w:r></w:p><w:p><w:r><w:t>old</w:t></w:r></w:p><w:p><w:r><w:t>middle</w:t></w:r></w:p><w:p><w:r><w:t>removed</w:t></w:r></w:p><w:p><w:r><w:t>suffix</w:t></w:r></w:p>",
4957        );
4958        let b = source(
4959            "<w:p><w:r><w:t>prefix</w:t></w:r></w:p><w:p><w:r><w:t>new</w:t></w:r></w:p><w:p><w:r><w:t>middle</w:t></w:r></w:p><w:p><w:r><w:t>added</w:t></w:r></w:p><w:p><w:r><w:t>suffix</w:t></w:r></w:p>",
4960        );
4961        let opts = Options {
4962            checks: vec![Check::Text],
4963            context: 1,
4964            limit: 1,
4965            ..Options::default()
4966        };
4967        assert_eq!(
4968            report(&a, Some(&b), &opts).unwrap(),
4969            "word/document.xml: 2 lines differ\n     ¶  prefix\n-A   ¶  old\n+B   ¶  new\n     ¶  middle\n  … 1 more hunks (raise --limit)\n"
4970        );
4971        let opts = Options {
4972            limit: 5,
4973            context: 0,
4974            ..opts
4975        };
4976        assert_eq!(
4977            report(&a, Some(&b), &opts).unwrap(),
4978            "word/document.xml: 2 lines differ\n-A   ¶  old\n+B   ¶  new\n  ~\n-A   ¶  removed\n+B   ¶  added\n"
4979        );
4980        assert_eq!(report(&a, Some(&a), &opts).unwrap(), "text identical\n");
4981        let extra_a = zip_bytes(&[(
4982            "word/left.xml",
4983            format!(r#"<w:hdr xmlns:w="{W}"><w:p/></w:hdr>"#).as_bytes(),
4984        )]);
4985        let extra_b = zip_bytes(&[(
4986            "word/right.xml",
4987            format!(r#"<w:ftr xmlns:w="{W}"><w:p/></w:ftr>"#).as_bytes(),
4988        )]);
4989        assert_eq!(
4990            report(&extra_a, Some(&extra_b), &opts).unwrap(),
4991            "word/left.xml: only in A\nword/right.xml: only in B\n"
4992        );
4993    }
4994
4995    #[test]
4996    fn xml_diagnostic_view_normalizes_noise_without_losing_literal_space_or_quoted_angles() {
4997        let xml = r#"<?xml version="1.0"?><w:p xmlns:w="urn:w" xmlns:w14="urn:w14" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="w14" w14:paraId="A" w:rsidR="0"><w:r><w:t xml:space="preserve"> </w:t><w:t title='a>b'>漢</w:t></w:r></w:p>"#;
4998        assert_eq!(
4999            xml_lines(xml),
5000            vec![
5001                "<w:p>",
5002                "  <w:r>",
5003                "    <w:t xml:space=\"preserve\"> </w:t>",
5004                "    <w:t title=\"a>b\">漢</w:t>",
5005                "  </w:r>",
5006                "</w:p>"
5007            ]
5008        );
5009        // Malformed lexical probes exercise a readable partial diagnostic,
5010        // never claim the strings are schema-valid XML.
5011        assert_eq!(xml_lines("<p key="), vec!["<p>"]);
5012        assert_eq!(xml_lines("<p key='unterminated>"), vec!["<p>"]);
5013        assert_eq!(
5014            strip_namespace_declarations("<x xmlns=\"urn:one\" xmlns:a=\"urn:two\" k=\"v\"/>"),
5015            "<x k=\"v\"/>"
5016        );
5017        assert_eq!(strip_namespace_declarations("<x xmlns:a="), "<x xmlns:a=");
5018        assert_eq!(
5019            strip_namespace_declarations("<x xmlns:a=\"unterminated"),
5020            "<x xmlns:a=\"unterminated"
5021        );
5022    }
5023
5024    /// `--full-lines` prints a listing's lines whole, in one file and in
5025    /// the lines two files differ by, where a report clips them at
5026    /// `WIDTH` characters around their first difference.
5027    #[test]
5028    fn full_lines_prints_listing_lines_whole() {
5029        let long = "漢".repeat(300);
5030        let a = source(&format!("<w:p><w:r><w:t>{long}a</w:t></w:r></w:p>"));
5031        let b = source(&format!("<w:p><w:r><w:t>{long}b</w:t></w:r></w:p>"));
5032        let runs = Options {
5033            checks: vec![Check::Runs],
5034            ..Options::default()
5035        };
5036        let clipped = report(&a, Some(&b), &runs).unwrap();
5037        assert!(!clipped.contains(&long), "{clipped}");
5038        let opts = Options {
5039            full_lines: true,
5040            ..runs.clone()
5041        };
5042        let whole = report(&a, Some(&b), &opts).unwrap();
5043        assert!(
5044            whole.contains(&format!("-A   ¶  [] ¶«» «»{long}a\n")),
5045            "{whole}"
5046        );
5047        assert!(
5048            whole.contains(&format!("+B   ¶  [] ¶«» «»{long}b\n")),
5049            "{whole}"
5050        );
5051        let one = report(&a, None, &opts).unwrap();
5052        assert!(one.contains(&format!("  ¶  [] ¶«» «»{long}a\n")), "{one}");
5053        assert!(!report(&a, None, &runs).unwrap().contains(&long));
5054    }
5055
5056    #[test]
5057    fn grep_across_run_and_revision_marks_preserves_the_complete_unclipped_paragraph() {
5058        let long = format!("{}needle{}", "漢".repeat(205), "界".repeat(205));
5059        let body = format!(
5060            r#"<w:p><w:r><w:t>{long}</w:t></w:r></w:p><w:p><w:r><w:rPr><w:b/></w:rPr><w:t>cross</w:t></w:r><w:ins w:id="1" w:author="A"><w:r><w:t>run</w:t></w:r></w:ins></w:p>"#
5061        );
5062        let bytes = source(&body);
5063        let before = bytes.clone();
5064        let opts = Options {
5065            checks: vec![Check::Runs],
5066            grep: Some("needle".into()),
5067            ..Options::default()
5068        };
5069        assert_eq!(
5070            report(&bytes, None, &opts).unwrap(),
5071            format!("word/document.xml: 2 paragraphs\n  ¶  [] ¶«» «»{long}\n")
5072        );
5073        let opts = Options {
5074            grep: Some("crossrun".into()),
5075            ..opts
5076        };
5077        assert_eq!(
5078            report(&bytes, None, &opts).unwrap(),
5079            "word/document.xml: 2 paragraphs\n  ¶  [] ¶«» «b»cross{+«»run+}\n"
5080        );
5081        assert!(!line_has("«nested«property»»hid«b»den", "hiddenz"));
5082        assert!(line_has("«nested«property»»hid«b»den", "hidden"));
5083        assert_eq!(bytes, before);
5084        assert_eq!(
5085            clip_line(&"漢".repeat(201)),
5086            format!("{}…", "漢".repeat(200))
5087        );
5088        assert_eq!(
5089            clip_from(&"漢".repeat(201), 195),
5090            format!("…{}", "漢".repeat(6))
5091        );
5092    }
5093
5094    #[test]
5095    fn count_reports_keep_zero_missing_sides_sorted_and_do_not_invent_empty_headers() {
5096        let a = BTreeMap::from([("a".into(), 2), ("b".into(), 2), ("same".into(), 1)]);
5097        let b = BTreeMap::from([("b".into(), 3), ("c".into(), 1), ("same".into(), 1)]);
5098        let mut text = String::new();
5099        print_counts(&mut text, "chains", &a, None, 2);
5100        assert_eq!(text, "chains:\n       2 a\n       2 b\n");
5101        text.clear();
5102        print_counts(&mut text, "chains", &a, Some(&b), 9);
5103        assert_eq!(text, "chains: 3 differ\n  a 2 → 0\n  b 2 → 3\n  c 0 → 1\n");
5104        text.clear();
5105        print_counts(&mut text, "chains", &a, Some(&a), 9);
5106        assert_eq!(text, "chains: 0 differ\n");
5107        text.clear();
5108        print_counts(
5109            &mut text,
5110            "chains",
5111            &BTreeMap::new(),
5112            Some(&BTreeMap::new()),
5113            9,
5114        );
5115        assert_eq!(text, "");
5116    }
5117
5118    #[test]
5119    fn list_filter_keeps_package_totals_but_prints_only_selected_changed_entries() {
5120        let a = zip_bytes(&[
5121            ("same.xml", b"same"),
5122            ("change.xml", b"old"),
5123            ("only-a.xml", b"a"),
5124        ]);
5125        let b = zip_bytes(&[
5126            ("same.xml", b"same"),
5127            ("change.xml", b"new value"),
5128            ("only-b.xml", b"b"),
5129        ]);
5130        let before_a = a.clone();
5131        let before_b = b.clone();
5132        let opts = Options {
5133            part: Some("change".into()),
5134            ..Options::default()
5135        };
5136        assert_eq!(
5137            list(&a, Some(&b), &opts).unwrap(),
5138            "1 identical, 1 changed, 1 only in A, 1 only in B\n~          3 → 9          change.xml\n"
5139        );
5140        let opts = Options {
5141            part: Some("absent".into()),
5142            ..opts
5143        };
5144        assert_eq!(
5145            list(&a, None, &opts).unwrap(),
5146            "3 entries, 8 bytes unpacked\n"
5147        );
5148        assert_eq!(a, before_a);
5149        assert_eq!(b, before_b);
5150    }
5151
5152    #[test]
5153    fn property_style_and_numbering_diagnostics_preserve_fallback_ids_and_missing_abstracts() {
5154        // The style name is optional; referenced unknown IDs are explicit
5155        // malformed-source diagnostics rather than silently dropped links.
5156        let (d, root) = dom(&format!(
5157            r#"<w:styles xmlns:w="{W}"><w:style w:type="paragraph" w:styleId="Fallback"><w:basedOn w:val="absent"/><w:link w:val="other"/><w:pPr><w:jc w:val="center"/></w:pPr></w:style></w:styles>"#
5158        ));
5159        assert_eq!(
5160            style_lines(&d, root),
5161            (
5162                vec![
5163                    "  paragraph \"Fallback\" basedOn=\"absent\" link=\"other\"".into(),
5164                    "  paragraph \"Fallback\" pPr[jc=center]".into(),
5165                    "  paragraph \"Fallback\" rPr[]".into()
5166                ],
5167                1
5168            )
5169        );
5170        let (n, nr) = dom(&format!(
5171            r#"<w:numbering xmlns:w="{W}"><w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:lvlJc w:val="left"/></w:lvl></w:abstractNum><w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num><w:num w:numId="10"><w:abstractNumId w:val="99"/></w:num></w:numbering>"#
5172        ));
5173        assert_eq!(
5174            numbering_lines(&n, nr),
5175            (
5176                vec![
5177                    "  num 2 lvl 0 start=1 decimal \"%1.\" jc=left pPr[] rPr[]".into(),
5178                    "  num 10 abstract 99 missing".into()
5179                ],
5180                2
5181            )
5182        );
5183        // Intentional malformed absent style type defaults to paragraph for
5184        // twin detection; distinct named types must never become twins.
5185        let (s, sr) = dom(&format!(
5186            r#"<w:styles xmlns:w="{W}"><w:style w:styleId="A"><w:name w:val="Name"/></w:style><w:style w:type="paragraph" w:styleId="B"><w:name w:val="NAME"/></w:style><w:style w:type="character" w:styleId="C"><w:name w:val="name"/></w:style></w:styles>"#
5187        ));
5188        let mut f = Findings::default();
5189        check_styles(&[(STYLES_PART.into(), s, sr)], &mut f);
5190        assert_eq!(
5191            f.by_kind,
5192            BTreeMap::from([(
5193                "style-name-twin".into(),
5194                vec![(STYLES_PART.into(), "paragraph \"name\": A, B".into())]
5195            )])
5196        );
5197    }
5198
5199    #[test]
5200    fn field_deletion_states_distinguish_correct_deleted_code_from_wrong_code_kind() {
5201        let valid = r#"<w:p><w:del w:id="1" w:author="A"><w:r><w:fldChar w:fldCharType="begin"/><w:delInstrText> PAGE </w:delInstrText><w:fldChar w:fldCharType="separate"/><w:delText>1</w:delText><w:fldChar w:fldCharType="end"/></w:r></w:del></w:p>"#;
5202        let (d, root) = dom(&document(valid));
5203        let mut f = Findings::default();
5204        check_fields(&d, root, "word/document.xml", &mut f);
5205        assert!(f.by_kind.is_empty());
5206        // Intentional wrong instruction kind and mixed live/deleted field.
5207        let invalid = r#"<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:del w:id="1" w:author="A"><w:r><w:instrText> PAGE </w:instrText></w:r></w:del><w:r><w:fldChar w:fldCharType="separate"/><w:fldChar w:fldCharType="end"/></w:r></w:p>"#;
5208        let (d, root) = dom(&document(invalid));
5209        let before = d.serialize_element(root);
5210        let mut f = Findings::default();
5211        check_fields(&d, root, "word/document.xml", &mut f);
5212        assert_eq!(
5213            f.by_kind,
5214            BTreeMap::from([
5215                (
5216                    "field-code-kind-vs-state".into(),
5217                    vec![(
5218                        "word/document.xml".into(),
5219                        "states=-D-- \"PAGE\" at document/body/p/r/fldChar".into()
5220                    )]
5221                ),
5222                (
5223                    "field-partly-deleted".into(),
5224                    vec![(
5225                        "word/document.xml".into(),
5226                        "begin/code/separate/end=-D-- \"PAGE\" at document/body/p/r/fldChar".into()
5227                    )]
5228                ),
5229            ])
5230        );
5231        assert_eq!(d.serialize_element(root), before);
5232    }
5233
5234    #[test]
5235    fn mixed_listing_and_triage_reports_retain_each_independent_contract() {
5236        let bytes = source("<w:p><w:r><w:t>plain</w:t></w:r></w:p>");
5237        let opts = Options {
5238            checks: vec![Check::Text, Check::Structure],
5239            ..Options::default()
5240        };
5241        assert_eq!(
5242            report(&bytes, None, &opts).unwrap(),
5243            "word/document.xml: 1 paragraphs\n  ¶  plain\nno findings\n"
5244        );
5245        let opts = Options {
5246            checks: vec![Check::Elements],
5247            ..Options::default()
5248        };
5249        assert_eq!(
5250            report(&bytes, None, &opts).unwrap(),
5251            "elements: Default 2, Override 1, Relationship 1, body 1, p 1, r 1, t 1\n"
5252        );
5253        let opts = Options {
5254            checks: vec![Check::Chains],
5255            ..Options::default()
5256        };
5257        assert_eq!(report(&bytes, None, &opts).unwrap(), "");
5258        assert_eq!(report(&bytes, Some(&bytes), &opts).unwrap(), "");
5259    }
5260}
5261
5262#[cfg(test)]
5263#[cfg_attr(all(coverage_nightly, test), coverage(off))]
5264mod bounded_input_tests {
5265    use super::*;
5266    use crate::admission::{InputLimits, limit_test_support as fixture};
5267
5268    fn refuses(limits: InputLimits, detail: &str) {
5269        let bytes = fixture::package();
5270        let text = Package::open_within(&bytes, limits)
5271            .err()
5272            .expect("over-budget package must be refused");
5273        assert!(text.contains("INPUT_LIMIT"), "{text}");
5274        assert!(text.contains(detail), "{text}");
5275    }
5276    #[test]
5277    fn compressed_limit() {
5278        refuses(fixture::compressed(), "input is");
5279    }
5280    #[test]
5281    fn count_limit() {
5282        refuses(fixture::count(), "3 ZIP entries; the limit is 2");
5283    }
5284    #[test]
5285    fn part_limit() {
5286        refuses(fixture::part(), "a.bin");
5287    }
5288    #[test]
5289    fn aggregate_limit() {
5290        refuses(fixture::total(), "the package limit is 160");
5291    }
5292    #[test]
5293    fn exact_budget_control() {
5294        let bytes = fixture::package();
5295        assert!(Package::open_within(&bytes, fixture::limits()).is_ok());
5296    }
5297}