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