Skip to main content

docling_core/
document.rs

1//! The unified document representation.
2
3use crate::markdown::{to_markdown, to_markdown_images};
4use crate::ImageMode;
5
6/// The unified, format-agnostic document produced by every backend.
7///
8/// This is the heart of docling: backends parse their source format into a
9/// `DoclingDocument`, and serializers turn it back into Markdown, HTML, JSON,
10/// etc. Phase 0 uses a flat sequence of [`Node`]s; the production schema will
11/// match docling-core's body-tree-with-references layout.
12#[derive(Debug, Clone, PartialEq)]
13pub struct DoclingDocument {
14    /// Logical document name (usually the input file stem).
15    pub name: String,
16    /// Top-level content, in reading order.
17    pub nodes: Vec<Node>,
18    /// Default Markdown export mode for [`Self::export_to_markdown`]. `false`
19    /// (the default) reproduces docling's legacy output byte-for-byte; `true`
20    /// emits cleaner, more conformant Markdown. Set by `DocumentConverter`.
21    pub strict_markdown: bool,
22    /// Emit tables in the compact `| a | b |` / `| - | - |` form rather than
23    /// docling-core's width-padded GitHub serializer. The PDF backend sets this
24    /// (its committed groundtruth corpus predates the padded serializer); DOCX/HTML
25    /// leave it `false` to match current published docling.
26    pub compact_tables: bool,
27    /// Render a picture's author-written alt text (#676: the `descr` /
28    /// `title` of an OOXML picture's non-visual properties, carried as a
29    /// [`PictureDescription`] whose provenance is
30    /// [`PictureDescription::ALT_TEXT`]) in the Markdown and HTML exports
31    /// (the `![alt](…)` of an image line or the line above a placeholder;
32    /// the `<img alt>` and the description text). `false` (the default)
33    /// keeps it to the JSON (and DCLX) output, so the default Markdown and
34    /// HTML stay byte-for-byte docling's; strict Markdown renders it
35    /// regardless. Set by `DocumentConverter::picture_alt_text`.
36    pub picture_alt_text: bool,
37    /// What the file says about itself (#679): an EPUB's Dublin Core, an
38    /// Office package's properties, a photo's EXIF, an audio file's tags —
39    /// see [`crate::metadata`]. Read by the converter when
40    /// [`metadata_output`](Self::metadata_output) asks for it (a document
41    /// read from docling JSON keeps the `metadata` the JSON carried).
42    pub metadata: crate::metadata::DocumentMetadata,
43    /// Where [`metadata`](Self::metadata) goes in the exports: nowhere (the
44    /// default — every export stays docling's), the JSON's `metadata`
45    /// object, or that and YAML front matter at the top of the Markdown.
46    /// Set by `DocumentConverter::metadata_output`.
47    pub metadata_output: crate::metadata::MetadataOutput,
48    /// Text the Markdown export inserts between two pages — docling-core's
49    /// `MarkdownParams.page_break_placeholder` (e.g. `"<!-- page break -->"`).
50    /// `None` (the default) omits page breaks from Markdown, as docling does.
51    /// Set by `DocumentConverter::page_break_placeholder`. See
52    /// [`crate::markdown`] for where a break lands (only between two rendered
53    /// blocks that sit on different pages, never leading or trailing).
54    pub page_break_placeholder: Option<String>,
55    /// Hyperlinks recovered from the source, as `(anchor_text, href)` pairs in
56    /// document order. docling's standard pipeline drops PDF link annotations, so
57    /// these are rendered as Markdown `[anchor](href)` **only in strict mode**
58    /// (legacy/docling output is left byte-for-byte unchanged). The PDF backend
59    /// populates this from pdfium link annotations; other backends leave it empty.
60    pub links: Vec<(String, String)>,
61    /// Conversion-confidence report (#183), populated by the PDF/image ML
62    /// pipeline; `None` for declarative conversions. Deliberately **not**
63    /// part of any document export (docling keeps it on the conversion
64    /// result, outside the document schema) — docling-serve surfaces it in
65    /// the HTTP response instead.
66    pub confidence: Option<crate::confidence::ConfidenceReport>,
67    /// docling's item tree, when the backend built one (the HTML backend
68    /// does): the JSON export serializes it instead of deriving a tree from
69    /// `nodes`, so the JSON carries upstream's exact parent/child structure,
70    /// item numbering, inline groups, formatting and content layers. Every
71    /// other serializer reads `nodes`. See [`crate::tree`].
72    pub tree: Option<crate::tree::ItemTree>,
73    /// Rendered page images by 1-based page number — docling's
74    /// `PageItem.image`, filled by the PDF/image pipeline only when page
75    /// images are requested (docling's `generate_page_images`, #520). The
76    /// JSON export writes each as the page's `image`, so docling-core's
77    /// `TableItem.get_image` / `FormulaItem.get_image` can crop from it.
78    /// Empty otherwise; no other export reads it.
79    pub page_images: std::collections::BTreeMap<usize, PictureImage>,
80    /// What the reader ran into and read around (#912): a limit it hit —
81    /// an HTML page nested past `DOCLING_RS_MAX_HTML_DEPTH`, read as flat
82    /// text with no item tree and no source blocks — named, with the
83    /// effective limit, so a caller sees why the document lacks what it
84    /// lacks instead of an unexplained success. The converter reports each
85    /// as a `partial_success` error item.
86    pub notices: Vec<Notice>,
87}
88
89/// Something the reader did instead of what it does by default (#912),
90/// with the reason — see [`DoclingDocument::notices`].
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct Notice {
93    pub kind: NoticeKind,
94    /// One line: what was hit, the effective limit, what the document
95    /// lacks because of it.
96    pub message: String,
97}
98
99/// What a [`Notice`] is about.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub enum NoticeKind {
102    /// The source nests deeper than the cap `variable` sets (its effective
103    /// value `limit`): it was read as flat text — the content is there,
104    /// the item tree and the source blocks are not.
105    DepthLimit {
106        /// The environment variable that sets the cap.
107        variable: &'static str,
108        limit: usize,
109    },
110}
111
112impl Notice {
113    /// A [`NoticeKind::DepthLimit`] notice for `what` (the format read).
114    pub fn depth_limit(what: &str, variable: &'static str, limit: usize) -> Self {
115        Notice {
116            kind: NoticeKind::DepthLimit { variable, limit },
117            message: format!(
118                "{what} nested deeper than {limit} elements ({variable}): read as flat text, \
119                 without the item tree and the source blocks"
120            ),
121        }
122    }
123}
124
125/// A single piece of document content.
126#[derive(Debug, Clone, PartialEq)]
127pub enum Node {
128    /// A heading. `level` is 1-6.
129    Heading { level: u8, text: String },
130    /// A run of body text.
131    Paragraph { text: String },
132    /// A form checkbox (docling's `checkbox_selected`/`checkbox_unselected`): its
133    /// clean label `text` with the checked state. DocLang emits a `<checkbox>`
134    /// element head; Markdown/JSON render the task-list form (`- [x] `/`- [ ] `).
135    CheckboxItem { checked: bool, text: String },
136    /// A single list item at the given nesting `level` (0 = top). For ordered
137    /// items, `number` is the display number (honoring the list's `start`); it
138    /// is unused for unordered items. `first_in_list` marks the first item of a
139    /// list so the serializer can blank-line-separate adjacent sibling lists.
140    ///
141    /// `marker` is the DocLang enumeration marker (`"1."`, `"1.1."`, …) when the
142    /// backend provides one — HTML and DOCX set it for enumerated items, so
143    /// DocLang emits `<ldiv><marker>…</marker></ldiv>`; Markdown and the other
144    /// declarative backends leave it `None`, giving a bare `<ldiv/>` (matching
145    /// docling, whose Markdown backend passes no marker).
146    ListItem {
147        ordered: bool,
148        number: u64,
149        first_in_list: bool,
150        text: String,
151        level: u8,
152        marker: Option<String>,
153        /// Optional layout provenance (`x0,y0,x1,y1`, normalized to 0–511): the
154        /// four DocLang `<location>` values emitted inside the `<list>` right
155        /// after the item's `<ldiv>`. Set only by backends with real geometry
156        /// (e.g. PPTX shapes); `None` for the declarative backends. Kept on the
157        /// item itself (rather than a [`Node::Located`] wrapper) so consecutive
158        /// items still group into one `<list>`.
159        location: Option<[u16; 4]>,
160        /// DocLang-only override for items whose DocLang form diverges from their
161        /// flat Markdown `text`. Markdown/JSON always render the fields above; the
162        /// DocLang serializer, when this is `Some`, takes the list kind, marker,
163        /// and content from here instead. Used for docx multilevel numbering
164        /// (Markdown shows `- 1.1. x`, DocLang an ordered `<marker>1.1.</marker>`
165        /// with clean text) and inline equations/formatting in list items.
166        dclx: Option<ListItemDclx>,
167        /// JSON-only: the item as docling's `ListItemMarkerProcessor` leaves
168        /// it on a page pipeline (PDF) — `orig` with the marker, `text`
169        /// without it, the marker itself and whether it enumerates. Markdown
170        /// and DocLang keep reading the fields above, whose spelling follows
171        /// docling-core's serializers (`- [3] text` is a bullet item there).
172        /// `None` for every other backend: the JSON then writes `text` twice
173        /// and `-` or `N.` as before.
174        split: Option<Box<ListItemSplit>>,
175        /// The item's hyperlink target, when its content is a link — docling's
176        /// HTML backend emits it as an `<href uri=…/>` in the item head, and the
177        /// anchor's Markdown link markup is stripped from the rendered content.
178        /// `None` for a plain item; ignored by Markdown/JSON.
179        href: Option<String>,
180        /// Non-body content layer (docling's HTML site chrome before the first
181        /// heading → `furniture`). DocLang emits a `<layer value=…/>` in the item
182        /// head; Markdown/JSON drop a non-body item entirely.
183        layer: Option<ContentLayer>,
184    },
185    /// A fenced code block.
186    Code {
187        language: Option<String>,
188        text: String,
189        /// The original (pre-enrichment) text when the CodeFormula model
190        /// rewrote `text`: docling keeps the raw extraction in the JSON `orig`
191        /// field while `text` carries the model output. `None` → `orig == text`.
192        orig: Option<String>,
193        /// A line-preserving rendering, when the backend can reconstruct one
194        /// but docling's own output for the format cannot. The PDF pipeline
195        /// sets it (docling-parse joins code lines with single spaces, so
196        /// `text` carries that flat docling-parity form): **strict** Markdown
197        /// prefers `pretty`, every byte-conformance surface (legacy Markdown,
198        /// JSON, DocLang, chunks) serializes `text`.
199        pretty: Option<String>,
200    },
201    /// A table. The first row is treated as the header.
202    Table(Table),
203    /// A picture/figure, with an optional caption and (when a backend extracts
204    /// it) the embedded image itself.
205    Picture {
206        caption: Option<String>,
207        /// Hyperlink annotation on the caption (docling's caption text item
208        /// `hyperlink`): the HTML backend sets it when an `<a href>` wraps the
209        /// image whose `alt` became the caption. DocLang emits the block-form
210        /// `<caption>` with an `<href uri=…/>` head; JSON puts `hyperlink` on
211        /// the caption item; Markdown and LaTeX print the plain caption text,
212        /// as docling does.
213        caption_href: Option<String>,
214        image: Option<PictureImage>,
215        /// DocumentPictureClassifier predictions (all classes, descending
216        /// confidence), when the picture-classification enrichment ran.
217        /// Serialized as docling's `classification` annotation + `meta` field
218        /// on the JSON picture item; Markdown/DocLang output is unaffected.
219        classification: Option<Vec<PictureClass>>,
220        /// Text read off the embedded image by the picture-OCR enrichment
221        /// (#645) — docling's `PictureDescriptionData` annotation /
222        /// `meta.description`, which is where upstream's picture-description
223        /// models (VLM captioning) put their text too. JSON and DCLX carry it
224        /// structurally; Markdown prints it between the caption and the
225        /// image placeholder, where docling's picture serializer renders
226        /// annotations. `None` when the enrichment did not run or read no
227        /// text, so every default export stays unchanged.
228        description: Option<PictureDescription>,
229        /// Where the caption item hangs in the JSON tree (#390); see
230        /// [`CaptionParent`]. Markdown, DocLang and LaTeX ignore it.
231        caption_parent: CaptionParent,
232        /// The caption's own box on the picture's page (0–511 grid, like
233        /// [`Node::Located`]) — the PDF pipeline's caption layout region. The
234        /// JSON export writes it as the caption item's `prov` (#609), as
235        /// docling's `ReadingOrderModel._add_caption_or_footnote` does; `None`
236        /// (every declarative backend) leaves the caption without one.
237        caption_location: Option<[u16; 4]>,
238    },
239    /// A display-math formula item decoded by the CodeFormula enrichment:
240    /// `latex` is the model's LaTeX (no `$$` wrapping), `orig` the raw glyph
241    /// text extracted from the PDF. Markdown renders `$$latex$$`; JSON emits a
242    /// `formula` text item (docling's un-enriched pipeline instead emits a
243    /// placeholder paragraph — see the PDF assembler).
244    Formula {
245        latex: String,
246        orig: String,
247        location: Option<[u16; 4]>,
248    },
249    /// A standalone caption item (docling's `DocItemLabel.CAPTION` text that
250    /// no picture or table claims): the HTML backend emits a `<figure>`'s
251    /// `<figcaption>` this way when the figure produced no picture and its
252    /// first item is not a table (docling#4050). `href` is the caption's
253    /// hyperlink annotation (the first link inside the figcaption); Markdown
254    /// renders it as `[text](href)`, JSON puts `hyperlink` on the caption
255    /// item, DocLang emits the block-form `<caption>` with an `<href>` head.
256    Caption { text: String, href: Option<String> },
257    /// A body text item with a docling label of its own and an optional
258    /// hyperlink — the PDF pipeline's `footnote` regions, whose item docling
259    /// keeps as a `footnote` text with the link annotation covering it as its
260    /// `hyperlink` (`PageAssembleModel._match_hyperlink`). The JSON writes
261    /// exactly that (label, raw text, `hyperlink`); every other serializer
262    /// renders it as the paragraph [`Self::labeled_markdown`] spells —
263    /// docling's Markdown wraps a linked item's whole text, `[text](uri)`.
264    LabeledText {
265        label: String,
266        text: String,
267        href: Option<String>,
268    },
269    /// A chart (docling's `PictureItem` classified as a chart, carrying a
270    /// `PictureTabularChartData` annotation). Markdown and JSON render it exactly
271    /// like a [`Node::Picture`] placeholder (an `<!-- image -->` / `picture`
272    /// item); the DocLang serializer emits `<picture class="chart">` with a
273    /// `<label value="{kind}"/>` and the data `table` as a `<tabular>`.
274    Chart {
275        /// docling's classification label, e.g. `bar_chart`, `line_chart`.
276        kind: String,
277        /// The chart's data grid (row 0 is the header band).
278        table: Table,
279        /// The chart title (docling's caption item on the picture).
280        caption: Option<String>,
281        /// DocLang `<location>` provenance for the picture element.
282        location: Option<[u16; 4]>,
283    },
284    /// A logical grouping of child nodes (e.g. a list, a section, a spreadsheet
285    /// sheet). `name` is docling's group name when it differs from the label —
286    /// an xlsx sheet group is `label: "sheet"`, `name: Some("Sheet1")`. `layer`
287    /// puts the group *and* everything it contains on a non-body content layer
288    /// (a hidden sheet is `invisible`), which is how the serializers that only
289    /// render body content know to skip it; DocLang stamps each child with the
290    /// layer token, exactly as a [`Node::Furniture`] wrapper on each would.
291    /// DocLang has no group element, so a group is transparent there.
292    Group {
293        label: String,
294        name: Option<String>,
295        layer: Option<ContentLayer>,
296        children: Vec<Node>,
297    },
298    /// A form key-value region (docling's `field_region`): a set of form fields,
299    /// each pairing an optional marker, key, and value. Backends detect these
300    /// from form structure (e.g. HTML's `keyN` / `keyN_valueM` / `keyN_marker`
301    /// `id`-convention); the serializers render each item's parts as separate
302    /// labelled texts (`marker` / `field_key` / `field_value`).
303    FieldRegion { items: Vec<FieldItem> },
304    /// docling's `KeyValueItem`: a graph of key and value cells and the links
305    /// between them (docling-core's `GraphData`). The XBRL backend builds one
306    /// from an instance's numeric facts and the presentation and calculation
307    /// hierarchies of its taxonomy. Only the JSON export carries the graph:
308    /// docling's Markdown serializer has no rendering for the item and writes
309    /// its `<!-- missing-key-value-item -->` placeholder, which the Markdown
310    /// export reproduces; the other serializers omit it.
311    KeyValueGraph {
312        cells: Vec<GraphCell>,
313        links: Vec<GraphLink>,
314    },
315    /// Rich inline content — docling's `InlineGroup`: a run of styled text
316    /// segments that a backend captured with formatting (`<bold>`, `<italic>`,
317    /// `<underline>`, `<strikethrough>`, sub/superscript, inline `<code>`) the
318    /// flat Markdown text cannot represent. Markdown/JSON render this exactly
319    /// like `Paragraph { text: md_text }` (so their output is unchanged); the
320    /// DocLang serializer uses the structured `runs`. `unwrapped` is set when the
321    /// group's docling parent is a heading/text (no enclosing `<text>` wrapper).
322    InlineGroup {
323        unwrapped: bool,
324        runs: Vec<InlineRun>,
325        md_text: String,
326    },
327    /// A PDF text item whose superscripts and subscripts the opt-in
328    /// script-position stage marked (#1005, docling's `ScriptPositionModel`,
329    /// `script_position_options.enabled`). `inner` is the item — a paragraph
330    /// or a footnote — with its text already the runs' joined text (Markdown-
331    /// escaped, `E = mc2 in 1905.`): every serializer but JSON and DocLang
332    /// renders it as it is. The JSON writes docling's shape — the item with
333    /// an empty `text`, holding an inline group of the runs, each a text item
334    /// with `formatting.script` and the box of its own characters — and
335    /// DocLang writes the runs as an inline group.
336    ScriptText {
337        inner: Box<Node>,
338        runs: Vec<ScriptRun>,
339    },
340    /// A node in a non-body content layer — `furniture` (page headers/footers,
341    /// the HTML `<title>`, site navigation/chrome) or `notes` (docx comments).
342    /// Markdown and JSON omit these layers by default; DocLang renders the wrapped
343    /// node with a `<layer value="{layer}"/>` head.
344    Furniture {
345        layer: ContentLayer,
346        inner: Box<Node>,
347    },
348    /// One reviewer comment: docling's notes-layer `comment_section` group
349    /// holding a single text item. `name` is docling's own — `comment-{id}` for
350    /// a docx `w:comment`, `comment-{sheet}-{cell}` for a spreadsheet cell note.
351    /// JSON emits the group plus its notes-layer text; DocLang emits the flat
352    /// `<text><layer value="notes"/>…</text>` upstream writes (its DocLang
353    /// carries no group for comments); Markdown and LaTeX omit the notes layer.
354    ///
355    /// `refs_note_text` picks what a [`Node::Commented`] annotation points at,
356    /// mirroring an upstream asymmetry: docling-core's `add_comment` appends the
357    /// **note text**'s ref to each target (which is what the xlsx backend gets),
358    /// while the docx backend overwrites that with the **group**'s ref so a
359    /// comment's replies group together.
360    ///
361    /// `grouped` is whether docling wraps the note in a `comment_section`
362    /// group at all: the docx and spreadsheet backends do, while backends that
363    /// call docling-core's `add_comment` directly (Pages, #383) get a bare
364    /// notes-layer text item under the body — JSON then emits no group and
365    /// `name` is unused.
366    CommentSection {
367        name: String,
368        text: String,
369        refs_note_text: bool,
370        grouped: bool,
371    },
372    /// A body item annotated by reviewer comments: `comments` are indices into
373    /// the document's [`Node::CommentSection`] nodes, in document order. JSON
374    /// emits docling's `comments: [{"$ref": …}]` on the item, each ref pointing
375    /// where the section says (see [`Node::CommentSection::refs_note_text`]);
376    /// every other serializer renders `inner` unchanged.
377    Commented {
378        comments: Vec<usize>,
379        inner: Box<Node>,
380    },
381    /// A text node taken from a time-based track — an ASR segment (#614):
382    /// A link destination (#852: a `.doc` bookmark; the DOCX item tree
383    /// keeps its own, #849): the identifier the document's internal links
384    /// (`#id`) point at. Rendered by nothing but the JSON builder, which
385    /// hands it to the next text item for the Pandoc AST (`_anchors`).
386    Anchor { id: String },
387    /// docling's `TrackSource`. The JSON writes docling's ASR text item — `cue`
388    /// (the segment's words) as its text, `track` as its `source: [{"kind":
389    /// "track", …}]` — which the WebVTT export makes a cue of; every other
390    /// serializer renders `inner` (the `[time: start-end] words` paragraph)
391    /// unchanged.
392    Track {
393        track: crate::tree::TreeTrack,
394        cue: String,
395        inner: Box<Node>,
396    },
397    /// A node carrying layout provenance — the four DocLang `<location>` values
398    /// (`x0,y0,x1,y1`, normalized to 0–511) docling attaches to elements from
399    /// backends with real geometry (e.g. the slide shapes in PPTX). Markdown and
400    /// JSON render the wrapped node unchanged; DocLang emits the `<location>`
401    /// tokens as the element's first children.
402    Located {
403        location: [u16; 4],
404        inner: Box<Node>,
405    },
406    /// Exact page provenance for a backend whose geometry already *is* the
407    /// page's coordinate system — an XLSX item's cell-index box on its sheet,
408    /// which docling writes verbatim (`bbox` in a top-left origin, the
409    /// `charspan` the backend chose) and sizes the page from. The 0–511 grid
410    /// of a [`Node::Located`] cannot round-trip such integers exactly, so the
411    /// JSON export reads this wrapper; every other serializer renders `inner`
412    /// unchanged (DocLang keeps taking its `<location>` tokens from the grid).
413    Prov {
414        page_no: usize,
415        /// `[l, t, r, b]`, page units, top-left origin.
416        bbox: [f32; 4],
417        /// docling's `charspan` for the item (`[0, 0]` for an XLSX table).
418        charspan: [usize; 2],
419        /// The bbox's origin: docling's `BOTTOMLEFT` (a PDF page's
420        /// provenance, as a docling-JSON input carries it — #899) or
421        /// `TOPLEFT` (an XLSX sheet's cell box).
422        bottom_left: bool,
423        /// The item's creation rank among its siblings, when that differs
424        /// from the node order: docling numbers `#/tables/N` / `#/texts/N` /
425        /// `#/pictures/N` in the order it *creates* items (a sheet's tables,
426        /// then its images, then its charts) and only afterwards sorts the
427        /// container's children by position. The JSON export adds siblings in
428        /// this order and lays their refs out in node order; `None` when the
429        /// two orders coincide.
430        seq: Option<usize>,
431        inner: Box<Node>,
432    },
433    /// A PDF page header or footer (docling's `page_header`/`page_footer`
434    /// furniture): DocLang emits `<page_header>`/`<page_footer>` with a
435    /// `<layer value="furniture"/>` head, the four `<location>` tokens, then the
436    /// text. The JSON writes it as a body-parented `page_header`/`page_footer`
437    /// text item on the furniture layer; Markdown omits it.
438    PageFurniture {
439        footer: bool,
440        location: [u16; 4],
441        text: String,
442    },
443    /// A furniture-layer text item with an explicit docling label — a page
444    /// header / footer paragraph (`page_header` / `page_footer`) or a note
445    /// body (`footnote`) from a backend that builds no item tree (#535: the
446    /// Word 97 `.doc` stories). The JSON writes a body-parented item of that
447    /// label on the furniture layer; DocLang `<{label}>` with a `<layer
448    /// value="furniture"/>` head (docling-core's own shape); Markdown, LaTeX
449    /// and the chunker leave it out like any furniture.
450    FurnitureText { label: String, text: String },
451    /// The text a PDF picture contains, kept the way docling keeps it: every
452    /// regular layout cluster > 80 % inside a picture cluster is that
453    /// `PictureItem`'s child (`LayoutPostprocessor._set_cluster_children`,
454    /// `ReadingOrderModel._add_child_elements`). Emitted right after its
455    /// picture node. The JSON export writes these nodes as items parented to
456    /// that picture, after its caption; docling's Markdown and LaTeX picture
457    /// serializers print only the caption and the image, so every other
458    /// serializer skips it — except the Markdown export asked to
459    /// `traverse_pictures` ([`MarkdownExportOptions`], #599), which renders
460    /// them after the picture like upstream's item walk does.
461    PictureChildren(Vec<Node>),
462    /// A page boundary — docling's implicit page break between pages. The PPTX
463    /// backend emits one between consecutive slides. DocLang renders it as
464    /// `<page_break/>`; Markdown and JSON omit it (matching docling's default
465    /// exports, which carry page breaks only in the document model).
466    PageBreak,
467    /// A text item docling hangs in a *list group*, after the item before it
468    /// (an AsciiDoc paragraph still pending when a list opened is flushed into
469    /// the list's group): docling-core's list serializer prints it as one more
470    /// line of the list, indented to the group's depth `level` — or, `glue`,
471    /// when it is an inline group, appended to the line before it with no
472    /// separator at all. `text` is Markdown, like a paragraph's. Every other
473    /// serializer reads it as a paragraph.
474    ListText { level: u8, text: String, glue: bool },
475    /// An invisible page marker — the first node of every page the PDF paths
476    /// assemble: the 1-based page number and the page size in PDF points. It
477    /// carries exactly what the JSON export needs to populate docling's
478    /// `pages` map and to denormalize the 0–511 `<location>` grid back into
479    /// BOTTOMLEFT point bboxes for per-item `prov` (#171). Every other
480    /// serializer skips it, so Markdown / DocLang / DocTags output is
481    /// byte-for-byte unchanged.
482    PageInfo {
483        /// 1-based page number (0 = "not yet numbered": the assembler emits
484        /// the marker, the document-level collector stamps the real number).
485        page_no: usize,
486        /// Page width in PDF points.
487        width: f32,
488        /// Page height in PDF points.
489        height: f32,
490    },
491    /// A node docling keeps in the document model (and DocLang) but leaves out
492    /// of the Markdown and JSON exports — e.g. an ODF *presentation*'s pictures
493    /// and charts, which appear in the `.dclx` body but not in its `.md`/`.json`.
494    /// DocLang renders the wrapped node in place; Markdown and JSON skip it.
495    DoclangOnly(Box<Node>),
496    /// A verbatim plain-text dump: one text item holding text whose line
497    /// breaks are content (a nested table flattened to its cells' text, an
498    /// ODF text box's raw text). Markdown/JSON render it as one text block,
499    /// DocLang as one `<text>` whose `<content>` keeps the breaks.
500    TextDump(String),
501}
502
503/// One run of a [`Node::ScriptText`]: a piece of the item's text at one
504/// script position, with its provenance — one entry per page it is on.
505#[derive(Debug, Clone, PartialEq)]
506pub struct ScriptRun {
507    /// The run's raw text (not Markdown-escaped), its spaces included:
508    /// serializers join runs with nothing.
509    pub text: String,
510    pub script: Script,
511    /// The run's provenance, one per page, in text order.
512    pub prov: Vec<ScriptRunProv>,
513    /// The item's link, on its baseline runs (each linked run exports as a
514    /// link of its own, so a marker stays out of it).
515    pub hyperlink: Option<String>,
516}
517
518/// Where a [`ScriptRun`] sits on one page: docling's `ProvenanceItem` with a
519/// bottom-left-origin box.
520#[derive(Debug, Clone, Copy, PartialEq)]
521pub struct ScriptRunProv {
522    /// 1-based page number.
523    pub page_no: usize,
524    /// `[l, t, r, b]`, PDF points, bottom-left origin (`t > b`).
525    pub bbox: [f32; 4],
526    /// The run's characters on this page, as a span of its `text`.
527    pub charspan: [usize; 2],
528}
529
530/// Vertical text position of an [`InlineRun`] — docling's `Script`.
531#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
532pub enum Script {
533    #[default]
534    Baseline,
535    Sub,
536    Super,
537}
538
539/// One styled segment of a [`Node::InlineGroup`] — the docling.rs analogue of a
540/// `TextItem` inside an `InlineGroup`, carrying the ancestor formatting docling
541/// tracks. `text` is already whitespace-normalized/trimmed (one segment per
542/// source text node). A hyperlink is intentionally not stored: DocLang drops the
543/// target inside inline scope, keeping only the anchor text.
544#[derive(Debug, Clone, PartialEq, Eq, Default)]
545pub struct InlineRun {
546    pub text: String,
547    pub bold: bool,
548    pub italic: bool,
549    pub underline: bool,
550    pub strike: bool,
551    pub script: Script,
552    pub code: bool,
553    /// An inline equation (`text` holds LaTeX): DocLang renders `<formula>…`,
554    /// Markdown/JSON keep the `$…$` already baked into the group's `md_text`.
555    pub formula: bool,
556}
557
558/// A DocLang content layer other than the default `body` (see [`Node::Furniture`]).
559#[derive(Debug, Clone, Copy, PartialEq, Eq)]
560pub enum ContentLayer {
561    /// Page headers/footers, HTML `<title>`, site navigation/chrome.
562    Furniture,
563    /// Editorial notes (docx reviewer comments).
564    Notes,
565    /// Invisible content (hidden spreadsheet sheets).
566    Invisible,
567    /// Background content (watermarks): docling-core 2.99's `background`
568    /// layer, which DocLang has and an `invisible` item is written to
569    /// (docling-core#800) — read back from a DocLang document.
570    Background,
571}
572
573impl ContentLayer {
574    /// The `<layer value="…"/>` token value.
575    pub fn value(self) -> &'static str {
576        match self {
577            ContentLayer::Furniture => "furniture",
578            ContentLayer::Notes => "notes",
579            ContentLayer::Invisible => "invisible",
580            ContentLayer::Background => "background",
581        }
582    }
583}
584
585/// A set of content layers, `body` included — docling-core's
586/// `set[ContentLayer]` (`HTMLParams.layers`,
587/// `export_to_html(included_content_layers=…)`), where `body` is a member
588/// like any other. [`Default`] is docling's `DEFAULT_CONTENT_LAYERS`: body
589/// only, so an export built with it is unchanged from before layers could
590/// be chosen (#499).
591#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
592pub struct ContentLayers {
593    /// The main content (items without an explicit layer).
594    pub body: bool,
595    /// [`ContentLayer::Furniture`]: page headers/footers, navigation chrome.
596    pub furniture: bool,
597    /// [`ContentLayer::Notes`]: reviewer comments and other editorial notes.
598    pub notes: bool,
599    /// [`ContentLayer::Invisible`]: hidden content (hidden sheets, …).
600    pub invisible: bool,
601    /// [`ContentLayer::Background`]: background content (watermarks).
602    pub background: bool,
603}
604
605impl Default for ContentLayers {
606    fn default() -> Self {
607        Self::BODY
608    }
609}
610
611impl ContentLayers {
612    /// Body only — docling's `DEFAULT_CONTENT_LAYERS`.
613    pub const BODY: Self = Self {
614        body: true,
615        furniture: false,
616        notes: false,
617        invisible: false,
618        background: false,
619    };
620    /// Every layer — Python's `set(ContentLayer)`.
621    pub const ALL: Self = Self {
622        body: true,
623        furniture: true,
624        notes: true,
625        invisible: true,
626        background: true,
627    };
628    /// No layer at all (nothing renders); build a set from it with
629    /// [`with`](Self::with) / [`with_body`](Self::with_body).
630    pub const NONE: Self = Self {
631        body: false,
632        furniture: false,
633        notes: false,
634        invisible: false,
635        background: false,
636    };
637
638    /// The set plus `layer`.
639    pub const fn with(mut self, layer: ContentLayer) -> Self {
640        match layer {
641            ContentLayer::Furniture => self.furniture = true,
642            ContentLayer::Notes => self.notes = true,
643            ContentLayer::Invisible => self.invisible = true,
644            ContentLayer::Background => self.background = true,
645        }
646        self
647    }
648
649    /// The set plus the body layer.
650    pub const fn with_body(mut self) -> Self {
651        self.body = true;
652        self
653    }
654
655    /// Whether `layer` is in the set; `None` is the body layer.
656    pub fn contains(&self, layer: Option<ContentLayer>) -> bool {
657        match layer {
658            None => self.body,
659            Some(ContentLayer::Furniture) => self.furniture,
660            Some(ContentLayer::Notes) => self.notes,
661            Some(ContentLayer::Invisible) => self.invisible,
662            Some(ContentLayer::Background) => self.background,
663        }
664    }
665
666    /// Whether the layer spelled `name` (`body`, `furniture`, `notes`,
667    /// `invisible`, `background` — the JSON `content_layer` values) is in
668    /// the set; an unknown name is not.
669    pub fn contains_name(&self, name: &str) -> bool {
670        match name {
671            "body" => self.body,
672            "furniture" => self.furniture,
673            "notes" => self.notes,
674            "invisible" => self.invisible,
675            "background" => self.background,
676            _ => false,
677        }
678    }
679
680    /// Parse a comma-separated list of layer names (`body,furniture`;
681    /// whitespace around a name is ignored, `all` is every layer). An
682    /// unknown name is the error.
683    pub fn parse_list(list: &str) -> Result<Self, String> {
684        let mut set = Self::NONE;
685        for name in list.split(',').map(str::trim).filter(|n| !n.is_empty()) {
686            match name {
687                "body" => set.body = true,
688                "furniture" => set.furniture = true,
689                "notes" => set.notes = true,
690                "invisible" => set.invisible = true,
691                "background" => set.background = true,
692                "all" => set = Self::ALL,
693                other => {
694                    return Err(format!(
695                        "unknown content layer `{other}` (expected body, furniture, notes, invisible, background or all)"
696                    ))
697                }
698            }
699        }
700        Ok(set)
701    }
702}
703
704/// Options of the HTML export ([`DoclingDocument::export_to_html_with`]):
705/// docling-core's `HTMLParams` subset the port honours. [`Default`] is
706/// upstream's default export — placeholder images, `artifacts` as the
707/// referenced-image directory, the body layer only.
708#[derive(Debug, Clone, PartialEq, Eq)]
709pub struct HtmlExportOptions {
710    /// How pictures render (`HTMLParams.image_mode`): nothing but captions
711    /// and meta for [`ImageMode::Placeholder`], `data:` URIs when embedded,
712    /// `<img src>` paths under [`artifacts_dir`](Self::artifacts_dir) when
713    /// referenced.
714    pub image_mode: ImageMode,
715    /// The directory referenced images are named under, the Markdown
716    /// export's convention (`<artifacts_dir>/image_NNNNNN.<ext>`).
717    pub artifacts_dir: String,
718    /// The content layers rendered (`HTMLParams.layers`, #499): an item on a
719    /// layer outside the set is skipped, its children still walked — exactly
720    /// how docling-core's `get_excluded_refs` reads the set.
721    pub layers: ContentLayers,
722}
723
724impl Default for HtmlExportOptions {
725    fn default() -> Self {
726        Self {
727            image_mode: ImageMode::Placeholder,
728            artifacts_dir: "artifacts".to_string(),
729            layers: ContentLayers::BODY,
730        }
731    }
732}
733
734/// Options of the Markdown export
735/// ([`DoclingDocument::export_to_markdown_with_options`], #599): the
736/// docling-core `MarkdownParams` the port honours beyond the image mode.
737/// [`Default`] is upstream's default export — placeholder images,
738/// `artifacts` as the referenced-image directory, the body layer only, no
739/// picture traversal, HTML and underscore escaping on, `<!-- image -->` —
740/// so a document exported with it is byte-identical to
741/// [`DoclingDocument::export_to_markdown`].
742#[derive(Debug, Clone, PartialEq, Eq)]
743pub struct MarkdownExportOptions {
744    /// How pictures render (`MarkdownParams.image_mode`): the placeholder,
745    /// `data:` URIs when embedded, `![Image](<artifacts_dir>/image_NNNNNN.<ext>)`
746    /// when referenced (the bytes come back for the caller to write).
747    pub image_mode: ImageMode,
748    /// The directory referenced images are named under.
749    pub artifacts_dir: String,
750    /// The content layers rendered (`MarkdownParams.layers`,
751    /// `export_to_markdown(included_content_layers=…)`): an item on a layer
752    /// outside the set is skipped, its children still walked. The default
753    /// body-only set drops page headers/footers (`furniture`), reviewer
754    /// comments (`notes`) and hidden sheets (`invisible`), as upstream does; a
755    /// scanned form's running header reads out with
756    /// `ContentLayers::BODY.with(ContentLayer::Furniture)`. The extra items
757    /// render through the body's serializers — a page header is a paragraph.
758    pub layers: ContentLayers,
759    /// `CommonParams.traverse_pictures`: render the text items nested in a
760    /// picture (the PDF pipeline's picture children — a bordered form laid
761    /// out as one picture holds every field as a child) after the picture's
762    /// own caption and image, as upstream yields them. Off, a picture prints
763    /// only its caption and image.
764    pub traverse_pictures: bool,
765    /// `MarkdownParams.escape_html`: `&`, `<` and `>` in text as `&amp;`,
766    /// `&lt;`, `&gt;` (Python's `html.escape(quote=False)`). Off, `R&D` stays
767    /// `R&D`.
768    pub escape_html: bool,
769    /// `MarkdownParams.escape_underscores`: `_` in text as `\_`. Off, the
770    /// text keeps its underscores.
771    pub escape_underscores: bool,
772    /// `MarkdownParams.image_placeholder`: what a picture prints as when it
773    /// renders no image data (the placeholder mode, or a picture without a
774    /// payload); upstream's `<!-- image -->`.
775    pub image_placeholder: String,
776    /// docling-core's `PlainTextDocSerializer` (#613, `export_to_text`,
777    /// docling's `--to text`): the Markdown walk with the decoration turned
778    /// off — headings without `#`, bold/italic/strikethrough markers and
779    /// inline code backticks dropped, a hyperlink reduced to its label, code
780    /// blocks unfenced, no GFM hard line breaks. List bullets/numbers,
781    /// checkbox marks and table grids stay. [`Self::plain_text`] pairs it
782    /// with upstream's `PlainTextParams` (no escaping, an empty image
783    /// placeholder).
784    pub plain_text: bool,
785}
786
787impl MarkdownExportOptions {
788    /// docling-core's `PlainTextParams` defaults (#613): [`Self::plain_text`]
789    /// on, HTML and underscore escaping off, pictures print nothing (their
790    /// captions still do), body layer only, no picture traversal — what
791    /// `DoclingDocument.export_to_text()` and docling's `--to text` write.
792    pub fn plain_text() -> Self {
793        Self {
794            escape_html: false,
795            escape_underscores: false,
796            image_placeholder: String::new(),
797            plain_text: true,
798            ..Self::default()
799        }
800    }
801}
802
803impl Default for MarkdownExportOptions {
804    fn default() -> Self {
805        Self {
806            image_mode: ImageMode::Placeholder,
807            artifacts_dir: "artifacts".to_string(),
808            layers: ContentLayers::BODY,
809            traverse_pictures: false,
810            escape_html: true,
811            escape_underscores: true,
812            image_placeholder: "<!-- image -->".to_string(),
813            plain_text: false,
814        }
815    }
816}
817
818/// DocLang-only content for a [`Node::ListItem`] whose DocLang form differs from
819/// its flat Markdown `text` (see [`Node::ListItem::dclx`]). `ordered` picks the
820/// enclosing `<list>` kind, `marker` the `<ldiv><marker>`; content is `runs`
821/// (structured equations/formatting) when non-empty, else `text` re-parsed for
822/// inline markers.
823#[derive(Debug, Clone, PartialEq, Eq, Default)]
824pub struct ListItemDclx {
825    pub ordered: bool,
826    pub marker: Option<String>,
827    pub text: String,
828    pub runs: Vec<InlineRun>,
829}
830
831/// A page pipeline's list item as docling's `ListItemMarkerProcessor`
832/// exports it to JSON (see [`Node::ListItem::split`]): the source text
833/// (`orig`), the `marker` split off its head (empty when it has none), the
834/// `text` left, and `enumerated` for a numbered marker of any spelling (`1.`,
835/// `[1]`, `a)`, `iv.`). Plain text, not Markdown-escaped.
836#[derive(Debug, Clone, PartialEq, Eq, Default)]
837pub struct ListItemSplit {
838    pub orig: String,
839    pub marker: String,
840    pub text: String,
841    pub enumerated: bool,
842}
843
844impl Node {
845    /// The paragraph a [`Node::LabeledText`] renders as outside the JSON:
846    /// its text, wrapped as `[text](uri)` when it carries a hyperlink. Any
847    /// other node is returned unchanged.
848    pub fn labeled_as_paragraph(&self) -> std::borrow::Cow<'_, Node> {
849        match self {
850            Node::LabeledText { text, href, .. } => std::borrow::Cow::Owned(Node::Paragraph {
851                text: match href {
852                    Some(uri) => crate::hyperlink::markdown_link(text, uri),
853                    None => text.clone(),
854                },
855            }),
856            other => std::borrow::Cow::Borrowed(other),
857        }
858    }
859}
860
861impl InlineRun {
862    /// A run with no active formatting (renders as bare inline text).
863    pub fn is_plain(&self) -> bool {
864        !self.bold
865            && !self.italic
866            && !self.underline
867            && !self.strike
868            && !self.code
869            && !self.formula
870            && self.script == Script::Baseline
871    }
872}
873
874/// Build the [`Node`] for a paragraph of inline content from its structured
875/// `runs` and Markdown text, applying docling's `InlineGroup` boundary:
876///
877/// * a single plain run (or none) → a plain [`Node::Paragraph`] (which the
878///   serializers render as `<text>…</text>`, and a lone hyperlink via `<href>`);
879/// * a single uniformly-formatted run, or two or more runs → a
880///   [`Node::InlineGroup`]. `unwrapped` (the group's docling parent is a
881///   heading, so no enclosing `<text>`) only applies to multi-run groups.
882///
883/// Markdown/JSON render the group's `md_text`, so their output is identical to
884/// emitting a `Paragraph` — the structured runs are DocLang-only.
885pub fn inline_paragraph_node(md_text: String, runs: Vec<InlineRun>, unwrapped: bool) -> Node {
886    let single_plain = runs.len() <= 1 && runs.first().is_none_or(|r| r.is_plain());
887    if single_plain {
888        Node::Paragraph { text: md_text }
889    } else {
890        Node::InlineGroup {
891            unwrapped: unwrapped && runs.len() >= 2,
892            runs,
893            md_text,
894        }
895    }
896}
897
898/// One entry of a [`Node::FieldRegion`]: a marker/key/value triple, any of which
899/// may be absent. Mirrors docling's `field_item` with its `marker` / `field_key`
900/// / `field_value` child texts.
901#[derive(Debug, Clone, PartialEq, Default)]
902pub struct FieldItem {
903    pub marker: Option<String>,
904    pub key: Option<String>,
905    pub value: Option<String>,
906    /// docling's `kind` on the `field_value` item — `read_only` or
907    /// `fillable` (the value is or holds a form control); JSON-only.
908    pub value_kind: Option<String>,
909}
910
911/// One node of a [`Node::KeyValueGraph`] — docling-core's `GraphCell`.
912#[derive(Debug, Clone, PartialEq)]
913pub struct GraphCell {
914    /// docling's `GraphCellLabel` value: `key` or `value` (it also knows
915    /// `unspecified` and `checkbox`).
916    pub label: String,
917    /// The cell's number within its graph, what the links refer to.
918    pub cell_id: usize,
919    pub text: String,
920    /// The text before any cleanup — for an XBRL fact key, the concept's
921    /// qualified name where `text` is its local name.
922    pub orig: String,
923}
924
925/// One edge of a [`Node::KeyValueGraph`] — docling-core's `GraphLink`.
926#[derive(Debug, Clone, PartialEq)]
927pub struct GraphLink {
928    /// docling's `GraphLinkLabel` value: `to_value`, `to_child`, `to_parent`
929    /// or `to_key`.
930    pub label: String,
931    pub source_cell_id: usize,
932    pub target_cell_id: usize,
933}
934
935/// One DocumentPictureClassifier prediction — docling-core's
936/// `PictureClassificationClass` (`class_name` + `confidence`).
937#[derive(Debug, Clone, PartialEq)]
938pub struct PictureClass {
939    /// e.g. `bar_chart`, `logo`, `signature` (the classifier's 26-label set).
940    pub class_name: String,
941    pub confidence: f32,
942}
943
944/// A picture's text annotation — docling-core's `PictureDescriptionData`
945/// (`text` + `provenance`), the one shape upstream uses for every model that
946/// writes prose about a picture. The picture-OCR enrichment (#645) fills it
947/// with the lines the OCR engine read off the image, `provenance` naming the
948/// engine (`ppocr` / `tesseract`) the way a VLM description names its model.
949#[derive(Debug, Clone, PartialEq, Eq)]
950pub struct PictureDescription {
951    pub text: String,
952    pub provenance: String,
953}
954
955impl PictureDescription {
956    /// The provenance of a picture's author-written alt text (#676): the
957    /// `descr` (else `title`) of an OOXML picture's non-visual properties
958    /// — what DOCX, PPTX and XLSX authors type into "Alt Text". JSON writes
959    /// it as `meta.description.created_by`; Markdown renders it under strict
960    /// Markdown or `DoclingDocument::picture_alt_text`, HTML under the latter.
961    pub const ALT_TEXT: &'static str = "alt_text";
962
963    /// An alt-text description, see [`Self::ALT_TEXT`].
964    pub fn alt_text(text: impl Into<String>) -> Self {
965        Self {
966            text: text.into(),
967            provenance: Self::ALT_TEXT.to_string(),
968        }
969    }
970
971    /// Whether this description is a picture's alt text.
972    pub fn is_alt_text(&self) -> bool {
973        self.provenance == Self::ALT_TEXT
974    }
975
976    /// The (empty) provenance of a description docling's backend writes
977    /// itself as `PictureMeta.description` — `text` only, no `created_by`
978    /// and no legacy `annotations` entry: the alt text of an XLSX image
979    /// placed in a cell (docling#5015). Unlike [`Self::ALT_TEXT`] it is
980    /// upstream's own output, so every format renders it unconditionally.
981    pub const DOCLING_META: &'static str = "";
982
983    /// A docling-native description, see [`Self::DOCLING_META`].
984    pub fn docling_meta(text: impl Into<String>) -> Self {
985        Self {
986            text: text.into(),
987            provenance: Self::DOCLING_META.to_string(),
988        }
989    }
990
991    /// Whether this is a docling-native description ([`Self::DOCLING_META`]).
992    pub fn is_docling_meta(&self) -> bool {
993        self.provenance == Self::DOCLING_META
994    }
995}
996
997/// An extracted picture's raw encoded bytes plus its mimetype and pixel size —
998/// the docling.rs analogue of docling-core's `ImageRef`.
999#[derive(Debug, Clone, PartialEq)]
1000pub struct PictureImage {
1001    /// e.g. `image/png`, `image/jpeg`.
1002    pub mimetype: String,
1003    pub width: u32,
1004    pub height: u32,
1005    /// The image file bytes, exactly as embedded (PNG/JPEG/…).
1006    pub data: Vec<u8>,
1007    /// Pixels per inch of the image relative to the page it came from —
1008    /// docling-core's `ImageRef.dpi`, which consumers use to map pixels back
1009    /// to points. A crop rendered from a PDF page at `s` px/pt is `72·s`
1010    /// (docling: `int(72 * images_scale)`, #519); an image embedded in an
1011    /// office file has no render scale and keeps docling's `72`
1012    /// ([`Self::DEFAULT_DPI`]).
1013    pub dpi: u32,
1014    /// The size the picture is *displayed* at in its document, in inches
1015    /// (`[width, height]`, #834): a DOCX drawing's `wp:extent`, an ODT
1016    /// frame's `svg:width` / `svg:height` — not the bitmap's pixel size
1017    /// above, which docling's `ImageRef.size` carries. `None` when the
1018    /// format has no such extent (a PDF crop, a standalone image). The
1019    /// Pandoc export writes it as the `Image`'s `width` / `height`
1020    /// attributes, as Pandoc's own readers do; docling's JSON has no field
1021    /// for it, so the JSON export leaves it out.
1022    pub display_size: Option<[f32; 2]>,
1023}
1024
1025impl PictureImage {
1026    /// docling's `ImageRef` default when no render scale applies.
1027    pub const DEFAULT_DPI: u32 = 72;
1028
1029    /// The `dpi` of an image rendered at `scale` pixels per PDF point
1030    /// (`72·scale`, rounded — `int()` would floor 143.99… to 143).
1031    pub fn dpi_for_scale(scale: f32) -> u32 {
1032        (72.0 * scale).round().max(1.0) as u32
1033    }
1034
1035    /// A `data:` URI for the image (`data:<mimetype>;base64,<…>`).
1036    pub fn data_uri(&self) -> String {
1037        format!(
1038            "data:{};base64,{}",
1039            self.mimetype,
1040            crate::base64::encode(&self.data)
1041        )
1042    }
1043}
1044
1045/// One table cell as a first-class object (#240) — the Rust counterpart of
1046/// docling's `TableCell`: its text, page geometry, grid rectangle and header
1047/// roles. Produced by the PDF TableFormer paths from the predicted OTSL
1048/// structure; `bbox` is `[l, t, r, b]` in page points with a top-left origin.
1049#[derive(Debug, Clone, PartialEq)]
1050pub struct TableCell {
1051    pub text: String,
1052    /// `[l, t, r, b]`, page points, top-left origin; `None` without geometry.
1053    pub bbox: Option<[f32; 4]>,
1054    /// Anchor grid position (0-based row/column offsets).
1055    pub start_row: usize,
1056    pub start_col: usize,
1057    /// Span extents (≥ 1); the covered grid positions repeat the cell's text
1058    /// in [`Table::rows`].
1059    pub row_span: usize,
1060    pub col_span: usize,
1061    /// OTSL `ched` — a column-header cell.
1062    pub column_header: bool,
1063    /// OTSL `rhed` — a row-header cell.
1064    pub row_header: bool,
1065    /// OTSL `srow` — a section-row cell.
1066    pub row_section: bool,
1067}
1068
1069/// Where a picture's or table's caption text item hangs in the docling-JSON
1070/// tree (#390). docling's backends do not agree, and the JSON structure is
1071/// the only surface that shows it (Markdown, DocLang and LaTeX place a
1072/// caption by its item, whatever its parent): the PDF pipeline parents a
1073/// layout caption to the picture or table it belongs to, while every
1074/// declarative backend creates the caption with `doc.add_text(label=CAPTION)`
1075/// and no parent — the document body — even when the item itself sits in a
1076/// group or under a section header (JATS, LaTeX, HTML, Markdown, EPUB,
1077/// AsciiDoc all do). The office backends hang a chart's title caption off the
1078/// chart's container (the sheet group, the slide, docx's current parent,
1079/// docling#4190) — that is [`Node::Chart`]'s own path, not this choice. A
1080/// backend that adds a new captioned item picks the variant matching
1081/// upstream's `add_text` call for that format; the default is upstream's
1082/// default.
1083#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1084pub enum CaptionParent {
1085    /// `#/body`, listed after the enclosing top-level item — docling's
1086    /// `add_text` default, which every declarative backend leaves alone.
1087    #[default]
1088    Body,
1089    /// The item's own container (its `parent`), listed ahead of the item:
1090    /// the caption is created first, as docling's office backends do.
1091    Container,
1092    /// The item's own container, listed *after* the item: docling's HTML
1093    /// backend adds a `<figure>`-wrapped table, then its `<figcaption>` under
1094    /// `self.parents[self.level]` (docling#4050).
1095    ContainerAfter,
1096    /// The item itself — the caption is the picture's or table's first
1097    /// child, as docling's PDF pipeline attaches a layout caption.
1098    Item,
1099}
1100
1101/// A simple row-major table. By default `rows[0]` is the header row; a
1102/// [`TableStructure`] overlay overrides that and adds column spans.
1103#[derive(Debug, Clone, PartialEq, Default)]
1104pub struct Table {
1105    pub rows: Vec<Vec<String>>,
1106    /// Optional layout provenance: the four DocLang `<location>` values
1107    /// (`x0,y0,x1,y1`, each already normalized to the 0–511 resolution) emitted
1108    /// before the table's cells. Set only by backends with real geometry (e.g.
1109    /// the spreadsheet backend, whose cell grid yields a bounding box); left
1110    /// `None` by declarative backends, which have no coordinates.
1111    pub location: Option<[u16; 4]>,
1112    /// Optional OTSL structure overlay for backends that parse real table
1113    /// geometry (USPTO CALS): explicit header-row count and horizontal-span
1114    /// continuations. `None` → the default (row 0 is the header, no spans).
1115    /// `rows` still carries the full text grid (span text replicated) for
1116    /// Markdown/JSON; DocLang uses this overlay to emit `<ched/>`/`<lcel/>`.
1117    pub structure: Option<TableStructure>,
1118    /// Optional per-cell block content, parallel to `rows`. A *rich* cell (an
1119    /// ODF cell holding a list, several paragraphs, or a nested table) carries
1120    /// its DocLang blocks here; the DocLang serializer emits them after the
1121    /// cell token instead of the flat `rows` text. Markdown/JSON ignore this
1122    /// and render `rows`, so their output is unchanged. `None` (or an empty
1123    /// `Vec` for a given cell) → the flat text is used everywhere.
1124    pub cell_blocks: Option<Vec<Vec<Vec<Node>>>>,
1125    /// Optional caption (docling's `TableItem.captions`): the JATS
1126    /// `<table-wrap>` label+caption, an HTML `<caption>`, etc. Markdown renders
1127    /// it as a text line *before* the grid; JSON emits a caption text item the
1128    /// table references; DocLang emits a `<caption>` as the table's first child.
1129    /// `None` → the table has no caption.
1130    pub caption: Option<String>,
1131    /// Where the caption item hangs in the JSON tree (#390); see
1132    /// [`CaptionParent`]. Only the JSON export reads it.
1133    pub caption_parent: CaptionParent,
1134    /// The caption's own box on the table's page (0–511 grid) — the PDF
1135    /// pipeline's caption layout region, written as the caption item's
1136    /// `prov` (#609); see [`Node::Picture`]'s field of the same name.
1137    pub caption_location: Option<[u16; 4]>,
1138    /// The table's footnotes (docling's `TableItem.footnotes`, #1009): one
1139    /// text each, escaped like [`Self::caption`]. Markdown prints them after
1140    /// the grid, one paragraph each; JSON emits `footnote` text items under
1141    /// the table that its `footnotes` list references (docling-core#675).
1142    pub footnotes: Vec<String>,
1143    /// Optional per-cell bounding boxes, same shape as [`Self::rows`]: `[l, t,
1144    /// r, b]` in page points with a **top-left** origin (the PDF pipeline's
1145    /// native space). Set by the ML pipeline's TableFormer paths — a spanned
1146    /// cell repeats its anchor's box across the covered grid positions — and
1147    /// First-class cells (#240): the authoritative per-cell records —
1148    /// text, page geometry, spans and header roles — when the backend
1149    /// produces them (the PDF TableFormer paths do; declarative backends
1150    /// leave `None`). [`Self::rows`] stays the dense text grid every
1151    /// serializer renders (a spanning cell's text is replicated across its
1152    /// covered positions there); JSON serializes these cells verbatim when
1153    /// present, and the DocLang structure overlay is derived from them.
1154    pub cells: Option<Vec<TableCell>>,
1155    /// The table is a table of contents — docling's `document_index` label
1156    /// (#1091), which the PDF layout model gives a TOC region and docling
1157    /// keeps on the `TableItem`. Only the JSON export (and its read-back)
1158    /// tells it apart: every other serializer renders it as a table, as
1159    /// docling-core does.
1160    pub document_index: bool,
1161}
1162
1163/// The name a [`rich_cell_group`] carries, which the JSON export reads.
1164pub(crate) const RICH_CELL: &str = "rich_cell";
1165
1166/// A rich table cell's blocks as docling's `RichTableCell` (#1119): the one
1167/// entry of a [`Table::cell_blocks`] cell, wrapping the cell's paragraphs and
1168/// pictures in reading order. The JSON export writes it as the table's
1169/// `rich_cell_group_<table>_<col>_<row>` group the cell's `ref` points at,
1170/// as the DOCX backend's item tree does; DocLang, which has no group
1171/// element, renders the blocks in place. [`Table::rows`] keeps the cell's
1172/// Markdown text, its pictures as `<!-- image -->` paragraphs, and the
1173/// JSON's cell text leaves those out (python-docx's `cell.text`).
1174pub fn rich_cell_group(children: Vec<Node>) -> Node {
1175    Node::Group {
1176        label: "unspecified".into(),
1177        name: Some(RICH_CELL.into()),
1178        layer: None,
1179        children,
1180    }
1181}
1182
1183impl Table {
1184    /// A cell's text at a grid position, `None` outside the grid.
1185    pub fn cell_text(&self, row: usize, col: usize) -> Option<&str> {
1186        self.rows.get(row)?.get(col).map(String::as_str)
1187    }
1188
1189    /// Replace the text at a grid position; `false` (and no change) outside
1190    /// the grid. When a first-class cell covers the position, the whole
1191    /// cell is updated: its record text and every grid position its span
1192    /// covers, so the repair shows once in Markdown, not once per covered
1193    /// column.
1194    pub fn set_cell_text(&mut self, row: usize, col: usize, text: impl Into<String>) -> bool {
1195        if self.rows.get(row).and_then(|r| r.get(col)).is_none() {
1196            return false;
1197        }
1198        let text = text.into();
1199        let covering = self.cells.as_mut().and_then(|cells| {
1200            cells.iter_mut().find(|c| {
1201                (c.start_row..c.start_row + c.row_span).contains(&row)
1202                    && (c.start_col..c.start_col + c.col_span).contains(&col)
1203            })
1204        });
1205        if let Some(cell) = covering {
1206            cell.text = text.clone();
1207            let (r0, r1) = (cell.start_row, cell.start_row + cell.row_span);
1208            let (c0, c1) = (cell.start_col, cell.start_col + cell.col_span);
1209            for r in self.rows.iter_mut().take(r1).skip(r0) {
1210                for slot in r.iter_mut().take(c1).skip(c0) {
1211                    *slot = text.clone();
1212                }
1213            }
1214        } else {
1215            self.rows[row][col] = text;
1216        }
1217        true
1218    }
1219
1220    /// Derive first-class cells (#240) from the dense grid plus the
1221    /// [`TableStructure`] overlay — how declarative tables (DOCX/XLSX merged
1222    /// regions, HTML `th`/spans, ODF covered cells, USPTO CALS) get real
1223    /// `TableCell` records without page geometry. Anchors are the positions
1224    /// not marked as span continuations; extents scan the continuation grids
1225    /// right/down (matching the DocLang `lcel`/`ucel` reading). Header roles
1226    /// come from the per-cell `col_header`/`row_header` grids when present,
1227    /// else the `header_row` band, else docling's declarative default (row 0
1228    /// is the header). Without any overlay every position is a 1×1 cell.
1229    pub fn derive_cells(&self) -> Vec<TableCell> {
1230        let s = self.structure.as_ref();
1231        let flag = |grid: Option<&Vec<Vec<bool>>>, r: usize, c: usize| {
1232            grid.and_then(|g| g.get(r))
1233                .and_then(|row| row.get(c))
1234                .copied()
1235                .unwrap_or(false)
1236        };
1237        let col_cont = |r: usize, c: usize| flag(s.map(|s| &s.col_continuation), r, c);
1238        let row_cont = |r: usize, c: usize| flag(s.map(|s| &s.row_continuation), r, c);
1239        let is_col_header = |r: usize, c: usize| match s {
1240            Some(st) if !st.col_header.is_empty() => flag(Some(&st.col_header), r, c),
1241            Some(st) if !st.header_row.is_empty() => st.header_row.get(r).copied().unwrap_or(false),
1242            _ => r == 0,
1243        };
1244        let mut cells = Vec::new();
1245        for (r, row) in self.rows.iter().enumerate() {
1246            for (c, text) in row.iter().enumerate() {
1247                if col_cont(r, c) || row_cont(r, c) {
1248                    continue; // covered by a span anchor
1249                }
1250                let mut col_span = 1;
1251                while c + col_span < row.len() && col_cont(r, c + col_span) {
1252                    col_span += 1;
1253                }
1254                let mut row_span = 1;
1255                while r + row_span < self.rows.len() && row_cont(r + row_span, c) {
1256                    row_span += 1;
1257                }
1258                cells.push(TableCell {
1259                    text: text.clone(),
1260                    bbox: None,
1261                    start_row: r,
1262                    start_col: c,
1263                    row_span,
1264                    col_span,
1265                    column_header: is_col_header(r, c),
1266                    row_header: flag(s.map(|s| &s.row_header), r, c),
1267                    row_section: false,
1268                });
1269            }
1270        }
1271        cells
1272    }
1273
1274    /// The number of leading grid rows that form the column header block —
1275    /// docling-core's `TableData._count_column_header_rows` (docling-core#767,
1276    /// 2.102, #778), shared by the Markdown serializer
1277    /// ([`Self::header_row_count`]) and the chunker's dataframe view, which
1278    /// must agree on where the header ends. Uses the first-class
1279    /// [`Self::cells`] when present (the PDF pipeline's TableFormer flags),
1280    /// else the cells derived from the structure overlay.
1281    ///
1282    /// - A row counts only when a `column_header` cell *starts* on it
1283    ///   (docling-core#723): a header spanning several rows is replicated
1284    ///   into each row it covers, and counting those would pull the data rows
1285    ///   beneath it into the header block.
1286    /// - A row also stops the block when it *carries body text* (#604,
1287    ///   docling-core#766): a cell starting on it that is not a column
1288    ///   header, has non-blank text and does not start in the table's first
1289    ///   column, which holds row labels left unmarked even on header rows. A
1290    ///   scanned form flags its first-column labels `column_header` on every
1291    ///   row; without the check each such row folded its values into the
1292    ///   header.
1293    /// - Row 0 is exempt from that check — model-predicted header rows are
1294    ///   often only partly flagged — unless a later row flags a cell starting
1295    ///   in the first column: that marks a column of row headers, not a
1296    ///   partly flagged header row.
1297    ///
1298    /// No fallback: a table without flags has no header rows here.
1299    pub fn column_header_row_count(&self) -> usize {
1300        if self.rows.is_empty() {
1301            return 0;
1302        }
1303        let derived;
1304        let cells: &[TableCell] = match &self.cells {
1305            Some(c) if !c.is_empty() => c,
1306            _ => {
1307                derived = self.derive_cells();
1308                &derived
1309            }
1310        };
1311        let num_rows = self.rows.len();
1312        let first_col = cells.iter().map(|c| c.start_col).min().unwrap_or(0);
1313        let leading_col_flagged_below = cells.iter().any(|c| {
1314            c.column_header && c.start_col == first_col && (1..num_rows).contains(&c.start_row)
1315        });
1316        let is_header_row = |r: usize| {
1317            let check_body = r > 0 || leading_col_flagged_below;
1318            let mut flagged = false;
1319            for c in cells.iter().filter(|c| c.start_row == r) {
1320                if c.column_header {
1321                    flagged = true;
1322                } else if check_body && c.start_col != first_col && !c.text.trim().is_empty() {
1323                    return false;
1324                }
1325            }
1326            flagged
1327        };
1328        (0..num_rows).take_while(|&r| is_header_row(r)).count()
1329    }
1330
1331    /// The number of leading grid rows the Markdown serializer renders as the
1332    /// header — docling-core's `_count_header_rows`:
1333    /// [`Self::column_header_row_count`], plus upstream's row-0 fallback for
1334    /// GFM, which needs a header row: `1` when no flag sits on any grid row
1335    /// below the first (a spanning header cell counts on every row it
1336    /// covers), so tables from backends that never set the flag keep row 0
1337    /// as the header. When flags exist but none makes a header row, the
1338    /// count is `0` and every row stays in the body under an empty header.
1339    pub fn header_row_count(&self) -> usize {
1340        let count = self.column_header_row_count();
1341        if count > 0 || self.rows.is_empty() {
1342            return count;
1343        }
1344        let derived;
1345        let cells: &[TableCell] = match &self.cells {
1346            Some(c) if !c.is_empty() => c,
1347            _ => {
1348                derived = self.derive_cells();
1349                &derived
1350            }
1351        };
1352        if cells
1353            .iter()
1354            .any(|c| c.column_header && c.start_row + c.row_span.max(1) > 1)
1355        {
1356            0
1357        } else {
1358            1
1359        }
1360    }
1361
1362    /// For every grid position, the position of the cell that covers it — its
1363    /// anchor (top-left start): itself for an unmerged position, the merge's
1364    /// start for one a spanning cell covers. Uses the first-class
1365    /// [`Self::cells`] when present, else the cells derived from the
1366    /// structure overlay. A rich cell's blocks ([`Self::cell_blocks`]) live on
1367    /// its anchor only, so a serializer that repeats a merged cell in every
1368    /// position it covers (docling-core#857) reads them through this.
1369    pub fn span_anchors(&self) -> Vec<Vec<(usize, usize)>> {
1370        let num_cols = self.rows.iter().map(Vec::len).max().unwrap_or(0);
1371        let mut anchors: Vec<Vec<(usize, usize)>> = (0..self.rows.len())
1372            .map(|r| (0..num_cols).map(|c| (r, c)).collect())
1373            .collect();
1374        let derived;
1375        let cells: &[TableCell] = match &self.cells {
1376            Some(c) if !c.is_empty() => c,
1377            _ => {
1378                derived = self.derive_cells();
1379                &derived
1380            }
1381        };
1382        for cell in cells {
1383            let rows = cell.start_row..cell.start_row + cell.row_span.max(1);
1384            for row in anchors.iter_mut().take(rows.end).skip(rows.start) {
1385                let cols = cell.start_col..cell.start_col + cell.col_span.max(1);
1386                for pos in row.iter_mut().take(cols.end).skip(cols.start) {
1387                    *pos = (cell.start_row, cell.start_col);
1388                }
1389            }
1390        }
1391        anchors
1392    }
1393
1394    /// The first-class cell covering a grid position, if any.
1395    pub fn cell_at(&self, row: usize, col: usize) -> Option<&TableCell> {
1396        self.cells.as_ref()?.iter().find(|c| {
1397            (c.start_row..c.start_row + c.row_span).contains(&row)
1398                && (c.start_col..c.start_col + c.col_span).contains(&col)
1399        })
1400    }
1401
1402    /// A cell's bounding box (`[l, t, r, b]`, page points, top-left origin);
1403    /// `None` when no cell with geometry covers the position.
1404    pub fn cell_bbox(&self, row: usize, col: usize) -> Option<[f32; 4]> {
1405        self.cell_at(row, col)?.bbox
1406    }
1407
1408    /// Set (or replace) the bounding box of the cell covering a grid
1409    /// position; `false` outside the text grid. A table without first-class
1410    /// cells materializes them first (one 1×1 cell per grid position, texts
1411    /// from the grid), so declarative tables can be annotated too.
1412    pub fn set_cell_bbox(&mut self, row: usize, col: usize, bbox: [f32; 4]) -> bool {
1413        if self.rows.get(row).and_then(|r| r.get(col)).is_none() {
1414            return false;
1415        }
1416        let rows = &self.rows;
1417        let cells = self.cells.get_or_insert_with(|| {
1418            rows.iter()
1419                .enumerate()
1420                .flat_map(|(r, cols)| {
1421                    cols.iter().enumerate().map(move |(c, text)| TableCell {
1422                        text: text.clone(),
1423                        bbox: None,
1424                        start_row: r,
1425                        start_col: c,
1426                        row_span: 1,
1427                        col_span: 1,
1428                        column_header: false,
1429                        row_header: false,
1430                        row_section: false,
1431                    })
1432                })
1433                .collect()
1434        });
1435        match cells.iter_mut().find(|c| {
1436            (c.start_row..c.start_row + c.row_span).contains(&row)
1437                && (c.start_col..c.start_col + c.col_span).contains(&col)
1438        }) {
1439            Some(cell) => {
1440                cell.bbox = Some(bbox);
1441                true
1442            }
1443            None => {
1444                cells.push(TableCell {
1445                    text: self.rows[row][col].clone(),
1446                    bbox: Some(bbox),
1447                    start_row: row,
1448                    start_col: col,
1449                    row_span: 1,
1450                    col_span: 1,
1451                    column_header: false,
1452                    row_header: false,
1453                    row_section: false,
1454                });
1455                true
1456            }
1457        }
1458    }
1459
1460    /// The anchor position of the cell whose box overlaps `bbox` best
1461    /// (largest intersection-over-union), ties resolved in cell order.
1462    /// `None` when nothing overlaps or the table carries no geometry. This
1463    /// is the lookup half of the repair workflow: find the cell an external
1464    /// OCR box refers to, then [`Self::set_cell_text`] it.
1465    pub fn find_cell_by_bbox(&self, bbox: [f32; 4]) -> Option<(usize, usize)> {
1466        let area = |b: &[f32; 4]| ((b[2] - b[0]) * (b[3] - b[1])).max(0.0);
1467        let mut best: Option<(f32, (usize, usize))> = None;
1468        for cell in self.cells.as_deref()?.iter() {
1469            let Some(cb) = cell.bbox else { continue };
1470            let iw = (bbox[2].min(cb[2]) - bbox[0].max(cb[0])).max(0.0);
1471            let ih = (bbox[3].min(cb[3]) - bbox[1].max(cb[1])).max(0.0);
1472            let inter = iw * ih;
1473            if inter <= 0.0 {
1474                continue;
1475            }
1476            let iou = inter / (area(&bbox) + area(&cb) - inter).max(f32::EPSILON);
1477            if best.is_none_or(|(b, _)| iou > b) {
1478                best = Some((iou, (cell.start_row, cell.start_col)));
1479            }
1480        }
1481        best.map(|(_, pos)| pos)
1482    }
1483
1484    /// Locate the cell overlapping `bbox` best and replace its text — the
1485    /// one-call form of the OCR-repair loop. Returns the updated anchor.
1486    pub fn update_cell_by_bbox(
1487        &mut self,
1488        bbox: [f32; 4],
1489        text: impl Into<String>,
1490    ) -> Option<(usize, usize)> {
1491        let (row, col) = self.find_cell_by_bbox(bbox)?;
1492        self.set_cell_text(row, col, text);
1493        Some((row, col))
1494    }
1495}
1496
1497/// OTSL structure overlay for a [`Table`], parallel to [`Table::rows`].
1498#[derive(Debug, Clone, PartialEq, Default)]
1499pub struct TableStructure {
1500    /// Per-row: `true` if the row's non-empty cells are column headers
1501    /// (emitted as `<ched/>` rather than `<fcel/>`).
1502    pub header_row: Vec<bool>,
1503    /// Same shape as [`Table::rows`]; `true` where a cell continues a
1504    /// horizontal span from its left neighbour (emitted as `<lcel/>`).
1505    pub col_continuation: Vec<Vec<bool>>,
1506    /// Same shape as [`Table::rows`]; `true` where a cell continues a
1507    /// vertical span from the cell above (emitted as `<ucel/>`). Empty or all
1508    /// `false` when the backend has no vertical spans (e.g. USPTO CALS).
1509    pub row_continuation: Vec<Vec<bool>>,
1510    /// Same shape as [`Table::rows`]; `true` where a non-empty cell is a row
1511    /// header (emitted as `<rhed/>`) — a chart's category column. Empty when
1512    /// the table has no row headers.
1513    pub row_header: Vec<Vec<bool>>,
1514    /// Same shape as [`Table::rows`]; `true` where a cell is a *column header*
1515    /// cell (an HTML `<th>`). When non-empty this per-cell grid supersedes the
1516    /// per-row [`Self::header_row`] for `<ched/>` emission, matching docling's
1517    /// cell-level `column_header` flag; the chunker derives its header-row
1518    /// count from it.
1519    pub col_header: Vec<Vec<bool>>,
1520}
1521
1522/// [`for_each_picture_in_mut`], read-only: every picture in `nodes`, however
1523/// nested, for a pass that only looks (the DocLang asset digests, #898).
1524pub fn for_each_picture_in<'a>(nodes: &'a [Node], f: &mut dyn FnMut(&'a Node)) {
1525    for node in nodes {
1526        match node {
1527            Node::Picture { .. } => f(node),
1528            Node::Group { children, .. } | Node::PictureChildren(children) => {
1529                for_each_picture_in(children, f)
1530            }
1531            Node::Located { inner, .. }
1532            | Node::Prov { inner, .. }
1533            | Node::Track { inner, .. }
1534            | Node::Furniture { inner, .. }
1535            | Node::Commented { inner, .. }
1536            | Node::DoclangOnly(inner) => for_each_picture_in(std::slice::from_ref(inner), f),
1537            Node::Table(t) => {
1538                if let Some(blocks) = t.cell_blocks.as_ref() {
1539                    for row in blocks {
1540                        for cell in row {
1541                            for_each_picture_in(cell, f);
1542                        }
1543                    }
1544                }
1545            }
1546            _ => {}
1547        }
1548    }
1549}
1550
1551/// [`DoclingDocument::for_each_picture_mut`] over a node slice — every
1552/// picture in `nodes`, however nested (groups, wrappers, table cell blocks),
1553/// for a caller that holds page batches rather than a document (the
1554/// streaming PDF path, #896).
1555pub fn for_each_picture_in_mut(nodes: &mut [Node], f: &mut dyn FnMut(&mut Node)) {
1556    for node in nodes {
1557        match node {
1558            Node::Picture { .. } => f(node),
1559            Node::Group { children, .. } | Node::PictureChildren(children) => {
1560                for_each_picture_in_mut(children, f)
1561            }
1562            Node::Located { inner, .. }
1563            | Node::Prov { inner, .. }
1564            | Node::Track { inner, .. }
1565            | Node::Furniture { inner, .. }
1566            | Node::Commented { inner, .. }
1567            | Node::DoclangOnly(inner) => for_each_picture_in_mut(std::slice::from_mut(inner), f),
1568            Node::Table(t) => {
1569                if let Some(blocks) = t.cell_blocks.as_mut() {
1570                    for row in blocks {
1571                        for cell in row {
1572                            for_each_picture_in_mut(cell, f);
1573                        }
1574                    }
1575                }
1576            }
1577            _ => {}
1578        }
1579    }
1580}
1581
1582impl DoclingDocument {
1583    /// Create an empty document with the given name.
1584    pub fn new(name: impl Into<String>) -> Self {
1585        Self {
1586            name: name.into(),
1587            nodes: Vec::new(),
1588            strict_markdown: false,
1589            compact_tables: false,
1590            picture_alt_text: false,
1591            metadata: Default::default(),
1592            metadata_output: Default::default(),
1593            page_break_placeholder: None,
1594            links: Vec::new(),
1595            confidence: None,
1596            tree: None,
1597            page_images: std::collections::BTreeMap::new(),
1598            notices: Vec::new(),
1599        }
1600    }
1601
1602    /// Append a node.
1603    /// The document's top-level tables in reading order — the read half of
1604    /// the post-extraction table API (#238). [`Node::Located`] wrappers (the
1605    /// PDF pipeline attaches layout provenance that way) are looked through;
1606    /// tables nested inside rich table cells (`Table::cell_blocks`) are not
1607    /// traversed.
1608    pub fn tables(&self) -> impl Iterator<Item = &Table> {
1609        fn unwrap_table(n: &Node) -> Option<&Table> {
1610            match n {
1611                Node::Table(t) => Some(t),
1612                Node::Located { inner, .. }
1613                | Node::Prov { inner, .. }
1614                | Node::Track { inner, .. } => unwrap_table(inner),
1615                _ => None,
1616            }
1617        }
1618        self.nodes.iter().filter_map(unwrap_table)
1619    }
1620
1621    /// Mutable access to the document's top-level tables, for repair
1622    /// workflows (#238): locate a cell via [`Table::find_cell_by_bbox`], fix
1623    /// its text with [`Table::set_cell_text`], then re-export — every
1624    /// serializer reads the same grid.
1625    pub fn tables_mut(&mut self) -> impl Iterator<Item = &mut Table> {
1626        fn unwrap_table(n: &mut Node) -> Option<&mut Table> {
1627            match n {
1628                Node::Table(t) => Some(t),
1629                Node::Located { inner, .. }
1630                | Node::Prov { inner, .. }
1631                | Node::Track { inner, .. } => unwrap_table(inner),
1632                _ => None,
1633            }
1634        }
1635        self.nodes.iter_mut().filter_map(unwrap_table)
1636    }
1637
1638    pub fn push(&mut self, node: Node) {
1639        self.nodes.push(node);
1640    }
1641
1642    /// Visit every [`Node::Picture`] in the flat node stream, wherever it
1643    /// nests — group children, table cell blocks, a picture's own
1644    /// children, the located/prov/track/comment/furniture wrappers — so an
1645    /// enrichment that reads the embedded images (picture OCR, #645) reaches
1646    /// each one. The callback gets the picture node itself.
1647    pub fn for_each_picture_mut(&mut self, f: &mut dyn FnMut(&mut Node)) {
1648        for_each_picture_in_mut(&mut self.nodes, f);
1649    }
1650
1651    /// Change the unit the pages are measured in: every length in page units
1652    /// — each [`Node::PageInfo`] size, a [`Node::Prov`] box, a first-class
1653    /// table cell's box, a script run's box — is multiplied by `sx`
1654    /// horizontally and `sy` vertically, and every image's `dpi` (its pixels
1655    /// per inch *of the page unit*: a picture crop, a page image) is divided
1656    /// by `sx`, so the same pixels still cover the same part of the page. The
1657    /// 0–511 `<location>` grid is relative to the page and needs nothing. The
1658    /// image input sizes its page from the file's resolution this way once
1659    /// the models have run on its pixels (#1093).
1660    pub fn rescale_page_units(&mut self, sx: f32, sy: f32) {
1661        let scale_box = |b: &mut [f32; 4]| {
1662            b[0] *= sx;
1663            b[1] *= sy;
1664            b[2] *= sx;
1665            b[3] *= sy;
1666        };
1667        let scale_dpi = |img: &mut PictureImage| {
1668            img.dpi = (img.dpi as f32 / sx).round().max(1.0) as u32;
1669        };
1670        fn table(t: &mut Table, scale_box: &dyn Fn(&mut [f32; 4]), walk: &dyn Fn(&mut [Node])) {
1671            for cell in t.cells.iter_mut().flatten() {
1672                if let Some(b) = cell.bbox.as_mut() {
1673                    scale_box(b);
1674                }
1675            }
1676            for row in t.cell_blocks.iter_mut().flatten() {
1677                for cell in row {
1678                    walk(cell);
1679                }
1680            }
1681        }
1682        fn walk(
1683            nodes: &mut [Node],
1684            sx: f32,
1685            sy: f32,
1686            scale_box: &dyn Fn(&mut [f32; 4]),
1687            scale_dpi: &dyn Fn(&mut PictureImage),
1688        ) {
1689            let recurse = |n: &mut [Node]| walk(n, sx, sy, scale_box, scale_dpi);
1690            for node in nodes {
1691                match node {
1692                    Node::PageInfo { width, height, .. } => {
1693                        *width *= sx;
1694                        *height *= sy;
1695                    }
1696                    Node::Prov { bbox, inner, .. } => {
1697                        scale_box(bbox);
1698                        recurse(std::slice::from_mut(inner));
1699                    }
1700                    Node::ScriptText { inner, runs } => {
1701                        for run in runs {
1702                            for prov in &mut run.prov {
1703                                scale_box(&mut prov.bbox);
1704                            }
1705                        }
1706                        recurse(std::slice::from_mut(inner));
1707                    }
1708                    Node::Located { inner, .. }
1709                    | Node::Track { inner, .. }
1710                    | Node::Furniture { inner, .. }
1711                    | Node::Commented { inner, .. }
1712                    | Node::DoclangOnly(inner) => recurse(std::slice::from_mut(inner)),
1713                    Node::Group { children, .. } | Node::PictureChildren(children) => {
1714                        recurse(children)
1715                    }
1716                    Node::Table(t) | Node::Chart { table: t, .. } => table(t, scale_box, &recurse),
1717                    Node::Picture {
1718                        image: Some(img), ..
1719                    } => scale_dpi(img),
1720                    _ => {}
1721                }
1722            }
1723        }
1724        walk(&mut self.nodes, sx, sy, &scale_box, &scale_dpi);
1725        for img in self.page_images.values_mut() {
1726            scale_dpi(img);
1727        }
1728    }
1729
1730    /// Convenience: append a heading.
1731    pub fn add_heading(&mut self, level: u8, text: impl Into<String>) {
1732        self.push(Node::Heading {
1733            level,
1734            text: text.into(),
1735        });
1736    }
1737
1738    /// Convenience: append a paragraph.
1739    pub fn add_paragraph(&mut self, text: impl Into<String>) {
1740        self.push(Node::Paragraph { text: text.into() });
1741    }
1742
1743    /// Serialize the document to Markdown.
1744    ///
1745    /// The Rust equivalent of docling-core's
1746    /// `DoclingDocument.export_to_markdown()`. Uses [`Self::strict_markdown`] to
1747    /// pick between docling-legacy output (default) and the cleaner, more
1748    /// conformant variant.
1749    pub fn export_to_markdown(&self) -> String {
1750        to_markdown(self, self.strict_markdown)
1751    }
1752
1753    /// Serialize to Markdown, explicitly choosing the mode regardless of
1754    /// [`Self::strict_markdown`]. `strict = true` produces cleaner, more
1755    /// conformant Markdown (code-fence languages preserved, no inline-run
1756    /// spacing artifacts); `strict = false` reproduces docling's legacy output.
1757    pub fn export_to_markdown_with(&self, strict: bool) -> String {
1758        to_markdown(self, strict)
1759    }
1760
1761    /// Markdown for this document as the *content of a rich table cell*
1762    /// (docling-core's `in_table_cell` serialization, docling-core#540):
1763    /// headings render as plain text since Markdown tables can't hold them.
1764    /// Backends build a sub-document per rich cell and flatten this into the
1765    /// cell text; no trailing newline.
1766    pub fn export_to_table_cell_markdown(&self) -> String {
1767        crate::markdown::to_markdown_table_cell(self, self.strict_markdown)
1768    }
1769
1770    /// Serialize to docling-core's native JSON wire format (`DoclingDocument`
1771    /// schema), pretty-printed — the Rust equivalent of
1772    /// `DoclingDocument.export_to_dict()` / `save_as_json()`. The output loads
1773    /// back into Python docling-core and round-trips to the same Markdown.
1774    pub fn export_to_json(&self) -> String {
1775        let mut out = Vec::new();
1776        self.write_json_pretty(&mut out)
1777            .expect("DoclingDocument JSON is always serializable");
1778        String::from_utf8(out).expect("serde_json writes UTF-8")
1779    }
1780
1781    /// The same JSON wire format as [`Self::export_to_json`], as a
1782    /// `serde_json::Value` — for callers that append response-level extras
1783    /// (docling-serve adds the confidence report, #183) before serializing.
1784    ///
1785    /// The `Value` is large — ~2.7 KB per text item — so on a long document
1786    /// prefer [`Self::write_json`], which writes the same JSON without it.
1787    pub fn export_to_json_value(&self) -> serde_json::Value {
1788        crate::json::to_json(self)
1789    }
1790
1791    /// Write the JSON of [`Self::export_to_json_value`] to `writer`, compact
1792    /// — byte for byte `serde_json::to_writer(writer, &doc.export_to_json_value())`
1793    /// — without building the `Value`: the export holds its text items in a
1794    /// compact form and serializes them straight to the writer. Wrap a file
1795    /// or socket in a `BufWriter`.
1796    pub fn write_json<W: std::io::Write>(&self, writer: W) -> std::io::Result<()> {
1797        crate::json::write_json(self, writer, false).map_err(std::io::Error::from)
1798    }
1799
1800    /// [`Self::write_json`], indented as [`Self::export_to_json`] is.
1801    pub fn write_json_pretty<W: std::io::Write>(&self, writer: W) -> std::io::Result<()> {
1802        crate::json::write_json(self, writer, true).map_err(std::io::Error::from)
1803    }
1804
1805    /// [`Self::write_json_pretty`] with `extras` appended to the top-level
1806    /// object after `pages` — byte for byte `serde_json::to_writer_pretty`
1807    /// of [`Self::export_to_json_value`] with each `value[key] = v` set (a
1808    /// key the document JSON does not have), without building that `Value`:
1809    /// docling-serve's response adds its `confidence` report this way.
1810    pub fn write_json_pretty_with<W: std::io::Write>(
1811        &self,
1812        writer: W,
1813        extras: &[(&str, &serde_json::Value)],
1814    ) -> std::io::Result<()> {
1815        crate::json::write_json_with(self, writer, true, extras).map_err(std::io::Error::from)
1816    }
1817
1818    /// Serialize to a complete LaTeX document — the Rust counterpart of
1819    /// docling-core's `LaTeXDocSerializer` with default parameters (docling
1820    /// 2.124's `--to latex`, #317). No trailing newline, like the upstream
1821    /// CLI's `<stem>.tex`.
1822    pub fn export_to_latex(&self) -> String {
1823        crate::latex::to_latex(self)
1824    }
1825
1826    /// Serialize to Pandoc's AST as JSON (`pandoc -f json`, #515) with the
1827    /// default options: pictures as captioned figures without image data,
1828    /// body layer only, the [`PANDOC_API_VERSION`](crate::pandoc::PANDOC_API_VERSION)
1829    /// API. One line, no trailing newline. See [`crate::pandoc`].
1830    pub fn export_to_pandoc_json(&self) -> String {
1831        crate::pandoc::to_pandoc(self, &crate::pandoc::PandocExportOptions::default())
1832            .expect("the default Pandoc API version is always supported")
1833            .0
1834    }
1835
1836    /// Pandoc JSON per `options` (image mode, artifacts directory, content
1837    /// layers, required API version). Returns the JSON and, for
1838    /// [`ImageMode::Referenced`], the `(path, bytes)` image files; an
1839    /// unsupported `api_version` is an error.
1840    pub fn export_to_pandoc_json_with(
1841        &self,
1842        options: &crate::pandoc::PandocExportOptions,
1843    ) -> Result<crate::pandoc::PandocOutput, crate::pandoc::PandocError> {
1844        crate::pandoc::to_pandoc(self, options)
1845    }
1846
1847    /// Serialize to DocLang XML (`<doclang version="0.7">…`), the markup that
1848    /// lives inside a `.dclx` archive — the Rust counterpart of docling-core's
1849    /// `export_to_doclang()` with default parameters. No trailing newline; the
1850    /// archive writer appends exactly one.
1851    pub fn export_to_doclang(&self) -> String {
1852        self.export_doclang(crate::doclang::Pictures::Referenced { collect: false })
1853            .0
1854    }
1855
1856    /// [`Self::export_to_doclang`] plus the picture assets its
1857    /// `<src uri="assets/image_….png"/>` references name, as `(path, bytes)`
1858    /// in document order — the parts docling's `save_as_doclang_archive`
1859    /// stores next to `document.xml`. PNG and JPEG pictures come back as PNG
1860    /// (a JPEG re-encoded from its libjpeg-decoded pixels); other encodings
1861    /// keep their own bytes for the archive writer to convert.
1862    pub fn export_to_doclang_with_assets(&self) -> (String, Vec<(String, Vec<u8>)>) {
1863        self.export_doclang(crate::doclang::Pictures::Referenced { collect: true })
1864    }
1865
1866    /// DocLang with docling's `image_mode` for pictures (#884):
1867    /// [`ImageMode::Placeholder`] writes no `<src>` — docling-core's own
1868    /// `export_to_doclang()` default, which upstream's `.dclg` fixtures hold
1869    /// — [`ImageMode::Embedded`] a `data:` URI of the PNG,
1870    /// [`ImageMode::Referenced`] is [`Self::export_to_doclang_with_assets`].
1871    pub fn export_to_doclang_with_images(
1872        &self,
1873        mode: ImageMode,
1874    ) -> (String, Vec<(String, Vec<u8>)>) {
1875        use crate::doclang::Pictures;
1876        self.export_doclang(match mode {
1877            ImageMode::Placeholder => Pictures::Placeholder,
1878            ImageMode::Embedded => Pictures::Embedded,
1879            ImageMode::Referenced => Pictures::Referenced { collect: true },
1880        })
1881    }
1882
1883    /// The item tree's DocLang — docling-core's `DocLangDocSerializer`
1884    /// ported over the tree (`doclang_tree.rs`, #884), the structure the
1885    /// JSON export writes — else (no tree, or one the port does not cover:
1886    /// provenance, picture meta, form fields) the nodes'. The flat nodes
1887    /// cannot carry a footnote's label, a caption's or a cell's inline
1888    /// formulas, text docling never wrote as Markdown, or the whitespace of
1889    /// an inline group's runs, which DocLang 0.9 reads as written.
1890    fn export_doclang(
1891        &self,
1892        pictures: crate::doclang::Pictures,
1893    ) -> (String, Vec<(String, Vec<u8>)>) {
1894        self.tree
1895            .as_ref()
1896            .filter(|t| !t.doclang_nodes)
1897            .and_then(|t| crate::doclang_tree::export(t, pictures))
1898            .unwrap_or_else(|| crate::doclang::render(&self.nodes, pictures))
1899    }
1900
1901    /// Serialize to Markdown with an explicit picture [`ImageMode`] (mirrors
1902    /// docling's `image_mode`). Returns the Markdown and, for
1903    /// [`ImageMode::Referenced`], the `(relative-path, bytes)` of each image the
1904    /// caller should write next to the Markdown file. `artifacts_dir` is the
1905    /// directory name used in referenced links.
1906    pub fn export_to_markdown_with_images(
1907        &self,
1908        image_mode: ImageMode,
1909        artifacts_dir: &str,
1910    ) -> (String, Vec<(String, Vec<u8>)>) {
1911        to_markdown_images(self, self.strict_markdown, image_mode, artifacts_dir)
1912    }
1913
1914    /// Markdown per `options` (#599) — docling-core's
1915    /// `export_to_markdown(included_content_layers=…, image_mode=…,
1916    /// image_placeholder=…, escape_html=…, escape_underscores=…,
1917    /// traverse_pictures=…)`: the content layers rendered, whether a
1918    /// picture's nested text items print, HTML and underscore escaping, the
1919    /// image placeholder, and the image mode with its referenced-image
1920    /// directory. [`Self::strict_markdown`] still picks the Markdown flavour.
1921    /// Returns the Markdown and, for [`ImageMode::Referenced`], the
1922    /// `(path, bytes)` artifacts. With [`MarkdownExportOptions::default`]
1923    /// the Markdown is [`Self::export_to_markdown`]'s byte for byte.
1924    pub fn export_to_markdown_with_options(
1925        &self,
1926        options: &MarkdownExportOptions,
1927    ) -> (String, Vec<(String, Vec<u8>)>) {
1928        crate::markdown::to_markdown_with_options(self, self.strict_markdown, options)
1929    }
1930
1931    /// WebVTT (#614) — what docling's `--to vtt` writes
1932    /// (`DoclingDocument.save_as_vtt`): a cue per timed text item — a WebVTT
1933    /// input's cues, an audio/video transcript's segments — hours always
1934    /// written, the `</v>` of a lone voice span omitted. A document without
1935    /// timed text is the bare `WEBVTT` header. No trailing newline.
1936    pub fn export_to_vtt(&self) -> String {
1937        crate::vtt::to_vtt(self, &crate::vtt::VttExportOptions::default())
1938    }
1939
1940    /// [`Self::export_to_vtt`] with docling-core's `WebVTTParams`
1941    /// (`omit_hours_if_zero`, `omit_voice_end`).
1942    pub fn export_to_vtt_with_options(&self, options: &crate::vtt::VttExportOptions) -> String {
1943        crate::vtt::to_vtt(self, options)
1944    }
1945
1946    /// Plain text — docling-core's `DoclingDocument.export_to_text()` with
1947    /// its defaults (#613, docling's `--to text` / `<stem>.txt`): the
1948    /// Markdown export without decoration ([`MarkdownExportOptions::plain_text`]).
1949    /// Lists keep their bullets and numbers, tables their `|` grid. No
1950    /// trailing newline: upstream's `serialize().text`, which its CLI
1951    /// writes verbatim to `<stem>.txt`.
1952    pub fn export_to_text(&self) -> String {
1953        let (mut text, _) = crate::markdown::to_markdown_with_options(
1954            self,
1955            self.strict_markdown,
1956            &MarkdownExportOptions::plain_text(),
1957        );
1958        if text.ends_with('\n') {
1959            text.pop();
1960        }
1961        text
1962    }
1963
1964    /// A complete HTML document — docling-core's `HTMLDocSerializer` with its
1965    /// defaults (#492): pictures stay out (`ImageRefMode.PLACEHOLDER`, only
1966    /// their captions and meta render). See [`export_to_html_with_images`]
1967    /// for the embedded / referenced modes and [`crate::html`]'s module docs
1968    /// for what is reproduced.
1969    ///
1970    /// [`export_to_html_with_images`]: Self::export_to_html_with_images
1971    pub fn export_to_html(&self) -> String {
1972        crate::html::to_html(self, &HtmlExportOptions::default()).0
1973    }
1974
1975    /// HTML with pictures per `image_mode`: `data:` URIs when embedded, and
1976    /// when referenced `<img src>` paths under `artifacts_dir` whose bytes come
1977    /// back as `(path, bytes)` for the caller to write — the Markdown export's
1978    /// contract and file names.
1979    pub fn export_to_html_with_images(
1980        &self,
1981        image_mode: ImageMode,
1982        artifacts_dir: &str,
1983    ) -> (String, Vec<(String, Vec<u8>)>) {
1984        crate::html::to_html(
1985            self,
1986            &HtmlExportOptions {
1987                image_mode,
1988                artifacts_dir: artifacts_dir.to_string(),
1989                ..HtmlExportOptions::default()
1990            },
1991        )
1992    }
1993
1994    /// HTML rendering the content `layers` — docling-core's
1995    /// `export_to_html(included_content_layers=…)` (#499). The default export
1996    /// is body only; `ContentLayers::BODY.with(ContentLayer::Furniture)` adds
1997    /// page headers/footers, `.with(ContentLayer::Notes)` reviewer comments,
1998    /// [`ContentLayers::ALL`] is Python's `set(ContentLayer)`. An item on a
1999    /// layer outside the set is skipped while its children are still walked,
2000    /// and the items that do render go through the same serializers as the
2001    /// body (a page header is a `<p>`, a comment a `<p>`, a header table a
2002    /// `<table>`), exactly as upstream's `HTMLParams.layers` behaves. Pictures
2003    /// stay placeholders; see [`export_to_html_with`] for the full option set.
2004    ///
2005    /// [`export_to_html_with`]: Self::export_to_html_with
2006    pub fn export_to_html_with_layers(&self, layers: ContentLayers) -> String {
2007        crate::html::to_html(
2008            self,
2009            &HtmlExportOptions {
2010                layers,
2011                ..HtmlExportOptions::default()
2012            },
2013        )
2014        .0
2015    }
2016
2017    /// HTML per `options` — image mode, referenced-image directory and content
2018    /// layers in one call; the other `export_to_html*` methods are
2019    /// shorthands for it. Returns the HTML and, for
2020    /// [`ImageMode::Referenced`], the `(path, bytes)` artifacts.
2021    pub fn export_to_html_with(
2022        &self,
2023        options: &HtmlExportOptions,
2024    ) -> (String, Vec<(String, Vec<u8>)>) {
2025        crate::html::to_html(self, options)
2026    }
2027}
2028
2029#[cfg(test)]
2030mod table_api_tests {
2031    use super::*;
2032
2033    fn cell(
2034        text: &str,
2035        bbox: [f32; 4],
2036        (start_row, start_col): (usize, usize),
2037        (row_span, col_span): (usize, usize),
2038    ) -> TableCell {
2039        TableCell {
2040            text: text.into(),
2041            bbox: Some(bbox),
2042            start_row,
2043            start_col,
2044            row_span,
2045            col_span,
2046            column_header: false,
2047            row_header: false,
2048            row_section: false,
2049        }
2050    }
2051
2052    fn table() -> Table {
2053        Table {
2054            rows: vec![
2055                vec!["Year".into(), "Ducks".into()],
2056                vec!["2019".into(), "120".into()],
2057            ],
2058            cells: Some(vec![
2059                cell("Year", [0.0, 0.0, 50.0, 10.0], (0, 0), (1, 1)),
2060                cell("Ducks", [50.0, 0.0, 100.0, 10.0], (0, 1), (1, 1)),
2061                cell("2019", [0.0, 10.0, 50.0, 20.0], (1, 0), (1, 1)),
2062                cell("120", [50.0, 10.0, 100.0, 20.0], (1, 1), (1, 1)),
2063            ]),
2064            ..Default::default()
2065        }
2066    }
2067
2068    /// Declarative tables derive first-class cells from the structure
2069    /// overlay: continuation grids become span extents, `col_header` (or the
2070    /// row-0 fallback) becomes the header role — the XLSX/DOCX/HTML merge
2071    /// path into real `TableCell`s (#240).
2072    #[test]
2073    fn derive_cells_reads_spans_and_headers_from_structure() {
2074        let t = Table {
2075            rows: vec![
2076                vec!["Wide".into(), "Wide".into(), "C".into()],
2077                vec!["a".into(), "b".into(), "c".into()],
2078            ],
2079            structure: Some(TableStructure {
2080                header_row: vec![true, false],
2081                col_continuation: vec![vec![false, true, false], vec![false; 3]],
2082                row_continuation: vec![vec![false; 3], vec![false; 3]],
2083                row_header: Vec::new(),
2084                col_header: Vec::new(),
2085            }),
2086            ..Default::default()
2087        };
2088        let cells = t.derive_cells();
2089        assert_eq!(cells.len(), 5, "two anchors in row 0, three in row 1");
2090        let wide = &cells[0];
2091        assert_eq!((wide.col_span, wide.row_span), (2, 1));
2092        assert!(wide.column_header, "header_row band");
2093        assert!(cells.iter().skip(2).all(|c| !c.column_header));
2094
2095        // Without any overlay: every position 1x1, row 0 the header
2096        // (docling's declarative default — the old JSON synthesis).
2097        let plain = Table {
2098            rows: vec![vec!["h".into()], vec!["x".into()]],
2099            ..Default::default()
2100        };
2101        let cells = plain.derive_cells();
2102        assert_eq!(cells.len(), 2);
2103        assert!(cells[0].column_header && !cells[1].column_header);
2104    }
2105
2106    /// A spanning cell updates once: the record text and every covered grid
2107    /// position — a repair shows once in Markdown, not once per column.
2108    #[test]
2109    fn span_repair_updates_the_whole_cell() {
2110        let mut t = Table {
2111            rows: vec![
2112                vec!["Wide".into(), "Wide".into(), "C".into()],
2113                vec!["a".into(), "b".into(), "c".into()],
2114            ],
2115            cells: Some(vec![
2116                cell("Wide", [0.0, 0.0, 100.0, 10.0], (0, 0), (1, 2)),
2117                cell("C", [100.0, 0.0, 150.0, 10.0], (0, 2), (1, 1)),
2118            ]),
2119            ..Default::default()
2120        };
2121        // Update through the covered (non-anchor) position.
2122        assert!(t.set_cell_text(0, 1, "Fixed"));
2123        assert_eq!(
2124            t.rows[0],
2125            vec!["Fixed".to_string(), "Fixed".into(), "C".into()]
2126        );
2127        assert_eq!(t.cell_at(0, 1).unwrap().text, "Fixed");
2128        assert_eq!(t.cell_at(0, 1).unwrap().col_span, 2);
2129    }
2130
2131    /// The OCR-repair loop (#238): locate a cell by an external box (best
2132    /// IoU), replace its text, and see the fix in the export — the grid is
2133    /// the single source of truth for every serializer.
2134    #[test]
2135    fn bbox_lookup_and_repair_flow_into_exports() {
2136        let mut doc = DoclingDocument::new("t");
2137        doc.push(Node::Table(table()));
2138        assert_eq!(doc.tables().count(), 1);
2139
2140        let t = doc.tables_mut().next().unwrap();
2141        // A slightly-off OCR box still lands on the (1,1) cell.
2142        assert_eq!(t.find_cell_by_bbox([52.0, 11.0, 98.0, 19.0]), Some((1, 1)));
2143        assert_eq!(
2144            t.update_cell_by_bbox([52.0, 11.0, 98.0, 19.0], "125"),
2145            Some((1, 1))
2146        );
2147        assert_eq!(t.cell_text(1, 1), Some("125"));
2148        assert!(doc.export_to_markdown().contains("125"));
2149
2150        // No overlap → no match, nothing changed.
2151        let t = doc.tables_mut().next().unwrap();
2152        assert_eq!(t.find_cell_by_bbox([500.0, 500.0, 600.0, 600.0]), None);
2153    }
2154
2155    #[test]
2156    fn cell_accessors_bound_check_and_geometry_materializes() {
2157        let mut t = table();
2158        assert_eq!(t.cell_text(0, 0), Some("Year"));
2159        assert_eq!(t.cell_text(5, 0), None);
2160        assert!(!t.set_cell_text(0, 9, "x"), "outside the grid");
2161        assert_eq!(t.cell_bbox(1, 0), Some([0.0, 10.0, 50.0, 20.0]));
2162
2163        // A geometry-less table materializes its box grid on first set.
2164        let mut plain = Table {
2165            rows: vec![vec!["a".into(), "b".into()]],
2166            ..Default::default()
2167        };
2168        assert_eq!(plain.cell_bbox(0, 1), None);
2169        assert!(!plain.set_cell_bbox(0, 5, [0.0; 4]), "outside the grid");
2170        assert!(plain.set_cell_bbox(0, 1, [1.0, 2.0, 3.0, 4.0]));
2171        assert_eq!(plain.cell_bbox(0, 1), Some([1.0, 2.0, 3.0, 4.0]));
2172        assert_eq!(plain.find_cell_by_bbox([1.5, 2.5, 2.5, 3.5]), Some((0, 1)));
2173    }
2174}
2175
2176#[cfg(test)]
2177mod rescale_tests {
2178    use super::*;
2179
2180    fn image(dpi: u32) -> PictureImage {
2181        PictureImage {
2182            mimetype: "image/png".into(),
2183            width: 300,
2184            height: 150,
2185            data: Vec::new(),
2186            dpi,
2187            display_size: None,
2188        }
2189    }
2190
2191    /// #1093: a page measured in pixels re-measured in points — the page size,
2192    /// a table cell's box and a script run's box scale per axis, an image's
2193    /// pixels per inch of the page grow by the inverse, and the 0–511
2194    /// locations, relative to the page, stay.
2195    #[test]
2196    fn a_page_unit_change_scales_lengths_and_resolutions() {
2197        let table = Table {
2198            rows: vec![vec!["a".into()]],
2199            location: Some([10, 20, 30, 40]),
2200            cells: Some(vec![TableCell {
2201                text: "a".into(),
2202                bbox: Some([100.0, 200.0, 300.0, 400.0]),
2203                start_row: 0,
2204                start_col: 0,
2205                row_span: 1,
2206                col_span: 1,
2207                column_header: false,
2208                row_header: false,
2209                row_section: false,
2210            }]),
2211            ..Table::default()
2212        };
2213        let mut doc = DoclingDocument::new("scan");
2214        doc.push(Node::PageInfo {
2215            page_no: 1,
2216            width: 1000.0,
2217            height: 2000.0,
2218        });
2219        doc.push(Node::Located {
2220            location: [1, 2, 3, 4],
2221            inner: Box::new(Node::Table(table)),
2222        });
2223        doc.push(Node::Group {
2224            label: "group".into(),
2225            name: None,
2226            layer: None,
2227            children: vec![Node::Picture {
2228                caption: None,
2229                caption_href: None,
2230                image: Some(image(72)),
2231                classification: None,
2232                description: None,
2233                caption_parent: Default::default(),
2234                caption_location: None,
2235            }],
2236        });
2237        doc.page_images.insert(1, image(144));
2238
2239        doc.rescale_page_units(0.24, 0.5);
2240
2241        assert!(matches!(
2242            doc.nodes[0],
2243            Node::PageInfo { width, height, .. } if width == 240.0 && height == 1000.0
2244        ));
2245        let Node::Located { location, inner } = &doc.nodes[1] else {
2246            panic!("located table")
2247        };
2248        assert_eq!(*location, [1, 2, 3, 4]);
2249        let Node::Table(t) = inner.as_ref() else {
2250            panic!("table")
2251        };
2252        assert_eq!(t.location, Some([10, 20, 30, 40]));
2253        assert_eq!(
2254            t.cells.as_ref().unwrap()[0].bbox,
2255            Some([24.0, 100.0, 72.0, 200.0])
2256        );
2257        let Node::Group { children, .. } = &doc.nodes[2] else {
2258            panic!("group")
2259        };
2260        assert!(matches!(&children[0], Node::Picture { image: Some(i), .. } if i.dpi == 300));
2261        assert_eq!(doc.page_images[&1].dpi, 600);
2262    }
2263}