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