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}
53
54/// A single piece of document content.
55#[derive(Debug, Clone, PartialEq)]
56pub enum Node {
57    /// A heading. `level` is 1-6.
58    Heading { level: u8, text: String },
59    /// A run of body text.
60    Paragraph { text: String },
61    /// A form checkbox (docling's `checkbox_selected`/`checkbox_unselected`): its
62    /// clean label `text` with the checked state. DocLang emits a `<checkbox>`
63    /// element head; Markdown/JSON render the task-list form (`- [x] `/`- [ ] `).
64    CheckboxItem { checked: bool, text: String },
65    /// A single list item at the given nesting `level` (0 = top). For ordered
66    /// items, `number` is the display number (honoring the list's `start`); it
67    /// is unused for unordered items. `first_in_list` marks the first item of a
68    /// list so the serializer can blank-line-separate adjacent sibling lists.
69    ///
70    /// `marker` is the DocLang enumeration marker (`"1."`, `"1.1."`, …) when the
71    /// backend provides one — HTML and DOCX set it for enumerated items, so
72    /// DocLang emits `<ldiv><marker>…</marker></ldiv>`; Markdown and the other
73    /// declarative backends leave it `None`, giving a bare `<ldiv/>` (matching
74    /// docling, whose Markdown backend passes no marker).
75    ListItem {
76        ordered: bool,
77        number: u64,
78        first_in_list: bool,
79        text: String,
80        level: u8,
81        marker: Option<String>,
82        /// Optional layout provenance (`x0,y0,x1,y1`, normalized to 0–511): the
83        /// four DocLang `<location>` values emitted inside the `<list>` right
84        /// after the item's `<ldiv>`. Set only by backends with real geometry
85        /// (e.g. PPTX shapes); `None` for the declarative backends. Kept on the
86        /// item itself (rather than a [`Node::Located`] wrapper) so consecutive
87        /// items still group into one `<list>`.
88        location: Option<[u16; 4]>,
89        /// DocLang-only override for items whose DocLang form diverges from their
90        /// flat Markdown `text`. Markdown/JSON always render the fields above; the
91        /// DocLang serializer, when this is `Some`, takes the list kind, marker,
92        /// and content from here instead. Used for docx multilevel numbering
93        /// (Markdown shows `- 1.1. x`, DocLang an ordered `<marker>1.1.</marker>`
94        /// with clean text) and inline equations/formatting in list items.
95        dclx: Option<ListItemDclx>,
96        /// The item's hyperlink target, when its content is a link — docling's
97        /// HTML backend emits it as an `<href uri=…/>` in the item head, and the
98        /// anchor's Markdown link markup is stripped from the rendered content.
99        /// `None` for a plain item; ignored by Markdown/JSON.
100        href: Option<String>,
101        /// Non-body content layer (docling's HTML site chrome before the first
102        /// heading → `furniture`). DocLang emits a `<layer value=…/>` in the item
103        /// head; Markdown/JSON drop a non-body item entirely.
104        layer: Option<ContentLayer>,
105    },
106    /// A fenced code block.
107    Code {
108        language: Option<String>,
109        text: String,
110        /// The original (pre-enrichment) text when the CodeFormula model
111        /// rewrote `text`: docling keeps the raw extraction in the JSON `orig`
112        /// field while `text` carries the model output. `None` → `orig == text`.
113        orig: Option<String>,
114        /// A line-preserving rendering, when the backend can reconstruct one
115        /// but docling's own output for the format cannot. The PDF pipeline
116        /// sets it (docling-parse joins code lines with single spaces, so
117        /// `text` carries that flat docling-parity form): **strict** Markdown
118        /// prefers `pretty`, every byte-conformance surface (legacy Markdown,
119        /// JSON, DocLang, chunks) serializes `text`.
120        pretty: Option<String>,
121    },
122    /// A table. The first row is treated as the header.
123    Table(Table),
124    /// A picture/figure, with an optional caption and (when a backend extracts
125    /// it) the embedded image itself.
126    Picture {
127        caption: Option<String>,
128        /// Hyperlink annotation on the caption (docling's caption text item
129        /// `hyperlink`): the HTML backend sets it when an `<a href>` wraps the
130        /// image whose `alt` became the caption. DocLang emits the block-form
131        /// `<caption>` with an `<href uri=…/>` head; JSON puts `hyperlink` on
132        /// the caption item; Markdown and LaTeX print the plain caption text,
133        /// as docling does.
134        caption_href: Option<String>,
135        image: Option<PictureImage>,
136        /// DocumentPictureClassifier predictions (all classes, descending
137        /// confidence), when the picture-classification enrichment ran.
138        /// Serialized as docling's `classification` annotation + `meta` field
139        /// on the JSON picture item; Markdown/DocLang output is unaffected.
140        classification: Option<Vec<PictureClass>>,
141        /// Where the caption item hangs in the JSON tree (#390); see
142        /// [`CaptionParent`]. Markdown, DocLang and LaTeX ignore it.
143        caption_parent: CaptionParent,
144    },
145    /// A display-math formula item decoded by the CodeFormula enrichment:
146    /// `latex` is the model's LaTeX (no `$$` wrapping), `orig` the raw glyph
147    /// text extracted from the PDF. Markdown renders `$$latex$$`; JSON emits a
148    /// `formula` text item (docling's un-enriched pipeline instead emits a
149    /// placeholder paragraph — see the PDF assembler).
150    Formula {
151        latex: String,
152        orig: String,
153        location: Option<[u16; 4]>,
154    },
155    /// A standalone caption item (docling's `DocItemLabel.CAPTION` text that
156    /// no picture or table claims): the HTML backend emits a `<figure>`'s
157    /// `<figcaption>` this way when the figure produced no picture and its
158    /// first item is not a table (docling#4050). `href` is the caption's
159    /// hyperlink annotation (the first link inside the figcaption); Markdown
160    /// renders it as `[text](href)`, JSON puts `hyperlink` on the caption
161    /// item, DocLang emits the block-form `<caption>` with an `<href>` head.
162    Caption { text: String, href: Option<String> },
163    /// A chart (docling's `PictureItem` classified as a chart, carrying a
164    /// `PictureTabularChartData` annotation). Markdown and JSON render it exactly
165    /// like a [`Node::Picture`] placeholder (an `<!-- image -->` / `picture`
166    /// item); the DocLang serializer emits `<picture class="chart">` with a
167    /// `<label value="{kind}"/>` and the data `table` as a `<tabular>`.
168    Chart {
169        /// docling's classification label, e.g. `bar_chart`, `line_chart`.
170        kind: String,
171        /// The chart's data grid (row 0 is the header band).
172        table: Table,
173        /// The chart title (docling's caption item on the picture).
174        caption: Option<String>,
175        /// DocLang `<location>` provenance for the picture element.
176        location: Option<[u16; 4]>,
177    },
178    /// A logical grouping of child nodes (e.g. a list, a section, a spreadsheet
179    /// sheet). `name` is docling's group name when it differs from the label —
180    /// an xlsx sheet group is `label: "sheet"`, `name: Some("Sheet1")`. `layer`
181    /// puts the group *and* everything it contains on a non-body content layer
182    /// (a hidden sheet is `invisible`), which is how the serializers that only
183    /// render body content know to skip it; DocLang stamps each child with the
184    /// layer token, exactly as a [`Node::Furniture`] wrapper on each would.
185    /// DocLang has no group element, so a group is transparent there.
186    Group {
187        label: String,
188        name: Option<String>,
189        layer: Option<ContentLayer>,
190        children: Vec<Node>,
191    },
192    /// A form key-value region (docling's `field_region`): a set of form fields,
193    /// each pairing an optional marker, key, and value. Backends detect these
194    /// from form structure (e.g. HTML's `keyN` / `keyN_valueM` / `keyN_marker`
195    /// `id`-convention); the serializers render each item's parts as separate
196    /// labelled texts (`marker` / `field_key` / `field_value`).
197    FieldRegion { items: Vec<FieldItem> },
198    /// Rich inline content — docling's `InlineGroup`: a run of styled text
199    /// segments that a backend captured with formatting (`<bold>`, `<italic>`,
200    /// `<underline>`, `<strikethrough>`, sub/superscript, inline `<code>`) the
201    /// flat Markdown text cannot represent. Markdown/JSON render this exactly
202    /// like `Paragraph { text: md_text }` (so their output is unchanged); the
203    /// DocLang serializer uses the structured `runs`. `unwrapped` is set when the
204    /// group's docling parent is a heading/text (no enclosing `<text>` wrapper).
205    InlineGroup {
206        unwrapped: bool,
207        runs: Vec<InlineRun>,
208        md_text: String,
209    },
210    /// A node in a non-body content layer — `furniture` (page headers/footers,
211    /// the HTML `<title>`, site navigation/chrome) or `notes` (docx comments).
212    /// Markdown and JSON omit these layers by default; DocLang renders the wrapped
213    /// node with a `<layer value="{layer}"/>` head.
214    Furniture {
215        layer: ContentLayer,
216        inner: Box<Node>,
217    },
218    /// One reviewer comment: docling's notes-layer `comment_section` group
219    /// holding a single text item. `name` is docling's own — `comment-{id}` for
220    /// a docx `w:comment`, `comment-{sheet}-{cell}` for a spreadsheet cell note.
221    /// JSON emits the group plus its notes-layer text; DocLang emits the flat
222    /// `<text><layer value="notes"/>…</text>` upstream writes (its DocLang
223    /// carries no group for comments); Markdown and LaTeX omit the notes layer.
224    ///
225    /// `refs_note_text` picks what a [`Node::Commented`] annotation points at,
226    /// mirroring an upstream asymmetry: docling-core's `add_comment` appends the
227    /// **note text**'s ref to each target (which is what the xlsx backend gets),
228    /// while the docx backend overwrites that with the **group**'s ref so a
229    /// comment's replies group together.
230    ///
231    /// `grouped` is whether docling wraps the note in a `comment_section`
232    /// group at all: the docx and spreadsheet backends do, while backends that
233    /// call docling-core's `add_comment` directly (Pages, #383) get a bare
234    /// notes-layer text item under the body — JSON then emits no group and
235    /// `name` is unused.
236    CommentSection {
237        name: String,
238        text: String,
239        refs_note_text: bool,
240        grouped: bool,
241    },
242    /// A body item annotated by reviewer comments: `comments` are indices into
243    /// the document's [`Node::CommentSection`] nodes, in document order. JSON
244    /// emits docling's `comments: [{"$ref": …}]` on the item, each ref pointing
245    /// where the section says (see [`Node::CommentSection::refs_note_text`]);
246    /// every other serializer renders `inner` unchanged.
247    Commented {
248        comments: Vec<usize>,
249        inner: Box<Node>,
250    },
251    /// A node carrying layout provenance — the four DocLang `<location>` values
252    /// (`x0,y0,x1,y1`, normalized to 0–511) docling attaches to elements from
253    /// backends with real geometry (e.g. the slide shapes in PPTX). Markdown and
254    /// JSON render the wrapped node unchanged; DocLang emits the `<location>`
255    /// tokens as the element's first children.
256    Located {
257        location: [u16; 4],
258        inner: Box<Node>,
259    },
260    /// Exact page provenance for a backend whose geometry already *is* the
261    /// page's coordinate system — an XLSX item's cell-index box on its sheet,
262    /// which docling writes verbatim (`bbox` in a top-left origin, the
263    /// `charspan` the backend chose) and sizes the page from. The 0–511 grid
264    /// of a [`Node::Located`] cannot round-trip such integers exactly, so the
265    /// JSON export reads this wrapper; every other serializer renders `inner`
266    /// unchanged (DocLang keeps taking its `<location>` tokens from the grid).
267    Prov {
268        page_no: usize,
269        /// `[l, t, r, b]`, page units, top-left origin.
270        bbox: [f32; 4],
271        /// docling's `charspan` for the item (`[0, 0]` for an XLSX table).
272        charspan: [usize; 2],
273        /// The item's creation rank among its siblings, when that differs
274        /// from the node order: docling numbers `#/tables/N` / `#/texts/N` /
275        /// `#/pictures/N` in the order it *creates* items (a sheet's tables,
276        /// then its images, then its charts) and only afterwards sorts the
277        /// container's children by position. The JSON export adds siblings in
278        /// this order and lays their refs out in node order; `None` when the
279        /// two orders coincide.
280        seq: Option<usize>,
281        inner: Box<Node>,
282    },
283    /// A PDF page header or footer (docling's `page_header`/`page_footer`
284    /// furniture): DocLang emits `<page_header>`/`<page_footer>` with a
285    /// `<layer value="furniture"/>` head, the four `<location>` tokens, then the
286    /// text. Markdown and JSON omit it like other furniture.
287    PageFurniture {
288        footer: bool,
289        location: [u16; 4],
290        text: String,
291    },
292    /// A page boundary — docling's implicit page break between pages. The PPTX
293    /// backend emits one between consecutive slides. DocLang renders it as
294    /// `<page_break/>`; Markdown and JSON omit it (matching docling's default
295    /// exports, which carry page breaks only in the document model).
296    PageBreak,
297    /// An invisible page marker — the first node of every page the PDF paths
298    /// assemble: the 1-based page number and the page size in PDF points. It
299    /// carries exactly what the JSON export needs to populate docling's
300    /// `pages` map and to denormalize the 0–511 `<location>` grid back into
301    /// BOTTOMLEFT point bboxes for per-item `prov` (#171). Every other
302    /// serializer skips it, so Markdown / DocLang / DocTags output is
303    /// byte-for-byte unchanged.
304    PageInfo {
305        /// 1-based page number (0 = "not yet numbered": the assembler emits
306        /// the marker, the document-level collector stamps the real number).
307        page_no: usize,
308        /// Page width in PDF points.
309        width: f32,
310        /// Page height in PDF points.
311        height: f32,
312    },
313    /// A node docling keeps in the document model (and DocLang) but leaves out
314    /// of the Markdown and JSON exports — e.g. an ODF *presentation*'s pictures
315    /// and charts, which appear in the `.dclx` body but not in its `.md`/`.json`.
316    /// DocLang renders the wrapped node in place; Markdown and JSON skip it.
317    DoclangOnly(Box<Node>),
318    /// A verbatim plain-text dump — docling's plain-text backend emits the whole
319    /// file as a single text item (used for legacy USPTO APS `.txt` grants, which
320    /// docling routes to plain text rather than its APS parser). The stored string
321    /// is the file body, one record per line. Markdown/JSON render it as one text
322    /// block; the DocLang serializer reproduces minidom's per-line layout, CDATA-
323    /// escaping only the lines that need it (see `emit_text_dump`).
324    TextDump(String),
325}
326
327/// Vertical text position of an [`InlineRun`] — docling's `Script`.
328#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
329pub enum Script {
330    #[default]
331    Baseline,
332    Sub,
333    Super,
334}
335
336/// One styled segment of a [`Node::InlineGroup`] — the docling.rs analogue of a
337/// `TextItem` inside an `InlineGroup`, carrying the ancestor formatting docling
338/// tracks. `text` is already whitespace-normalized/trimmed (one segment per
339/// source text node). A hyperlink is intentionally not stored: DocLang drops the
340/// target inside inline scope, keeping only the anchor text.
341#[derive(Debug, Clone, PartialEq, Eq, Default)]
342pub struct InlineRun {
343    pub text: String,
344    pub bold: bool,
345    pub italic: bool,
346    pub underline: bool,
347    pub strike: bool,
348    pub script: Script,
349    pub code: bool,
350    /// An inline equation (`text` holds LaTeX): DocLang renders `<formula>…`,
351    /// Markdown/JSON keep the `$…$` already baked into the group's `md_text`.
352    pub formula: bool,
353}
354
355/// A DocLang content layer other than the default `body` (see [`Node::Furniture`]).
356#[derive(Debug, Clone, Copy, PartialEq, Eq)]
357pub enum ContentLayer {
358    /// Page headers/footers, HTML `<title>`, site navigation/chrome.
359    Furniture,
360    /// Editorial notes (docx reviewer comments).
361    Notes,
362    /// Invisible content (hidden spreadsheet sheets).
363    Invisible,
364}
365
366impl ContentLayer {
367    /// The `<layer value="…"/>` token value.
368    pub fn value(self) -> &'static str {
369        match self {
370            ContentLayer::Furniture => "furniture",
371            ContentLayer::Notes => "notes",
372            ContentLayer::Invisible => "invisible",
373        }
374    }
375}
376
377/// DocLang-only content for a [`Node::ListItem`] whose DocLang form differs from
378/// its flat Markdown `text` (see [`Node::ListItem::dclx`]). `ordered` picks the
379/// enclosing `<list>` kind, `marker` the `<ldiv><marker>`; content is `runs`
380/// (structured equations/formatting) when non-empty, else `text` re-parsed for
381/// inline markers.
382#[derive(Debug, Clone, PartialEq, Eq, Default)]
383pub struct ListItemDclx {
384    pub ordered: bool,
385    pub marker: Option<String>,
386    pub text: String,
387    pub runs: Vec<InlineRun>,
388}
389
390impl InlineRun {
391    /// A run with no active formatting (renders as bare inline text).
392    pub fn is_plain(&self) -> bool {
393        !self.bold
394            && !self.italic
395            && !self.underline
396            && !self.strike
397            && !self.code
398            && !self.formula
399            && self.script == Script::Baseline
400    }
401}
402
403/// Build the [`Node`] for a paragraph of inline content from its structured
404/// `runs` and Markdown text, applying docling's `InlineGroup` boundary:
405///
406/// * a single plain run (or none) → a plain [`Node::Paragraph`] (which the
407///   serializers render as `<text>…</text>`, and a lone hyperlink via `<href>`);
408/// * a single uniformly-formatted run, or two or more runs → a
409///   [`Node::InlineGroup`]. `unwrapped` (the group's docling parent is a
410///   heading, so no enclosing `<text>`) only applies to multi-run groups.
411///
412/// Markdown/JSON render the group's `md_text`, so their output is identical to
413/// emitting a `Paragraph` — the structured runs are DocLang-only.
414pub fn inline_paragraph_node(md_text: String, runs: Vec<InlineRun>, unwrapped: bool) -> Node {
415    let single_plain = runs.len() <= 1 && runs.first().is_none_or(|r| r.is_plain());
416    if single_plain {
417        Node::Paragraph { text: md_text }
418    } else {
419        Node::InlineGroup {
420            unwrapped: unwrapped && runs.len() >= 2,
421            runs,
422            md_text,
423        }
424    }
425}
426
427/// One entry of a [`Node::FieldRegion`]: a marker/key/value triple, any of which
428/// may be absent. Mirrors docling's `field_item` with its `marker` / `field_key`
429/// / `field_value` child texts.
430#[derive(Debug, Clone, PartialEq, Default)]
431pub struct FieldItem {
432    pub marker: Option<String>,
433    pub key: Option<String>,
434    pub value: Option<String>,
435    /// docling's `kind` on the `field_value` item — `read_only` or
436    /// `fillable` (the value is or holds a form control); JSON-only.
437    pub value_kind: Option<String>,
438}
439
440/// One DocumentPictureClassifier prediction — docling-core's
441/// `PictureClassificationClass` (`class_name` + `confidence`).
442#[derive(Debug, Clone, PartialEq)]
443pub struct PictureClass {
444    /// e.g. `bar_chart`, `logo`, `signature` (the classifier's 26-label set).
445    pub class_name: String,
446    pub confidence: f32,
447}
448
449/// An extracted picture's raw encoded bytes plus its mimetype and pixel size —
450/// the docling.rs analogue of docling-core's `ImageRef`.
451#[derive(Debug, Clone, PartialEq)]
452pub struct PictureImage {
453    /// e.g. `image/png`, `image/jpeg`.
454    pub mimetype: String,
455    pub width: u32,
456    pub height: u32,
457    /// The image file bytes, exactly as embedded (PNG/JPEG/…).
458    pub data: Vec<u8>,
459}
460
461impl PictureImage {
462    /// A `data:` URI for the image (`data:<mimetype>;base64,<…>`).
463    pub fn data_uri(&self) -> String {
464        format!(
465            "data:{};base64,{}",
466            self.mimetype,
467            crate::base64::encode(&self.data)
468        )
469    }
470}
471
472/// One table cell as a first-class object (#240) — the Rust counterpart of
473/// docling's `TableCell`: its text, page geometry, grid rectangle and header
474/// roles. Produced by the PDF TableFormer paths from the predicted OTSL
475/// structure; `bbox` is `[l, t, r, b]` in page points with a top-left origin.
476#[derive(Debug, Clone, PartialEq)]
477pub struct TableCell {
478    pub text: String,
479    /// `[l, t, r, b]`, page points, top-left origin; `None` without geometry.
480    pub bbox: Option<[f32; 4]>,
481    /// Anchor grid position (0-based row/column offsets).
482    pub start_row: usize,
483    pub start_col: usize,
484    /// Span extents (≥ 1); the covered grid positions repeat the cell's text
485    /// in [`Table::rows`].
486    pub row_span: usize,
487    pub col_span: usize,
488    /// OTSL `ched` — a column-header cell.
489    pub column_header: bool,
490    /// OTSL `rhed` — a row-header cell.
491    pub row_header: bool,
492    /// OTSL `srow` — a section-row cell.
493    pub row_section: bool,
494}
495
496/// Where a picture's or table's caption text item hangs in the docling-JSON
497/// tree (#390). docling's backends do not agree, and the JSON structure is
498/// the only surface that shows it (Markdown, DocLang and LaTeX place a
499/// caption by its item, whatever its parent): the PDF pipeline parents a
500/// layout caption to the picture or table it belongs to, while every
501/// declarative backend creates the caption with `doc.add_text(label=CAPTION)`
502/// and no parent — the document body — even when the item itself sits in a
503/// group or under a section header (JATS, LaTeX, HTML, Markdown, EPUB,
504/// AsciiDoc all do). The office backends hang a chart's title caption off the
505/// chart's container (the sheet group, the slide, docx's current parent,
506/// docling#4190) — that is [`Node::Chart`]'s own path, not this choice. A
507/// backend that adds a new captioned item picks the variant matching
508/// upstream's `add_text` call for that format; the default is upstream's
509/// default.
510#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
511pub enum CaptionParent {
512    /// `#/body`, listed after the enclosing top-level item — docling's
513    /// `add_text` default, which every declarative backend leaves alone.
514    #[default]
515    Body,
516    /// The item's own container (its `parent`), listed ahead of the item:
517    /// the caption is created first, as docling's office backends do.
518    Container,
519    /// The item's own container, listed *after* the item: docling's HTML
520    /// backend adds a `<figure>`-wrapped table, then its `<figcaption>` under
521    /// `self.parents[self.level]` (docling#4050).
522    ContainerAfter,
523    /// The item itself — the caption is the picture's or table's first
524    /// child, as docling's PDF pipeline attaches a layout caption.
525    Item,
526}
527
528/// A simple row-major table. By default `rows[0]` is the header row; a
529/// [`TableStructure`] overlay overrides that and adds column spans.
530#[derive(Debug, Clone, PartialEq, Default)]
531pub struct Table {
532    pub rows: Vec<Vec<String>>,
533    /// Optional layout provenance: the four DocLang `<location>` values
534    /// (`x0,y0,x1,y1`, each already normalized to the 0–511 resolution) emitted
535    /// before the table's cells. Set only by backends with real geometry (e.g.
536    /// the spreadsheet backend, whose cell grid yields a bounding box); left
537    /// `None` by declarative backends, which have no coordinates.
538    pub location: Option<[u16; 4]>,
539    /// Optional OTSL structure overlay for backends that parse real table
540    /// geometry (USPTO CALS): explicit header-row count and horizontal-span
541    /// continuations. `None` → the default (row 0 is the header, no spans).
542    /// `rows` still carries the full text grid (span text replicated) for
543    /// Markdown/JSON; DocLang uses this overlay to emit `<ched/>`/`<lcel/>`.
544    pub structure: Option<TableStructure>,
545    /// Optional per-cell block content, parallel to `rows`. A *rich* cell (an
546    /// ODF cell holding a list, several paragraphs, or a nested table) carries
547    /// its DocLang blocks here; the DocLang serializer emits them after the
548    /// cell token instead of the flat `rows` text. Markdown/JSON ignore this
549    /// and render `rows`, so their output is unchanged. `None` (or an empty
550    /// `Vec` for a given cell) → the flat text is used everywhere.
551    pub cell_blocks: Option<Vec<Vec<Vec<Node>>>>,
552    /// Optional caption (docling's `TableItem.captions`): the JATS
553    /// `<table-wrap>` label+caption, an HTML `<caption>`, etc. Markdown renders
554    /// it as a text line *before* the grid; JSON emits a caption text item the
555    /// table references; DocLang emits a `<caption>` as the table's first child.
556    /// `None` → the table has no caption.
557    pub caption: Option<String>,
558    /// Where the caption item hangs in the JSON tree (#390); see
559    /// [`CaptionParent`]. Only the JSON export reads it.
560    pub caption_parent: CaptionParent,
561    /// Optional per-cell bounding boxes, same shape as [`Self::rows`]: `[l, t,
562    /// r, b]` in page points with a **top-left** origin (the PDF pipeline's
563    /// native space). Set by the ML pipeline's TableFormer paths — a spanned
564    /// cell repeats its anchor's box across the covered grid positions — and
565    /// First-class cells (#240): the authoritative per-cell records —
566    /// text, page geometry, spans and header roles — when the backend
567    /// produces them (the PDF TableFormer paths do; declarative backends
568    /// leave `None`). [`Self::rows`] stays the dense text grid every
569    /// serializer renders (a spanning cell's text is replicated across its
570    /// covered positions there); JSON serializes these cells verbatim when
571    /// present, and the DocLang structure overlay is derived from them.
572    pub cells: Option<Vec<TableCell>>,
573}
574
575impl Table {
576    /// A cell's text at a grid position, `None` outside the grid.
577    pub fn cell_text(&self, row: usize, col: usize) -> Option<&str> {
578        self.rows.get(row)?.get(col).map(String::as_str)
579    }
580
581    /// Replace the text at a grid position; `false` (and no change) outside
582    /// the grid. When a first-class cell covers the position, the whole
583    /// cell is updated: its record text and every grid position its span
584    /// covers, so the repair shows once in Markdown, not once per covered
585    /// column.
586    pub fn set_cell_text(&mut self, row: usize, col: usize, text: impl Into<String>) -> bool {
587        if self.rows.get(row).and_then(|r| r.get(col)).is_none() {
588            return false;
589        }
590        let text = text.into();
591        let covering = self.cells.as_mut().and_then(|cells| {
592            cells.iter_mut().find(|c| {
593                (c.start_row..c.start_row + c.row_span).contains(&row)
594                    && (c.start_col..c.start_col + c.col_span).contains(&col)
595            })
596        });
597        if let Some(cell) = covering {
598            cell.text = text.clone();
599            let (r0, r1) = (cell.start_row, cell.start_row + cell.row_span);
600            let (c0, c1) = (cell.start_col, cell.start_col + cell.col_span);
601            for r in self.rows.iter_mut().take(r1).skip(r0) {
602                for slot in r.iter_mut().take(c1).skip(c0) {
603                    *slot = text.clone();
604                }
605            }
606        } else {
607            self.rows[row][col] = text;
608        }
609        true
610    }
611
612    /// Derive first-class cells (#240) from the dense grid plus the
613    /// [`TableStructure`] overlay — how declarative tables (DOCX/XLSX merged
614    /// regions, HTML `th`/spans, ODF covered cells, USPTO CALS) get real
615    /// `TableCell` records without page geometry. Anchors are the positions
616    /// not marked as span continuations; extents scan the continuation grids
617    /// right/down (matching the DocLang `lcel`/`ucel` reading). Header roles
618    /// come from the per-cell `col_header`/`row_header` grids when present,
619    /// else the `header_row` band, else docling's declarative default (row 0
620    /// is the header). Without any overlay every position is a 1×1 cell.
621    pub fn derive_cells(&self) -> Vec<TableCell> {
622        let s = self.structure.as_ref();
623        let flag = |grid: Option<&Vec<Vec<bool>>>, r: usize, c: usize| {
624            grid.and_then(|g| g.get(r))
625                .and_then(|row| row.get(c))
626                .copied()
627                .unwrap_or(false)
628        };
629        let col_cont = |r: usize, c: usize| flag(s.map(|s| &s.col_continuation), r, c);
630        let row_cont = |r: usize, c: usize| flag(s.map(|s| &s.row_continuation), r, c);
631        let is_col_header = |r: usize, c: usize| match s {
632            Some(st) if !st.col_header.is_empty() => flag(Some(&st.col_header), r, c),
633            Some(st) if !st.header_row.is_empty() => st.header_row.get(r).copied().unwrap_or(false),
634            _ => r == 0,
635        };
636        let mut cells = Vec::new();
637        for (r, row) in self.rows.iter().enumerate() {
638            for (c, text) in row.iter().enumerate() {
639                if col_cont(r, c) || row_cont(r, c) {
640                    continue; // covered by a span anchor
641                }
642                let mut col_span = 1;
643                while c + col_span < row.len() && col_cont(r, c + col_span) {
644                    col_span += 1;
645                }
646                let mut row_span = 1;
647                while r + row_span < self.rows.len() && row_cont(r + row_span, c) {
648                    row_span += 1;
649                }
650                cells.push(TableCell {
651                    text: text.clone(),
652                    bbox: None,
653                    start_row: r,
654                    start_col: c,
655                    row_span,
656                    col_span,
657                    column_header: is_col_header(r, c),
658                    row_header: flag(s.map(|s| &s.row_header), r, c),
659                    row_section: false,
660                });
661            }
662        }
663        cells
664    }
665
666    /// The number of leading grid rows that form the column header —
667    /// docling-core's `_count_header_rows` (docling-core#723, 2.96) shared by
668    /// the Markdown serializer and the chunker's dataframe view: a row counts
669    /// only when a `column_header` cell *starts* on it (a header spanning
670    /// several rows is replicated into each row it covers, and counting those
671    /// would pull the data rows beneath it into the header block). Two
672    /// special cases: `1` when no cell carries the flag at all, so tables from
673    /// backends that never set it keep row 0 as the header; `0` when flags
674    /// exist but none starts on row 0 — then nothing is promotable and every
675    /// row stays in the body. Uses the first-class [`Self::cells`] when
676    /// present (the PDF pipeline's TableFormer flags), else the cells derived
677    /// from the structure overlay.
678    ///
679    /// A pivot table's row headers no longer disturb this: docling#4216 flags
680    /// a spanning `<th>` row as `row_header`, not `column_header`, so the
681    /// first data row is no longer folded into the header block and the
682    /// deviation this port carried for docling-core#765 is gone.
683    pub fn header_row_count(&self) -> usize {
684        if self.rows.is_empty() {
685            return 0;
686        }
687        let derived;
688        let cells: &[TableCell] = match &self.cells {
689            Some(c) if !c.is_empty() => c,
690            _ => {
691                derived = self.derive_cells();
692                &derived
693            }
694        };
695        if !cells.iter().any(|c| c.column_header) {
696            return 1;
697        }
698        (0..self.rows.len())
699            .take_while(|&r| cells.iter().any(|c| c.column_header && c.start_row == r))
700            .count()
701    }
702
703    /// The first-class cell covering a grid position, if any.
704    pub fn cell_at(&self, row: usize, col: usize) -> Option<&TableCell> {
705        self.cells.as_ref()?.iter().find(|c| {
706            (c.start_row..c.start_row + c.row_span).contains(&row)
707                && (c.start_col..c.start_col + c.col_span).contains(&col)
708        })
709    }
710
711    /// A cell's bounding box (`[l, t, r, b]`, page points, top-left origin);
712    /// `None` when no cell with geometry covers the position.
713    pub fn cell_bbox(&self, row: usize, col: usize) -> Option<[f32; 4]> {
714        self.cell_at(row, col)?.bbox
715    }
716
717    /// Set (or replace) the bounding box of the cell covering a grid
718    /// position; `false` outside the text grid. A table without first-class
719    /// cells materializes them first (one 1×1 cell per grid position, texts
720    /// from the grid), so declarative tables can be annotated too.
721    pub fn set_cell_bbox(&mut self, row: usize, col: usize, bbox: [f32; 4]) -> bool {
722        if self.rows.get(row).and_then(|r| r.get(col)).is_none() {
723            return false;
724        }
725        let rows = &self.rows;
726        let cells = self.cells.get_or_insert_with(|| {
727            rows.iter()
728                .enumerate()
729                .flat_map(|(r, cols)| {
730                    cols.iter().enumerate().map(move |(c, text)| TableCell {
731                        text: text.clone(),
732                        bbox: None,
733                        start_row: r,
734                        start_col: c,
735                        row_span: 1,
736                        col_span: 1,
737                        column_header: false,
738                        row_header: false,
739                        row_section: false,
740                    })
741                })
742                .collect()
743        });
744        match cells.iter_mut().find(|c| {
745            (c.start_row..c.start_row + c.row_span).contains(&row)
746                && (c.start_col..c.start_col + c.col_span).contains(&col)
747        }) {
748            Some(cell) => {
749                cell.bbox = Some(bbox);
750                true
751            }
752            None => {
753                cells.push(TableCell {
754                    text: self.rows[row][col].clone(),
755                    bbox: Some(bbox),
756                    start_row: row,
757                    start_col: col,
758                    row_span: 1,
759                    col_span: 1,
760                    column_header: false,
761                    row_header: false,
762                    row_section: false,
763                });
764                true
765            }
766        }
767    }
768
769    /// The anchor position of the cell whose box overlaps `bbox` best
770    /// (largest intersection-over-union), ties resolved in cell order.
771    /// `None` when nothing overlaps or the table carries no geometry. This
772    /// is the lookup half of the repair workflow: find the cell an external
773    /// OCR box refers to, then [`Self::set_cell_text`] it.
774    pub fn find_cell_by_bbox(&self, bbox: [f32; 4]) -> Option<(usize, usize)> {
775        let area = |b: &[f32; 4]| ((b[2] - b[0]) * (b[3] - b[1])).max(0.0);
776        let mut best: Option<(f32, (usize, usize))> = None;
777        for cell in self.cells.as_deref()?.iter() {
778            let Some(cb) = cell.bbox else { continue };
779            let iw = (bbox[2].min(cb[2]) - bbox[0].max(cb[0])).max(0.0);
780            let ih = (bbox[3].min(cb[3]) - bbox[1].max(cb[1])).max(0.0);
781            let inter = iw * ih;
782            if inter <= 0.0 {
783                continue;
784            }
785            let iou = inter / (area(&bbox) + area(&cb) - inter).max(f32::EPSILON);
786            if best.is_none_or(|(b, _)| iou > b) {
787                best = Some((iou, (cell.start_row, cell.start_col)));
788            }
789        }
790        best.map(|(_, pos)| pos)
791    }
792
793    /// Locate the cell overlapping `bbox` best and replace its text — the
794    /// one-call form of the OCR-repair loop. Returns the updated anchor.
795    pub fn update_cell_by_bbox(
796        &mut self,
797        bbox: [f32; 4],
798        text: impl Into<String>,
799    ) -> Option<(usize, usize)> {
800        let (row, col) = self.find_cell_by_bbox(bbox)?;
801        self.set_cell_text(row, col, text);
802        Some((row, col))
803    }
804}
805
806/// OTSL structure overlay for a [`Table`], parallel to [`Table::rows`].
807#[derive(Debug, Clone, PartialEq, Default)]
808pub struct TableStructure {
809    /// Per-row: `true` if the row's non-empty cells are column headers
810    /// (emitted as `<ched/>` rather than `<fcel/>`).
811    pub header_row: Vec<bool>,
812    /// Same shape as [`Table::rows`]; `true` where a cell continues a
813    /// horizontal span from its left neighbour (emitted as `<lcel/>`).
814    pub col_continuation: Vec<Vec<bool>>,
815    /// Same shape as [`Table::rows`]; `true` where a cell continues a
816    /// vertical span from the cell above (emitted as `<ucel/>`). Empty or all
817    /// `false` when the backend has no vertical spans (e.g. USPTO CALS).
818    pub row_continuation: Vec<Vec<bool>>,
819    /// Same shape as [`Table::rows`]; `true` where a non-empty cell is a row
820    /// header (emitted as `<rhed/>`) — a chart's category column. Empty when
821    /// the table has no row headers.
822    pub row_header: Vec<Vec<bool>>,
823    /// Same shape as [`Table::rows`]; `true` where a cell is a *column header*
824    /// cell (an HTML `<th>`). When non-empty this per-cell grid supersedes the
825    /// per-row [`Self::header_row`] for `<ched/>` emission, matching docling's
826    /// cell-level `column_header` flag; the chunker derives its header-row
827    /// count from it.
828    pub col_header: Vec<Vec<bool>>,
829}
830
831impl DoclingDocument {
832    /// Create an empty document with the given name.
833    pub fn new(name: impl Into<String>) -> Self {
834        Self {
835            name: name.into(),
836            nodes: Vec::new(),
837            strict_markdown: false,
838            compact_tables: false,
839            page_break_placeholder: None,
840            links: Vec::new(),
841            confidence: None,
842            tree: None,
843        }
844    }
845
846    /// Append a node.
847    /// The document's top-level tables in reading order — the read half of
848    /// the post-extraction table API (#238). [`Node::Located`] wrappers (the
849    /// PDF pipeline attaches layout provenance that way) are looked through;
850    /// tables nested inside rich table cells (`Table::cell_blocks`) are not
851    /// traversed.
852    pub fn tables(&self) -> impl Iterator<Item = &Table> {
853        fn unwrap_table(n: &Node) -> Option<&Table> {
854            match n {
855                Node::Table(t) => Some(t),
856                Node::Located { inner, .. } | Node::Prov { inner, .. } => unwrap_table(inner),
857                _ => None,
858            }
859        }
860        self.nodes.iter().filter_map(unwrap_table)
861    }
862
863    /// Mutable access to the document's top-level tables, for repair
864    /// workflows (#238): locate a cell via [`Table::find_cell_by_bbox`], fix
865    /// its text with [`Table::set_cell_text`], then re-export — every
866    /// serializer reads the same grid.
867    pub fn tables_mut(&mut self) -> impl Iterator<Item = &mut Table> {
868        fn unwrap_table(n: &mut Node) -> Option<&mut Table> {
869            match n {
870                Node::Table(t) => Some(t),
871                Node::Located { inner, .. } | Node::Prov { inner, .. } => unwrap_table(inner),
872                _ => None,
873            }
874        }
875        self.nodes.iter_mut().filter_map(unwrap_table)
876    }
877
878    pub fn push(&mut self, node: Node) {
879        self.nodes.push(node);
880    }
881
882    /// Convenience: append a heading.
883    pub fn add_heading(&mut self, level: u8, text: impl Into<String>) {
884        self.push(Node::Heading {
885            level,
886            text: text.into(),
887        });
888    }
889
890    /// Convenience: append a paragraph.
891    pub fn add_paragraph(&mut self, text: impl Into<String>) {
892        self.push(Node::Paragraph { text: text.into() });
893    }
894
895    /// Serialize the document to Markdown.
896    ///
897    /// The Rust equivalent of docling-core's
898    /// `DoclingDocument.export_to_markdown()`. Uses [`Self::strict_markdown`] to
899    /// pick between docling-legacy output (default) and the cleaner, more
900    /// conformant variant.
901    pub fn export_to_markdown(&self) -> String {
902        to_markdown(self, self.strict_markdown)
903    }
904
905    /// Serialize to Markdown, explicitly choosing the mode regardless of
906    /// [`Self::strict_markdown`]. `strict = true` produces cleaner, more
907    /// conformant Markdown (code-fence languages preserved, no inline-run
908    /// spacing artifacts); `strict = false` reproduces docling's legacy output.
909    pub fn export_to_markdown_with(&self, strict: bool) -> String {
910        to_markdown(self, strict)
911    }
912
913    /// Markdown for this document as the *content of a rich table cell*
914    /// (docling-core's `in_table_cell` serialization, docling-core#540):
915    /// headings render as plain text since Markdown tables can't hold them.
916    /// Backends build a sub-document per rich cell and flatten this into the
917    /// cell text; no trailing newline.
918    pub fn export_to_table_cell_markdown(&self) -> String {
919        crate::markdown::to_markdown_table_cell(self, self.strict_markdown)
920    }
921
922    /// Serialize to docling-core's native JSON wire format (`DoclingDocument`
923    /// schema), pretty-printed — the Rust equivalent of
924    /// `DoclingDocument.export_to_dict()` / `save_as_json()`. The output loads
925    /// back into Python docling-core and round-trips to the same Markdown.
926    pub fn export_to_json(&self) -> String {
927        serde_json::to_string_pretty(&self.export_to_json_value())
928            .expect("DoclingDocument JSON is always serializable")
929    }
930
931    /// The same JSON wire format as [`Self::export_to_json`], as a
932    /// `serde_json::Value` — for callers that append response-level extras
933    /// (docling-serve adds the confidence report, #183) before serializing.
934    pub fn export_to_json_value(&self) -> serde_json::Value {
935        crate::json::to_json(self)
936    }
937
938    /// Serialize to a complete LaTeX document — the Rust counterpart of
939    /// docling-core's `LaTeXDocSerializer` with default parameters (docling
940    /// 2.124's `--to latex`, #317). No trailing newline, like the upstream
941    /// CLI's `<stem>.tex`.
942    pub fn export_to_latex(&self) -> String {
943        crate::latex::to_latex(self)
944    }
945
946    /// Serialize to DocLang XML (`<doclang version="0.7">…`), the markup that
947    /// lives inside a `.dclx` archive — the Rust counterpart of docling-core's
948    /// `export_to_doclang()` with default parameters. No trailing newline; the
949    /// archive writer appends exactly one.
950    pub fn export_to_doclang(&self) -> String {
951        crate::doclang::export_to_doclang(&self.nodes)
952    }
953
954    /// Serialize to Markdown with an explicit picture [`ImageMode`] (mirrors
955    /// docling's `image_mode`). Returns the Markdown and, for
956    /// [`ImageMode::Referenced`], the `(relative-path, bytes)` of each image the
957    /// caller should write next to the Markdown file. `artifacts_dir` is the
958    /// directory name used in referenced links.
959    pub fn export_to_markdown_with_images(
960        &self,
961        image_mode: ImageMode,
962        artifacts_dir: &str,
963    ) -> (String, Vec<(String, Vec<u8>)>) {
964        to_markdown_images(self, self.strict_markdown, image_mode, artifacts_dir)
965    }
966}
967
968#[cfg(test)]
969mod table_api_tests {
970    use super::*;
971
972    fn cell(
973        text: &str,
974        bbox: [f32; 4],
975        (start_row, start_col): (usize, usize),
976        (row_span, col_span): (usize, usize),
977    ) -> TableCell {
978        TableCell {
979            text: text.into(),
980            bbox: Some(bbox),
981            start_row,
982            start_col,
983            row_span,
984            col_span,
985            column_header: false,
986            row_header: false,
987            row_section: false,
988        }
989    }
990
991    fn table() -> Table {
992        Table {
993            rows: vec![
994                vec!["Year".into(), "Ducks".into()],
995                vec!["2019".into(), "120".into()],
996            ],
997            cells: Some(vec![
998                cell("Year", [0.0, 0.0, 50.0, 10.0], (0, 0), (1, 1)),
999                cell("Ducks", [50.0, 0.0, 100.0, 10.0], (0, 1), (1, 1)),
1000                cell("2019", [0.0, 10.0, 50.0, 20.0], (1, 0), (1, 1)),
1001                cell("120", [50.0, 10.0, 100.0, 20.0], (1, 1), (1, 1)),
1002            ]),
1003            ..Default::default()
1004        }
1005    }
1006
1007    /// Declarative tables derive first-class cells from the structure
1008    /// overlay: continuation grids become span extents, `col_header` (or the
1009    /// row-0 fallback) becomes the header role — the XLSX/DOCX/HTML merge
1010    /// path into real `TableCell`s (#240).
1011    #[test]
1012    fn derive_cells_reads_spans_and_headers_from_structure() {
1013        let t = Table {
1014            rows: vec![
1015                vec!["Wide".into(), "Wide".into(), "C".into()],
1016                vec!["a".into(), "b".into(), "c".into()],
1017            ],
1018            structure: Some(TableStructure {
1019                header_row: vec![true, false],
1020                col_continuation: vec![vec![false, true, false], vec![false; 3]],
1021                row_continuation: vec![vec![false; 3], vec![false; 3]],
1022                row_header: Vec::new(),
1023                col_header: Vec::new(),
1024            }),
1025            ..Default::default()
1026        };
1027        let cells = t.derive_cells();
1028        assert_eq!(cells.len(), 5, "two anchors in row 0, three in row 1");
1029        let wide = &cells[0];
1030        assert_eq!((wide.col_span, wide.row_span), (2, 1));
1031        assert!(wide.column_header, "header_row band");
1032        assert!(cells.iter().skip(2).all(|c| !c.column_header));
1033
1034        // Without any overlay: every position 1x1, row 0 the header
1035        // (docling's declarative default — the old JSON synthesis).
1036        let plain = Table {
1037            rows: vec![vec!["h".into()], vec!["x".into()]],
1038            ..Default::default()
1039        };
1040        let cells = plain.derive_cells();
1041        assert_eq!(cells.len(), 2);
1042        assert!(cells[0].column_header && !cells[1].column_header);
1043    }
1044
1045    /// A spanning cell updates once: the record text and every covered grid
1046    /// position — a repair shows once in Markdown, not once per column.
1047    #[test]
1048    fn span_repair_updates_the_whole_cell() {
1049        let mut t = Table {
1050            rows: vec![
1051                vec!["Wide".into(), "Wide".into(), "C".into()],
1052                vec!["a".into(), "b".into(), "c".into()],
1053            ],
1054            cells: Some(vec![
1055                cell("Wide", [0.0, 0.0, 100.0, 10.0], (0, 0), (1, 2)),
1056                cell("C", [100.0, 0.0, 150.0, 10.0], (0, 2), (1, 1)),
1057            ]),
1058            ..Default::default()
1059        };
1060        // Update through the covered (non-anchor) position.
1061        assert!(t.set_cell_text(0, 1, "Fixed"));
1062        assert_eq!(
1063            t.rows[0],
1064            vec!["Fixed".to_string(), "Fixed".into(), "C".into()]
1065        );
1066        assert_eq!(t.cell_at(0, 1).unwrap().text, "Fixed");
1067        assert_eq!(t.cell_at(0, 1).unwrap().col_span, 2);
1068    }
1069
1070    /// The OCR-repair loop (#238): locate a cell by an external box (best
1071    /// IoU), replace its text, and see the fix in the export — the grid is
1072    /// the single source of truth for every serializer.
1073    #[test]
1074    fn bbox_lookup_and_repair_flow_into_exports() {
1075        let mut doc = DoclingDocument::new("t");
1076        doc.push(Node::Table(table()));
1077        assert_eq!(doc.tables().count(), 1);
1078
1079        let t = doc.tables_mut().next().unwrap();
1080        // A slightly-off OCR box still lands on the (1,1) cell.
1081        assert_eq!(t.find_cell_by_bbox([52.0, 11.0, 98.0, 19.0]), Some((1, 1)));
1082        assert_eq!(
1083            t.update_cell_by_bbox([52.0, 11.0, 98.0, 19.0], "125"),
1084            Some((1, 1))
1085        );
1086        assert_eq!(t.cell_text(1, 1), Some("125"));
1087        assert!(doc.export_to_markdown().contains("125"));
1088
1089        // No overlap → no match, nothing changed.
1090        let t = doc.tables_mut().next().unwrap();
1091        assert_eq!(t.find_cell_by_bbox([500.0, 500.0, 600.0, 600.0]), None);
1092    }
1093
1094    #[test]
1095    fn cell_accessors_bound_check_and_geometry_materializes() {
1096        let mut t = table();
1097        assert_eq!(t.cell_text(0, 0), Some("Year"));
1098        assert_eq!(t.cell_text(5, 0), None);
1099        assert!(!t.set_cell_text(0, 9, "x"), "outside the grid");
1100        assert_eq!(t.cell_bbox(1, 0), Some([0.0, 10.0, 50.0, 20.0]));
1101
1102        // A geometry-less table materializes its box grid on first set.
1103        let mut plain = Table {
1104            rows: vec![vec!["a".into(), "b".into()]],
1105            ..Default::default()
1106        };
1107        assert_eq!(plain.cell_bbox(0, 1), None);
1108        assert!(!plain.set_cell_bbox(0, 5, [0.0; 4]), "outside the grid");
1109        assert!(plain.set_cell_bbox(0, 1, [1.0, 2.0, 3.0, 4.0]));
1110        assert_eq!(plain.cell_bbox(0, 1), Some([1.0, 2.0, 3.0, 4.0]));
1111        assert_eq!(plain.find_cell_by_bbox([1.5, 2.5, 2.5, 3.5]), Some((0, 1)));
1112    }
1113}