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