Skip to main content

jubarte_doc/
inspect.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Read-only views of a DOCX for agents and tools: body paragraphs an edit can
6//! address, package facts, and a Markdown projection that carries paragraph
7//! ids so the reader's coordinates are the editor's coordinates.
8//!
9//! Paragraph order is body XML order, table cells included; text boxes are
10//! not stories and are omitted from the body (their owner paragraph is
11//! flagged). Text is the visible-run projection: `w:del` and `w:moveFrom`
12//! content is skipped, tabs stay `\t`, line breaks become `\n`, `w:sym`
13//! becomes U+FFFC. Constructs this projection cannot represent are reported per
14//! paragraph in `limitations`; they never refuse the document. Malformed
15//! packages and XML do.
16
17use std::collections::BTreeSet;
18use std::fmt;
19
20use serde::Serialize;
21
22use crate::namespaces::{MC, W, W14, W15};
23use crate::opc::PartFs;
24use crate::xmllinq::{Dom, NodeId, XName};
25
26#[doc(hidden)]
27pub mod tables;
28#[doc(hidden)]
29pub use tables::top_level_table_nodes;
30
31pub use tables::{NestedTable, Table, TableCell};
32
33/// Wire schema version of legacy `jubarte::edit` plans and reports.
34pub const SCHEMA_VERSION: u32 = 1;
35
36/// Snapshot wire schema. Version 2 numbers top-level tables only and nests
37/// cell tables recursively, with a parent cell path rather than an index.
38/// Version 3 lists logical changes (plan 11): a change Word wrote as
39/// several marks is one entry with `members`, and kind `replacement`
40/// exists.
41pub const SNAPSHOT_SCHEMA_VERSION: u32 = 3;
42
43/// The story every document has; its paragraph ids are `pN`, and a
44/// selector without a `story` searches it.
45#[doc(hidden)]
46pub const BODY_STORY: &str = "body";
47
48/// Kinds of part an edit plan addresses as a story besides the body, in
49/// the order [`stories`] lists them. Each is the last segment of the part's
50/// relationship type; the story's id is the part's file stem (`header1`,
51/// `footer2`, `footnotes`, `endnotes`) and [`Story::kind`] is one of these.
52/// Comments and text boxes are not stories. `capabilities` advertises this
53/// list after `body`, so the manifest and the parser cannot drift.
54#[doc(hidden)]
55pub const STORY_KINDS: &[&str] = &["header", "footer", "footnotes", "endnotes"];
56
57/// One paragraph of the body or a story. `index` and `id` are valid for this
58/// exact snapshot.
59#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
60pub struct Paragraph {
61    /// Zero-based order in its story, table-cell paragraphs included.
62    pub index: usize,
63    /// `p{index}` (or `header1`, `header1.p{index}`, ...:
64    /// [`crate::ids::paragraph_id`]); the edit plan's paragraph selector.
65    pub id: String,
66    /// Visible text (see module docs for the projection rules).
67    pub text: String,
68    /// `w:pStyle` id when set directly on the paragraph.
69    pub style: Option<String>,
70    /// Paragraph carries direct `w:numPr` numbering.
71    pub numbered: bool,
72    /// Paragraph lives in a table cell.
73    pub in_table: bool,
74    /// Paragraph contains an explicit page break.
75    pub page_break: bool,
76    /// Direct run formatting over `text`, in char offsets, adjacent equal
77    /// formatting merged. Style-inherited formatting is not resolved.
78    pub runs: Vec<Span>,
79    /// Constructs present but not represented in `text` (`sym`, `field`,
80    /// `hyperlink`, `content_control`, `drawing`, `text_box_omitted`,
81    /// `alternate_content`, `column_break`, `revision`, `note_reference`,
82    /// `unknown:<local-name>`).
83    pub limitations: Vec<String>,
84}
85
86/// Direct formatting of a run of `text` (`[start, end)` in chars).
87#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
88pub struct Span {
89    /// First char (inclusive).
90    pub start: usize,
91    /// Last char (exclusive).
92    pub end: usize,
93    /// Direct bold.
94    pub bold: bool,
95    /// Direct italic.
96    pub italic: bool,
97    /// Direct underline.
98    pub underline: bool,
99    /// Direct highlight color name.
100    pub highlight: Option<String>,
101}
102
103/// Package facts. Counts are XML facts, not rendered-page facts.
104#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
105pub struct Summary {
106    /// Body paragraphs, table cells included.
107    pub paragraphs: usize,
108    /// Top-level body tables, numbered as the view's `tN`.
109    pub tables: usize,
110    /// `w:fldSimple` plus complex-field `begin` markers in the body.
111    pub fields: usize,
112    /// Body section properties, excluding saved revision copies.
113    pub sections: usize,
114    /// Comment definitions in the related comments part.
115    pub comments: usize,
116    /// Tracked changes, as `jubarte changes` lists them: the body, headers,
117    /// footers, notes and styles, a move's sides and a text box's two copies
118    /// counted once each, and a change Word wrote as several marks once.
119    pub revisions: usize,
120    /// Footnotes excluding separators.
121    pub footnotes: usize,
122    /// Endnotes excluding separators.
123    pub endnotes: usize,
124    /// Related header parts.
125    pub headers: usize,
126    /// Related footer parts.
127    pub footers: usize,
128    /// Parts whose content type starts with `image/`.
129    pub images: usize,
130    /// Body or paragraph-style numbering declarations exist.
131    pub list_numbering: bool,
132    /// Settings enable tracking of new revisions.
133    pub track_changes: bool,
134    /// The input's own validity findings, which `read --json` reports here
135    /// (#1309); absent where nothing validated the input.
136    #[serde(skip_serializing_if = "Option::is_none")]
137    pub input_validity: Option<crate::validate::InputValidity>,
138}
139
140/// Snapshot of a package as it stood at inspection time, serialized by
141/// [`inspect_json`] and consumed by `jubarte::edit::apply_plan_json`.
142#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
143pub struct Snapshot {
144    /// Wire schema version.
145    pub schema_version: u32,
146    /// SHA-256 of the inspected bytes.
147    pub source_sha256: String,
148    /// The choice [`settled_snapshot`] read the text under; absent from a
149    /// plain snapshot, whose text is the accepted one.
150    #[serde(skip_serializing_if = "Option::is_none")]
151    pub track_changes: Option<Settle>,
152    /// Package facts.
153    pub summary: Summary,
154    /// Body paragraphs.
155    pub paragraphs: Vec<Paragraph>,
156    /// Header, footer and note stories, each with its own paragraphs.
157    pub stories: Vec<Story>,
158    /// Top-level body tables as grids, with nested tables under their cells.
159    pub tables: Vec<Table>,
160    /// Content controls (`w:sdt`) in the body, in document order.
161    pub controls: Vec<ContentControl>,
162    /// Tracked changes, as [`crate::changes::list_logical_changes`] lists
163    /// them.
164    pub changes: Vec<crate::changes::Change>,
165    /// Comments, as [`crate::comments::list_comments`] lists them.
166    pub comments: Vec<crate::comments::CommentRecord>,
167}
168
169/// How [`settled_snapshot`] settles the tracked changes before it reads
170/// the text (`read --json --track-changes`).
171#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
172#[serde(rename_all = "lowercase")]
173pub enum Settle {
174    /// Every change accepted: the text a plain snapshot reads.
175    Accept,
176    /// Every change rejected, as Word's Reject All leaves the text:
177    /// insertions gone, deletions back.
178    Reject,
179}
180
181impl Snapshot {
182    /// Keep the body paragraphs numbered in `body_paragraphs` (`N` of
183    /// `pN`), and the changes and comments sitting in one of them; a
184    /// comment whose range spans a kept paragraph counts. `summary`,
185    /// `stories`, `tables` and `controls` stay whole.
186    pub fn retain(&mut self, body_paragraphs: &[usize]) {
187        self.retain_with(body_paragraphs, &[]);
188    }
189
190    /// [`Snapshot::retain`], keeping too the changes and comments in
191    /// `stories` (`header1`, `footnotes`): those a `--changed` selection
192    /// changed.
193    #[doc(hidden)]
194    pub fn retain_with(&mut self, body_paragraphs: &[usize], stories: &[String]) {
195        let kept: BTreeSet<usize> = body_paragraphs.iter().copied().collect();
196        self.paragraphs
197            .retain(|p| body_index(Some(&p.id)).is_some_and(|n| kept.contains(&n)));
198        let in_story = |paragraph: Option<&String>| {
199            paragraph
200                .and_then(|p| crate::ids::paragraph_place(p))
201                .is_some_and(|(story, _)| stories.contains(&story))
202        };
203        self.changes.retain(|c| {
204            body_index(c.paragraph.as_ref()).is_some_and(|n| kept.contains(&n))
205                || in_story(c.paragraph.as_ref())
206        });
207        self.comments.retain(|c| {
208            let first = body_index(c.paragraph.as_ref());
209            let last = body_index(c.last_paragraph.as_ref()).or(first);
210            match (first, last) {
211                (Some(a), Some(z)) => kept.range(a..=z.max(a)).next().is_some(),
212                _ => in_story(c.paragraph.as_ref()),
213            }
214        });
215    }
216}
217
218/// `N` of a body paragraph's id `pN`.
219fn body_index(id: Option<&String>) -> Option<usize> {
220    crate::ids::paragraph_place(id?)
221        .filter(|(story, _)| story == "body")
222        .map(|(_, n)| n)
223}
224
225/// A header, footer or notes part an edit plan can address. Its paragraph
226/// ids are `{id}` for the first and `{id}.p{index}` after it
227/// ([`crate::ids::paragraph_id`]).
228#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
229pub struct Story {
230    /// The part's file stem: `header1`, `footer2`, `footnotes`, `endnotes`.
231    pub id: String,
232    /// `header`, `footer`, `footnotes` or `endnotes`.
233    pub kind: String,
234    /// Package part name, e.g. `word/header1.xml`.
235    pub part: String,
236    /// The story's paragraphs; separator notes are left out.
237    pub paragraphs: Vec<Paragraph>,
238}
239
240/// A content control (`w:sdt`) in the body, in document order. Controls
241/// inside text boxes are not listed.
242#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
243pub struct ContentControl {
244    /// `ccN` for a block control, `pN.ccK` for one in paragraph `pN`.
245    pub id: String,
246    /// `w:tag`.
247    #[serde(skip_serializing_if = "Option::is_none")]
248    pub tag: Option<String>,
249    /// `w:alias`, the title Word shows.
250    #[serde(skip_serializing_if = "Option::is_none")]
251    pub alias: Option<String>,
252    /// `text`, `rich_text`, `drop_down`, `combo_box`, `date`, `checkbox`,
253    /// `picture`, `group`, `repeating`, `building_block`, `citation`,
254    /// `bibliography`, `equation`, `unknown`. A control whose properties
255    /// name no type is `rich_text`, as in Word.
256    pub kind: String,
257    /// Visible text of the control's content; paragraphs joined by `\n`.
258    pub text: String,
259    /// Paragraphs the control spans (`pN`); a run-level control lists
260    /// the paragraph that holds it.
261    pub paragraph_ids: Vec<String>,
262    /// `w:lock` is `contentLocked` or `sdtContentLocked`.
263    pub locked: bool,
264    /// Drop-down and combo-box choices (`w:listItem/@w:value`, or the
265    /// display text when an item has no value).
266    #[serde(skip_serializing_if = "Vec::is_empty")]
267    pub choices: Vec<String>,
268    /// Checkbox state (`w14:checked`).
269    #[serde(skip_serializing_if = "Option::is_none")]
270    pub checked: Option<bool>,
271    /// `w:showingPlcHdr` is set: the text is placeholder text.
272    pub placeholder: bool,
273}
274
275/// An invalid package or XML part.
276#[derive(Clone, Debug, PartialEq, Eq)]
277pub enum InspectError {
278    /// OPC/ZIP load failure.
279    Package(String),
280    /// Missing main document part or body.
281    MissingDocument,
282    /// Invalid XML, encoding or setting value, including the part name.
283    Invalid(String),
284    /// Refused before parsing by [`crate::admission`] (a resource budget,
285    /// duplicate or unsafe part, or not a Word package).
286    Admission(crate::admission::AdmissionError),
287}
288
289impl fmt::Display for InspectError {
290    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
291        match self {
292            Self::Package(message) => write!(f, "opening DOCX: {message}"),
293            Self::MissingDocument => f.write_str("DOCX has no main document part or body"),
294            Self::Invalid(message) => write!(f, "invalid DOCX content: {message}"),
295            Self::Admission(refused) => write!(f, "DOCX refused: {refused}"),
296        }
297    }
298}
299
300impl std::error::Error for InspectError {}
301
302pub use crate::util::source_sha256;
303
304/// Body paragraphs in body order.
305///
306/// # Errors
307///
308/// [`InspectError::Admission`] when the input is refused by admission;
309/// [`InspectError::Package`] when the package cannot be read;
310/// [`InspectError::MissingDocument`] when no main document part is found.
311pub fn paragraphs(docx: &[u8]) -> Result<Vec<Paragraph>, InspectError> {
312    let opened = Opened::open(docx)?;
313    Ok(body_paragraphs(&opened.dom, opened.body))
314}
315
316/// Paragraph locations for a comparison rendered under its active budget.
317/// One admitted open serves both the body and its related stories.
318#[doc(hidden)]
319pub fn paragraphs_and_stories_within(
320    docx: &[u8],
321    limits: crate::admission::InputLimits,
322) -> Result<(Vec<Paragraph>, Vec<Story>), InspectError> {
323    let opened = Opened::open_within(docx, limits)?;
324    Ok((
325        body_paragraphs(&opened.dom, opened.body),
326        opened.stories_within(limits, false)?,
327    ))
328}
329
330/// Package facts, following OPC relationships for related parts.
331///
332/// # Errors
333///
334/// [`InspectError::Admission`] when the input is refused by admission;
335/// [`InspectError::Package`] when a part cannot be read;
336/// [`InspectError::Invalid`] for a malformed XML part or an invalid setting
337/// value; [`InspectError::MissingDocument`] when no main document part is
338/// found.
339pub fn summary(docx: &[u8]) -> Result<Summary, InspectError> {
340    let opened = Opened::open(docx)?;
341    opened.summary()
342}
343
344/// Header, footer and note stories in a stable order (headers, footers,
345/// footnotes, endnotes).
346///
347/// # Errors
348///
349/// [`InspectError::Admission`] when the input is refused by admission;
350/// [`InspectError::Package`] when the package cannot be read;
351/// [`InspectError::Invalid`] for a malformed part;
352/// [`InspectError::MissingDocument`] when no main document part is found.
353pub fn stories(docx: &[u8]) -> Result<Vec<Story>, InspectError> {
354    Opened::open(docx)?.stories()
355}
356
357/// Content controls (`w:sdt`) in the body, in document order.
358///
359/// # Errors
360///
361/// [`InspectError::Admission`] when the input is refused by admission;
362/// [`InspectError::Package`] when the package cannot be read;
363/// [`InspectError::MissingDocument`] when no main document part is found.
364pub fn controls(docx: &[u8]) -> Result<Vec<ContentControl>, InspectError> {
365    let opened = Opened::open(docx)?;
366    Ok(collect_controls(&opened.dom, opened.body))
367}
368
369/// Paragraphs prefixed with their ids and direct formatting as Markdown
370/// marks: `[p12 Heading1] (a) **Confidentiality.** You will ...`.
371/// Story paragraphs (`[header1] ...`, `[header1.p1] ...`) follow the body's.
372pub fn markdown(docx: &[u8]) -> Result<String, InspectError> {
373    let opened = Opened::open(docx)?;
374    let mut all = body_paragraphs(&opened.dom, opened.body);
375    for story in opened.stories()? {
376        all.extend(story.paragraphs);
377    }
378    Ok(render_markdown(&all))
379}
380
381/// Body tables as grids: each cell's text and paragraph ids, the header
382/// rows and the grid widths.
383///
384/// # Errors
385///
386/// [`InspectError::Admission`] when the input is refused by admission;
387/// [`InspectError::Package`] when the package cannot be read;
388/// [`InspectError::MissingDocument`] when no main document part is found.
389pub fn tables(docx: &[u8]) -> Result<Vec<Table>, InspectError> {
390    let opened = Opened::open(docx)?;
391    Ok(tables::body_tables(&opened.dom, opened.body))
392}
393
394/// The full snapshot: `schema_version`, `source_sha256`, `summary`,
395/// `paragraphs`, `stories`, `tables`, `controls`, `changes` and `comments`.
396///
397/// # Errors
398///
399/// [`InspectError::Admission`] when the input is refused by admission;
400/// [`InspectError::Package`] when the package or comments part cannot be
401/// read; [`InspectError::Invalid`] for a malformed part;
402/// [`InspectError::MissingDocument`] when no main document part is found.
403pub fn snapshot(docx: &[u8]) -> Result<Snapshot, InspectError> {
404    // One open serves every field; the comment scan marks up the body's
405    // DOM, so it runs last.
406    let mut opened = Opened::open(docx)?;
407    let summary = opened.summary()?;
408    let paragraphs = body_paragraphs(&opened.dom, opened.body);
409    let stories = opened.stories()?;
410    let tables = tables::body_tables(&opened.dom, opened.body);
411    let controls = collect_controls(&opened.dom, opened.body);
412    let changes = crate::changes::logical_changes_in(&opened.pkg);
413    let comments = crate::comments::comments_in(&mut opened).map_err(|e| match e {
414        crate::comments::CommentError::Admission(refused) => InspectError::Admission(refused),
415        crate::comments::CommentError::Package(m) => InspectError::Package(m),
416    })?;
417    Ok(Snapshot {
418        schema_version: SNAPSHOT_SCHEMA_VERSION,
419        source_sha256: source_sha256(docx),
420        track_changes: None,
421        summary,
422        paragraphs,
423        stories,
424        tables,
425        controls,
426        changes,
427        comments,
428    })
429}
430
431/// [`snapshot`] with every tracked change settled by `settle`, and
432/// `track_changes` saying how. The paragraphs, cells and controls of the
433/// body and of every story read the settled text and keep their ids: the
434/// paragraphs, rows and cells a choice would remove stay, with the text it
435/// leaves them (often none). `summary`, `changes` and `comments` describe
436/// the file as stored, every revision still listed: the facts of what
437/// `track_changes` settles.
438///
439/// # Errors
440///
441/// As [`snapshot`].
442pub fn settled_snapshot(docx: &[u8], settle: Settle) -> Result<Snapshot, InspectError> {
443    let mut snapshot = snapshot(docx)?;
444    snapshot.track_changes = Some(settle);
445    if settle == Settle::Reject {
446        // The comment scan marks up the DOM it reads, so the rejected text
447        // comes from a second open of its own.
448        let mut opened = Opened::open(docx)?;
449        reject_text(&mut opened.dom, opened.body);
450        snapshot.paragraphs = body_paragraphs(&opened.dom, opened.body);
451        snapshot.tables = tables::body_tables(&opened.dom, opened.body);
452        snapshot.controls = collect_controls(&opened.dom, opened.body);
453        snapshot.stories = opened.stories_within(crate::admission::InputLimits::default(), true)?;
454    }
455    Ok(snapshot)
456}
457
458/// [`tables()`], with every change rejected when `settle` says so, each
459/// beside the number of its table in `read`'s view: the `tN` of the table
460/// outside every cell that is it or holds it, as `read -p tN` picks it.
461///
462/// # Errors
463///
464/// As [`tables()`].
465pub fn view_tables(
466    docx: &[u8],
467    settle: Option<Settle>,
468) -> Result<Vec<(usize, Table)>, InspectError> {
469    let mut opened = Opened::open(docx)?;
470    if settle == Some(Settle::Reject) {
471        reject_text(&mut opened.dom, opened.body);
472    }
473    // `body_tables` lists the tables the view numbers, each under its `tN`.
474    Ok(tables::body_tables(&opened.dom, opened.body)
475        .into_iter()
476        .map(|table| (table.index, table))
477        .collect())
478}
479
480/// Word's Reject All on the text under `root`, in place: inserted and
481/// moved-to runs go, deleted and moved-from runs come back, their
482/// `w:delText` read as `w:t`, and a formatting change gives back the
483/// properties it replaced. Paragraph marks, rows and cells stay (their
484/// own revisions hold no text), so every paragraph keeps its id.
485fn reject_text(dom: &mut Dom, root: NodeId) {
486    // A paragraph's old base properties are in its `w:pPrChange`; its
487    // mark's `w:rPr` and its `w:sectPr` are not, and stay. A run's (or a
488    // mark's) old properties are the whole `w:rPr` of its `w:rPrChange`.
489    for (change, kept) in [
490        ("pPrChange", &["rPr", "sectPr"][..]),
491        ("rPrChange", &[][..]),
492    ] {
493        for node in dom.descendants(root, Some(&W::name(change))) {
494            let Some(properties) = dom.parent(node) else {
495                continue;
496            };
497            let old = dom
498                .elements(node, None)
499                .first()
500                .map(|&old| {
501                    let kids = dom.nodes(old);
502                    dom.remove_nodes(old);
503                    kids
504                })
505                .unwrap_or_default();
506            let stay: Vec<NodeId> = dom
507                .elements(properties, None)
508                .into_iter()
509                .filter(|&e| kept.iter().any(|k| dom.name_is(e, &W::name(k))))
510                .collect();
511            dom.remove_nodes(properties);
512            for kid in old.into_iter().chain(stay) {
513                dom.add(properties, kid);
514            }
515        }
516    }
517    for local in ["ins", "moveTo"] {
518        for node in dom.descendants(root, Some(&W::name(local))) {
519            dom.remove(node);
520        }
521    }
522    for local in ["del", "moveFrom"] {
523        for node in dom.descendants(root, Some(&W::name(local))) {
524            let kids = dom.nodes(node);
525            dom.remove_nodes(node);
526            dom.replace_with(node, &kids);
527        }
528    }
529    for (from, to) in [("delText", "t"), ("delInstrText", "instrText")] {
530        for node in dom.descendants(root, Some(&W::name(from))) {
531            dom.set_name(node, W::name(to));
532        }
533    }
534}
535
536/// [`snapshot`] as JSON.
537///
538/// # Errors
539///
540/// As [`snapshot`]; [`InspectError::Invalid`] when the snapshot cannot be
541/// serialized.
542pub fn inspect_json(docx: &[u8]) -> Result<String, InspectError> {
543    serde_json::to_string(&snapshot(docx)?).map_err(|e| InspectError::Invalid(e.to_string()))
544}
545
546/// Tables as `read --tables` prints them: a `table N: RxC header_rows=H
547/// widths=W` line per table, then a line per row of tab-separated
548/// `ids=text` cells (`-` for a cell with no paragraph; `\`, newlines and
549/// tabs escaped), or `no tables`. Cell ids are short paragraph ids (`p1`),
550/// via [`crate::ids::short_paragraph`]; a cell of several paragraphs joins
551/// them with commas (`p3,p4`), a spelling only this listing prints. Every line
552/// ends with a newline. Nested tables follow their containing cell row,
553/// indented two spaces per level and labelled `nested in CELL_PATH`.
554pub fn tables_text(tables: &[Table]) -> String {
555    let mut out = String::new();
556    if tables.is_empty() {
557        out.push_str("no tables\n");
558    }
559    for table in tables {
560        render_grid(
561            &mut out,
562            &format!("table {}", table.index),
563            &table.rows,
564            table.header_rows,
565            &table.widths_dxa,
566            &table.nested,
567            0,
568        );
569    }
570    out
571}
572
573fn render_grid(
574    out: &mut String,
575    label: &str,
576    rows: &[Vec<TableCell>],
577    header_rows: usize,
578    widths_dxa: &[u32],
579    nested: &[NestedTable],
580    depth: usize,
581) {
582    use std::fmt::Write as _;
583    let indent = "  ".repeat(depth);
584    let columns = rows.iter().map(Vec::len).max().unwrap_or(0);
585    let widths: Vec<String> = widths_dxa.iter().map(u32::to_string).collect();
586    let _ = writeln!(
587        out,
588        "{indent}{label}: {}x{columns} header_rows={header_rows} widths={}",
589        rows.len(),
590        widths.join(",")
591    );
592    for (r, row) in rows.iter().enumerate() {
593        let cells: Vec<String> = row
594            .iter()
595            .map(|cell| {
596                let ids = if cell.paragraph_ids.is_empty() {
597                    "-".to_string()
598                } else {
599                    cell.paragraph_ids
600                        .iter()
601                        .map(|id| crate::ids::short_paragraph(id))
602                        .collect::<Vec<_>>()
603                        .join(",")
604                };
605                let text = cell
606                    .text
607                    .replace('\\', "\\\\")
608                    .replace('\n', "\\n")
609                    .replace('\t', "\\t");
610                format!("{ids}={text}")
611            })
612            .collect();
613        let _ = writeln!(out, "{indent}{}", cells.join("\t"));
614        // The final row/cell segment is this table's own cell, even at
615        // several nesting levels. Emit its children directly below the row.
616        let row_prefix = format!("{r}.cell");
617        for child in nested.iter().filter(|child| {
618            child
619                .parent
620                .rsplit_once(".row")
621                .is_some_and(|(_, tail)| tail.starts_with(&row_prefix))
622        }) {
623            render_grid(
624                out,
625                &format!("nested in {}", child.parent),
626                &child.rows,
627                child.header_rows,
628                &child.widths_dxa,
629                &child.nested,
630                depth + 1,
631            );
632        }
633    }
634}
635
636/// Markdown rendering of already inspected paragraphs.
637pub fn render_markdown(paragraphs: &[Paragraph]) -> String {
638    let mut out = String::new();
639    for p in paragraphs {
640        out.push('[');
641        out.push_str(&p.id);
642        if let Some(style) = &p.style {
643            out.push(' ');
644            out.push_str(style);
645        }
646        out.push(']');
647        let body = markdown_body(p);
648        if !body.is_empty() {
649            out.push(' ');
650            out.push_str(&body);
651        }
652        out.push_str("\n\n");
653    }
654    if out.ends_with("\n\n") {
655        out.pop();
656    }
657    out
658}
659
660fn markdown_body(p: &Paragraph) -> String {
661    let chars: Vec<char> = p.text.chars().collect();
662    let mut out = String::new();
663    let mut cursor = 0;
664    for span in &p.runs {
665        let start = span.start.min(chars.len());
666        let end = span.end.min(chars.len());
667        if start > cursor {
668            out.extend(&chars[cursor..start]);
669        }
670        let piece: String = chars[start..end].iter().collect();
671        out.push_str(&emphasize(&piece, span));
672        cursor = end;
673    }
674    if cursor < chars.len() {
675        out.extend(&chars[cursor..]);
676    }
677    out.trim_end().to_string()
678}
679
680fn emphasize(piece: &str, span: &Span) -> String {
681    let core = piece.trim();
682    if core.is_empty() || (!span.bold && !span.italic && span.highlight.is_none()) {
683        return piece.to_string();
684    }
685    let lead = &piece[..piece.len() - piece.trim_start().len()];
686    let trail = &piece[piece.trim_end().len()..];
687    let mut open = String::new();
688    if span.highlight.is_some() {
689        open.push_str("==");
690    }
691    if span.bold {
692        open.push_str("**");
693    }
694    if span.italic {
695        open.push('*');
696    }
697    let close: String = open.chars().rev().collect();
698    format!("{lead}{open}{core}{close}{trail}")
699}
700
701// Documents this thread has reopened through `Opened::open` since the last
702// `reset_reopened_packages`. Tests that must not pay for a reparse of bytes
703// they already hold reset the counter, run the phase under test, and read
704// it back.
705#[cfg(any(test, feature = "test-support"))]
706thread_local! {
707    #[doc(hidden)]
708    pub static REOPENED_PACKAGES: std::cell::Cell<usize> =
709        const { std::cell::Cell::new(0) };
710}
711
712/// Add one to this thread's [`REOPENED_PACKAGES`].
713#[cfg(test)]
714#[cfg_attr(all(coverage_nightly, test), coverage(off))]
715fn bump_reopened_packages() {
716    REOPENED_PACKAGES.with(|count| count.set(count.get() + 1));
717}
718
719/// Zero this thread's [`REOPENED_PACKAGES`].
720#[cfg(any(test, feature = "test-support"))]
721#[cfg_attr(all(coverage_nightly, test), coverage(off))]
722#[doc(hidden)]
723pub fn reset_reopened_packages() {
724    REOPENED_PACKAGES.with(|count| count.set(0));
725}
726
727/// A parsed main document part plus its package.
728#[doc(hidden)]
729pub struct Opened {
730    pub pkg: PartFs,
731    pub main: String,
732    pub dom: Dom,
733    pub document: NodeId,
734    pub body: NodeId,
735}
736
737impl Opened {
738    #[doc(hidden)]
739    pub fn open(bytes: &[u8]) -> Result<Self, InspectError> {
740        Self::open_within(bytes, crate::admission::InputLimits::default())
741    }
742
743    pub(crate) fn open_within(
744        bytes: &[u8],
745        limits: crate::admission::InputLimits,
746    ) -> Result<Self, InspectError> {
747        #[cfg(test)]
748        bump_reopened_packages();
749        crate::admission::admit(bytes, limits).map_err(InspectError::Admission)?;
750        let normalized =
751            crate::strict_translation::strict_to_transitional_docx_within(bytes, limits)
752                .map_err(|error| InspectError::Package(error.to_string()))?;
753        let pkg = PartFs::open_within(&normalized, limits)
754            .map_err(|error| InspectError::Package(error.to_string()))?;
755        let main = main_part(&pkg)?;
756        let (dom, document, root) = parse_part_within(&pkg, &main, limits)?;
757        let body = dom
758            .element(root, &W::body())
759            .ok_or(InspectError::MissingDocument)?;
760        Ok(Self {
761            pkg,
762            main,
763            dom,
764            document,
765            body,
766        })
767    }
768
769    fn summary(&self) -> Result<Summary, InspectError> {
770        let (dom, body, pkg) = (&self.dom, self.body, &self.pkg);
771        let mut summary = Summary {
772            paragraphs: body_paragraphs(dom, body).len(),
773            tables: tables::top_level_table_nodes(dom, body).len(),
774            fields: dom.descendants(body, Some(&W::fld_simple())).len()
775                + dom
776                    .descendants(body, Some(&W::fld_char()))
777                    .iter()
778                    .filter(|&&node| dom.attribute(node, &W::name("fldCharType")) == Some("begin"))
779                    .count(),
780            sections: dom
781                .descendants(body, Some(&W::sect_pr()))
782                .iter()
783                .filter(|&&node| {
784                    !has_ancestor(dom, node, &W::name("sectPrChange"))
785                        && !has_ancestor(dom, node, &W::p_pr_change())
786                })
787                .count(),
788            list_numbering: !dom.descendants(body, Some(&W::num_pr())).is_empty(),
789            ..Summary::default()
790        };
791        for name in pkg.parts() {
792            let mime = pkg.content_type_for(&name);
793            let mime = mime.as_deref();
794            if mime.is_some_and(|mime| mime.starts_with("image/")) {
795                summary.images += 1;
796            }
797            // The checked reader refuses a malformed WordprocessingML part;
798            // custom XML items and vendor parts are not read, so it cannot
799            // refuse the document over them.
800            let wordprocessing = mime.is_some_and(|mime| {
801                mime.starts_with("application/vnd.openxmlformats-officedocument.wordprocessingml.")
802            });
803            if wordprocessing && name != self.main {
804                parse_part(pkg, &name)?;
805            }
806        }
807        summary.revisions = crate::changes::logical_changes_in(pkg).len();
808        for (kind, targets) in [
809            ("header", self.related("header")),
810            ("footer", self.related("footer")),
811            ("comments", self.related("comments")),
812            ("footnotes", self.related("footnotes")),
813            ("endnotes", self.related("endnotes")),
814            ("settings", self.related("settings")),
815            ("styles", self.related("styles")),
816        ] {
817            for target in targets {
818                let (part_dom, _, part_root) = parse_part(pkg, &target)?;
819                match kind {
820                    "header" => summary.headers += 1,
821                    "footer" => summary.footers += 1,
822                    "comments" => {
823                        part_dom.for_each_descendant_element(
824                            part_root,
825                            Some(&W::comment()),
826                            |_| summary.comments += 1,
827                        );
828                    }
829                    "footnotes" => {
830                        summary.footnotes += note_count(&part_dom, part_root, "footnote");
831                    }
832                    "endnotes" => summary.endnotes += note_count(&part_dom, part_root, "endnote"),
833                    "styles" => {
834                        let numbered_style = part_dom
835                            .descendants(part_root, Some(&W::name("style")))
836                            .into_iter()
837                            .any(|style| {
838                                part_dom.attribute(style, &W::type_()) == Some("paragraph")
839                                    && !part_dom.descendants(style, Some(&W::num_pr())).is_empty()
840                            });
841                        summary.list_numbering |= numbered_style;
842                    }
843                    _ => {
844                        if let Some(setting) =
845                            part_dom.element(part_root, &W::name("trackRevisions"))
846                        {
847                            summary.track_changes = match part_dom.attribute(setting, &W::val()) {
848                                None | Some("true" | "1" | "on") => true,
849                                Some("false" | "0" | "off") => false,
850                                Some(value) => {
851                                    return Err(InspectError::Invalid(format!(
852                                        "{target}: invalid trackRevisions value {value}"
853                                    )));
854                                }
855                            };
856                        }
857                    }
858                }
859            }
860        }
861        Ok(summary)
862    }
863
864    /// Internal targets of the main part's relationships of one kind.
865    /// Header, footer and note parts: `(story id, kind, part name)`. The id
866    /// is the part's file stem; `header2` sorts before `header10`.
867    #[doc(hidden)]
868    pub fn story_parts(&self) -> Vec<(String, &'static str, String)> {
869        let mut out = Vec::new();
870        for kind in STORY_KINDS.iter().copied() {
871            let mut parts: Vec<String> = self.related(kind).into_iter().collect();
872            parts.sort_by_key(|part| (part.len(), part.clone()));
873            for part in parts {
874                out.push((crate::ids::part_story(&part), kind, part));
875            }
876        }
877        out
878    }
879
880    fn stories(&self) -> Result<Vec<Story>, InspectError> {
881        self.stories_within(crate::admission::InputLimits::default(), false)
882    }
883
884    /// [`Self::stories`] under `limits`, every change rejected when
885    /// `reject` is set.
886    fn stories_within(
887        &self,
888        limits: crate::admission::InputLimits,
889        reject: bool,
890    ) -> Result<Vec<Story>, InspectError> {
891        self.story_parts()
892            .into_iter()
893            .map(|(id, kind, part)| {
894                let (mut dom, _, root) = parse_part_within(&self.pkg, &part, limits)?;
895                if reject {
896                    reject_text(&mut dom, root);
897                }
898                let paragraphs = paragraphs_of(&dom, story_paragraph_nodes(&dom, root), &id);
899                Ok(Story {
900                    id,
901                    kind: kind.to_string(),
902                    part,
903                    paragraphs,
904                })
905            })
906            .collect()
907    }
908
909    #[doc(hidden)]
910    pub fn related(&self, kind: &str) -> BTreeSet<String> {
911        self.pkg
912            .read_rels_for(&self.main)
913            .into_iter()
914            .flat_map(|rels| &rels.items)
915            .filter(|rel| {
916                rel.target_mode.as_deref() != Some("External")
917                    && rel.rel_type.rsplit('/').next() == Some(kind)
918            })
919            .map(|rel| self.pkg.resolve_rel_target(&self.main, &rel.target))
920            .collect()
921    }
922}
923
924fn main_part(pkg: &PartFs) -> Result<String, InspectError> {
925    pkg.main_document_part()
926        .or_else(|| {
927            pkg.part_bytes("word/document.xml")
928                .map(|_| "word/document.xml".to_string())
929        })
930        .ok_or(InspectError::MissingDocument)
931}
932
933/// Parse one XML part through the checked reader: `(dom, document, root)`.
934#[doc(hidden)]
935pub fn parse_part(pkg: &PartFs, name: &str) -> Result<(Dom, NodeId, NodeId), InspectError> {
936    parse_part_within(pkg, name, crate::admission::InputLimits::default())
937}
938
939fn parse_part_within(
940    pkg: &PartFs,
941    name: &str,
942    limits: crate::admission::InputLimits,
943) -> Result<(Dom, NodeId, NodeId), InspectError> {
944    let bytes = pkg
945        .part_bytes(name)
946        .ok_or_else(|| InspectError::Invalid(format!("missing related part {name}")))?;
947    let xml = std::str::from_utf8(bytes)
948        .map_err(|error| InspectError::Invalid(format!("{name}: {error}")))?;
949    crate::xmllinq::parse::validate_xml_with_limits(xml, limits)
950        .map_err(|error| InspectError::Invalid(format!("{name}: {error}")))?;
951    let mut dom = Dom::new();
952    let document = dom.parse_xdocument(xml);
953    let root = dom
954        .root(document)
955        .ok_or_else(|| InspectError::Invalid(format!("{name}: missing XML root")))?;
956    Ok((dom, document, root))
957}
958
959fn has_ancestor(dom: &Dom, node: NodeId, name: &XName) -> bool {
960    !dom.ancestors(node, Some(name)).is_empty()
961}
962
963pub(crate) use crate::ooxml::text_box_names;
964
965/// Whether `node` sits inside a text box.
966#[doc(hidden)]
967pub fn in_text_box(dom: &Dom, node: NodeId) -> bool {
968    text_box_names()
969        .iter()
970        .any(|name| has_ancestor(dom, node, name))
971}
972
973/// Whether `node` holds a text box.
974fn holds_text_box(dom: &Dom, node: NodeId) -> bool {
975    text_box_names()
976        .iter()
977        .any(|name| !dom.descendants(node, Some(name)).is_empty())
978}
979
980fn note_count(dom: &Dom, root: NodeId, local: &str) -> usize {
981    dom.descendants(root, Some(&W::name(local)))
982        .iter()
983        .filter(|&&node| {
984            !matches!(
985                dom.attribute(node, &W::type_()),
986                Some("separator" | "continuationSeparator")
987            )
988        })
989        .count()
990}
991
992/// The body paragraphs (`w:p` outside text boxes) in document order.
993#[doc(hidden)]
994pub fn body_paragraph_nodes(dom: &Dom, body: NodeId) -> Vec<NodeId> {
995    dom.descendants(body, Some(&W::p()))
996        .into_iter()
997        .filter(|&p| !in_text_box(dom, p))
998        .collect()
999}
1000
1001/// The body's content controls (`w:sdt` outside text boxes) in document
1002/// order, the order [`collect_controls`] numbers them in.
1003#[doc(hidden)]
1004pub fn body_control_nodes(dom: &Dom, body: NodeId) -> Vec<NodeId> {
1005    dom.descendants(body, Some(&W::sdt()))
1006        .into_iter()
1007        .filter(|&sdt| !in_text_box(dom, sdt))
1008        .collect()
1009}
1010
1011/// One record per [`body_control_nodes`] entry.
1012#[doc(hidden)]
1013pub fn collect_controls(dom: &Dom, body: NodeId) -> Vec<ContentControl> {
1014    let paragraphs = body_paragraph_nodes(dom, body);
1015    let index: std::collections::HashMap<NodeId, usize> = paragraphs
1016        .iter()
1017        .enumerate()
1018        .map(|(i, &p)| (p, i))
1019        .collect();
1020    // A block control is `ccN`, counting the body's block controls; one in
1021    // a paragraph is `pN.ccK`, counting that paragraph's controls.
1022    let mut blocks = 0usize;
1023    let mut inline: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
1024    body_control_nodes(dom, body)
1025        .into_iter()
1026        .map(|sdt| {
1027            let owner = dom
1028                .ancestors(sdt, Some(&W::p()))
1029                .first()
1030                .and_then(|p| index.get(p).copied());
1031            let id = match owner {
1032                Some(i) => {
1033                    let k = inline.entry(i).or_default();
1034                    *k += 1;
1035                    format!("{}.cc{}", crate::ids::paragraph_id("body", i), *k - 1)
1036                }
1037                None => {
1038                    blocks += 1;
1039                    format!("cc{}", blocks - 1)
1040                }
1041            };
1042            control_record(dom, sdt, id, &index)
1043        })
1044        .collect()
1045}
1046
1047fn control_record(
1048    dom: &Dom,
1049    sdt: NodeId,
1050    id: String,
1051    index: &std::collections::HashMap<NodeId, usize>,
1052) -> ContentControl {
1053    let pr = dom.element(sdt, &W::sdt_pr());
1054    let child = |name: &XName| pr.and_then(|pr| dom.element(pr, name));
1055    let val = |name: &XName| {
1056        child(name)
1057            .and_then(|e| dom.attribute(e, &W::val()))
1058            .map(str::to_string)
1059    };
1060    let kind = pr.map_or("rich_text", |pr| control_kind(dom, pr));
1061    let list = child(&W::name("dropDownList")).or_else(|| child(&W::name("comboBox")));
1062    let choices = list
1063        .map(|list| {
1064            dom.elements(list, Some(&W::name("listItem")))
1065                .into_iter()
1066                .filter_map(|item| {
1067                    dom.attribute(item, &W::name("value"))
1068                        .or_else(|| dom.attribute(item, &W::name("displayText")))
1069                        .map(str::to_string)
1070                })
1071                .collect()
1072        })
1073        .unwrap_or_default();
1074    let checked = child(&W14::name("checkbox")).map(|checkbox| {
1075        dom.element(checkbox, &W14::name("checked"))
1076            .and_then(|c| dom.attribute(c, &W14::name("val")))
1077            .is_some_and(on_off)
1078    });
1079    let placeholder = child(&W::name("showingPlcHdr"))
1080        .is_some_and(|e| dom.attribute(e, &W::val()).is_none_or(on_off));
1081    let locked = matches!(
1082        val(&W::name("lock")).as_deref(),
1083        Some("contentLocked" | "sdtContentLocked")
1084    );
1085    let content = dom.element(sdt, &W::sdt_content());
1086    let owner = dom.ancestors(sdt, Some(&W::p())).first().copied();
1087    let (paragraph_ids, text) = match (owner, content) {
1088        (Some(p), _) => {
1089            let text = content.map_or_else(String::new, |c| project_container(dom, c).text);
1090            (index.get(&p).map(|&i| vec![i]).unwrap_or_default(), text)
1091        }
1092        (None, Some(c)) => {
1093            let inner: Vec<(usize, NodeId)> = dom
1094                .descendants(c, Some(&W::p()))
1095                .into_iter()
1096                .filter_map(|p| index.get(&p).map(|&i| (i, p)))
1097                .collect();
1098            let text = inner
1099                .iter()
1100                .map(|&(_, p)| project_paragraph(dom, p).text)
1101                .collect::<Vec<_>>()
1102                .join("\n");
1103            (inner.into_iter().map(|(i, _)| i).collect(), text)
1104        }
1105        (None, None) => (Vec::new(), String::new()),
1106    };
1107    ContentControl {
1108        id,
1109        tag: val(&W::name("tag")),
1110        alias: val(&W::name("alias")),
1111        kind: kind.to_string(),
1112        text,
1113        paragraph_ids: paragraph_ids
1114            .into_iter()
1115            .map(|i| crate::ids::paragraph_id("body", i))
1116            .collect(),
1117        locked,
1118        choices,
1119        checked,
1120        placeholder,
1121    }
1122}
1123
1124/// `1`, `true` and `on` are set; anything else is clear.
1125fn on_off(value: &str) -> bool {
1126    matches!(value, "1" | "true" | "on")
1127}
1128
1129/// `w:sdtPr` children that are properties, not the control's type.
1130const SDT_PROPERTIES: &[&str] = &[
1131    "rPr",
1132    "alias",
1133    "tag",
1134    "id",
1135    "lock",
1136    "placeholder",
1137    "temporary",
1138    "showingPlcHdr",
1139    "dataBinding",
1140    "label",
1141    "tabIndex",
1142];
1143
1144/// The control's type from its `w:sdtPr` (see [`ContentControl::kind`]).
1145fn control_kind(dom: &Dom, pr: NodeId) -> &'static str {
1146    for child in dom.elements(pr, None) {
1147        let Some(name) = dom.name(child) else {
1148            continue;
1149        };
1150        let (ns, local) = (name.namespace_name(), name.local_name());
1151        let kind = if ns == W::URI {
1152            match local {
1153                "text" => "text",
1154                "richText" => "rich_text",
1155                "dropDownList" => "drop_down",
1156                "comboBox" => "combo_box",
1157                "date" => "date",
1158                "picture" => "picture",
1159                "group" => "group",
1160                "docPartObj" | "docPartList" => "building_block",
1161                "citation" => "citation",
1162                "bibliography" => "bibliography",
1163                "equation" => "equation",
1164                local if SDT_PROPERTIES.contains(&local) => continue,
1165                _ => "unknown",
1166            }
1167        } else if ns == W14::URI {
1168            match local {
1169                "checkbox" => "checkbox",
1170                _ => continue,
1171            }
1172        } else if ns == W15::URI {
1173            match local {
1174                "repeatingSection" | "repeatingSectionItem" => "repeating",
1175                _ => continue,
1176            }
1177        } else {
1178            "unknown"
1179        };
1180        return kind;
1181    }
1182    "rich_text"
1183}
1184
1185/// A header, footer or notes part's paragraphs, separator notes left out.
1186#[doc(hidden)]
1187pub fn story_paragraph_nodes(dom: &Dom, root: NodeId) -> Vec<NodeId> {
1188    body_paragraph_nodes(dom, root)
1189        .into_iter()
1190        .filter(|&p| {
1191            !dom.ancestors(p, None).into_iter().any(|a| {
1192                (dom.name_is(a, &W::footnote()) || dom.name_is(a, &W::endnote()))
1193                    && matches!(
1194                        dom.attribute(a, &W::type_()),
1195                        Some("separator" | "continuationSeparator" | "continuationNotice")
1196                    )
1197            })
1198        })
1199        .collect()
1200}
1201
1202fn body_paragraphs(dom: &Dom, body: NodeId) -> Vec<Paragraph> {
1203    paragraphs_of(dom, body_paragraph_nodes(dom, body), BODY_STORY)
1204}
1205
1206fn paragraphs_of(dom: &Dom, nodes: Vec<NodeId>, story: &str) -> Vec<Paragraph> {
1207    nodes
1208        .into_iter()
1209        .enumerate()
1210        .map(|(index, p)| {
1211            let projection = project_paragraph(dom, p);
1212            let ppr = dom.element(p, &W::p_pr());
1213            let style = ppr
1214                .and_then(|ppr| dom.element(ppr, &W::p_style()))
1215                .and_then(|s| dom.attribute(s, &W::val()))
1216                .map(str::to_string);
1217            let numbered = ppr.is_some_and(|ppr| dom.element(ppr, &W::num_pr()).is_some());
1218            Paragraph {
1219                index,
1220                id: crate::ids::paragraph_id(story, index),
1221                text: projection.text,
1222                style,
1223                numbered,
1224                in_table: has_ancestor(dom, p, &W::tc()),
1225                page_break: projection.page_break,
1226                runs: projection.spans,
1227                limitations: projection.limitations.into_iter().collect(),
1228            }
1229        })
1230        .collect()
1231}
1232
1233/// What one visible piece of paragraph text maps back to.
1234#[derive(Clone, Debug, PartialEq, Eq)]
1235#[doc(hidden)]
1236pub enum Piece {
1237    /// A `w:t` element and the `w:r` that owns it.
1238    Text { t: NodeId, run: NodeId },
1239    /// A non-text run child projected as one char (`w:tab`, `w:br`, ...).
1240    Glyph { element: NodeId, run: NodeId },
1241}
1242
1243/// One projected segment: `text[start..end]` (bytes) comes from `piece`.
1244#[derive(Clone, Debug, PartialEq, Eq)]
1245#[doc(hidden)]
1246pub struct Segment {
1247    pub start: usize,
1248    pub end: usize,
1249    pub piece: Piece,
1250    /// The run is a direct child of the paragraph (editable position).
1251    pub direct: bool,
1252}
1253
1254/// Visible projection of one paragraph, with the segment map edits need.
1255#[derive(Clone, Debug, Default, PartialEq, Eq)]
1256#[doc(hidden)]
1257pub struct Projection {
1258    pub text: String,
1259    pub segments: Vec<Segment>,
1260    pub(crate) spans: Vec<Span>,
1261    pub(crate) page_break: bool,
1262    pub limitations: BTreeSet<String>,
1263    /// Byte offsets of complex-field `w:fldChar` markers. A field with an
1264    /// empty result adds no text, so its markers are the only trace of it.
1265    pub field_marks: Vec<usize>,
1266}
1267
1268#[derive(Clone, Debug, Default, PartialEq, Eq)]
1269struct Format {
1270    bold: bool,
1271    italic: bool,
1272    underline: bool,
1273    highlight: Option<String>,
1274}
1275
1276/// Project one `w:p` (see module docs for the rules).
1277#[doc(hidden)]
1278pub fn project_paragraph(dom: &Dom, paragraph: NodeId) -> Projection {
1279    let mut projection = Projection::default();
1280    let mut formats: Vec<(usize, usize, Format)> = Vec::new();
1281    let mut fields = 0;
1282    walk_container(
1283        dom,
1284        paragraph,
1285        true,
1286        &mut fields,
1287        &mut projection,
1288        &mut formats,
1289    );
1290    projection.spans = merge_spans(&projection.text, formats);
1291    projection
1292}
1293
1294/// Project the inline content of any container (a run-level `w:sdtContent`)
1295/// with the paragraph rules.
1296pub(crate) fn project_container(dom: &Dom, container: NodeId) -> Projection {
1297    let mut projection = Projection::default();
1298    let mut formats: Vec<(usize, usize, Format)> = Vec::new();
1299    let mut fields = 0;
1300    walk_container(
1301        dom,
1302        container,
1303        false,
1304        &mut fields,
1305        &mut projection,
1306        &mut formats,
1307    );
1308    projection.spans = merge_spans(&projection.text, formats);
1309    projection
1310}
1311
1312/// `fields` counts the complex fields open at this point of the paragraph:
1313/// their `begin`/`end` runs are siblings of the result runs, so a result run
1314/// is direct by position yet belongs to the field.
1315fn walk_container(
1316    dom: &Dom,
1317    container: NodeId,
1318    direct: bool,
1319    fields: &mut usize,
1320    out: &mut Projection,
1321    formats: &mut Vec<(usize, usize, Format)>,
1322) {
1323    for child in dom.elements(container, None) {
1324        let Some(name) = dom.name(child) else {
1325            continue;
1326        };
1327        let ns = name.namespace_name();
1328        let local = name.local_name();
1329        if ns == MC::URI {
1330            out.limitations.insert("alternate_content".into());
1331            if local == "AlternateContent"
1332                && let Some(choice) = dom.element(child, &MC::name("Choice"))
1333            {
1334                walk_container(dom, choice, false, fields, out, formats);
1335            }
1336            continue;
1337        }
1338        if ns != W::URI {
1339            out.limitations.insert(format!("unknown:{local}"));
1340            continue;
1341        }
1342        match local {
1343            "pPr" | "proofErr" | "bookmarkStart" | "bookmarkEnd" | "commentRangeStart"
1344            | "commentRangeEnd" | "permStart" | "permEnd" | "moveFromRangeStart"
1345            | "moveFromRangeEnd" | "moveToRangeStart" | "moveToRangeEnd" => {}
1346            "del" | "moveFrom" => {
1347                out.limitations.insert("revision".into());
1348            }
1349            "ins" | "moveTo" => {
1350                out.limitations.insert("revision".into());
1351                walk_container(dom, child, false, fields, out, formats);
1352            }
1353            "r" => walk_run(dom, child, direct, fields, out, formats),
1354            "hyperlink" => {
1355                out.limitations.insert("hyperlink".into());
1356                walk_container(dom, child, false, fields, out, formats);
1357            }
1358            "fldSimple" => {
1359                out.limitations.insert("field".into());
1360                walk_container(dom, child, false, fields, out, formats);
1361            }
1362            "sdt" => {
1363                out.limitations.insert("content_control".into());
1364                if let Some(content) = dom.element(child, &W::sdt_content()) {
1365                    walk_container(dom, content, false, fields, out, formats);
1366                }
1367            }
1368            "smartTag" | "customXml" | "dir" | "bdo" => {
1369                walk_container(dom, child, false, fields, out, formats);
1370            }
1371            _ => {
1372                out.limitations.insert(format!("unknown:{local}"));
1373            }
1374        }
1375    }
1376}
1377
1378fn walk_run(
1379    dom: &Dom,
1380    run: NodeId,
1381    direct: bool,
1382    fields: &mut usize,
1383    out: &mut Projection,
1384    formats: &mut Vec<(usize, usize, Format)>,
1385) {
1386    let format = run_format(dom, run);
1387    let start = out.text.len();
1388    for child in dom.elements(run, None) {
1389        let Some(name) = dom.name(child) else {
1390            continue;
1391        };
1392        // Word's text boxes and shapes sit in a run as `mc:AlternateContent`:
1393        // the same construct `walk_container` names.
1394        if name.namespace_name() == MC::URI {
1395            out.limitations.insert("alternate_content".into());
1396            if ["drawing", "pict", "object"]
1397                .iter()
1398                .any(|local| !dom.descendants(child, Some(&W::name(local))).is_empty())
1399            {
1400                out.limitations.insert("drawing".into());
1401            }
1402            if holds_text_box(dom, child) {
1403                out.limitations.insert("text_box_omitted".into());
1404            }
1405            continue;
1406        }
1407        if name.namespace_name() != W::URI {
1408            out.limitations
1409                .insert(format!("unknown:{}", name.local_name()));
1410            continue;
1411        }
1412        let direct = direct && *fields == 0;
1413        let glyph = |out: &mut Projection, ch: char| {
1414            let s = out.text.len();
1415            out.text.push(ch);
1416            out.segments.push(Segment {
1417                start: s,
1418                end: out.text.len(),
1419                piece: Piece::Glyph {
1420                    element: child,
1421                    run,
1422                },
1423                direct,
1424            });
1425        };
1426        match name.local_name() {
1427            "t" => {
1428                let s = out.text.len();
1429                let value = dom.value_str(child);
1430                out.text.push_str(&value);
1431                out.segments.push(Segment {
1432                    start: s,
1433                    end: out.text.len(),
1434                    piece: Piece::Text { t: child, run },
1435                    direct,
1436                });
1437            }
1438            "tab" | "ptab" => glyph(out, '\t'),
1439            "cr" => glyph(out, '\n'),
1440            "br" => match dom.attribute(child, &W::type_()) {
1441                Some("page") => out.page_break = true,
1442                Some("column") => {
1443                    out.limitations.insert("column_break".into());
1444                }
1445                _ => glyph(out, '\n'),
1446            },
1447            "noBreakHyphen" => glyph(out, '\u{2011}'),
1448            "softHyphen" => glyph(out, '\u{00ad}'),
1449            "sym" => {
1450                out.limitations.insert("sym".into());
1451                glyph(out, '\u{fffc}');
1452            }
1453            "fldChar" => {
1454                out.limitations.insert("field".into());
1455                out.field_marks.push(out.text.len());
1456                match dom.attribute(child, &W::name("fldCharType")) {
1457                    Some("begin") => *fields += 1,
1458                    Some("end") => *fields = fields.saturating_sub(1),
1459                    _ => {}
1460                }
1461            }
1462            "drawing" | "pict" | "object" => {
1463                out.limitations.insert("drawing".into());
1464                if holds_text_box(dom, child) {
1465                    out.limitations.insert("text_box_omitted".into());
1466                }
1467            }
1468            "footnoteReference" | "endnoteReference" => {
1469                out.limitations.insert("note_reference".into());
1470            }
1471            "rPr"
1472            | "instrText"
1473            | "delText"
1474            | "delInstrText"
1475            | "lastRenderedPageBreak"
1476            | "commentReference"
1477            | "annotationRef"
1478            | "footnoteRef"
1479            | "endnoteRef"
1480            | "separator"
1481            | "continuationSeparator"
1482            | "dayShort"
1483            | "dayLong"
1484            | "monthShort"
1485            | "monthLong"
1486            | "yearShort"
1487            | "yearLong"
1488            | "pgNum" => {}
1489            other => {
1490                out.limitations.insert(format!("unknown:{other}"));
1491            }
1492        }
1493    }
1494    if out.text.len() > start {
1495        formats.push((start, out.text.len(), format));
1496    }
1497}
1498
1499fn run_format(dom: &Dom, run: NodeId) -> Format {
1500    let Some(rpr) = dom.element(run, &W::r_pr()) else {
1501        return Format::default();
1502    };
1503    let on = |local: &str| -> bool {
1504        dom.element(rpr, &W::name(local))
1505            .is_some_and(|el| !matches!(dom.attribute(el, &W::val()), Some("false" | "0" | "off")))
1506    };
1507    let underline = dom
1508        .element(rpr, &W::name("u"))
1509        .is_some_and(|u| dom.attribute(u, &W::val()).is_none_or(|v| v != "none"));
1510    let highlight = dom
1511        .element(rpr, &W::name("highlight"))
1512        .and_then(|h| dom.attribute(h, &W::val()))
1513        .filter(|v| *v != "none")
1514        .map(str::to_string);
1515    Format {
1516        bold: on("b"),
1517        italic: on("i"),
1518        underline,
1519        highlight,
1520    }
1521}
1522
1523fn merge_spans(text: &str, formats: Vec<(usize, usize, Format)>) -> Vec<Span> {
1524    let mut merged: Vec<(usize, usize, Format)> = Vec::new();
1525    for (start, end, format) in formats {
1526        if let Some(last) = merged.last_mut()
1527            && last.1 == start
1528            && last.2 == format
1529        {
1530            last.1 = end;
1531        } else {
1532            merged.push((start, end, format));
1533        }
1534    }
1535    let char_at = |byte: usize| text[..byte].chars().count();
1536    merged
1537        .into_iter()
1538        .map(|(start, end, format)| Span {
1539            start: char_at(start),
1540            end: char_at(end),
1541            bold: format.bold,
1542            italic: format.italic,
1543            underline: format.underline,
1544            highlight: format.highlight,
1545        })
1546        .collect()
1547}
1548
1549#[cfg(test)]
1550#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1551mod tests {
1552    use super::*;
1553
1554    #[test]
1555    fn sha256_is_lowercase_hex_of_the_bytes() {
1556        assert_eq!(
1557            source_sha256(b"abc"),
1558            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
1559        );
1560    }
1561
1562    #[test]
1563    fn markdown_moves_edge_whitespace_outside_emphasis() {
1564        let span = Span {
1565            start: 0,
1566            end: 0,
1567            bold: true,
1568            italic: true,
1569            underline: false,
1570            highlight: Some("yellow".into()),
1571        };
1572        assert_eq!(emphasize("  Title ", &span), "  ==***Title***== ");
1573        assert_eq!(emphasize("   ", &span), "   ");
1574        let plain = Span {
1575            bold: false,
1576            italic: false,
1577            highlight: None,
1578            ..span
1579        };
1580        assert_eq!(emphasize(" x ", &plain), " x ");
1581    }
1582
1583    #[test]
1584    fn markdown_of_empty_and_styled_paragraphs() {
1585        let p = |id: &str, text: &str, style: Option<&str>| Paragraph {
1586            index: 0,
1587            id: id.into(),
1588            text: text.into(),
1589            style: style.map(str::to_string),
1590            numbered: false,
1591            in_table: false,
1592            page_break: false,
1593            runs: Vec::new(),
1594            limitations: Vec::new(),
1595        };
1596        let md = render_markdown(&[p("p0", "Scope", Some("Heading1")), p("p1", "", None)]);
1597        assert_eq!(md, "[p0 Heading1] Scope\n\n[p1]\n");
1598        assert_eq!(render_markdown(&[]), "");
1599    }
1600
1601    #[test]
1602    fn spans_merge_only_adjacent_equal_formatting() {
1603        let bold = Format {
1604            bold: true,
1605            ..Format::default()
1606        };
1607        let spans = merge_spans(
1608            "abcdef",
1609            vec![
1610                (0, 2, bold.clone()),
1611                (2, 4, bold.clone()),
1612                (4, 6, Format::default()),
1613            ],
1614        );
1615        assert_eq!(spans.len(), 2);
1616        assert_eq!((spans[0].start, spans[0].end, spans[0].bold), (0, 4, true));
1617        assert_eq!((spans[1].start, spans[1].end, spans[1].bold), (4, 6, false));
1618    }
1619}
1620
1621#[cfg(test)]
1622#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1623mod span_branch_tests {
1624    use super::*;
1625
1626    fn format(bold: bool, highlight: Option<&str>) -> Format {
1627        Format {
1628            bold,
1629            italic: false,
1630            underline: false,
1631            highlight: highlight.map(str::to_string),
1632        }
1633    }
1634
1635    #[test]
1636    fn touching_equal_formats_merge_and_gaps_split() {
1637        let text = "ab cd ef";
1638        let spans = merge_spans(
1639            text,
1640            vec![
1641                (0, 1, format(true, None)),
1642                (1, 2, format(true, None)),
1643                (3, 5, format(true, None)),
1644            ],
1645        );
1646        assert_eq!(
1647            spans.iter().map(|s| (s.start, s.end)).collect::<Vec<_>>(),
1648            [(0, 2), (3, 5)]
1649        );
1650    }
1651
1652    #[test]
1653    fn highlight_alone_is_marked_and_space_stays_outside() {
1654        let span = merge_spans("x", vec![(0, 1, format(false, Some("yellow")))]).remove(0);
1655        assert_eq!(emphasize(" lit ", &span), " ==lit== ");
1656        let plain = merge_spans("x", vec![(0, 1, format(false, None))]).remove(0);
1657        assert_eq!(emphasize(" lit ", &plain), " lit ");
1658        assert_eq!(emphasize("  ", &span), "  ");
1659    }
1660}