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