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    /// Text the Markdown export inserts between two pages — docling-core's
28    /// `MarkdownParams.page_break_placeholder` (e.g. `"<!-- page break -->"`).
29    /// `None` (the default) omits page breaks from Markdown, as docling does.
30    /// Set by `DocumentConverter::page_break_placeholder`. See
31    /// [`crate::markdown`] for where a break lands (only between two rendered
32    /// blocks that sit on different pages, never leading or trailing).
33    pub page_break_placeholder: Option<String>,
34    /// Hyperlinks recovered from the source, as `(anchor_text, href)` pairs in
35    /// document order. docling's standard pipeline drops PDF link annotations, so
36    /// these are rendered as Markdown `[anchor](href)` **only in strict mode**
37    /// (legacy/docling output is left byte-for-byte unchanged). The PDF backend
38    /// populates this from pdfium link annotations; other backends leave it empty.
39    pub links: Vec<(String, String)>,
40    /// Conversion-confidence report (#183), populated by the PDF/image ML
41    /// pipeline; `None` for declarative conversions. Deliberately **not**
42    /// part of any document export (docling keeps it on the conversion
43    /// result, outside the document schema) — docling-serve surfaces it in
44    /// the HTTP response instead.
45    pub confidence: Option<crate::confidence::ConfidenceReport>,
46    /// docling's item tree, when the backend built one (the HTML backend
47    /// does): the JSON export serializes it instead of deriving a tree from
48    /// `nodes`, so the JSON carries upstream's exact parent/child structure,
49    /// item numbering, inline groups, formatting and content layers. Every
50    /// other serializer reads `nodes`. See [`crate::tree`].
51    pub tree: Option<crate::tree::ItemTree>,
52    /// Rendered page images by 1-based page number — docling's
53    /// `PageItem.image`, filled by the PDF/image pipeline only when page
54    /// images are requested (docling's `generate_page_images`, #520). The
55    /// JSON export writes each as the page's `image`, so docling-core's
56    /// `TableItem.get_image` / `FormulaItem.get_image` can crop from it.
57    /// Empty otherwise; no other export reads it.
58    pub page_images: std::collections::BTreeMap<usize, PictureImage>,
59}
60
61/// A single piece of document content.
62#[derive(Debug, Clone, PartialEq)]
63pub enum Node {
64    /// A heading. `level` is 1-6.
65    Heading { level: u8, text: String },
66    /// A run of body text.
67    Paragraph { text: String },
68    /// A form checkbox (docling's `checkbox_selected`/`checkbox_unselected`): its
69    /// clean label `text` with the checked state. DocLang emits a `<checkbox>`
70    /// element head; Markdown/JSON render the task-list form (`- [x] `/`- [ ] `).
71    CheckboxItem { checked: bool, text: String },
72    /// A single list item at the given nesting `level` (0 = top). For ordered
73    /// items, `number` is the display number (honoring the list's `start`); it
74    /// is unused for unordered items. `first_in_list` marks the first item of a
75    /// list so the serializer can blank-line-separate adjacent sibling lists.
76    ///
77    /// `marker` is the DocLang enumeration marker (`"1."`, `"1.1."`, …) when the
78    /// backend provides one — HTML and DOCX set it for enumerated items, so
79    /// DocLang emits `<ldiv><marker>…</marker></ldiv>`; Markdown and the other
80    /// declarative backends leave it `None`, giving a bare `<ldiv/>` (matching
81    /// docling, whose Markdown backend passes no marker).
82    ListItem {
83        ordered: bool,
84        number: u64,
85        first_in_list: bool,
86        text: String,
87        level: u8,
88        marker: Option<String>,
89        /// Optional layout provenance (`x0,y0,x1,y1`, normalized to 0–511): the
90        /// four DocLang `<location>` values emitted inside the `<list>` right
91        /// after the item's `<ldiv>`. Set only by backends with real geometry
92        /// (e.g. PPTX shapes); `None` for the declarative backends. Kept on the
93        /// item itself (rather than a [`Node::Located`] wrapper) so consecutive
94        /// items still group into one `<list>`.
95        location: Option<[u16; 4]>,
96        /// DocLang-only override for items whose DocLang form diverges from their
97        /// flat Markdown `text`. Markdown/JSON always render the fields above; the
98        /// DocLang serializer, when this is `Some`, takes the list kind, marker,
99        /// and content from here instead. Used for docx multilevel numbering
100        /// (Markdown shows `- 1.1. x`, DocLang an ordered `<marker>1.1.</marker>`
101        /// with clean text) and inline equations/formatting in list items.
102        dclx: Option<ListItemDclx>,
103        /// The item's hyperlink target, when its content is a link — docling's
104        /// HTML backend emits it as an `<href uri=…/>` in the item head, and the
105        /// anchor's Markdown link markup is stripped from the rendered content.
106        /// `None` for a plain item; ignored by Markdown/JSON.
107        href: Option<String>,
108        /// Non-body content layer (docling's HTML site chrome before the first
109        /// heading → `furniture`). DocLang emits a `<layer value=…/>` in the item
110        /// head; Markdown/JSON drop a non-body item entirely.
111        layer: Option<ContentLayer>,
112    },
113    /// A fenced code block.
114    Code {
115        language: Option<String>,
116        text: String,
117        /// The original (pre-enrichment) text when the CodeFormula model
118        /// rewrote `text`: docling keeps the raw extraction in the JSON `orig`
119        /// field while `text` carries the model output. `None` → `orig == text`.
120        orig: Option<String>,
121        /// A line-preserving rendering, when the backend can reconstruct one
122        /// but docling's own output for the format cannot. The PDF pipeline
123        /// sets it (docling-parse joins code lines with single spaces, so
124        /// `text` carries that flat docling-parity form): **strict** Markdown
125        /// prefers `pretty`, every byte-conformance surface (legacy Markdown,
126        /// JSON, DocLang, chunks) serializes `text`.
127        pretty: Option<String>,
128    },
129    /// A table. The first row is treated as the header.
130    Table(Table),
131    /// A picture/figure, with an optional caption and (when a backend extracts
132    /// it) the embedded image itself.
133    Picture {
134        caption: Option<String>,
135        /// Hyperlink annotation on the caption (docling's caption text item
136        /// `hyperlink`): the HTML backend sets it when an `<a href>` wraps the
137        /// image whose `alt` became the caption. DocLang emits the block-form
138        /// `<caption>` with an `<href uri=…/>` head; JSON puts `hyperlink` on
139        /// the caption item; Markdown and LaTeX print the plain caption text,
140        /// as docling does.
141        caption_href: Option<String>,
142        image: Option<PictureImage>,
143        /// DocumentPictureClassifier predictions (all classes, descending
144        /// confidence), when the picture-classification enrichment ran.
145        /// Serialized as docling's `classification` annotation + `meta` field
146        /// on the JSON picture item; Markdown/DocLang output is unaffected.
147        classification: Option<Vec<PictureClass>>,
148        /// Where the caption item hangs in the JSON tree (#390); see
149        /// [`CaptionParent`]. Markdown, DocLang and LaTeX ignore it.
150        caption_parent: CaptionParent,
151        /// The caption's own box on the picture's page (0–511 grid, like
152        /// [`Node::Located`]) — the PDF pipeline's caption layout region. The
153        /// JSON export writes it as the caption item's `prov` (#609), as
154        /// docling's `ReadingOrderModel._add_caption_or_footnote` does; `None`
155        /// (every declarative backend) leaves the caption without one.
156        caption_location: Option<[u16; 4]>,
157    },
158    /// A display-math formula item decoded by the CodeFormula enrichment:
159    /// `latex` is the model's LaTeX (no `$$` wrapping), `orig` the raw glyph
160    /// text extracted from the PDF. Markdown renders `$$latex$$`; JSON emits a
161    /// `formula` text item (docling's un-enriched pipeline instead emits a
162    /// placeholder paragraph — see the PDF assembler).
163    Formula {
164        latex: String,
165        orig: String,
166        location: Option<[u16; 4]>,
167    },
168    /// A standalone caption item (docling's `DocItemLabel.CAPTION` text that
169    /// no picture or table claims): the HTML backend emits a `<figure>`'s
170    /// `<figcaption>` this way when the figure produced no picture and its
171    /// first item is not a table (docling#4050). `href` is the caption's
172    /// hyperlink annotation (the first link inside the figcaption); Markdown
173    /// renders it as `[text](href)`, JSON puts `hyperlink` on the caption
174    /// item, DocLang emits the block-form `<caption>` with an `<href>` head.
175    Caption { text: String, href: Option<String> },
176    /// A body text item with a docling label of its own and an optional
177    /// hyperlink — the PDF pipeline's `footnote` regions, whose item docling
178    /// keeps as a `footnote` text with the link annotation covering it as its
179    /// `hyperlink` (`PageAssembleModel._match_hyperlink`). The JSON writes
180    /// exactly that (label, raw text, `hyperlink`); every other serializer
181    /// renders it as the paragraph [`Self::labeled_markdown`] spells —
182    /// docling's Markdown wraps a linked item's whole text, `[text](uri)`.
183    LabeledText {
184        label: String,
185        text: String,
186        href: Option<String>,
187    },
188    /// A chart (docling's `PictureItem` classified as a chart, carrying a
189    /// `PictureTabularChartData` annotation). Markdown and JSON render it exactly
190    /// like a [`Node::Picture`] placeholder (an `<!-- image -->` / `picture`
191    /// item); the DocLang serializer emits `<picture class="chart">` with a
192    /// `<label value="{kind}"/>` and the data `table` as a `<tabular>`.
193    Chart {
194        /// docling's classification label, e.g. `bar_chart`, `line_chart`.
195        kind: String,
196        /// The chart's data grid (row 0 is the header band).
197        table: Table,
198        /// The chart title (docling's caption item on the picture).
199        caption: Option<String>,
200        /// DocLang `<location>` provenance for the picture element.
201        location: Option<[u16; 4]>,
202    },
203    /// A logical grouping of child nodes (e.g. a list, a section, a spreadsheet
204    /// sheet). `name` is docling's group name when it differs from the label —
205    /// an xlsx sheet group is `label: "sheet"`, `name: Some("Sheet1")`. `layer`
206    /// puts the group *and* everything it contains on a non-body content layer
207    /// (a hidden sheet is `invisible`), which is how the serializers that only
208    /// render body content know to skip it; DocLang stamps each child with the
209    /// layer token, exactly as a [`Node::Furniture`] wrapper on each would.
210    /// DocLang has no group element, so a group is transparent there.
211    Group {
212        label: String,
213        name: Option<String>,
214        layer: Option<ContentLayer>,
215        children: Vec<Node>,
216    },
217    /// A form key-value region (docling's `field_region`): a set of form fields,
218    /// each pairing an optional marker, key, and value. Backends detect these
219    /// from form structure (e.g. HTML's `keyN` / `keyN_valueM` / `keyN_marker`
220    /// `id`-convention); the serializers render each item's parts as separate
221    /// labelled texts (`marker` / `field_key` / `field_value`).
222    FieldRegion { items: Vec<FieldItem> },
223    /// docling's `KeyValueItem`: a graph of key and value cells and the links
224    /// between them (docling-core's `GraphData`). The XBRL backend builds one
225    /// from an instance's numeric facts and the presentation and calculation
226    /// hierarchies of its taxonomy. Only the JSON export carries the graph:
227    /// docling's Markdown serializer has no rendering for the item and writes
228    /// its `<!-- missing-key-value-item -->` placeholder, which the Markdown
229    /// export reproduces; the other serializers omit it.
230    KeyValueGraph {
231        cells: Vec<GraphCell>,
232        links: Vec<GraphLink>,
233    },
234    /// Rich inline content — docling's `InlineGroup`: a run of styled text
235    /// segments that a backend captured with formatting (`<bold>`, `<italic>`,
236    /// `<underline>`, `<strikethrough>`, sub/superscript, inline `<code>`) the
237    /// flat Markdown text cannot represent. Markdown/JSON render this exactly
238    /// like `Paragraph { text: md_text }` (so their output is unchanged); the
239    /// DocLang serializer uses the structured `runs`. `unwrapped` is set when the
240    /// group's docling parent is a heading/text (no enclosing `<text>` wrapper).
241    InlineGroup {
242        unwrapped: bool,
243        runs: Vec<InlineRun>,
244        md_text: String,
245    },
246    /// A node in a non-body content layer — `furniture` (page headers/footers,
247    /// the HTML `<title>`, site navigation/chrome) or `notes` (docx comments).
248    /// Markdown and JSON omit these layers by default; DocLang renders the wrapped
249    /// node with a `<layer value="{layer}"/>` head.
250    Furniture {
251        layer: ContentLayer,
252        inner: Box<Node>,
253    },
254    /// One reviewer comment: docling's notes-layer `comment_section` group
255    /// holding a single text item. `name` is docling's own — `comment-{id}` for
256    /// a docx `w:comment`, `comment-{sheet}-{cell}` for a spreadsheet cell note.
257    /// JSON emits the group plus its notes-layer text; DocLang emits the flat
258    /// `<text><layer value="notes"/>…</text>` upstream writes (its DocLang
259    /// carries no group for comments); Markdown and LaTeX omit the notes layer.
260    ///
261    /// `refs_note_text` picks what a [`Node::Commented`] annotation points at,
262    /// mirroring an upstream asymmetry: docling-core's `add_comment` appends the
263    /// **note text**'s ref to each target (which is what the xlsx backend gets),
264    /// while the docx backend overwrites that with the **group**'s ref so a
265    /// comment's replies group together.
266    ///
267    /// `grouped` is whether docling wraps the note in a `comment_section`
268    /// group at all: the docx and spreadsheet backends do, while backends that
269    /// call docling-core's `add_comment` directly (Pages, #383) get a bare
270    /// notes-layer text item under the body — JSON then emits no group and
271    /// `name` is unused.
272    CommentSection {
273        name: String,
274        text: String,
275        refs_note_text: bool,
276        grouped: bool,
277    },
278    /// A body item annotated by reviewer comments: `comments` are indices into
279    /// the document's [`Node::CommentSection`] nodes, in document order. JSON
280    /// emits docling's `comments: [{"$ref": …}]` on the item, each ref pointing
281    /// where the section says (see [`Node::CommentSection::refs_note_text`]);
282    /// every other serializer renders `inner` unchanged.
283    Commented {
284        comments: Vec<usize>,
285        inner: Box<Node>,
286    },
287    /// A text node taken from a time-based track — an ASR segment (#614):
288    /// docling's `TrackSource`. The JSON writes docling's ASR text item — `cue`
289    /// (the segment's words) as its text, `track` as its `source: [{"kind":
290    /// "track", …}]` — which the WebVTT export makes a cue of; every other
291    /// serializer renders `inner` (the `[time: start-end] words` paragraph)
292    /// unchanged.
293    Track {
294        track: crate::tree::TreeTrack,
295        cue: String,
296        inner: Box<Node>,
297    },
298    /// A node carrying layout provenance — the four DocLang `<location>` values
299    /// (`x0,y0,x1,y1`, normalized to 0–511) docling attaches to elements from
300    /// backends with real geometry (e.g. the slide shapes in PPTX). Markdown and
301    /// JSON render the wrapped node unchanged; DocLang emits the `<location>`
302    /// tokens as the element's first children.
303    Located {
304        location: [u16; 4],
305        inner: Box<Node>,
306    },
307    /// Exact page provenance for a backend whose geometry already *is* the
308    /// page's coordinate system — an XLSX item's cell-index box on its sheet,
309    /// which docling writes verbatim (`bbox` in a top-left origin, the
310    /// `charspan` the backend chose) and sizes the page from. The 0–511 grid
311    /// of a [`Node::Located`] cannot round-trip such integers exactly, so the
312    /// JSON export reads this wrapper; every other serializer renders `inner`
313    /// unchanged (DocLang keeps taking its `<location>` tokens from the grid).
314    Prov {
315        page_no: usize,
316        /// `[l, t, r, b]`, page units, top-left origin.
317        bbox: [f32; 4],
318        /// docling's `charspan` for the item (`[0, 0]` for an XLSX table).
319        charspan: [usize; 2],
320        /// The item's creation rank among its siblings, when that differs
321        /// from the node order: docling numbers `#/tables/N` / `#/texts/N` /
322        /// `#/pictures/N` in the order it *creates* items (a sheet's tables,
323        /// then its images, then its charts) and only afterwards sorts the
324        /// container's children by position. The JSON export adds siblings in
325        /// this order and lays their refs out in node order; `None` when the
326        /// two orders coincide.
327        seq: Option<usize>,
328        inner: Box<Node>,
329    },
330    /// A PDF page header or footer (docling's `page_header`/`page_footer`
331    /// furniture): DocLang emits `<page_header>`/`<page_footer>` with a
332    /// `<layer value="furniture"/>` head, the four `<location>` tokens, then the
333    /// text. The JSON writes it as a body-parented `page_header`/`page_footer`
334    /// text item on the furniture layer; Markdown omits it.
335    PageFurniture {
336        footer: bool,
337        location: [u16; 4],
338        text: String,
339    },
340    /// A furniture-layer text item with an explicit docling label — a page
341    /// header / footer paragraph (`page_header` / `page_footer`) or a note
342    /// body (`footnote`) from a backend that builds no item tree (#535: the
343    /// Word 97 `.doc` stories). The JSON writes a body-parented item of that
344    /// label on the furniture layer; DocLang `<{label}>` with a `<layer
345    /// value="furniture"/>` head (docling-core's own shape); Markdown, LaTeX
346    /// and the chunker leave it out like any furniture.
347    FurnitureText { label: String, text: String },
348    /// The text a PDF picture contains, kept the way docling keeps it: every
349    /// regular layout cluster > 80 % inside a picture cluster is that
350    /// `PictureItem`'s child (`LayoutPostprocessor._set_cluster_children`,
351    /// `ReadingOrderModel._add_child_elements`). Emitted right after its
352    /// picture node. The JSON export writes these nodes as items parented to
353    /// that picture, after its caption; docling's Markdown and LaTeX picture
354    /// serializers print only the caption and the image, so every other
355    /// serializer skips it — except the Markdown export asked to
356    /// `traverse_pictures` ([`MarkdownExportOptions`], #599), which renders
357    /// them after the picture like upstream's item walk does.
358    PictureChildren(Vec<Node>),
359    /// A page boundary — docling's implicit page break between pages. The PPTX
360    /// backend emits one between consecutive slides. DocLang renders it as
361    /// `<page_break/>`; Markdown and JSON omit it (matching docling's default
362    /// exports, which carry page breaks only in the document model).
363    PageBreak,
364    /// An invisible page marker — the first node of every page the PDF paths
365    /// assemble: the 1-based page number and the page size in PDF points. It
366    /// carries exactly what the JSON export needs to populate docling's
367    /// `pages` map and to denormalize the 0–511 `<location>` grid back into
368    /// BOTTOMLEFT point bboxes for per-item `prov` (#171). Every other
369    /// serializer skips it, so Markdown / DocLang / DocTags output is
370    /// byte-for-byte unchanged.
371    PageInfo {
372        /// 1-based page number (0 = "not yet numbered": the assembler emits
373        /// the marker, the document-level collector stamps the real number).
374        page_no: usize,
375        /// Page width in PDF points.
376        width: f32,
377        /// Page height in PDF points.
378        height: f32,
379    },
380    /// A node docling keeps in the document model (and DocLang) but leaves out
381    /// of the Markdown and JSON exports — e.g. an ODF *presentation*'s pictures
382    /// and charts, which appear in the `.dclx` body but not in its `.md`/`.json`.
383    /// DocLang renders the wrapped node in place; Markdown and JSON skip it.
384    DoclangOnly(Box<Node>),
385    /// A verbatim plain-text dump — docling's plain-text backend emits the whole
386    /// file as a single text item (used for legacy USPTO APS `.txt` grants, which
387    /// docling routes to plain text rather than its APS parser). The stored string
388    /// is the file body, one record per line. Markdown/JSON render it as one text
389    /// block; the DocLang serializer reproduces minidom's per-line layout, CDATA-
390    /// escaping only the lines that need it (see `emit_text_dump`).
391    TextDump(String),
392}
393
394/// Vertical text position of an [`InlineRun`] — docling's `Script`.
395#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
396pub enum Script {
397    #[default]
398    Baseline,
399    Sub,
400    Super,
401}
402
403/// One styled segment of a [`Node::InlineGroup`] — the docling.rs analogue of a
404/// `TextItem` inside an `InlineGroup`, carrying the ancestor formatting docling
405/// tracks. `text` is already whitespace-normalized/trimmed (one segment per
406/// source text node). A hyperlink is intentionally not stored: DocLang drops the
407/// target inside inline scope, keeping only the anchor text.
408#[derive(Debug, Clone, PartialEq, Eq, Default)]
409pub struct InlineRun {
410    pub text: String,
411    pub bold: bool,
412    pub italic: bool,
413    pub underline: bool,
414    pub strike: bool,
415    pub script: Script,
416    pub code: bool,
417    /// An inline equation (`text` holds LaTeX): DocLang renders `<formula>…`,
418    /// Markdown/JSON keep the `$…$` already baked into the group's `md_text`.
419    pub formula: bool,
420}
421
422/// A DocLang content layer other than the default `body` (see [`Node::Furniture`]).
423#[derive(Debug, Clone, Copy, PartialEq, Eq)]
424pub enum ContentLayer {
425    /// Page headers/footers, HTML `<title>`, site navigation/chrome.
426    Furniture,
427    /// Editorial notes (docx reviewer comments).
428    Notes,
429    /// Invisible content (hidden spreadsheet sheets).
430    Invisible,
431}
432
433impl ContentLayer {
434    /// The `<layer value="…"/>` token value.
435    pub fn value(self) -> &'static str {
436        match self {
437            ContentLayer::Furniture => "furniture",
438            ContentLayer::Notes => "notes",
439            ContentLayer::Invisible => "invisible",
440        }
441    }
442}
443
444/// A set of content layers, `body` included — docling-core's
445/// `set[ContentLayer]` (`HTMLParams.layers`,
446/// `export_to_html(included_content_layers=…)`), where `body` is a member
447/// like any other. [`Default`] is docling's `DEFAULT_CONTENT_LAYERS`: body
448/// only, so an export built with it is unchanged from before layers could
449/// be chosen (#499).
450#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
451pub struct ContentLayers {
452    /// The main content (items without an explicit layer).
453    pub body: bool,
454    /// [`ContentLayer::Furniture`]: page headers/footers, navigation chrome.
455    pub furniture: bool,
456    /// [`ContentLayer::Notes`]: reviewer comments and other editorial notes.
457    pub notes: bool,
458    /// [`ContentLayer::Invisible`]: hidden content (hidden sheets, …).
459    pub invisible: bool,
460}
461
462impl Default for ContentLayers {
463    fn default() -> Self {
464        Self::BODY
465    }
466}
467
468impl ContentLayers {
469    /// Body only — docling's `DEFAULT_CONTENT_LAYERS`.
470    pub const BODY: Self = Self {
471        body: true,
472        furniture: false,
473        notes: false,
474        invisible: false,
475    };
476    /// Every layer — Python's `set(ContentLayer)`.
477    pub const ALL: Self = Self {
478        body: true,
479        furniture: true,
480        notes: true,
481        invisible: true,
482    };
483    /// No layer at all (nothing renders); build a set from it with
484    /// [`with`](Self::with) / [`with_body`](Self::with_body).
485    pub const NONE: Self = Self {
486        body: false,
487        furniture: false,
488        notes: false,
489        invisible: false,
490    };
491
492    /// The set plus `layer`.
493    pub const fn with(mut self, layer: ContentLayer) -> Self {
494        match layer {
495            ContentLayer::Furniture => self.furniture = true,
496            ContentLayer::Notes => self.notes = true,
497            ContentLayer::Invisible => self.invisible = true,
498        }
499        self
500    }
501
502    /// The set plus the body layer.
503    pub const fn with_body(mut self) -> Self {
504        self.body = true;
505        self
506    }
507
508    /// Whether `layer` is in the set; `None` is the body layer.
509    pub fn contains(&self, layer: Option<ContentLayer>) -> bool {
510        match layer {
511            None => self.body,
512            Some(ContentLayer::Furniture) => self.furniture,
513            Some(ContentLayer::Notes) => self.notes,
514            Some(ContentLayer::Invisible) => self.invisible,
515        }
516    }
517
518    /// Whether the layer spelled `name` (`body`, `furniture`, `notes`,
519    /// `invisible` — the JSON `content_layer` values) is in the set; an
520    /// unknown name is not.
521    pub fn contains_name(&self, name: &str) -> bool {
522        match name {
523            "body" => self.body,
524            "furniture" => self.furniture,
525            "notes" => self.notes,
526            "invisible" => self.invisible,
527            _ => false,
528        }
529    }
530
531    /// Parse a comma-separated list of layer names (`body,furniture`;
532    /// whitespace around a name is ignored, `all` is every layer). An
533    /// unknown name is the error. docling-core 2.99's `background` layer
534    /// (watermarks) has no items in this model, so the name is accepted and
535    /// adds nothing — a set written for Python keeps parsing.
536    pub fn parse_list(list: &str) -> Result<Self, String> {
537        let mut set = Self::NONE;
538        for name in list.split(',').map(str::trim).filter(|n| !n.is_empty()) {
539            match name {
540                "body" => set.body = true,
541                "furniture" => set.furniture = true,
542                "notes" => set.notes = true,
543                "invisible" => set.invisible = true,
544                "background" => {}
545                "all" => set = Self::ALL,
546                other => {
547                    return Err(format!(
548                        "unknown content layer `{other}` (expected body, furniture, notes, invisible or all)"
549                    ))
550                }
551            }
552        }
553        Ok(set)
554    }
555}
556
557/// Options of the HTML export ([`DoclingDocument::export_to_html_with`]):
558/// docling-core's `HTMLParams` subset the port honours. [`Default`] is
559/// upstream's default export — placeholder images, `artifacts` as the
560/// referenced-image directory, the body layer only.
561#[derive(Debug, Clone, PartialEq, Eq)]
562pub struct HtmlExportOptions {
563    /// How pictures render (`HTMLParams.image_mode`): nothing but captions
564    /// and meta for [`ImageMode::Placeholder`], `data:` URIs when embedded,
565    /// `<img src>` paths under [`artifacts_dir`](Self::artifacts_dir) when
566    /// referenced.
567    pub image_mode: ImageMode,
568    /// The directory referenced images are named under, the Markdown
569    /// export's convention (`<artifacts_dir>/image_NNNNNN.<ext>`).
570    pub artifacts_dir: String,
571    /// The content layers rendered (`HTMLParams.layers`, #499): an item on a
572    /// layer outside the set is skipped, its children still walked — exactly
573    /// how docling-core's `get_excluded_refs` reads the set.
574    pub layers: ContentLayers,
575}
576
577impl Default for HtmlExportOptions {
578    fn default() -> Self {
579        Self {
580            image_mode: ImageMode::Placeholder,
581            artifacts_dir: "artifacts".to_string(),
582            layers: ContentLayers::BODY,
583        }
584    }
585}
586
587/// Options of the Markdown export
588/// ([`DoclingDocument::export_to_markdown_with_options`], #599): the
589/// docling-core `MarkdownParams` the port honours beyond the image mode.
590/// [`Default`] is upstream's default export — placeholder images,
591/// `artifacts` as the referenced-image directory, the body layer only, no
592/// picture traversal, HTML and underscore escaping on, `<!-- image -->` —
593/// so a document exported with it is byte-identical to
594/// [`DoclingDocument::export_to_markdown`].
595#[derive(Debug, Clone, PartialEq, Eq)]
596pub struct MarkdownExportOptions {
597    /// How pictures render (`MarkdownParams.image_mode`): the placeholder,
598    /// `data:` URIs when embedded, `![Image](<artifacts_dir>/image_NNNNNN.<ext>)`
599    /// when referenced (the bytes come back for the caller to write).
600    pub image_mode: ImageMode,
601    /// The directory referenced images are named under.
602    pub artifacts_dir: String,
603    /// The content layers rendered (`MarkdownParams.layers`,
604    /// `export_to_markdown(included_content_layers=…)`): an item on a layer
605    /// outside the set is skipped, its children still walked. The default
606    /// body-only set drops page headers/footers (`furniture`), reviewer
607    /// comments (`notes`) and hidden sheets (`invisible`), as upstream does; a
608    /// scanned form's running header reads out with
609    /// `ContentLayers::BODY.with(ContentLayer::Furniture)`. The extra items
610    /// render through the body's serializers — a page header is a paragraph.
611    pub layers: ContentLayers,
612    /// `CommonParams.traverse_pictures`: render the text items nested in a
613    /// picture (the PDF pipeline's picture children — a bordered form laid
614    /// out as one picture holds every field as a child) after the picture's
615    /// own caption and image, as upstream yields them. Off, a picture prints
616    /// only its caption and image.
617    pub traverse_pictures: bool,
618    /// `MarkdownParams.escape_html`: `&`, `<` and `>` in text as `&amp;`,
619    /// `&lt;`, `&gt;` (Python's `html.escape(quote=False)`). Off, `R&D` stays
620    /// `R&D`.
621    pub escape_html: bool,
622    /// `MarkdownParams.escape_underscores`: `_` in text as `\_`. Off, the
623    /// text keeps its underscores.
624    pub escape_underscores: bool,
625    /// `MarkdownParams.image_placeholder`: what a picture prints as when it
626    /// renders no image data (the placeholder mode, or a picture without a
627    /// payload); upstream's `<!-- image -->`.
628    pub image_placeholder: String,
629    /// docling-core's `PlainTextDocSerializer` (#613, `export_to_text`,
630    /// docling's `--to text`): the Markdown walk with the decoration turned
631    /// off — headings without `#`, bold/italic/strikethrough markers and
632    /// inline code backticks dropped, a hyperlink reduced to its label, code
633    /// blocks unfenced, no GFM hard line breaks. List bullets/numbers,
634    /// checkbox marks and table grids stay. [`Self::plain_text`] pairs it
635    /// with upstream's `PlainTextParams` (no escaping, an empty image
636    /// placeholder).
637    pub plain_text: bool,
638}
639
640impl MarkdownExportOptions {
641    /// docling-core's `PlainTextParams` defaults (#613): [`Self::plain_text`]
642    /// on, HTML and underscore escaping off, pictures print nothing (their
643    /// captions still do), body layer only, no picture traversal — what
644    /// `DoclingDocument.export_to_text()` and docling's `--to text` write.
645    pub fn plain_text() -> Self {
646        Self {
647            escape_html: false,
648            escape_underscores: false,
649            image_placeholder: String::new(),
650            plain_text: true,
651            ..Self::default()
652        }
653    }
654}
655
656impl Default for MarkdownExportOptions {
657    fn default() -> Self {
658        Self {
659            image_mode: ImageMode::Placeholder,
660            artifacts_dir: "artifacts".to_string(),
661            layers: ContentLayers::BODY,
662            traverse_pictures: false,
663            escape_html: true,
664            escape_underscores: true,
665            image_placeholder: "<!-- image -->".to_string(),
666            plain_text: false,
667        }
668    }
669}
670
671/// DocLang-only content for a [`Node::ListItem`] whose DocLang form differs from
672/// its flat Markdown `text` (see [`Node::ListItem::dclx`]). `ordered` picks the
673/// enclosing `<list>` kind, `marker` the `<ldiv><marker>`; content is `runs`
674/// (structured equations/formatting) when non-empty, else `text` re-parsed for
675/// inline markers.
676#[derive(Debug, Clone, PartialEq, Eq, Default)]
677pub struct ListItemDclx {
678    pub ordered: bool,
679    pub marker: Option<String>,
680    pub text: String,
681    pub runs: Vec<InlineRun>,
682}
683
684impl Node {
685    /// The paragraph a [`Node::LabeledText`] renders as outside the JSON:
686    /// its text, wrapped as `[text](uri)` when it carries a hyperlink. Any
687    /// other node is returned unchanged.
688    pub fn labeled_as_paragraph(&self) -> std::borrow::Cow<'_, Node> {
689        match self {
690            Node::LabeledText { text, href, .. } => std::borrow::Cow::Owned(Node::Paragraph {
691                text: match href {
692                    Some(uri) => format!("[{text}]({uri})"),
693                    None => text.clone(),
694                },
695            }),
696            other => std::borrow::Cow::Borrowed(other),
697        }
698    }
699}
700
701impl InlineRun {
702    /// A run with no active formatting (renders as bare inline text).
703    pub fn is_plain(&self) -> bool {
704        !self.bold
705            && !self.italic
706            && !self.underline
707            && !self.strike
708            && !self.code
709            && !self.formula
710            && self.script == Script::Baseline
711    }
712}
713
714/// Build the [`Node`] for a paragraph of inline content from its structured
715/// `runs` and Markdown text, applying docling's `InlineGroup` boundary:
716///
717/// * a single plain run (or none) → a plain [`Node::Paragraph`] (which the
718///   serializers render as `<text>…</text>`, and a lone hyperlink via `<href>`);
719/// * a single uniformly-formatted run, or two or more runs → a
720///   [`Node::InlineGroup`]. `unwrapped` (the group's docling parent is a
721///   heading, so no enclosing `<text>`) only applies to multi-run groups.
722///
723/// Markdown/JSON render the group's `md_text`, so their output is identical to
724/// emitting a `Paragraph` — the structured runs are DocLang-only.
725pub fn inline_paragraph_node(md_text: String, runs: Vec<InlineRun>, unwrapped: bool) -> Node {
726    let single_plain = runs.len() <= 1 && runs.first().is_none_or(|r| r.is_plain());
727    if single_plain {
728        Node::Paragraph { text: md_text }
729    } else {
730        Node::InlineGroup {
731            unwrapped: unwrapped && runs.len() >= 2,
732            runs,
733            md_text,
734        }
735    }
736}
737
738/// One entry of a [`Node::FieldRegion`]: a marker/key/value triple, any of which
739/// may be absent. Mirrors docling's `field_item` with its `marker` / `field_key`
740/// / `field_value` child texts.
741#[derive(Debug, Clone, PartialEq, Default)]
742pub struct FieldItem {
743    pub marker: Option<String>,
744    pub key: Option<String>,
745    pub value: Option<String>,
746    /// docling's `kind` on the `field_value` item — `read_only` or
747    /// `fillable` (the value is or holds a form control); JSON-only.
748    pub value_kind: Option<String>,
749}
750
751/// One node of a [`Node::KeyValueGraph`] — docling-core's `GraphCell`.
752#[derive(Debug, Clone, PartialEq)]
753pub struct GraphCell {
754    /// docling's `GraphCellLabel` value: `key` or `value` (it also knows
755    /// `unspecified` and `checkbox`).
756    pub label: String,
757    /// The cell's number within its graph, what the links refer to.
758    pub cell_id: usize,
759    pub text: String,
760    /// The text before any cleanup — for an XBRL fact key, the concept's
761    /// qualified name where `text` is its local name.
762    pub orig: String,
763}
764
765/// One edge of a [`Node::KeyValueGraph`] — docling-core's `GraphLink`.
766#[derive(Debug, Clone, PartialEq)]
767pub struct GraphLink {
768    /// docling's `GraphLinkLabel` value: `to_value`, `to_child`, `to_parent`
769    /// or `to_key`.
770    pub label: String,
771    pub source_cell_id: usize,
772    pub target_cell_id: usize,
773}
774
775/// One DocumentPictureClassifier prediction — docling-core's
776/// `PictureClassificationClass` (`class_name` + `confidence`).
777#[derive(Debug, Clone, PartialEq)]
778pub struct PictureClass {
779    /// e.g. `bar_chart`, `logo`, `signature` (the classifier's 26-label set).
780    pub class_name: String,
781    pub confidence: f32,
782}
783
784/// An extracted picture's raw encoded bytes plus its mimetype and pixel size —
785/// the docling.rs analogue of docling-core's `ImageRef`.
786#[derive(Debug, Clone, PartialEq)]
787pub struct PictureImage {
788    /// e.g. `image/png`, `image/jpeg`.
789    pub mimetype: String,
790    pub width: u32,
791    pub height: u32,
792    /// The image file bytes, exactly as embedded (PNG/JPEG/…).
793    pub data: Vec<u8>,
794    /// Pixels per inch of the image relative to the page it came from —
795    /// docling-core's `ImageRef.dpi`, which consumers use to map pixels back
796    /// to points. A crop rendered from a PDF page at `s` px/pt is `72·s`
797    /// (docling: `int(72 * images_scale)`, #519); an image embedded in an
798    /// office file has no render scale and keeps docling's `72`
799    /// ([`Self::DEFAULT_DPI`]).
800    pub dpi: u32,
801}
802
803impl PictureImage {
804    /// docling's `ImageRef` default when no render scale applies.
805    pub const DEFAULT_DPI: u32 = 72;
806
807    /// The `dpi` of an image rendered at `scale` pixels per PDF point
808    /// (`72·scale`, rounded — `int()` would floor 143.99… to 143).
809    pub fn dpi_for_scale(scale: f32) -> u32 {
810        (72.0 * scale).round().max(1.0) as u32
811    }
812
813    /// A `data:` URI for the image (`data:<mimetype>;base64,<…>`).
814    pub fn data_uri(&self) -> String {
815        format!(
816            "data:{};base64,{}",
817            self.mimetype,
818            crate::base64::encode(&self.data)
819        )
820    }
821}
822
823/// One table cell as a first-class object (#240) — the Rust counterpart of
824/// docling's `TableCell`: its text, page geometry, grid rectangle and header
825/// roles. Produced by the PDF TableFormer paths from the predicted OTSL
826/// structure; `bbox` is `[l, t, r, b]` in page points with a top-left origin.
827#[derive(Debug, Clone, PartialEq)]
828pub struct TableCell {
829    pub text: String,
830    /// `[l, t, r, b]`, page points, top-left origin; `None` without geometry.
831    pub bbox: Option<[f32; 4]>,
832    /// Anchor grid position (0-based row/column offsets).
833    pub start_row: usize,
834    pub start_col: usize,
835    /// Span extents (≥ 1); the covered grid positions repeat the cell's text
836    /// in [`Table::rows`].
837    pub row_span: usize,
838    pub col_span: usize,
839    /// OTSL `ched` — a column-header cell.
840    pub column_header: bool,
841    /// OTSL `rhed` — a row-header cell.
842    pub row_header: bool,
843    /// OTSL `srow` — a section-row cell.
844    pub row_section: bool,
845}
846
847/// Where a picture's or table's caption text item hangs in the docling-JSON
848/// tree (#390). docling's backends do not agree, and the JSON structure is
849/// the only surface that shows it (Markdown, DocLang and LaTeX place a
850/// caption by its item, whatever its parent): the PDF pipeline parents a
851/// layout caption to the picture or table it belongs to, while every
852/// declarative backend creates the caption with `doc.add_text(label=CAPTION)`
853/// and no parent — the document body — even when the item itself sits in a
854/// group or under a section header (JATS, LaTeX, HTML, Markdown, EPUB,
855/// AsciiDoc all do). The office backends hang a chart's title caption off the
856/// chart's container (the sheet group, the slide, docx's current parent,
857/// docling#4190) — that is [`Node::Chart`]'s own path, not this choice. A
858/// backend that adds a new captioned item picks the variant matching
859/// upstream's `add_text` call for that format; the default is upstream's
860/// default.
861#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
862pub enum CaptionParent {
863    /// `#/body`, listed after the enclosing top-level item — docling's
864    /// `add_text` default, which every declarative backend leaves alone.
865    #[default]
866    Body,
867    /// The item's own container (its `parent`), listed ahead of the item:
868    /// the caption is created first, as docling's office backends do.
869    Container,
870    /// The item's own container, listed *after* the item: docling's HTML
871    /// backend adds a `<figure>`-wrapped table, then its `<figcaption>` under
872    /// `self.parents[self.level]` (docling#4050).
873    ContainerAfter,
874    /// The item itself — the caption is the picture's or table's first
875    /// child, as docling's PDF pipeline attaches a layout caption.
876    Item,
877}
878
879/// A simple row-major table. By default `rows[0]` is the header row; a
880/// [`TableStructure`] overlay overrides that and adds column spans.
881#[derive(Debug, Clone, PartialEq, Default)]
882pub struct Table {
883    pub rows: Vec<Vec<String>>,
884    /// Optional layout provenance: the four DocLang `<location>` values
885    /// (`x0,y0,x1,y1`, each already normalized to the 0–511 resolution) emitted
886    /// before the table's cells. Set only by backends with real geometry (e.g.
887    /// the spreadsheet backend, whose cell grid yields a bounding box); left
888    /// `None` by declarative backends, which have no coordinates.
889    pub location: Option<[u16; 4]>,
890    /// Optional OTSL structure overlay for backends that parse real table
891    /// geometry (USPTO CALS): explicit header-row count and horizontal-span
892    /// continuations. `None` → the default (row 0 is the header, no spans).
893    /// `rows` still carries the full text grid (span text replicated) for
894    /// Markdown/JSON; DocLang uses this overlay to emit `<ched/>`/`<lcel/>`.
895    pub structure: Option<TableStructure>,
896    /// Optional per-cell block content, parallel to `rows`. A *rich* cell (an
897    /// ODF cell holding a list, several paragraphs, or a nested table) carries
898    /// its DocLang blocks here; the DocLang serializer emits them after the
899    /// cell token instead of the flat `rows` text. Markdown/JSON ignore this
900    /// and render `rows`, so their output is unchanged. `None` (or an empty
901    /// `Vec` for a given cell) → the flat text is used everywhere.
902    pub cell_blocks: Option<Vec<Vec<Vec<Node>>>>,
903    /// Optional caption (docling's `TableItem.captions`): the JATS
904    /// `<table-wrap>` label+caption, an HTML `<caption>`, etc. Markdown renders
905    /// it as a text line *before* the grid; JSON emits a caption text item the
906    /// table references; DocLang emits a `<caption>` as the table's first child.
907    /// `None` → the table has no caption.
908    pub caption: Option<String>,
909    /// Where the caption item hangs in the JSON tree (#390); see
910    /// [`CaptionParent`]. Only the JSON export reads it.
911    pub caption_parent: CaptionParent,
912    /// The caption's own box on the table's page (0–511 grid) — the PDF
913    /// pipeline's caption layout region, written as the caption item's
914    /// `prov` (#609); see [`Node::Picture`]'s field of the same name.
915    pub caption_location: Option<[u16; 4]>,
916    /// Optional per-cell bounding boxes, same shape as [`Self::rows`]: `[l, t,
917    /// r, b]` in page points with a **top-left** origin (the PDF pipeline's
918    /// native space). Set by the ML pipeline's TableFormer paths — a spanned
919    /// cell repeats its anchor's box across the covered grid positions — and
920    /// First-class cells (#240): the authoritative per-cell records —
921    /// text, page geometry, spans and header roles — when the backend
922    /// produces them (the PDF TableFormer paths do; declarative backends
923    /// leave `None`). [`Self::rows`] stays the dense text grid every
924    /// serializer renders (a spanning cell's text is replicated across its
925    /// covered positions there); JSON serializes these cells verbatim when
926    /// present, and the DocLang structure overlay is derived from them.
927    pub cells: Option<Vec<TableCell>>,
928}
929
930impl Table {
931    /// A cell's text at a grid position, `None` outside the grid.
932    pub fn cell_text(&self, row: usize, col: usize) -> Option<&str> {
933        self.rows.get(row)?.get(col).map(String::as_str)
934    }
935
936    /// Replace the text at a grid position; `false` (and no change) outside
937    /// the grid. When a first-class cell covers the position, the whole
938    /// cell is updated: its record text and every grid position its span
939    /// covers, so the repair shows once in Markdown, not once per covered
940    /// column.
941    pub fn set_cell_text(&mut self, row: usize, col: usize, text: impl Into<String>) -> bool {
942        if self.rows.get(row).and_then(|r| r.get(col)).is_none() {
943            return false;
944        }
945        let text = text.into();
946        let covering = self.cells.as_mut().and_then(|cells| {
947            cells.iter_mut().find(|c| {
948                (c.start_row..c.start_row + c.row_span).contains(&row)
949                    && (c.start_col..c.start_col + c.col_span).contains(&col)
950            })
951        });
952        if let Some(cell) = covering {
953            cell.text = text.clone();
954            let (r0, r1) = (cell.start_row, cell.start_row + cell.row_span);
955            let (c0, c1) = (cell.start_col, cell.start_col + cell.col_span);
956            for r in self.rows.iter_mut().take(r1).skip(r0) {
957                for slot in r.iter_mut().take(c1).skip(c0) {
958                    *slot = text.clone();
959                }
960            }
961        } else {
962            self.rows[row][col] = text;
963        }
964        true
965    }
966
967    /// Derive first-class cells (#240) from the dense grid plus the
968    /// [`TableStructure`] overlay — how declarative tables (DOCX/XLSX merged
969    /// regions, HTML `th`/spans, ODF covered cells, USPTO CALS) get real
970    /// `TableCell` records without page geometry. Anchors are the positions
971    /// not marked as span continuations; extents scan the continuation grids
972    /// right/down (matching the DocLang `lcel`/`ucel` reading). Header roles
973    /// come from the per-cell `col_header`/`row_header` grids when present,
974    /// else the `header_row` band, else docling's declarative default (row 0
975    /// is the header). Without any overlay every position is a 1×1 cell.
976    pub fn derive_cells(&self) -> Vec<TableCell> {
977        let s = self.structure.as_ref();
978        let flag = |grid: Option<&Vec<Vec<bool>>>, r: usize, c: usize| {
979            grid.and_then(|g| g.get(r))
980                .and_then(|row| row.get(c))
981                .copied()
982                .unwrap_or(false)
983        };
984        let col_cont = |r: usize, c: usize| flag(s.map(|s| &s.col_continuation), r, c);
985        let row_cont = |r: usize, c: usize| flag(s.map(|s| &s.row_continuation), r, c);
986        let is_col_header = |r: usize, c: usize| match s {
987            Some(st) if !st.col_header.is_empty() => flag(Some(&st.col_header), r, c),
988            Some(st) if !st.header_row.is_empty() => st.header_row.get(r).copied().unwrap_or(false),
989            _ => r == 0,
990        };
991        let mut cells = Vec::new();
992        for (r, row) in self.rows.iter().enumerate() {
993            for (c, text) in row.iter().enumerate() {
994                if col_cont(r, c) || row_cont(r, c) {
995                    continue; // covered by a span anchor
996                }
997                let mut col_span = 1;
998                while c + col_span < row.len() && col_cont(r, c + col_span) {
999                    col_span += 1;
1000                }
1001                let mut row_span = 1;
1002                while r + row_span < self.rows.len() && row_cont(r + row_span, c) {
1003                    row_span += 1;
1004                }
1005                cells.push(TableCell {
1006                    text: text.clone(),
1007                    bbox: None,
1008                    start_row: r,
1009                    start_col: c,
1010                    row_span,
1011                    col_span,
1012                    column_header: is_col_header(r, c),
1013                    row_header: flag(s.map(|s| &s.row_header), r, c),
1014                    row_section: false,
1015                });
1016            }
1017        }
1018        cells
1019    }
1020
1021    /// The number of leading grid rows that form the column header —
1022    /// docling-core's `_count_header_rows` (docling-core#723, 2.96) shared by
1023    /// the Markdown serializer and the chunker's dataframe view: a row counts
1024    /// only when a `column_header` cell *starts* on it (a header spanning
1025    /// several rows is replicated into each row it covers, and counting those
1026    /// would pull the data rows beneath it into the header block). Two
1027    /// special cases: `1` when no cell carries the flag at all, so tables from
1028    /// backends that never set it keep row 0 as the header; `0` when flags
1029    /// exist but none starts on row 0 — then nothing is promotable and every
1030    /// row stays in the body. Uses the first-class [`Self::cells`] when
1031    /// present (the PDF pipeline's TableFormer flags), else the cells derived
1032    /// from the structure overlay.
1033    ///
1034    /// A pivot table's row headers no longer disturb this: docling#4216 flags
1035    /// a spanning `<th>` row as `row_header`, not `column_header`, so the
1036    /// first data row is no longer folded into the header block and the
1037    /// deviation this port carried for docling-core#765 is gone.
1038    ///
1039    /// A row also stops the block when it *carries body text* (#604,
1040    /// docling-core#766, 2.97): a cell starting on it that is not a column
1041    /// header, has non-blank text and does not start in the table's first
1042    /// column. A scanned form flags its first-column labels `column_header`
1043    /// on every row; without the check each such row folded its values into
1044    /// the header, and a table labelled on every row lost its whole body.
1045    /// When row 0 itself is stopped that way and no later row carries a
1046    /// flag, row 0 is still the header (`1`), as for an unflagged table.
1047    pub fn header_row_count(&self) -> usize {
1048        if self.rows.is_empty() {
1049            return 0;
1050        }
1051        let derived;
1052        let cells: &[TableCell] = match &self.cells {
1053            Some(c) if !c.is_empty() => c,
1054            _ => {
1055                derived = self.derive_cells();
1056                &derived
1057            }
1058        };
1059        let first_col = cells.iter().map(|c| c.start_col).min().unwrap_or(0);
1060        let is_header_row = |r: usize| {
1061            let mut flagged = false;
1062            for c in cells.iter().filter(|c| c.start_row == r) {
1063                if c.column_header {
1064                    flagged = true;
1065                } else if c.start_col != first_col && !c.text.trim().is_empty() {
1066                    return false;
1067                }
1068            }
1069            flagged
1070        };
1071        let count = (0..self.rows.len())
1072            .take_while(|&r| is_header_row(r))
1073            .count();
1074        // Upstream's row-0 fallback: no flag on any grid row below the first
1075        // (a spanning header cell counts on every row it covers) → row 0.
1076        if count == 0
1077            && !cells
1078                .iter()
1079                .any(|c| c.column_header && c.start_row + c.row_span.max(1) > 1)
1080        {
1081            return 1;
1082        }
1083        count
1084    }
1085
1086    /// The first-class cell covering a grid position, if any.
1087    pub fn cell_at(&self, row: usize, col: usize) -> Option<&TableCell> {
1088        self.cells.as_ref()?.iter().find(|c| {
1089            (c.start_row..c.start_row + c.row_span).contains(&row)
1090                && (c.start_col..c.start_col + c.col_span).contains(&col)
1091        })
1092    }
1093
1094    /// A cell's bounding box (`[l, t, r, b]`, page points, top-left origin);
1095    /// `None` when no cell with geometry covers the position.
1096    pub fn cell_bbox(&self, row: usize, col: usize) -> Option<[f32; 4]> {
1097        self.cell_at(row, col)?.bbox
1098    }
1099
1100    /// Set (or replace) the bounding box of the cell covering a grid
1101    /// position; `false` outside the text grid. A table without first-class
1102    /// cells materializes them first (one 1×1 cell per grid position, texts
1103    /// from the grid), so declarative tables can be annotated too.
1104    pub fn set_cell_bbox(&mut self, row: usize, col: usize, bbox: [f32; 4]) -> bool {
1105        if self.rows.get(row).and_then(|r| r.get(col)).is_none() {
1106            return false;
1107        }
1108        let rows = &self.rows;
1109        let cells = self.cells.get_or_insert_with(|| {
1110            rows.iter()
1111                .enumerate()
1112                .flat_map(|(r, cols)| {
1113                    cols.iter().enumerate().map(move |(c, text)| TableCell {
1114                        text: text.clone(),
1115                        bbox: None,
1116                        start_row: r,
1117                        start_col: c,
1118                        row_span: 1,
1119                        col_span: 1,
1120                        column_header: false,
1121                        row_header: false,
1122                        row_section: false,
1123                    })
1124                })
1125                .collect()
1126        });
1127        match cells.iter_mut().find(|c| {
1128            (c.start_row..c.start_row + c.row_span).contains(&row)
1129                && (c.start_col..c.start_col + c.col_span).contains(&col)
1130        }) {
1131            Some(cell) => {
1132                cell.bbox = Some(bbox);
1133                true
1134            }
1135            None => {
1136                cells.push(TableCell {
1137                    text: self.rows[row][col].clone(),
1138                    bbox: Some(bbox),
1139                    start_row: row,
1140                    start_col: col,
1141                    row_span: 1,
1142                    col_span: 1,
1143                    column_header: false,
1144                    row_header: false,
1145                    row_section: false,
1146                });
1147                true
1148            }
1149        }
1150    }
1151
1152    /// The anchor position of the cell whose box overlaps `bbox` best
1153    /// (largest intersection-over-union), ties resolved in cell order.
1154    /// `None` when nothing overlaps or the table carries no geometry. This
1155    /// is the lookup half of the repair workflow: find the cell an external
1156    /// OCR box refers to, then [`Self::set_cell_text`] it.
1157    pub fn find_cell_by_bbox(&self, bbox: [f32; 4]) -> Option<(usize, usize)> {
1158        let area = |b: &[f32; 4]| ((b[2] - b[0]) * (b[3] - b[1])).max(0.0);
1159        let mut best: Option<(f32, (usize, usize))> = None;
1160        for cell in self.cells.as_deref()?.iter() {
1161            let Some(cb) = cell.bbox else { continue };
1162            let iw = (bbox[2].min(cb[2]) - bbox[0].max(cb[0])).max(0.0);
1163            let ih = (bbox[3].min(cb[3]) - bbox[1].max(cb[1])).max(0.0);
1164            let inter = iw * ih;
1165            if inter <= 0.0 {
1166                continue;
1167            }
1168            let iou = inter / (area(&bbox) + area(&cb) - inter).max(f32::EPSILON);
1169            if best.is_none_or(|(b, _)| iou > b) {
1170                best = Some((iou, (cell.start_row, cell.start_col)));
1171            }
1172        }
1173        best.map(|(_, pos)| pos)
1174    }
1175
1176    /// Locate the cell overlapping `bbox` best and replace its text — the
1177    /// one-call form of the OCR-repair loop. Returns the updated anchor.
1178    pub fn update_cell_by_bbox(
1179        &mut self,
1180        bbox: [f32; 4],
1181        text: impl Into<String>,
1182    ) -> Option<(usize, usize)> {
1183        let (row, col) = self.find_cell_by_bbox(bbox)?;
1184        self.set_cell_text(row, col, text);
1185        Some((row, col))
1186    }
1187}
1188
1189/// OTSL structure overlay for a [`Table`], parallel to [`Table::rows`].
1190#[derive(Debug, Clone, PartialEq, Default)]
1191pub struct TableStructure {
1192    /// Per-row: `true` if the row's non-empty cells are column headers
1193    /// (emitted as `<ched/>` rather than `<fcel/>`).
1194    pub header_row: Vec<bool>,
1195    /// Same shape as [`Table::rows`]; `true` where a cell continues a
1196    /// horizontal span from its left neighbour (emitted as `<lcel/>`).
1197    pub col_continuation: Vec<Vec<bool>>,
1198    /// Same shape as [`Table::rows`]; `true` where a cell continues a
1199    /// vertical span from the cell above (emitted as `<ucel/>`). Empty or all
1200    /// `false` when the backend has no vertical spans (e.g. USPTO CALS).
1201    pub row_continuation: Vec<Vec<bool>>,
1202    /// Same shape as [`Table::rows`]; `true` where a non-empty cell is a row
1203    /// header (emitted as `<rhed/>`) — a chart's category column. Empty when
1204    /// the table has no row headers.
1205    pub row_header: Vec<Vec<bool>>,
1206    /// Same shape as [`Table::rows`]; `true` where a cell is a *column header*
1207    /// cell (an HTML `<th>`). When non-empty this per-cell grid supersedes the
1208    /// per-row [`Self::header_row`] for `<ched/>` emission, matching docling's
1209    /// cell-level `column_header` flag; the chunker derives its header-row
1210    /// count from it.
1211    pub col_header: Vec<Vec<bool>>,
1212}
1213
1214impl DoclingDocument {
1215    /// Create an empty document with the given name.
1216    pub fn new(name: impl Into<String>) -> Self {
1217        Self {
1218            name: name.into(),
1219            nodes: Vec::new(),
1220            strict_markdown: false,
1221            compact_tables: false,
1222            page_break_placeholder: None,
1223            links: Vec::new(),
1224            confidence: None,
1225            tree: None,
1226            page_images: std::collections::BTreeMap::new(),
1227        }
1228    }
1229
1230    /// Append a node.
1231    /// The document's top-level tables in reading order — the read half of
1232    /// the post-extraction table API (#238). [`Node::Located`] wrappers (the
1233    /// PDF pipeline attaches layout provenance that way) are looked through;
1234    /// tables nested inside rich table cells (`Table::cell_blocks`) are not
1235    /// traversed.
1236    pub fn tables(&self) -> impl Iterator<Item = &Table> {
1237        fn unwrap_table(n: &Node) -> Option<&Table> {
1238            match n {
1239                Node::Table(t) => Some(t),
1240                Node::Located { inner, .. }
1241                | Node::Prov { inner, .. }
1242                | Node::Track { inner, .. } => unwrap_table(inner),
1243                _ => None,
1244            }
1245        }
1246        self.nodes.iter().filter_map(unwrap_table)
1247    }
1248
1249    /// Mutable access to the document's top-level tables, for repair
1250    /// workflows (#238): locate a cell via [`Table::find_cell_by_bbox`], fix
1251    /// its text with [`Table::set_cell_text`], then re-export — every
1252    /// serializer reads the same grid.
1253    pub fn tables_mut(&mut self) -> impl Iterator<Item = &mut Table> {
1254        fn unwrap_table(n: &mut Node) -> Option<&mut Table> {
1255            match n {
1256                Node::Table(t) => Some(t),
1257                Node::Located { inner, .. }
1258                | Node::Prov { inner, .. }
1259                | Node::Track { inner, .. } => unwrap_table(inner),
1260                _ => None,
1261            }
1262        }
1263        self.nodes.iter_mut().filter_map(unwrap_table)
1264    }
1265
1266    pub fn push(&mut self, node: Node) {
1267        self.nodes.push(node);
1268    }
1269
1270    /// Convenience: append a heading.
1271    pub fn add_heading(&mut self, level: u8, text: impl Into<String>) {
1272        self.push(Node::Heading {
1273            level,
1274            text: text.into(),
1275        });
1276    }
1277
1278    /// Convenience: append a paragraph.
1279    pub fn add_paragraph(&mut self, text: impl Into<String>) {
1280        self.push(Node::Paragraph { text: text.into() });
1281    }
1282
1283    /// Serialize the document to Markdown.
1284    ///
1285    /// The Rust equivalent of docling-core's
1286    /// `DoclingDocument.export_to_markdown()`. Uses [`Self::strict_markdown`] to
1287    /// pick between docling-legacy output (default) and the cleaner, more
1288    /// conformant variant.
1289    pub fn export_to_markdown(&self) -> String {
1290        to_markdown(self, self.strict_markdown)
1291    }
1292
1293    /// Serialize to Markdown, explicitly choosing the mode regardless of
1294    /// [`Self::strict_markdown`]. `strict = true` produces cleaner, more
1295    /// conformant Markdown (code-fence languages preserved, no inline-run
1296    /// spacing artifacts); `strict = false` reproduces docling's legacy output.
1297    pub fn export_to_markdown_with(&self, strict: bool) -> String {
1298        to_markdown(self, strict)
1299    }
1300
1301    /// Markdown for this document as the *content of a rich table cell*
1302    /// (docling-core's `in_table_cell` serialization, docling-core#540):
1303    /// headings render as plain text since Markdown tables can't hold them.
1304    /// Backends build a sub-document per rich cell and flatten this into the
1305    /// cell text; no trailing newline.
1306    pub fn export_to_table_cell_markdown(&self) -> String {
1307        crate::markdown::to_markdown_table_cell(self, self.strict_markdown)
1308    }
1309
1310    /// Serialize to docling-core's native JSON wire format (`DoclingDocument`
1311    /// schema), pretty-printed — the Rust equivalent of
1312    /// `DoclingDocument.export_to_dict()` / `save_as_json()`. The output loads
1313    /// back into Python docling-core and round-trips to the same Markdown.
1314    pub fn export_to_json(&self) -> String {
1315        let mut out = Vec::new();
1316        self.write_json_pretty(&mut out)
1317            .expect("DoclingDocument JSON is always serializable");
1318        String::from_utf8(out).expect("serde_json writes UTF-8")
1319    }
1320
1321    /// The same JSON wire format as [`Self::export_to_json`], as a
1322    /// `serde_json::Value` — for callers that append response-level extras
1323    /// (docling-serve adds the confidence report, #183) before serializing.
1324    ///
1325    /// The `Value` is large — ~2.7 KB per text item — so on a long document
1326    /// prefer [`Self::write_json`], which writes the same JSON without it.
1327    pub fn export_to_json_value(&self) -> serde_json::Value {
1328        crate::json::to_json(self)
1329    }
1330
1331    /// Write the JSON of [`Self::export_to_json_value`] to `writer`, compact
1332    /// — byte for byte `serde_json::to_writer(writer, &doc.export_to_json_value())`
1333    /// — without building the `Value`: the export holds its text items in a
1334    /// compact form and serializes them straight to the writer. Wrap a file
1335    /// or socket in a `BufWriter`.
1336    pub fn write_json<W: std::io::Write>(&self, writer: W) -> std::io::Result<()> {
1337        crate::json::write_json(self, writer, false).map_err(std::io::Error::from)
1338    }
1339
1340    /// [`Self::write_json`], indented as [`Self::export_to_json`] is.
1341    pub fn write_json_pretty<W: std::io::Write>(&self, writer: W) -> std::io::Result<()> {
1342        crate::json::write_json(self, writer, true).map_err(std::io::Error::from)
1343    }
1344
1345    /// Serialize to a complete LaTeX document — the Rust counterpart of
1346    /// docling-core's `LaTeXDocSerializer` with default parameters (docling
1347    /// 2.124's `--to latex`, #317). No trailing newline, like the upstream
1348    /// CLI's `<stem>.tex`.
1349    pub fn export_to_latex(&self) -> String {
1350        crate::latex::to_latex(self)
1351    }
1352
1353    /// Serialize to Pandoc's AST as JSON (`pandoc -f json`, #515) with the
1354    /// default options: pictures as captioned figures without image data,
1355    /// body layer only, the [`PANDOC_API_VERSION`](crate::pandoc::PANDOC_API_VERSION)
1356    /// API. One line, no trailing newline. See [`crate::pandoc`].
1357    pub fn export_to_pandoc_json(&self) -> String {
1358        crate::pandoc::to_pandoc(self, &crate::pandoc::PandocExportOptions::default())
1359            .expect("the default Pandoc API version is always supported")
1360            .0
1361    }
1362
1363    /// Pandoc JSON per `options` (image mode, artifacts directory, content
1364    /// layers, required API version). Returns the JSON and, for
1365    /// [`ImageMode::Referenced`], the `(path, bytes)` image files; an
1366    /// unsupported `api_version` is an error.
1367    pub fn export_to_pandoc_json_with(
1368        &self,
1369        options: &crate::pandoc::PandocExportOptions,
1370    ) -> Result<crate::pandoc::PandocOutput, crate::pandoc::PandocError> {
1371        crate::pandoc::to_pandoc(self, options)
1372    }
1373
1374    /// Serialize to DocLang XML (`<doclang version="0.7">…`), the markup that
1375    /// lives inside a `.dclx` archive — the Rust counterpart of docling-core's
1376    /// `export_to_doclang()` with default parameters. No trailing newline; the
1377    /// archive writer appends exactly one.
1378    pub fn export_to_doclang(&self) -> String {
1379        crate::doclang::export_to_doclang(&self.nodes)
1380    }
1381
1382    /// [`Self::export_to_doclang`] plus the picture assets its
1383    /// `<src uri="assets/image_….png"/>` references name, as `(path, bytes)`
1384    /// in document order — the parts docling's `save_as_doclang_archive`
1385    /// stores next to `document.xml`. PNG and JPEG pictures come back as PNG
1386    /// (a JPEG re-encoded from its libjpeg-decoded pixels); other encodings
1387    /// keep their own bytes for the archive writer to convert.
1388    pub fn export_to_doclang_with_assets(&self) -> (String, Vec<(String, Vec<u8>)>) {
1389        crate::doclang::export_to_doclang_with_assets(&self.nodes)
1390    }
1391
1392    /// Serialize to Markdown with an explicit picture [`ImageMode`] (mirrors
1393    /// docling's `image_mode`). Returns the Markdown and, for
1394    /// [`ImageMode::Referenced`], the `(relative-path, bytes)` of each image the
1395    /// caller should write next to the Markdown file. `artifacts_dir` is the
1396    /// directory name used in referenced links.
1397    pub fn export_to_markdown_with_images(
1398        &self,
1399        image_mode: ImageMode,
1400        artifacts_dir: &str,
1401    ) -> (String, Vec<(String, Vec<u8>)>) {
1402        to_markdown_images(self, self.strict_markdown, image_mode, artifacts_dir)
1403    }
1404
1405    /// Markdown per `options` (#599) — docling-core's
1406    /// `export_to_markdown(included_content_layers=…, image_mode=…,
1407    /// image_placeholder=…, escape_html=…, escape_underscores=…,
1408    /// traverse_pictures=…)`: the content layers rendered, whether a
1409    /// picture's nested text items print, HTML and underscore escaping, the
1410    /// image placeholder, and the image mode with its referenced-image
1411    /// directory. [`Self::strict_markdown`] still picks the Markdown flavour.
1412    /// Returns the Markdown and, for [`ImageMode::Referenced`], the
1413    /// `(path, bytes)` artifacts. With [`MarkdownExportOptions::default`]
1414    /// the Markdown is [`Self::export_to_markdown`]'s byte for byte.
1415    pub fn export_to_markdown_with_options(
1416        &self,
1417        options: &MarkdownExportOptions,
1418    ) -> (String, Vec<(String, Vec<u8>)>) {
1419        crate::markdown::to_markdown_with_options(self, self.strict_markdown, options)
1420    }
1421
1422    /// WebVTT (#614) — what docling's `--to vtt` writes
1423    /// (`DoclingDocument.save_as_vtt`): a cue per timed text item — a WebVTT
1424    /// input's cues, an audio/video transcript's segments — hours always
1425    /// written, the `</v>` of a lone voice span omitted. A document without
1426    /// timed text is the bare `WEBVTT` header. No trailing newline.
1427    pub fn export_to_vtt(&self) -> String {
1428        crate::vtt::to_vtt(self, &crate::vtt::VttExportOptions::default())
1429    }
1430
1431    /// [`Self::export_to_vtt`] with docling-core's `WebVTTParams`
1432    /// (`omit_hours_if_zero`, `omit_voice_end`).
1433    pub fn export_to_vtt_with_options(&self, options: &crate::vtt::VttExportOptions) -> String {
1434        crate::vtt::to_vtt(self, options)
1435    }
1436
1437    /// Plain text — docling-core's `DoclingDocument.export_to_text()` with
1438    /// its defaults (#613, docling's `--to text` / `<stem>.txt`): the
1439    /// Markdown export without decoration ([`MarkdownExportOptions::plain_text`]).
1440    /// Lists keep their bullets and numbers, tables their `|` grid. No
1441    /// trailing newline: upstream's `serialize().text`, which its CLI
1442    /// writes verbatim to `<stem>.txt`.
1443    pub fn export_to_text(&self) -> String {
1444        let (mut text, _) = crate::markdown::to_markdown_with_options(
1445            self,
1446            self.strict_markdown,
1447            &MarkdownExportOptions::plain_text(),
1448        );
1449        if text.ends_with('\n') {
1450            text.pop();
1451        }
1452        text
1453    }
1454
1455    /// A complete HTML document — docling-core's `HTMLDocSerializer` with its
1456    /// defaults (#492): pictures stay out (`ImageRefMode.PLACEHOLDER`, only
1457    /// their captions and meta render). See [`export_to_html_with_images`]
1458    /// for the embedded / referenced modes and [`crate::html`]'s module docs
1459    /// for what is reproduced.
1460    ///
1461    /// [`export_to_html_with_images`]: Self::export_to_html_with_images
1462    pub fn export_to_html(&self) -> String {
1463        crate::html::to_html(self, &HtmlExportOptions::default()).0
1464    }
1465
1466    /// HTML with pictures per `image_mode`: `data:` URIs when embedded, and
1467    /// when referenced `<img src>` paths under `artifacts_dir` whose bytes come
1468    /// back as `(path, bytes)` for the caller to write — the Markdown export's
1469    /// contract and file names.
1470    pub fn export_to_html_with_images(
1471        &self,
1472        image_mode: ImageMode,
1473        artifacts_dir: &str,
1474    ) -> (String, Vec<(String, Vec<u8>)>) {
1475        crate::html::to_html(
1476            self,
1477            &HtmlExportOptions {
1478                image_mode,
1479                artifacts_dir: artifacts_dir.to_string(),
1480                ..HtmlExportOptions::default()
1481            },
1482        )
1483    }
1484
1485    /// HTML rendering the content `layers` — docling-core's
1486    /// `export_to_html(included_content_layers=…)` (#499). The default export
1487    /// is body only; `ContentLayers::BODY.with(ContentLayer::Furniture)` adds
1488    /// page headers/footers, `.with(ContentLayer::Notes)` reviewer comments,
1489    /// [`ContentLayers::ALL`] is Python's `set(ContentLayer)`. An item on a
1490    /// layer outside the set is skipped while its children are still walked,
1491    /// and the items that do render go through the same serializers as the
1492    /// body (a page header is a `<p>`, a comment a `<p>`, a header table a
1493    /// `<table>`), exactly as upstream's `HTMLParams.layers` behaves. Pictures
1494    /// stay placeholders; see [`export_to_html_with`] for the full option set.
1495    ///
1496    /// [`export_to_html_with`]: Self::export_to_html_with
1497    pub fn export_to_html_with_layers(&self, layers: ContentLayers) -> String {
1498        crate::html::to_html(
1499            self,
1500            &HtmlExportOptions {
1501                layers,
1502                ..HtmlExportOptions::default()
1503            },
1504        )
1505        .0
1506    }
1507
1508    /// HTML per `options` — image mode, referenced-image directory and content
1509    /// layers in one call; the other `export_to_html*` methods are
1510    /// shorthands for it. Returns the HTML and, for
1511    /// [`ImageMode::Referenced`], the `(path, bytes)` artifacts.
1512    pub fn export_to_html_with(
1513        &self,
1514        options: &HtmlExportOptions,
1515    ) -> (String, Vec<(String, Vec<u8>)>) {
1516        crate::html::to_html(self, options)
1517    }
1518}
1519
1520#[cfg(test)]
1521mod table_api_tests {
1522    use super::*;
1523
1524    fn cell(
1525        text: &str,
1526        bbox: [f32; 4],
1527        (start_row, start_col): (usize, usize),
1528        (row_span, col_span): (usize, usize),
1529    ) -> TableCell {
1530        TableCell {
1531            text: text.into(),
1532            bbox: Some(bbox),
1533            start_row,
1534            start_col,
1535            row_span,
1536            col_span,
1537            column_header: false,
1538            row_header: false,
1539            row_section: false,
1540        }
1541    }
1542
1543    fn table() -> Table {
1544        Table {
1545            rows: vec![
1546                vec!["Year".into(), "Ducks".into()],
1547                vec!["2019".into(), "120".into()],
1548            ],
1549            cells: Some(vec![
1550                cell("Year", [0.0, 0.0, 50.0, 10.0], (0, 0), (1, 1)),
1551                cell("Ducks", [50.0, 0.0, 100.0, 10.0], (0, 1), (1, 1)),
1552                cell("2019", [0.0, 10.0, 50.0, 20.0], (1, 0), (1, 1)),
1553                cell("120", [50.0, 10.0, 100.0, 20.0], (1, 1), (1, 1)),
1554            ]),
1555            ..Default::default()
1556        }
1557    }
1558
1559    /// Declarative tables derive first-class cells from the structure
1560    /// overlay: continuation grids become span extents, `col_header` (or the
1561    /// row-0 fallback) becomes the header role — the XLSX/DOCX/HTML merge
1562    /// path into real `TableCell`s (#240).
1563    #[test]
1564    fn derive_cells_reads_spans_and_headers_from_structure() {
1565        let t = Table {
1566            rows: vec![
1567                vec!["Wide".into(), "Wide".into(), "C".into()],
1568                vec!["a".into(), "b".into(), "c".into()],
1569            ],
1570            structure: Some(TableStructure {
1571                header_row: vec![true, false],
1572                col_continuation: vec![vec![false, true, false], vec![false; 3]],
1573                row_continuation: vec![vec![false; 3], vec![false; 3]],
1574                row_header: Vec::new(),
1575                col_header: Vec::new(),
1576            }),
1577            ..Default::default()
1578        };
1579        let cells = t.derive_cells();
1580        assert_eq!(cells.len(), 5, "two anchors in row 0, three in row 1");
1581        let wide = &cells[0];
1582        assert_eq!((wide.col_span, wide.row_span), (2, 1));
1583        assert!(wide.column_header, "header_row band");
1584        assert!(cells.iter().skip(2).all(|c| !c.column_header));
1585
1586        // Without any overlay: every position 1x1, row 0 the header
1587        // (docling's declarative default — the old JSON synthesis).
1588        let plain = Table {
1589            rows: vec![vec!["h".into()], vec!["x".into()]],
1590            ..Default::default()
1591        };
1592        let cells = plain.derive_cells();
1593        assert_eq!(cells.len(), 2);
1594        assert!(cells[0].column_header && !cells[1].column_header);
1595    }
1596
1597    /// A spanning cell updates once: the record text and every covered grid
1598    /// position — a repair shows once in Markdown, not once per column.
1599    #[test]
1600    fn span_repair_updates_the_whole_cell() {
1601        let mut t = Table {
1602            rows: vec![
1603                vec!["Wide".into(), "Wide".into(), "C".into()],
1604                vec!["a".into(), "b".into(), "c".into()],
1605            ],
1606            cells: Some(vec![
1607                cell("Wide", [0.0, 0.0, 100.0, 10.0], (0, 0), (1, 2)),
1608                cell("C", [100.0, 0.0, 150.0, 10.0], (0, 2), (1, 1)),
1609            ]),
1610            ..Default::default()
1611        };
1612        // Update through the covered (non-anchor) position.
1613        assert!(t.set_cell_text(0, 1, "Fixed"));
1614        assert_eq!(
1615            t.rows[0],
1616            vec!["Fixed".to_string(), "Fixed".into(), "C".into()]
1617        );
1618        assert_eq!(t.cell_at(0, 1).unwrap().text, "Fixed");
1619        assert_eq!(t.cell_at(0, 1).unwrap().col_span, 2);
1620    }
1621
1622    /// The OCR-repair loop (#238): locate a cell by an external box (best
1623    /// IoU), replace its text, and see the fix in the export — the grid is
1624    /// the single source of truth for every serializer.
1625    #[test]
1626    fn bbox_lookup_and_repair_flow_into_exports() {
1627        let mut doc = DoclingDocument::new("t");
1628        doc.push(Node::Table(table()));
1629        assert_eq!(doc.tables().count(), 1);
1630
1631        let t = doc.tables_mut().next().unwrap();
1632        // A slightly-off OCR box still lands on the (1,1) cell.
1633        assert_eq!(t.find_cell_by_bbox([52.0, 11.0, 98.0, 19.0]), Some((1, 1)));
1634        assert_eq!(
1635            t.update_cell_by_bbox([52.0, 11.0, 98.0, 19.0], "125"),
1636            Some((1, 1))
1637        );
1638        assert_eq!(t.cell_text(1, 1), Some("125"));
1639        assert!(doc.export_to_markdown().contains("125"));
1640
1641        // No overlap → no match, nothing changed.
1642        let t = doc.tables_mut().next().unwrap();
1643        assert_eq!(t.find_cell_by_bbox([500.0, 500.0, 600.0, 600.0]), None);
1644    }
1645
1646    #[test]
1647    fn cell_accessors_bound_check_and_geometry_materializes() {
1648        let mut t = table();
1649        assert_eq!(t.cell_text(0, 0), Some("Year"));
1650        assert_eq!(t.cell_text(5, 0), None);
1651        assert!(!t.set_cell_text(0, 9, "x"), "outside the grid");
1652        assert_eq!(t.cell_bbox(1, 0), Some([0.0, 10.0, 50.0, 20.0]));
1653
1654        // A geometry-less table materializes its box grid on first set.
1655        let mut plain = Table {
1656            rows: vec![vec!["a".into(), "b".into()]],
1657            ..Default::default()
1658        };
1659        assert_eq!(plain.cell_bbox(0, 1), None);
1660        assert!(!plain.set_cell_bbox(0, 5, [0.0; 4]), "outside the grid");
1661        assert!(plain.set_cell_bbox(0, 1, [1.0, 2.0, 3.0, 4.0]));
1662        assert_eq!(plain.cell_bbox(0, 1), Some([1.0, 2.0, 3.0, 4.0]));
1663        assert_eq!(plain.find_cell_by_bbox([1.5, 2.5, 2.5, 3.5]), Some((0, 1)));
1664    }
1665}