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