Skip to main content

docling_core/
document.rs

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