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 /// Render a picture's author-written alt text (#676: the `descr` /
28 /// `title` of an OOXML picture's non-visual properties, carried as a
29 /// [`PictureDescription`] whose provenance is
30 /// [`PictureDescription::ALT_TEXT`]) in the Markdown and HTML exports
31 /// (the `` of an image line or the line above a placeholder;
32 /// the `<img alt>` and the description text). `false` (the default)
33 /// keeps it to the JSON (and DCLX) output, so the default Markdown and
34 /// HTML stay byte-for-byte docling's; strict Markdown renders it
35 /// regardless. Set by `DocumentConverter::picture_alt_text`.
36 pub picture_alt_text: bool,
37 /// What the file says about itself (#679): an EPUB's Dublin Core, an
38 /// Office package's properties, a photo's EXIF, an audio file's tags —
39 /// see [`crate::metadata`]. Read by the converter when
40 /// [`metadata_output`](Self::metadata_output) asks for it (a document
41 /// read from docling JSON keeps the `metadata` the JSON carried).
42 pub metadata: crate::metadata::DocumentMetadata,
43 /// Where [`metadata`](Self::metadata) goes in the exports: nowhere (the
44 /// default — every export stays docling's), the JSON's `metadata`
45 /// object, or that and YAML front matter at the top of the Markdown.
46 /// Set by `DocumentConverter::metadata_output`.
47 pub metadata_output: crate::metadata::MetadataOutput,
48 /// Text the Markdown export inserts between two pages — docling-core's
49 /// `MarkdownParams.page_break_placeholder` (e.g. `"<!-- page break -->"`).
50 /// `None` (the default) omits page breaks from Markdown, as docling does.
51 /// Set by `DocumentConverter::page_break_placeholder`. See
52 /// [`crate::markdown`] for where a break lands (only between two rendered
53 /// blocks that sit on different pages, never leading or trailing).
54 pub page_break_placeholder: Option<String>,
55 /// Hyperlinks recovered from the source, as `(anchor_text, href)` pairs in
56 /// document order. docling's standard pipeline drops PDF link annotations, so
57 /// these are rendered as Markdown `[anchor](href)` **only in strict mode**
58 /// (legacy/docling output is left byte-for-byte unchanged). The PDF backend
59 /// populates this from pdfium link annotations; other backends leave it empty.
60 pub links: Vec<(String, String)>,
61 /// Conversion-confidence report (#183), populated by the PDF/image ML
62 /// pipeline; `None` for declarative conversions. Deliberately **not**
63 /// part of any document export (docling keeps it on the conversion
64 /// result, outside the document schema) — docling-serve surfaces it in
65 /// the HTTP response instead.
66 pub confidence: Option<crate::confidence::ConfidenceReport>,
67 /// docling's item tree, when the backend built one (the HTML backend
68 /// does): the JSON export serializes it instead of deriving a tree from
69 /// `nodes`, so the JSON carries upstream's exact parent/child structure,
70 /// item numbering, inline groups, formatting and content layers. Every
71 /// other serializer reads `nodes`. See [`crate::tree`].
72 pub tree: Option<crate::tree::ItemTree>,
73 /// Rendered page images by 1-based page number — docling's
74 /// `PageItem.image`, filled by the PDF/image pipeline only when page
75 /// images are requested (docling's `generate_page_images`, #520). The
76 /// JSON export writes each as the page's `image`, so docling-core's
77 /// `TableItem.get_image` / `FormulaItem.get_image` can crop from it.
78 /// Empty otherwise; no other export reads it.
79 pub page_images: std::collections::BTreeMap<usize, PictureImage>,
80}
81
82/// A single piece of document content.
83#[derive(Debug, Clone, PartialEq)]
84pub enum Node {
85 /// A heading. `level` is 1-6.
86 Heading { level: u8, text: String },
87 /// A run of body text.
88 Paragraph { text: String },
89 /// A form checkbox (docling's `checkbox_selected`/`checkbox_unselected`): its
90 /// clean label `text` with the checked state. DocLang emits a `<checkbox>`
91 /// element head; Markdown/JSON render the task-list form (`- [x] `/`- [ ] `).
92 CheckboxItem { checked: bool, text: String },
93 /// A single list item at the given nesting `level` (0 = top). For ordered
94 /// items, `number` is the display number (honoring the list's `start`); it
95 /// is unused for unordered items. `first_in_list` marks the first item of a
96 /// list so the serializer can blank-line-separate adjacent sibling lists.
97 ///
98 /// `marker` is the DocLang enumeration marker (`"1."`, `"1.1."`, …) when the
99 /// backend provides one — HTML and DOCX set it for enumerated items, so
100 /// DocLang emits `<ldiv><marker>…</marker></ldiv>`; Markdown and the other
101 /// declarative backends leave it `None`, giving a bare `<ldiv/>` (matching
102 /// docling, whose Markdown backend passes no marker).
103 ListItem {
104 ordered: bool,
105 number: u64,
106 first_in_list: bool,
107 text: String,
108 level: u8,
109 marker: Option<String>,
110 /// Optional layout provenance (`x0,y0,x1,y1`, normalized to 0–511): the
111 /// four DocLang `<location>` values emitted inside the `<list>` right
112 /// after the item's `<ldiv>`. Set only by backends with real geometry
113 /// (e.g. PPTX shapes); `None` for the declarative backends. Kept on the
114 /// item itself (rather than a [`Node::Located`] wrapper) so consecutive
115 /// items still group into one `<list>`.
116 location: Option<[u16; 4]>,
117 /// DocLang-only override for items whose DocLang form diverges from their
118 /// flat Markdown `text`. Markdown/JSON always render the fields above; the
119 /// DocLang serializer, when this is `Some`, takes the list kind, marker,
120 /// and content from here instead. Used for docx multilevel numbering
121 /// (Markdown shows `- 1.1. x`, DocLang an ordered `<marker>1.1.</marker>`
122 /// with clean text) and inline equations/formatting in list items.
123 dclx: Option<ListItemDclx>,
124 /// The item's hyperlink target, when its content is a link — docling's
125 /// HTML backend emits it as an `<href uri=…/>` in the item head, and the
126 /// anchor's Markdown link markup is stripped from the rendered content.
127 /// `None` for a plain item; ignored by Markdown/JSON.
128 href: Option<String>,
129 /// Non-body content layer (docling's HTML site chrome before the first
130 /// heading → `furniture`). DocLang emits a `<layer value=…/>` in the item
131 /// head; Markdown/JSON drop a non-body item entirely.
132 layer: Option<ContentLayer>,
133 },
134 /// A fenced code block.
135 Code {
136 language: Option<String>,
137 text: String,
138 /// The original (pre-enrichment) text when the CodeFormula model
139 /// rewrote `text`: docling keeps the raw extraction in the JSON `orig`
140 /// field while `text` carries the model output. `None` → `orig == text`.
141 orig: Option<String>,
142 /// A line-preserving rendering, when the backend can reconstruct one
143 /// but docling's own output for the format cannot. The PDF pipeline
144 /// sets it (docling-parse joins code lines with single spaces, so
145 /// `text` carries that flat docling-parity form): **strict** Markdown
146 /// prefers `pretty`, every byte-conformance surface (legacy Markdown,
147 /// JSON, DocLang, chunks) serializes `text`.
148 pretty: Option<String>,
149 },
150 /// A table. The first row is treated as the header.
151 Table(Table),
152 /// A picture/figure, with an optional caption and (when a backend extracts
153 /// it) the embedded image itself.
154 Picture {
155 caption: Option<String>,
156 /// Hyperlink annotation on the caption (docling's caption text item
157 /// `hyperlink`): the HTML backend sets it when an `<a href>` wraps the
158 /// image whose `alt` became the caption. DocLang emits the block-form
159 /// `<caption>` with an `<href uri=…/>` head; JSON puts `hyperlink` on
160 /// the caption item; Markdown and LaTeX print the plain caption text,
161 /// as docling does.
162 caption_href: Option<String>,
163 image: Option<PictureImage>,
164 /// DocumentPictureClassifier predictions (all classes, descending
165 /// confidence), when the picture-classification enrichment ran.
166 /// Serialized as docling's `classification` annotation + `meta` field
167 /// on the JSON picture item; Markdown/DocLang output is unaffected.
168 classification: Option<Vec<PictureClass>>,
169 /// Text read off the embedded image by the picture-OCR enrichment
170 /// (#645) — docling's `PictureDescriptionData` annotation /
171 /// `meta.description`, which is where upstream's picture-description
172 /// models (VLM captioning) put their text too. JSON and DCLX carry it
173 /// structurally; Markdown prints it between the caption and the
174 /// image placeholder, where docling's picture serializer renders
175 /// annotations. `None` when the enrichment did not run or read no
176 /// text, so every default export stays unchanged.
177 description: Option<PictureDescription>,
178 /// Where the caption item hangs in the JSON tree (#390); see
179 /// [`CaptionParent`]. Markdown, DocLang and LaTeX ignore it.
180 caption_parent: CaptionParent,
181 /// The caption's own box on the picture's page (0–511 grid, like
182 /// [`Node::Located`]) — the PDF pipeline's caption layout region. The
183 /// JSON export writes it as the caption item's `prov` (#609), as
184 /// docling's `ReadingOrderModel._add_caption_or_footnote` does; `None`
185 /// (every declarative backend) leaves the caption without one.
186 caption_location: Option<[u16; 4]>,
187 },
188 /// A display-math formula item decoded by the CodeFormula enrichment:
189 /// `latex` is the model's LaTeX (no `$$` wrapping), `orig` the raw glyph
190 /// text extracted from the PDF. Markdown renders `$$latex$$`; JSON emits a
191 /// `formula` text item (docling's un-enriched pipeline instead emits a
192 /// placeholder paragraph — see the PDF assembler).
193 Formula {
194 latex: String,
195 orig: String,
196 location: Option<[u16; 4]>,
197 },
198 /// A standalone caption item (docling's `DocItemLabel.CAPTION` text that
199 /// no picture or table claims): the HTML backend emits a `<figure>`'s
200 /// `<figcaption>` this way when the figure produced no picture and its
201 /// first item is not a table (docling#4050). `href` is the caption's
202 /// hyperlink annotation (the first link inside the figcaption); Markdown
203 /// renders it as `[text](href)`, JSON puts `hyperlink` on the caption
204 /// item, DocLang emits the block-form `<caption>` with an `<href>` head.
205 Caption { text: String, href: Option<String> },
206 /// A body text item with a docling label of its own and an optional
207 /// hyperlink — the PDF pipeline's `footnote` regions, whose item docling
208 /// keeps as a `footnote` text with the link annotation covering it as its
209 /// `hyperlink` (`PageAssembleModel._match_hyperlink`). The JSON writes
210 /// exactly that (label, raw text, `hyperlink`); every other serializer
211 /// renders it as the paragraph [`Self::labeled_markdown`] spells —
212 /// docling's Markdown wraps a linked item's whole text, `[text](uri)`.
213 LabeledText {
214 label: String,
215 text: String,
216 href: Option<String>,
217 },
218 /// A chart (docling's `PictureItem` classified as a chart, carrying a
219 /// `PictureTabularChartData` annotation). Markdown and JSON render it exactly
220 /// like a [`Node::Picture`] placeholder (an `<!-- image -->` / `picture`
221 /// item); the DocLang serializer emits `<picture class="chart">` with a
222 /// `<label value="{kind}"/>` and the data `table` as a `<tabular>`.
223 Chart {
224 /// docling's classification label, e.g. `bar_chart`, `line_chart`.
225 kind: String,
226 /// The chart's data grid (row 0 is the header band).
227 table: Table,
228 /// The chart title (docling's caption item on the picture).
229 caption: Option<String>,
230 /// DocLang `<location>` provenance for the picture element.
231 location: Option<[u16; 4]>,
232 },
233 /// A logical grouping of child nodes (e.g. a list, a section, a spreadsheet
234 /// sheet). `name` is docling's group name when it differs from the label —
235 /// an xlsx sheet group is `label: "sheet"`, `name: Some("Sheet1")`. `layer`
236 /// puts the group *and* everything it contains on a non-body content layer
237 /// (a hidden sheet is `invisible`), which is how the serializers that only
238 /// render body content know to skip it; DocLang stamps each child with the
239 /// layer token, exactly as a [`Node::Furniture`] wrapper on each would.
240 /// DocLang has no group element, so a group is transparent there.
241 Group {
242 label: String,
243 name: Option<String>,
244 layer: Option<ContentLayer>,
245 children: Vec<Node>,
246 },
247 /// A form key-value region (docling's `field_region`): a set of form fields,
248 /// each pairing an optional marker, key, and value. Backends detect these
249 /// from form structure (e.g. HTML's `keyN` / `keyN_valueM` / `keyN_marker`
250 /// `id`-convention); the serializers render each item's parts as separate
251 /// labelled texts (`marker` / `field_key` / `field_value`).
252 FieldRegion { items: Vec<FieldItem> },
253 /// docling's `KeyValueItem`: a graph of key and value cells and the links
254 /// between them (docling-core's `GraphData`). The XBRL backend builds one
255 /// from an instance's numeric facts and the presentation and calculation
256 /// hierarchies of its taxonomy. Only the JSON export carries the graph:
257 /// docling's Markdown serializer has no rendering for the item and writes
258 /// its `<!-- missing-key-value-item -->` placeholder, which the Markdown
259 /// export reproduces; the other serializers omit it.
260 KeyValueGraph {
261 cells: Vec<GraphCell>,
262 links: Vec<GraphLink>,
263 },
264 /// Rich inline content — docling's `InlineGroup`: a run of styled text
265 /// segments that a backend captured with formatting (`<bold>`, `<italic>`,
266 /// `<underline>`, `<strikethrough>`, sub/superscript, inline `<code>`) the
267 /// flat Markdown text cannot represent. Markdown/JSON render this exactly
268 /// like `Paragraph { text: md_text }` (so their output is unchanged); the
269 /// DocLang serializer uses the structured `runs`. `unwrapped` is set when the
270 /// group's docling parent is a heading/text (no enclosing `<text>` wrapper).
271 InlineGroup {
272 unwrapped: bool,
273 runs: Vec<InlineRun>,
274 md_text: String,
275 },
276 /// A node in a non-body content layer — `furniture` (page headers/footers,
277 /// the HTML `<title>`, site navigation/chrome) or `notes` (docx comments).
278 /// Markdown and JSON omit these layers by default; DocLang renders the wrapped
279 /// node with a `<layer value="{layer}"/>` head.
280 Furniture {
281 layer: ContentLayer,
282 inner: Box<Node>,
283 },
284 /// One reviewer comment: docling's notes-layer `comment_section` group
285 /// holding a single text item. `name` is docling's own — `comment-{id}` for
286 /// a docx `w:comment`, `comment-{sheet}-{cell}` for a spreadsheet cell note.
287 /// JSON emits the group plus its notes-layer text; DocLang emits the flat
288 /// `<text><layer value="notes"/>…</text>` upstream writes (its DocLang
289 /// carries no group for comments); Markdown and LaTeX omit the notes layer.
290 ///
291 /// `refs_note_text` picks what a [`Node::Commented`] annotation points at,
292 /// mirroring an upstream asymmetry: docling-core's `add_comment` appends the
293 /// **note text**'s ref to each target (which is what the xlsx backend gets),
294 /// while the docx backend overwrites that with the **group**'s ref so a
295 /// comment's replies group together.
296 ///
297 /// `grouped` is whether docling wraps the note in a `comment_section`
298 /// group at all: the docx and spreadsheet backends do, while backends that
299 /// call docling-core's `add_comment` directly (Pages, #383) get a bare
300 /// notes-layer text item under the body — JSON then emits no group and
301 /// `name` is unused.
302 CommentSection {
303 name: String,
304 text: String,
305 refs_note_text: bool,
306 grouped: bool,
307 },
308 /// A body item annotated by reviewer comments: `comments` are indices into
309 /// the document's [`Node::CommentSection`] nodes, in document order. JSON
310 /// emits docling's `comments: [{"$ref": …}]` on the item, each ref pointing
311 /// where the section says (see [`Node::CommentSection::refs_note_text`]);
312 /// every other serializer renders `inner` unchanged.
313 Commented {
314 comments: Vec<usize>,
315 inner: Box<Node>,
316 },
317 /// A text node taken from a time-based track — an ASR segment (#614):
318 /// docling's `TrackSource`. The JSON writes docling's ASR text item — `cue`
319 /// (the segment's words) as its text, `track` as its `source: [{"kind":
320 /// "track", …}]` — which the WebVTT export makes a cue of; every other
321 /// serializer renders `inner` (the `[time: start-end] words` paragraph)
322 /// unchanged.
323 Track {
324 track: crate::tree::TreeTrack,
325 cue: String,
326 inner: Box<Node>,
327 },
328 /// A node carrying layout provenance — the four DocLang `<location>` values
329 /// (`x0,y0,x1,y1`, normalized to 0–511) docling attaches to elements from
330 /// backends with real geometry (e.g. the slide shapes in PPTX). Markdown and
331 /// JSON render the wrapped node unchanged; DocLang emits the `<location>`
332 /// tokens as the element's first children.
333 Located {
334 location: [u16; 4],
335 inner: Box<Node>,
336 },
337 /// Exact page provenance for a backend whose geometry already *is* the
338 /// page's coordinate system — an XLSX item's cell-index box on its sheet,
339 /// which docling writes verbatim (`bbox` in a top-left origin, the
340 /// `charspan` the backend chose) and sizes the page from. The 0–511 grid
341 /// of a [`Node::Located`] cannot round-trip such integers exactly, so the
342 /// JSON export reads this wrapper; every other serializer renders `inner`
343 /// unchanged (DocLang keeps taking its `<location>` tokens from the grid).
344 Prov {
345 page_no: usize,
346 /// `[l, t, r, b]`, page units, top-left origin.
347 bbox: [f32; 4],
348 /// docling's `charspan` for the item (`[0, 0]` for an XLSX table).
349 charspan: [usize; 2],
350 /// The item's creation rank among its siblings, when that differs
351 /// from the node order: docling numbers `#/tables/N` / `#/texts/N` /
352 /// `#/pictures/N` in the order it *creates* items (a sheet's tables,
353 /// then its images, then its charts) and only afterwards sorts the
354 /// container's children by position. The JSON export adds siblings in
355 /// this order and lays their refs out in node order; `None` when the
356 /// two orders coincide.
357 seq: Option<usize>,
358 inner: Box<Node>,
359 },
360 /// A PDF page header or footer (docling's `page_header`/`page_footer`
361 /// furniture): DocLang emits `<page_header>`/`<page_footer>` with a
362 /// `<layer value="furniture"/>` head, the four `<location>` tokens, then the
363 /// text. The JSON writes it as a body-parented `page_header`/`page_footer`
364 /// text item on the furniture layer; Markdown omits it.
365 PageFurniture {
366 footer: bool,
367 location: [u16; 4],
368 text: String,
369 },
370 /// A furniture-layer text item with an explicit docling label — a page
371 /// header / footer paragraph (`page_header` / `page_footer`) or a note
372 /// body (`footnote`) from a backend that builds no item tree (#535: the
373 /// Word 97 `.doc` stories). The JSON writes a body-parented item of that
374 /// label on the furniture layer; DocLang `<{label}>` with a `<layer
375 /// value="furniture"/>` head (docling-core's own shape); Markdown, LaTeX
376 /// and the chunker leave it out like any furniture.
377 FurnitureText { label: String, text: String },
378 /// The text a PDF picture contains, kept the way docling keeps it: every
379 /// regular layout cluster > 80 % inside a picture cluster is that
380 /// `PictureItem`'s child (`LayoutPostprocessor._set_cluster_children`,
381 /// `ReadingOrderModel._add_child_elements`). Emitted right after its
382 /// picture node. The JSON export writes these nodes as items parented to
383 /// that picture, after its caption; docling's Markdown and LaTeX picture
384 /// serializers print only the caption and the image, so every other
385 /// serializer skips it — except the Markdown export asked to
386 /// `traverse_pictures` ([`MarkdownExportOptions`], #599), which renders
387 /// them after the picture like upstream's item walk does.
388 PictureChildren(Vec<Node>),
389 /// A page boundary — docling's implicit page break between pages. The PPTX
390 /// backend emits one between consecutive slides. DocLang renders it as
391 /// `<page_break/>`; Markdown and JSON omit it (matching docling's default
392 /// exports, which carry page breaks only in the document model).
393 PageBreak,
394 /// A text item docling hangs in a *list group*, after the item before it
395 /// (an AsciiDoc paragraph still pending when a list opened is flushed into
396 /// the list's group): docling-core's list serializer prints it as one more
397 /// line of the list, indented to the group's depth `level` — or, `glue`,
398 /// when it is an inline group, appended to the line before it with no
399 /// separator at all. `text` is Markdown, like a paragraph's. Every other
400 /// serializer reads it as a paragraph.
401 ListText { level: u8, text: String, glue: bool },
402 /// An invisible page marker — the first node of every page the PDF paths
403 /// assemble: the 1-based page number and the page size in PDF points. It
404 /// carries exactly what the JSON export needs to populate docling's
405 /// `pages` map and to denormalize the 0–511 `<location>` grid back into
406 /// BOTTOMLEFT point bboxes for per-item `prov` (#171). Every other
407 /// serializer skips it, so Markdown / DocLang / DocTags output is
408 /// byte-for-byte unchanged.
409 PageInfo {
410 /// 1-based page number (0 = "not yet numbered": the assembler emits
411 /// the marker, the document-level collector stamps the real number).
412 page_no: usize,
413 /// Page width in PDF points.
414 width: f32,
415 /// Page height in PDF points.
416 height: f32,
417 },
418 /// A node docling keeps in the document model (and DocLang) but leaves out
419 /// of the Markdown and JSON exports — e.g. an ODF *presentation*'s pictures
420 /// and charts, which appear in the `.dclx` body but not in its `.md`/`.json`.
421 /// DocLang renders the wrapped node in place; Markdown and JSON skip it.
422 DoclangOnly(Box<Node>),
423 /// A verbatim plain-text dump — docling's plain-text backend emits the whole
424 /// file as a single text item (used for legacy USPTO APS `.txt` grants, which
425 /// docling routes to plain text rather than its APS parser). The stored string
426 /// is the file body, one record per line. Markdown/JSON render it as one text
427 /// block; the DocLang serializer reproduces minidom's per-line layout, CDATA-
428 /// escaping only the lines that need it (see `emit_text_dump`).
429 TextDump(String),
430}
431
432/// Vertical text position of an [`InlineRun`] — docling's `Script`.
433#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
434pub enum Script {
435 #[default]
436 Baseline,
437 Sub,
438 Super,
439}
440
441/// One styled segment of a [`Node::InlineGroup`] — the docling.rs analogue of a
442/// `TextItem` inside an `InlineGroup`, carrying the ancestor formatting docling
443/// tracks. `text` is already whitespace-normalized/trimmed (one segment per
444/// source text node). A hyperlink is intentionally not stored: DocLang drops the
445/// target inside inline scope, keeping only the anchor text.
446#[derive(Debug, Clone, PartialEq, Eq, Default)]
447pub struct InlineRun {
448 pub text: String,
449 pub bold: bool,
450 pub italic: bool,
451 pub underline: bool,
452 pub strike: bool,
453 pub script: Script,
454 pub code: bool,
455 /// An inline equation (`text` holds LaTeX): DocLang renders `<formula>…`,
456 /// Markdown/JSON keep the `$…$` already baked into the group's `md_text`.
457 pub formula: bool,
458}
459
460/// A DocLang content layer other than the default `body` (see [`Node::Furniture`]).
461#[derive(Debug, Clone, Copy, PartialEq, Eq)]
462pub enum ContentLayer {
463 /// Page headers/footers, HTML `<title>`, site navigation/chrome.
464 Furniture,
465 /// Editorial notes (docx reviewer comments).
466 Notes,
467 /// Invisible content (hidden spreadsheet sheets).
468 Invisible,
469}
470
471impl ContentLayer {
472 /// The `<layer value="…"/>` token value.
473 pub fn value(self) -> &'static str {
474 match self {
475 ContentLayer::Furniture => "furniture",
476 ContentLayer::Notes => "notes",
477 ContentLayer::Invisible => "invisible",
478 }
479 }
480}
481
482/// A set of content layers, `body` included — docling-core's
483/// `set[ContentLayer]` (`HTMLParams.layers`,
484/// `export_to_html(included_content_layers=…)`), where `body` is a member
485/// like any other. [`Default`] is docling's `DEFAULT_CONTENT_LAYERS`: body
486/// only, so an export built with it is unchanged from before layers could
487/// be chosen (#499).
488#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
489pub struct ContentLayers {
490 /// The main content (items without an explicit layer).
491 pub body: bool,
492 /// [`ContentLayer::Furniture`]: page headers/footers, navigation chrome.
493 pub furniture: bool,
494 /// [`ContentLayer::Notes`]: reviewer comments and other editorial notes.
495 pub notes: bool,
496 /// [`ContentLayer::Invisible`]: hidden content (hidden sheets, …).
497 pub invisible: bool,
498}
499
500impl Default for ContentLayers {
501 fn default() -> Self {
502 Self::BODY
503 }
504}
505
506impl ContentLayers {
507 /// Body only — docling's `DEFAULT_CONTENT_LAYERS`.
508 pub const BODY: Self = Self {
509 body: true,
510 furniture: false,
511 notes: false,
512 invisible: false,
513 };
514 /// Every layer — Python's `set(ContentLayer)`.
515 pub const ALL: Self = Self {
516 body: true,
517 furniture: true,
518 notes: true,
519 invisible: true,
520 };
521 /// No layer at all (nothing renders); build a set from it with
522 /// [`with`](Self::with) / [`with_body`](Self::with_body).
523 pub const NONE: Self = Self {
524 body: false,
525 furniture: false,
526 notes: false,
527 invisible: false,
528 };
529
530 /// The set plus `layer`.
531 pub const fn with(mut self, layer: ContentLayer) -> Self {
532 match layer {
533 ContentLayer::Furniture => self.furniture = true,
534 ContentLayer::Notes => self.notes = true,
535 ContentLayer::Invisible => self.invisible = true,
536 }
537 self
538 }
539
540 /// The set plus the body layer.
541 pub const fn with_body(mut self) -> Self {
542 self.body = true;
543 self
544 }
545
546 /// Whether `layer` is in the set; `None` is the body layer.
547 pub fn contains(&self, layer: Option<ContentLayer>) -> bool {
548 match layer {
549 None => self.body,
550 Some(ContentLayer::Furniture) => self.furniture,
551 Some(ContentLayer::Notes) => self.notes,
552 Some(ContentLayer::Invisible) => self.invisible,
553 }
554 }
555
556 /// Whether the layer spelled `name` (`body`, `furniture`, `notes`,
557 /// `invisible` — the JSON `content_layer` values) is in the set; an
558 /// unknown name is not.
559 pub fn contains_name(&self, name: &str) -> bool {
560 match name {
561 "body" => self.body,
562 "furniture" => self.furniture,
563 "notes" => self.notes,
564 "invisible" => self.invisible,
565 _ => false,
566 }
567 }
568
569 /// Parse a comma-separated list of layer names (`body,furniture`;
570 /// whitespace around a name is ignored, `all` is every layer). An
571 /// unknown name is the error. docling-core 2.99's `background` layer
572 /// (watermarks) has no items in this model, so the name is accepted and
573 /// adds nothing — a set written for Python keeps parsing.
574 pub fn parse_list(list: &str) -> Result<Self, String> {
575 let mut set = Self::NONE;
576 for name in list.split(',').map(str::trim).filter(|n| !n.is_empty()) {
577 match name {
578 "body" => set.body = true,
579 "furniture" => set.furniture = true,
580 "notes" => set.notes = true,
581 "invisible" => set.invisible = true,
582 "background" => {}
583 "all" => set = Self::ALL,
584 other => {
585 return Err(format!(
586 "unknown content layer `{other}` (expected body, furniture, notes, invisible or all)"
587 ))
588 }
589 }
590 }
591 Ok(set)
592 }
593}
594
595/// Options of the HTML export ([`DoclingDocument::export_to_html_with`]):
596/// docling-core's `HTMLParams` subset the port honours. [`Default`] is
597/// upstream's default export — placeholder images, `artifacts` as the
598/// referenced-image directory, the body layer only.
599#[derive(Debug, Clone, PartialEq, Eq)]
600pub struct HtmlExportOptions {
601 /// How pictures render (`HTMLParams.image_mode`): nothing but captions
602 /// and meta for [`ImageMode::Placeholder`], `data:` URIs when embedded,
603 /// `<img src>` paths under [`artifacts_dir`](Self::artifacts_dir) when
604 /// referenced.
605 pub image_mode: ImageMode,
606 /// The directory referenced images are named under, the Markdown
607 /// export's convention (`<artifacts_dir>/image_NNNNNN.<ext>`).
608 pub artifacts_dir: String,
609 /// The content layers rendered (`HTMLParams.layers`, #499): an item on a
610 /// layer outside the set is skipped, its children still walked — exactly
611 /// how docling-core's `get_excluded_refs` reads the set.
612 pub layers: ContentLayers,
613}
614
615impl Default for HtmlExportOptions {
616 fn default() -> Self {
617 Self {
618 image_mode: ImageMode::Placeholder,
619 artifacts_dir: "artifacts".to_string(),
620 layers: ContentLayers::BODY,
621 }
622 }
623}
624
625/// Options of the Markdown export
626/// ([`DoclingDocument::export_to_markdown_with_options`], #599): the
627/// docling-core `MarkdownParams` the port honours beyond the image mode.
628/// [`Default`] is upstream's default export — placeholder images,
629/// `artifacts` as the referenced-image directory, the body layer only, no
630/// picture traversal, HTML and underscore escaping on, `<!-- image -->` —
631/// so a document exported with it is byte-identical to
632/// [`DoclingDocument::export_to_markdown`].
633#[derive(Debug, Clone, PartialEq, Eq)]
634pub struct MarkdownExportOptions {
635 /// How pictures render (`MarkdownParams.image_mode`): the placeholder,
636 /// `data:` URIs when embedded, ``
637 /// when referenced (the bytes come back for the caller to write).
638 pub image_mode: ImageMode,
639 /// The directory referenced images are named under.
640 pub artifacts_dir: String,
641 /// The content layers rendered (`MarkdownParams.layers`,
642 /// `export_to_markdown(included_content_layers=…)`): an item on a layer
643 /// outside the set is skipped, its children still walked. The default
644 /// body-only set drops page headers/footers (`furniture`), reviewer
645 /// comments (`notes`) and hidden sheets (`invisible`), as upstream does; a
646 /// scanned form's running header reads out with
647 /// `ContentLayers::BODY.with(ContentLayer::Furniture)`. The extra items
648 /// render through the body's serializers — a page header is a paragraph.
649 pub layers: ContentLayers,
650 /// `CommonParams.traverse_pictures`: render the text items nested in a
651 /// picture (the PDF pipeline's picture children — a bordered form laid
652 /// out as one picture holds every field as a child) after the picture's
653 /// own caption and image, as upstream yields them. Off, a picture prints
654 /// only its caption and image.
655 pub traverse_pictures: bool,
656 /// `MarkdownParams.escape_html`: `&`, `<` and `>` in text as `&`,
657 /// `<`, `>` (Python's `html.escape(quote=False)`). Off, `R&D` stays
658 /// `R&D`.
659 pub escape_html: bool,
660 /// `MarkdownParams.escape_underscores`: `_` in text as `\_`. Off, the
661 /// text keeps its underscores.
662 pub escape_underscores: bool,
663 /// `MarkdownParams.image_placeholder`: what a picture prints as when it
664 /// renders no image data (the placeholder mode, or a picture without a
665 /// payload); upstream's `<!-- image -->`.
666 pub image_placeholder: String,
667 /// docling-core's `PlainTextDocSerializer` (#613, `export_to_text`,
668 /// docling's `--to text`): the Markdown walk with the decoration turned
669 /// off — headings without `#`, bold/italic/strikethrough markers and
670 /// inline code backticks dropped, a hyperlink reduced to its label, code
671 /// blocks unfenced, no GFM hard line breaks. List bullets/numbers,
672 /// checkbox marks and table grids stay. [`Self::plain_text`] pairs it
673 /// with upstream's `PlainTextParams` (no escaping, an empty image
674 /// placeholder).
675 pub plain_text: bool,
676}
677
678impl MarkdownExportOptions {
679 /// docling-core's `PlainTextParams` defaults (#613): [`Self::plain_text`]
680 /// on, HTML and underscore escaping off, pictures print nothing (their
681 /// captions still do), body layer only, no picture traversal — what
682 /// `DoclingDocument.export_to_text()` and docling's `--to text` write.
683 pub fn plain_text() -> Self {
684 Self {
685 escape_html: false,
686 escape_underscores: false,
687 image_placeholder: String::new(),
688 plain_text: true,
689 ..Self::default()
690 }
691 }
692}
693
694impl Default for MarkdownExportOptions {
695 fn default() -> Self {
696 Self {
697 image_mode: ImageMode::Placeholder,
698 artifacts_dir: "artifacts".to_string(),
699 layers: ContentLayers::BODY,
700 traverse_pictures: false,
701 escape_html: true,
702 escape_underscores: true,
703 image_placeholder: "<!-- image -->".to_string(),
704 plain_text: false,
705 }
706 }
707}
708
709/// DocLang-only content for a [`Node::ListItem`] whose DocLang form differs from
710/// its flat Markdown `text` (see [`Node::ListItem::dclx`]). `ordered` picks the
711/// enclosing `<list>` kind, `marker` the `<ldiv><marker>`; content is `runs`
712/// (structured equations/formatting) when non-empty, else `text` re-parsed for
713/// inline markers.
714#[derive(Debug, Clone, PartialEq, Eq, Default)]
715pub struct ListItemDclx {
716 pub ordered: bool,
717 pub marker: Option<String>,
718 pub text: String,
719 pub runs: Vec<InlineRun>,
720}
721
722impl Node {
723 /// The paragraph a [`Node::LabeledText`] renders as outside the JSON:
724 /// its text, wrapped as `[text](uri)` when it carries a hyperlink. Any
725 /// other node is returned unchanged.
726 pub fn labeled_as_paragraph(&self) -> std::borrow::Cow<'_, Node> {
727 match self {
728 Node::LabeledText { text, href, .. } => std::borrow::Cow::Owned(Node::Paragraph {
729 text: match href {
730 Some(uri) => format!("[{text}]({uri})"),
731 None => text.clone(),
732 },
733 }),
734 other => std::borrow::Cow::Borrowed(other),
735 }
736 }
737}
738
739impl InlineRun {
740 /// A run with no active formatting (renders as bare inline text).
741 pub fn is_plain(&self) -> bool {
742 !self.bold
743 && !self.italic
744 && !self.underline
745 && !self.strike
746 && !self.code
747 && !self.formula
748 && self.script == Script::Baseline
749 }
750}
751
752/// Build the [`Node`] for a paragraph of inline content from its structured
753/// `runs` and Markdown text, applying docling's `InlineGroup` boundary:
754///
755/// * a single plain run (or none) → a plain [`Node::Paragraph`] (which the
756/// serializers render as `<text>…</text>`, and a lone hyperlink via `<href>`);
757/// * a single uniformly-formatted run, or two or more runs → a
758/// [`Node::InlineGroup`]. `unwrapped` (the group's docling parent is a
759/// heading, so no enclosing `<text>`) only applies to multi-run groups.
760///
761/// Markdown/JSON render the group's `md_text`, so their output is identical to
762/// emitting a `Paragraph` — the structured runs are DocLang-only.
763pub fn inline_paragraph_node(md_text: String, runs: Vec<InlineRun>, unwrapped: bool) -> Node {
764 let single_plain = runs.len() <= 1 && runs.first().is_none_or(|r| r.is_plain());
765 if single_plain {
766 Node::Paragraph { text: md_text }
767 } else {
768 Node::InlineGroup {
769 unwrapped: unwrapped && runs.len() >= 2,
770 runs,
771 md_text,
772 }
773 }
774}
775
776/// One entry of a [`Node::FieldRegion`]: a marker/key/value triple, any of which
777/// may be absent. Mirrors docling's `field_item` with its `marker` / `field_key`
778/// / `field_value` child texts.
779#[derive(Debug, Clone, PartialEq, Default)]
780pub struct FieldItem {
781 pub marker: Option<String>,
782 pub key: Option<String>,
783 pub value: Option<String>,
784 /// docling's `kind` on the `field_value` item — `read_only` or
785 /// `fillable` (the value is or holds a form control); JSON-only.
786 pub value_kind: Option<String>,
787}
788
789/// One node of a [`Node::KeyValueGraph`] — docling-core's `GraphCell`.
790#[derive(Debug, Clone, PartialEq)]
791pub struct GraphCell {
792 /// docling's `GraphCellLabel` value: `key` or `value` (it also knows
793 /// `unspecified` and `checkbox`).
794 pub label: String,
795 /// The cell's number within its graph, what the links refer to.
796 pub cell_id: usize,
797 pub text: String,
798 /// The text before any cleanup — for an XBRL fact key, the concept's
799 /// qualified name where `text` is its local name.
800 pub orig: String,
801}
802
803/// One edge of a [`Node::KeyValueGraph`] — docling-core's `GraphLink`.
804#[derive(Debug, Clone, PartialEq)]
805pub struct GraphLink {
806 /// docling's `GraphLinkLabel` value: `to_value`, `to_child`, `to_parent`
807 /// or `to_key`.
808 pub label: String,
809 pub source_cell_id: usize,
810 pub target_cell_id: usize,
811}
812
813/// One DocumentPictureClassifier prediction — docling-core's
814/// `PictureClassificationClass` (`class_name` + `confidence`).
815#[derive(Debug, Clone, PartialEq)]
816pub struct PictureClass {
817 /// e.g. `bar_chart`, `logo`, `signature` (the classifier's 26-label set).
818 pub class_name: String,
819 pub confidence: f32,
820}
821
822/// A picture's text annotation — docling-core's `PictureDescriptionData`
823/// (`text` + `provenance`), the one shape upstream uses for every model that
824/// writes prose about a picture. The picture-OCR enrichment (#645) fills it
825/// with the lines the OCR engine read off the image, `provenance` naming the
826/// engine (`ppocr` / `tesseract`) the way a VLM description names its model.
827#[derive(Debug, Clone, PartialEq, Eq)]
828pub struct PictureDescription {
829 pub text: String,
830 pub provenance: String,
831}
832
833impl PictureDescription {
834 /// The provenance of a picture's author-written alt text (#676): the
835 /// `descr` (else `title`) of an OOXML picture's non-visual properties
836 /// — what DOCX, PPTX and XLSX authors type into "Alt Text". JSON writes
837 /// it as `meta.description.created_by`; Markdown renders it under strict
838 /// Markdown or `DoclingDocument::picture_alt_text`, HTML under the latter.
839 pub const ALT_TEXT: &'static str = "alt_text";
840
841 /// An alt-text description, see [`Self::ALT_TEXT`].
842 pub fn alt_text(text: impl Into<String>) -> Self {
843 Self {
844 text: text.into(),
845 provenance: Self::ALT_TEXT.to_string(),
846 }
847 }
848
849 /// Whether this description is a picture's alt text.
850 pub fn is_alt_text(&self) -> bool {
851 self.provenance == Self::ALT_TEXT
852 }
853}
854
855/// An extracted picture's raw encoded bytes plus its mimetype and pixel size —
856/// the docling.rs analogue of docling-core's `ImageRef`.
857#[derive(Debug, Clone, PartialEq)]
858pub struct PictureImage {
859 /// e.g. `image/png`, `image/jpeg`.
860 pub mimetype: String,
861 pub width: u32,
862 pub height: u32,
863 /// The image file bytes, exactly as embedded (PNG/JPEG/…).
864 pub data: Vec<u8>,
865 /// Pixels per inch of the image relative to the page it came from —
866 /// docling-core's `ImageRef.dpi`, which consumers use to map pixels back
867 /// to points. A crop rendered from a PDF page at `s` px/pt is `72·s`
868 /// (docling: `int(72 * images_scale)`, #519); an image embedded in an
869 /// office file has no render scale and keeps docling's `72`
870 /// ([`Self::DEFAULT_DPI`]).
871 pub dpi: u32,
872}
873
874impl PictureImage {
875 /// docling's `ImageRef` default when no render scale applies.
876 pub const DEFAULT_DPI: u32 = 72;
877
878 /// The `dpi` of an image rendered at `scale` pixels per PDF point
879 /// (`72·scale`, rounded — `int()` would floor 143.99… to 143).
880 pub fn dpi_for_scale(scale: f32) -> u32 {
881 (72.0 * scale).round().max(1.0) as u32
882 }
883
884 /// A `data:` URI for the image (`data:<mimetype>;base64,<…>`).
885 pub fn data_uri(&self) -> String {
886 format!(
887 "data:{};base64,{}",
888 self.mimetype,
889 crate::base64::encode(&self.data)
890 )
891 }
892}
893
894/// One table cell as a first-class object (#240) — the Rust counterpart of
895/// docling's `TableCell`: its text, page geometry, grid rectangle and header
896/// roles. Produced by the PDF TableFormer paths from the predicted OTSL
897/// structure; `bbox` is `[l, t, r, b]` in page points with a top-left origin.
898#[derive(Debug, Clone, PartialEq)]
899pub struct TableCell {
900 pub text: String,
901 /// `[l, t, r, b]`, page points, top-left origin; `None` without geometry.
902 pub bbox: Option<[f32; 4]>,
903 /// Anchor grid position (0-based row/column offsets).
904 pub start_row: usize,
905 pub start_col: usize,
906 /// Span extents (≥ 1); the covered grid positions repeat the cell's text
907 /// in [`Table::rows`].
908 pub row_span: usize,
909 pub col_span: usize,
910 /// OTSL `ched` — a column-header cell.
911 pub column_header: bool,
912 /// OTSL `rhed` — a row-header cell.
913 pub row_header: bool,
914 /// OTSL `srow` — a section-row cell.
915 pub row_section: bool,
916}
917
918/// Where a picture's or table's caption text item hangs in the docling-JSON
919/// tree (#390). docling's backends do not agree, and the JSON structure is
920/// the only surface that shows it (Markdown, DocLang and LaTeX place a
921/// caption by its item, whatever its parent): the PDF pipeline parents a
922/// layout caption to the picture or table it belongs to, while every
923/// declarative backend creates the caption with `doc.add_text(label=CAPTION)`
924/// and no parent — the document body — even when the item itself sits in a
925/// group or under a section header (JATS, LaTeX, HTML, Markdown, EPUB,
926/// AsciiDoc all do). The office backends hang a chart's title caption off the
927/// chart's container (the sheet group, the slide, docx's current parent,
928/// docling#4190) — that is [`Node::Chart`]'s own path, not this choice. A
929/// backend that adds a new captioned item picks the variant matching
930/// upstream's `add_text` call for that format; the default is upstream's
931/// default.
932#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
933pub enum CaptionParent {
934 /// `#/body`, listed after the enclosing top-level item — docling's
935 /// `add_text` default, which every declarative backend leaves alone.
936 #[default]
937 Body,
938 /// The item's own container (its `parent`), listed ahead of the item:
939 /// the caption is created first, as docling's office backends do.
940 Container,
941 /// The item's own container, listed *after* the item: docling's HTML
942 /// backend adds a `<figure>`-wrapped table, then its `<figcaption>` under
943 /// `self.parents[self.level]` (docling#4050).
944 ContainerAfter,
945 /// The item itself — the caption is the picture's or table's first
946 /// child, as docling's PDF pipeline attaches a layout caption.
947 Item,
948}
949
950/// A simple row-major table. By default `rows[0]` is the header row; a
951/// [`TableStructure`] overlay overrides that and adds column spans.
952#[derive(Debug, Clone, PartialEq, Default)]
953pub struct Table {
954 pub rows: Vec<Vec<String>>,
955 /// Optional layout provenance: the four DocLang `<location>` values
956 /// (`x0,y0,x1,y1`, each already normalized to the 0–511 resolution) emitted
957 /// before the table's cells. Set only by backends with real geometry (e.g.
958 /// the spreadsheet backend, whose cell grid yields a bounding box); left
959 /// `None` by declarative backends, which have no coordinates.
960 pub location: Option<[u16; 4]>,
961 /// Optional OTSL structure overlay for backends that parse real table
962 /// geometry (USPTO CALS): explicit header-row count and horizontal-span
963 /// continuations. `None` → the default (row 0 is the header, no spans).
964 /// `rows` still carries the full text grid (span text replicated) for
965 /// Markdown/JSON; DocLang uses this overlay to emit `<ched/>`/`<lcel/>`.
966 pub structure: Option<TableStructure>,
967 /// Optional per-cell block content, parallel to `rows`. A *rich* cell (an
968 /// ODF cell holding a list, several paragraphs, or a nested table) carries
969 /// its DocLang blocks here; the DocLang serializer emits them after the
970 /// cell token instead of the flat `rows` text. Markdown/JSON ignore this
971 /// and render `rows`, so their output is unchanged. `None` (or an empty
972 /// `Vec` for a given cell) → the flat text is used everywhere.
973 pub cell_blocks: Option<Vec<Vec<Vec<Node>>>>,
974 /// Optional caption (docling's `TableItem.captions`): the JATS
975 /// `<table-wrap>` label+caption, an HTML `<caption>`, etc. Markdown renders
976 /// it as a text line *before* the grid; JSON emits a caption text item the
977 /// table references; DocLang emits a `<caption>` as the table's first child.
978 /// `None` → the table has no caption.
979 pub caption: Option<String>,
980 /// Where the caption item hangs in the JSON tree (#390); see
981 /// [`CaptionParent`]. Only the JSON export reads it.
982 pub caption_parent: CaptionParent,
983 /// The caption's own box on the table's page (0–511 grid) — the PDF
984 /// pipeline's caption layout region, written as the caption item's
985 /// `prov` (#609); see [`Node::Picture`]'s field of the same name.
986 pub caption_location: Option<[u16; 4]>,
987 /// Optional per-cell bounding boxes, same shape as [`Self::rows`]: `[l, t,
988 /// r, b]` in page points with a **top-left** origin (the PDF pipeline's
989 /// native space). Set by the ML pipeline's TableFormer paths — a spanned
990 /// cell repeats its anchor's box across the covered grid positions — and
991 /// First-class cells (#240): the authoritative per-cell records —
992 /// text, page geometry, spans and header roles — when the backend
993 /// produces them (the PDF TableFormer paths do; declarative backends
994 /// leave `None`). [`Self::rows`] stays the dense text grid every
995 /// serializer renders (a spanning cell's text is replicated across its
996 /// covered positions there); JSON serializes these cells verbatim when
997 /// present, and the DocLang structure overlay is derived from them.
998 pub cells: Option<Vec<TableCell>>,
999}
1000
1001impl Table {
1002 /// A cell's text at a grid position, `None` outside the grid.
1003 pub fn cell_text(&self, row: usize, col: usize) -> Option<&str> {
1004 self.rows.get(row)?.get(col).map(String::as_str)
1005 }
1006
1007 /// Replace the text at a grid position; `false` (and no change) outside
1008 /// the grid. When a first-class cell covers the position, the whole
1009 /// cell is updated: its record text and every grid position its span
1010 /// covers, so the repair shows once in Markdown, not once per covered
1011 /// column.
1012 pub fn set_cell_text(&mut self, row: usize, col: usize, text: impl Into<String>) -> bool {
1013 if self.rows.get(row).and_then(|r| r.get(col)).is_none() {
1014 return false;
1015 }
1016 let text = text.into();
1017 let covering = self.cells.as_mut().and_then(|cells| {
1018 cells.iter_mut().find(|c| {
1019 (c.start_row..c.start_row + c.row_span).contains(&row)
1020 && (c.start_col..c.start_col + c.col_span).contains(&col)
1021 })
1022 });
1023 if let Some(cell) = covering {
1024 cell.text = text.clone();
1025 let (r0, r1) = (cell.start_row, cell.start_row + cell.row_span);
1026 let (c0, c1) = (cell.start_col, cell.start_col + cell.col_span);
1027 for r in self.rows.iter_mut().take(r1).skip(r0) {
1028 for slot in r.iter_mut().take(c1).skip(c0) {
1029 *slot = text.clone();
1030 }
1031 }
1032 } else {
1033 self.rows[row][col] = text;
1034 }
1035 true
1036 }
1037
1038 /// Derive first-class cells (#240) from the dense grid plus the
1039 /// [`TableStructure`] overlay — how declarative tables (DOCX/XLSX merged
1040 /// regions, HTML `th`/spans, ODF covered cells, USPTO CALS) get real
1041 /// `TableCell` records without page geometry. Anchors are the positions
1042 /// not marked as span continuations; extents scan the continuation grids
1043 /// right/down (matching the DocLang `lcel`/`ucel` reading). Header roles
1044 /// come from the per-cell `col_header`/`row_header` grids when present,
1045 /// else the `header_row` band, else docling's declarative default (row 0
1046 /// is the header). Without any overlay every position is a 1×1 cell.
1047 pub fn derive_cells(&self) -> Vec<TableCell> {
1048 let s = self.structure.as_ref();
1049 let flag = |grid: Option<&Vec<Vec<bool>>>, r: usize, c: usize| {
1050 grid.and_then(|g| g.get(r))
1051 .and_then(|row| row.get(c))
1052 .copied()
1053 .unwrap_or(false)
1054 };
1055 let col_cont = |r: usize, c: usize| flag(s.map(|s| &s.col_continuation), r, c);
1056 let row_cont = |r: usize, c: usize| flag(s.map(|s| &s.row_continuation), r, c);
1057 let is_col_header = |r: usize, c: usize| match s {
1058 Some(st) if !st.col_header.is_empty() => flag(Some(&st.col_header), r, c),
1059 Some(st) if !st.header_row.is_empty() => st.header_row.get(r).copied().unwrap_or(false),
1060 _ => r == 0,
1061 };
1062 let mut cells = Vec::new();
1063 for (r, row) in self.rows.iter().enumerate() {
1064 for (c, text) in row.iter().enumerate() {
1065 if col_cont(r, c) || row_cont(r, c) {
1066 continue; // covered by a span anchor
1067 }
1068 let mut col_span = 1;
1069 while c + col_span < row.len() && col_cont(r, c + col_span) {
1070 col_span += 1;
1071 }
1072 let mut row_span = 1;
1073 while r + row_span < self.rows.len() && row_cont(r + row_span, c) {
1074 row_span += 1;
1075 }
1076 cells.push(TableCell {
1077 text: text.clone(),
1078 bbox: None,
1079 start_row: r,
1080 start_col: c,
1081 row_span,
1082 col_span,
1083 column_header: is_col_header(r, c),
1084 row_header: flag(s.map(|s| &s.row_header), r, c),
1085 row_section: false,
1086 });
1087 }
1088 }
1089 cells
1090 }
1091
1092 /// The number of leading grid rows that form the column header block —
1093 /// docling-core's `TableData._count_column_header_rows` (docling-core#767,
1094 /// 2.102, #778), shared by the Markdown serializer
1095 /// ([`Self::header_row_count`]) and the chunker's dataframe view, which
1096 /// must agree on where the header ends. Uses the first-class
1097 /// [`Self::cells`] when present (the PDF pipeline's TableFormer flags),
1098 /// else the cells derived from the structure overlay.
1099 ///
1100 /// - A row counts only when a `column_header` cell *starts* on it
1101 /// (docling-core#723): a header spanning several rows is replicated
1102 /// into each row it covers, and counting those would pull the data rows
1103 /// beneath it into the header block.
1104 /// - A row also stops the block when it *carries body text* (#604,
1105 /// docling-core#766): a cell starting on it that is not a column
1106 /// header, has non-blank text and does not start in the table's first
1107 /// column, which holds row labels left unmarked even on header rows. A
1108 /// scanned form flags its first-column labels `column_header` on every
1109 /// row; without the check each such row folded its values into the
1110 /// header.
1111 /// - Row 0 is exempt from that check — model-predicted header rows are
1112 /// often only partly flagged — unless a later row flags a cell starting
1113 /// in the first column: that marks a column of row headers, not a
1114 /// partly flagged header row.
1115 ///
1116 /// No fallback: a table without flags has no header rows here.
1117 pub fn column_header_row_count(&self) -> usize {
1118 if self.rows.is_empty() {
1119 return 0;
1120 }
1121 let derived;
1122 let cells: &[TableCell] = match &self.cells {
1123 Some(c) if !c.is_empty() => c,
1124 _ => {
1125 derived = self.derive_cells();
1126 &derived
1127 }
1128 };
1129 let num_rows = self.rows.len();
1130 let first_col = cells.iter().map(|c| c.start_col).min().unwrap_or(0);
1131 let leading_col_flagged_below = cells.iter().any(|c| {
1132 c.column_header && c.start_col == first_col && (1..num_rows).contains(&c.start_row)
1133 });
1134 let is_header_row = |r: usize| {
1135 let check_body = r > 0 || leading_col_flagged_below;
1136 let mut flagged = false;
1137 for c in cells.iter().filter(|c| c.start_row == r) {
1138 if c.column_header {
1139 flagged = true;
1140 } else if check_body && c.start_col != first_col && !c.text.trim().is_empty() {
1141 return false;
1142 }
1143 }
1144 flagged
1145 };
1146 (0..num_rows).take_while(|&r| is_header_row(r)).count()
1147 }
1148
1149 /// The number of leading grid rows the Markdown serializer renders as the
1150 /// header — docling-core's `_count_header_rows`:
1151 /// [`Self::column_header_row_count`], plus upstream's row-0 fallback for
1152 /// GFM, which needs a header row: `1` when no flag sits on any grid row
1153 /// below the first (a spanning header cell counts on every row it
1154 /// covers), so tables from backends that never set the flag keep row 0
1155 /// as the header. When flags exist but none makes a header row, the
1156 /// count is `0` and every row stays in the body under an empty header.
1157 pub fn header_row_count(&self) -> usize {
1158 let count = self.column_header_row_count();
1159 if count > 0 || self.rows.is_empty() {
1160 return count;
1161 }
1162 let derived;
1163 let cells: &[TableCell] = match &self.cells {
1164 Some(c) if !c.is_empty() => c,
1165 _ => {
1166 derived = self.derive_cells();
1167 &derived
1168 }
1169 };
1170 if cells
1171 .iter()
1172 .any(|c| c.column_header && c.start_row + c.row_span.max(1) > 1)
1173 {
1174 0
1175 } else {
1176 1
1177 }
1178 }
1179
1180 /// For every grid position, the position of the cell that covers it — its
1181 /// anchor (top-left start): itself for an unmerged position, the merge's
1182 /// start for one a spanning cell covers. Uses the first-class
1183 /// [`Self::cells`] when present, else the cells derived from the
1184 /// structure overlay. A rich cell's blocks ([`Self::cell_blocks`]) live on
1185 /// its anchor only, so a serializer that repeats a merged cell in every
1186 /// position it covers (docling-core#857) reads them through this.
1187 pub fn span_anchors(&self) -> Vec<Vec<(usize, usize)>> {
1188 let num_cols = self.rows.iter().map(Vec::len).max().unwrap_or(0);
1189 let mut anchors: Vec<Vec<(usize, usize)>> = (0..self.rows.len())
1190 .map(|r| (0..num_cols).map(|c| (r, c)).collect())
1191 .collect();
1192 let derived;
1193 let cells: &[TableCell] = match &self.cells {
1194 Some(c) if !c.is_empty() => c,
1195 _ => {
1196 derived = self.derive_cells();
1197 &derived
1198 }
1199 };
1200 for cell in cells {
1201 let rows = cell.start_row..cell.start_row + cell.row_span.max(1);
1202 for row in anchors.iter_mut().take(rows.end).skip(rows.start) {
1203 let cols = cell.start_col..cell.start_col + cell.col_span.max(1);
1204 for pos in row.iter_mut().take(cols.end).skip(cols.start) {
1205 *pos = (cell.start_row, cell.start_col);
1206 }
1207 }
1208 }
1209 anchors
1210 }
1211
1212 /// The first-class cell covering a grid position, if any.
1213 pub fn cell_at(&self, row: usize, col: usize) -> Option<&TableCell> {
1214 self.cells.as_ref()?.iter().find(|c| {
1215 (c.start_row..c.start_row + c.row_span).contains(&row)
1216 && (c.start_col..c.start_col + c.col_span).contains(&col)
1217 })
1218 }
1219
1220 /// A cell's bounding box (`[l, t, r, b]`, page points, top-left origin);
1221 /// `None` when no cell with geometry covers the position.
1222 pub fn cell_bbox(&self, row: usize, col: usize) -> Option<[f32; 4]> {
1223 self.cell_at(row, col)?.bbox
1224 }
1225
1226 /// Set (or replace) the bounding box of the cell covering a grid
1227 /// position; `false` outside the text grid. A table without first-class
1228 /// cells materializes them first (one 1×1 cell per grid position, texts
1229 /// from the grid), so declarative tables can be annotated too.
1230 pub fn set_cell_bbox(&mut self, row: usize, col: usize, bbox: [f32; 4]) -> bool {
1231 if self.rows.get(row).and_then(|r| r.get(col)).is_none() {
1232 return false;
1233 }
1234 let rows = &self.rows;
1235 let cells = self.cells.get_or_insert_with(|| {
1236 rows.iter()
1237 .enumerate()
1238 .flat_map(|(r, cols)| {
1239 cols.iter().enumerate().map(move |(c, text)| TableCell {
1240 text: text.clone(),
1241 bbox: None,
1242 start_row: r,
1243 start_col: c,
1244 row_span: 1,
1245 col_span: 1,
1246 column_header: false,
1247 row_header: false,
1248 row_section: false,
1249 })
1250 })
1251 .collect()
1252 });
1253 match cells.iter_mut().find(|c| {
1254 (c.start_row..c.start_row + c.row_span).contains(&row)
1255 && (c.start_col..c.start_col + c.col_span).contains(&col)
1256 }) {
1257 Some(cell) => {
1258 cell.bbox = Some(bbox);
1259 true
1260 }
1261 None => {
1262 cells.push(TableCell {
1263 text: self.rows[row][col].clone(),
1264 bbox: Some(bbox),
1265 start_row: row,
1266 start_col: col,
1267 row_span: 1,
1268 col_span: 1,
1269 column_header: false,
1270 row_header: false,
1271 row_section: false,
1272 });
1273 true
1274 }
1275 }
1276 }
1277
1278 /// The anchor position of the cell whose box overlaps `bbox` best
1279 /// (largest intersection-over-union), ties resolved in cell order.
1280 /// `None` when nothing overlaps or the table carries no geometry. This
1281 /// is the lookup half of the repair workflow: find the cell an external
1282 /// OCR box refers to, then [`Self::set_cell_text`] it.
1283 pub fn find_cell_by_bbox(&self, bbox: [f32; 4]) -> Option<(usize, usize)> {
1284 let area = |b: &[f32; 4]| ((b[2] - b[0]) * (b[3] - b[1])).max(0.0);
1285 let mut best: Option<(f32, (usize, usize))> = None;
1286 for cell in self.cells.as_deref()?.iter() {
1287 let Some(cb) = cell.bbox else { continue };
1288 let iw = (bbox[2].min(cb[2]) - bbox[0].max(cb[0])).max(0.0);
1289 let ih = (bbox[3].min(cb[3]) - bbox[1].max(cb[1])).max(0.0);
1290 let inter = iw * ih;
1291 if inter <= 0.0 {
1292 continue;
1293 }
1294 let iou = inter / (area(&bbox) + area(&cb) - inter).max(f32::EPSILON);
1295 if best.is_none_or(|(b, _)| iou > b) {
1296 best = Some((iou, (cell.start_row, cell.start_col)));
1297 }
1298 }
1299 best.map(|(_, pos)| pos)
1300 }
1301
1302 /// Locate the cell overlapping `bbox` best and replace its text — the
1303 /// one-call form of the OCR-repair loop. Returns the updated anchor.
1304 pub fn update_cell_by_bbox(
1305 &mut self,
1306 bbox: [f32; 4],
1307 text: impl Into<String>,
1308 ) -> Option<(usize, usize)> {
1309 let (row, col) = self.find_cell_by_bbox(bbox)?;
1310 self.set_cell_text(row, col, text);
1311 Some((row, col))
1312 }
1313}
1314
1315/// OTSL structure overlay for a [`Table`], parallel to [`Table::rows`].
1316#[derive(Debug, Clone, PartialEq, Default)]
1317pub struct TableStructure {
1318 /// Per-row: `true` if the row's non-empty cells are column headers
1319 /// (emitted as `<ched/>` rather than `<fcel/>`).
1320 pub header_row: Vec<bool>,
1321 /// Same shape as [`Table::rows`]; `true` where a cell continues a
1322 /// horizontal span from its left neighbour (emitted as `<lcel/>`).
1323 pub col_continuation: Vec<Vec<bool>>,
1324 /// Same shape as [`Table::rows`]; `true` where a cell continues a
1325 /// vertical span from the cell above (emitted as `<ucel/>`). Empty or all
1326 /// `false` when the backend has no vertical spans (e.g. USPTO CALS).
1327 pub row_continuation: Vec<Vec<bool>>,
1328 /// Same shape as [`Table::rows`]; `true` where a non-empty cell is a row
1329 /// header (emitted as `<rhed/>`) — a chart's category column. Empty when
1330 /// the table has no row headers.
1331 pub row_header: Vec<Vec<bool>>,
1332 /// Same shape as [`Table::rows`]; `true` where a cell is a *column header*
1333 /// cell (an HTML `<th>`). When non-empty this per-cell grid supersedes the
1334 /// per-row [`Self::header_row`] for `<ched/>` emission, matching docling's
1335 /// cell-level `column_header` flag; the chunker derives its header-row
1336 /// count from it.
1337 pub col_header: Vec<Vec<bool>>,
1338}
1339
1340impl DoclingDocument {
1341 /// Create an empty document with the given name.
1342 pub fn new(name: impl Into<String>) -> Self {
1343 Self {
1344 name: name.into(),
1345 nodes: Vec::new(),
1346 strict_markdown: false,
1347 compact_tables: false,
1348 picture_alt_text: false,
1349 metadata: Default::default(),
1350 metadata_output: Default::default(),
1351 page_break_placeholder: None,
1352 links: Vec::new(),
1353 confidence: None,
1354 tree: None,
1355 page_images: std::collections::BTreeMap::new(),
1356 }
1357 }
1358
1359 /// Append a node.
1360 /// The document's top-level tables in reading order — the read half of
1361 /// the post-extraction table API (#238). [`Node::Located`] wrappers (the
1362 /// PDF pipeline attaches layout provenance that way) are looked through;
1363 /// tables nested inside rich table cells (`Table::cell_blocks`) are not
1364 /// traversed.
1365 pub fn tables(&self) -> impl Iterator<Item = &Table> {
1366 fn unwrap_table(n: &Node) -> Option<&Table> {
1367 match n {
1368 Node::Table(t) => Some(t),
1369 Node::Located { inner, .. }
1370 | Node::Prov { inner, .. }
1371 | Node::Track { inner, .. } => unwrap_table(inner),
1372 _ => None,
1373 }
1374 }
1375 self.nodes.iter().filter_map(unwrap_table)
1376 }
1377
1378 /// Mutable access to the document's top-level tables, for repair
1379 /// workflows (#238): locate a cell via [`Table::find_cell_by_bbox`], fix
1380 /// its text with [`Table::set_cell_text`], then re-export — every
1381 /// serializer reads the same grid.
1382 pub fn tables_mut(&mut self) -> impl Iterator<Item = &mut Table> {
1383 fn unwrap_table(n: &mut Node) -> Option<&mut Table> {
1384 match n {
1385 Node::Table(t) => Some(t),
1386 Node::Located { inner, .. }
1387 | Node::Prov { inner, .. }
1388 | Node::Track { inner, .. } => unwrap_table(inner),
1389 _ => None,
1390 }
1391 }
1392 self.nodes.iter_mut().filter_map(unwrap_table)
1393 }
1394
1395 pub fn push(&mut self, node: Node) {
1396 self.nodes.push(node);
1397 }
1398
1399 /// Visit every [`Node::Picture`] in the flat node stream, wherever it
1400 /// nests — group children, table cell blocks, a picture's own
1401 /// children, the located/prov/track/comment/furniture wrappers — so an
1402 /// enrichment that reads the embedded images (picture OCR, #645) reaches
1403 /// each one. The callback gets the picture node itself.
1404 pub fn for_each_picture_mut(&mut self, f: &mut dyn FnMut(&mut Node)) {
1405 fn walk(nodes: &mut [Node], f: &mut dyn FnMut(&mut Node)) {
1406 for node in nodes {
1407 match node {
1408 Node::Picture { .. } => f(node),
1409 Node::Group { children, .. } | Node::PictureChildren(children) => {
1410 walk(children, f)
1411 }
1412 Node::Located { inner, .. }
1413 | Node::Prov { inner, .. }
1414 | Node::Track { inner, .. }
1415 | Node::Furniture { inner, .. }
1416 | Node::Commented { inner, .. }
1417 | Node::DoclangOnly(inner) => walk(std::slice::from_mut(inner), f),
1418 Node::Table(t) => {
1419 if let Some(blocks) = t.cell_blocks.as_mut() {
1420 for row in blocks {
1421 for cell in row {
1422 walk(cell, f);
1423 }
1424 }
1425 }
1426 }
1427 _ => {}
1428 }
1429 }
1430 }
1431 walk(&mut self.nodes, f);
1432 }
1433
1434 /// Convenience: append a heading.
1435 pub fn add_heading(&mut self, level: u8, text: impl Into<String>) {
1436 self.push(Node::Heading {
1437 level,
1438 text: text.into(),
1439 });
1440 }
1441
1442 /// Convenience: append a paragraph.
1443 pub fn add_paragraph(&mut self, text: impl Into<String>) {
1444 self.push(Node::Paragraph { text: text.into() });
1445 }
1446
1447 /// Serialize the document to Markdown.
1448 ///
1449 /// The Rust equivalent of docling-core's
1450 /// `DoclingDocument.export_to_markdown()`. Uses [`Self::strict_markdown`] to
1451 /// pick between docling-legacy output (default) and the cleaner, more
1452 /// conformant variant.
1453 pub fn export_to_markdown(&self) -> String {
1454 to_markdown(self, self.strict_markdown)
1455 }
1456
1457 /// Serialize to Markdown, explicitly choosing the mode regardless of
1458 /// [`Self::strict_markdown`]. `strict = true` produces cleaner, more
1459 /// conformant Markdown (code-fence languages preserved, no inline-run
1460 /// spacing artifacts); `strict = false` reproduces docling's legacy output.
1461 pub fn export_to_markdown_with(&self, strict: bool) -> String {
1462 to_markdown(self, strict)
1463 }
1464
1465 /// Markdown for this document as the *content of a rich table cell*
1466 /// (docling-core's `in_table_cell` serialization, docling-core#540):
1467 /// headings render as plain text since Markdown tables can't hold them.
1468 /// Backends build a sub-document per rich cell and flatten this into the
1469 /// cell text; no trailing newline.
1470 pub fn export_to_table_cell_markdown(&self) -> String {
1471 crate::markdown::to_markdown_table_cell(self, self.strict_markdown)
1472 }
1473
1474 /// Serialize to docling-core's native JSON wire format (`DoclingDocument`
1475 /// schema), pretty-printed — the Rust equivalent of
1476 /// `DoclingDocument.export_to_dict()` / `save_as_json()`. The output loads
1477 /// back into Python docling-core and round-trips to the same Markdown.
1478 pub fn export_to_json(&self) -> String {
1479 let mut out = Vec::new();
1480 self.write_json_pretty(&mut out)
1481 .expect("DoclingDocument JSON is always serializable");
1482 String::from_utf8(out).expect("serde_json writes UTF-8")
1483 }
1484
1485 /// The same JSON wire format as [`Self::export_to_json`], as a
1486 /// `serde_json::Value` — for callers that append response-level extras
1487 /// (docling-serve adds the confidence report, #183) before serializing.
1488 ///
1489 /// The `Value` is large — ~2.7 KB per text item — so on a long document
1490 /// prefer [`Self::write_json`], which writes the same JSON without it.
1491 pub fn export_to_json_value(&self) -> serde_json::Value {
1492 crate::json::to_json(self)
1493 }
1494
1495 /// Write the JSON of [`Self::export_to_json_value`] to `writer`, compact
1496 /// — byte for byte `serde_json::to_writer(writer, &doc.export_to_json_value())`
1497 /// — without building the `Value`: the export holds its text items in a
1498 /// compact form and serializes them straight to the writer. Wrap a file
1499 /// or socket in a `BufWriter`.
1500 pub fn write_json<W: std::io::Write>(&self, writer: W) -> std::io::Result<()> {
1501 crate::json::write_json(self, writer, false).map_err(std::io::Error::from)
1502 }
1503
1504 /// [`Self::write_json`], indented as [`Self::export_to_json`] is.
1505 pub fn write_json_pretty<W: std::io::Write>(&self, writer: W) -> std::io::Result<()> {
1506 crate::json::write_json(self, writer, true).map_err(std::io::Error::from)
1507 }
1508
1509 /// Serialize to a complete LaTeX document — the Rust counterpart of
1510 /// docling-core's `LaTeXDocSerializer` with default parameters (docling
1511 /// 2.124's `--to latex`, #317). No trailing newline, like the upstream
1512 /// CLI's `<stem>.tex`.
1513 pub fn export_to_latex(&self) -> String {
1514 crate::latex::to_latex(self)
1515 }
1516
1517 /// Serialize to Pandoc's AST as JSON (`pandoc -f json`, #515) with the
1518 /// default options: pictures as captioned figures without image data,
1519 /// body layer only, the [`PANDOC_API_VERSION`](crate::pandoc::PANDOC_API_VERSION)
1520 /// API. One line, no trailing newline. See [`crate::pandoc`].
1521 pub fn export_to_pandoc_json(&self) -> String {
1522 crate::pandoc::to_pandoc(self, &crate::pandoc::PandocExportOptions::default())
1523 .expect("the default Pandoc API version is always supported")
1524 .0
1525 }
1526
1527 /// Pandoc JSON per `options` (image mode, artifacts directory, content
1528 /// layers, required API version). Returns the JSON and, for
1529 /// [`ImageMode::Referenced`], the `(path, bytes)` image files; an
1530 /// unsupported `api_version` is an error.
1531 pub fn export_to_pandoc_json_with(
1532 &self,
1533 options: &crate::pandoc::PandocExportOptions,
1534 ) -> Result<crate::pandoc::PandocOutput, crate::pandoc::PandocError> {
1535 crate::pandoc::to_pandoc(self, options)
1536 }
1537
1538 /// Serialize to DocLang XML (`<doclang version="0.7">…`), the markup that
1539 /// lives inside a `.dclx` archive — the Rust counterpart of docling-core's
1540 /// `export_to_doclang()` with default parameters. No trailing newline; the
1541 /// archive writer appends exactly one.
1542 pub fn export_to_doclang(&self) -> String {
1543 crate::doclang::export_to_doclang(&self.nodes)
1544 }
1545
1546 /// [`Self::export_to_doclang`] plus the picture assets its
1547 /// `<src uri="assets/image_….png"/>` references name, as `(path, bytes)`
1548 /// in document order — the parts docling's `save_as_doclang_archive`
1549 /// stores next to `document.xml`. PNG and JPEG pictures come back as PNG
1550 /// (a JPEG re-encoded from its libjpeg-decoded pixels); other encodings
1551 /// keep their own bytes for the archive writer to convert.
1552 pub fn export_to_doclang_with_assets(&self) -> (String, Vec<(String, Vec<u8>)>) {
1553 crate::doclang::export_to_doclang_with_assets(&self.nodes)
1554 }
1555
1556 /// Serialize to Markdown with an explicit picture [`ImageMode`] (mirrors
1557 /// docling's `image_mode`). Returns the Markdown and, for
1558 /// [`ImageMode::Referenced`], the `(relative-path, bytes)` of each image the
1559 /// caller should write next to the Markdown file. `artifacts_dir` is the
1560 /// directory name used in referenced links.
1561 pub fn export_to_markdown_with_images(
1562 &self,
1563 image_mode: ImageMode,
1564 artifacts_dir: &str,
1565 ) -> (String, Vec<(String, Vec<u8>)>) {
1566 to_markdown_images(self, self.strict_markdown, image_mode, artifacts_dir)
1567 }
1568
1569 /// Markdown per `options` (#599) — docling-core's
1570 /// `export_to_markdown(included_content_layers=…, image_mode=…,
1571 /// image_placeholder=…, escape_html=…, escape_underscores=…,
1572 /// traverse_pictures=…)`: the content layers rendered, whether a
1573 /// picture's nested text items print, HTML and underscore escaping, the
1574 /// image placeholder, and the image mode with its referenced-image
1575 /// directory. [`Self::strict_markdown`] still picks the Markdown flavour.
1576 /// Returns the Markdown and, for [`ImageMode::Referenced`], the
1577 /// `(path, bytes)` artifacts. With [`MarkdownExportOptions::default`]
1578 /// the Markdown is [`Self::export_to_markdown`]'s byte for byte.
1579 pub fn export_to_markdown_with_options(
1580 &self,
1581 options: &MarkdownExportOptions,
1582 ) -> (String, Vec<(String, Vec<u8>)>) {
1583 crate::markdown::to_markdown_with_options(self, self.strict_markdown, options)
1584 }
1585
1586 /// WebVTT (#614) — what docling's `--to vtt` writes
1587 /// (`DoclingDocument.save_as_vtt`): a cue per timed text item — a WebVTT
1588 /// input's cues, an audio/video transcript's segments — hours always
1589 /// written, the `</v>` of a lone voice span omitted. A document without
1590 /// timed text is the bare `WEBVTT` header. No trailing newline.
1591 pub fn export_to_vtt(&self) -> String {
1592 crate::vtt::to_vtt(self, &crate::vtt::VttExportOptions::default())
1593 }
1594
1595 /// [`Self::export_to_vtt`] with docling-core's `WebVTTParams`
1596 /// (`omit_hours_if_zero`, `omit_voice_end`).
1597 pub fn export_to_vtt_with_options(&self, options: &crate::vtt::VttExportOptions) -> String {
1598 crate::vtt::to_vtt(self, options)
1599 }
1600
1601 /// Plain text — docling-core's `DoclingDocument.export_to_text()` with
1602 /// its defaults (#613, docling's `--to text` / `<stem>.txt`): the
1603 /// Markdown export without decoration ([`MarkdownExportOptions::plain_text`]).
1604 /// Lists keep their bullets and numbers, tables their `|` grid. No
1605 /// trailing newline: upstream's `serialize().text`, which its CLI
1606 /// writes verbatim to `<stem>.txt`.
1607 pub fn export_to_text(&self) -> String {
1608 let (mut text, _) = crate::markdown::to_markdown_with_options(
1609 self,
1610 self.strict_markdown,
1611 &MarkdownExportOptions::plain_text(),
1612 );
1613 if text.ends_with('\n') {
1614 text.pop();
1615 }
1616 text
1617 }
1618
1619 /// A complete HTML document — docling-core's `HTMLDocSerializer` with its
1620 /// defaults (#492): pictures stay out (`ImageRefMode.PLACEHOLDER`, only
1621 /// their captions and meta render). See [`export_to_html_with_images`]
1622 /// for the embedded / referenced modes and [`crate::html`]'s module docs
1623 /// for what is reproduced.
1624 ///
1625 /// [`export_to_html_with_images`]: Self::export_to_html_with_images
1626 pub fn export_to_html(&self) -> String {
1627 crate::html::to_html(self, &HtmlExportOptions::default()).0
1628 }
1629
1630 /// HTML with pictures per `image_mode`: `data:` URIs when embedded, and
1631 /// when referenced `<img src>` paths under `artifacts_dir` whose bytes come
1632 /// back as `(path, bytes)` for the caller to write — the Markdown export's
1633 /// contract and file names.
1634 pub fn export_to_html_with_images(
1635 &self,
1636 image_mode: ImageMode,
1637 artifacts_dir: &str,
1638 ) -> (String, Vec<(String, Vec<u8>)>) {
1639 crate::html::to_html(
1640 self,
1641 &HtmlExportOptions {
1642 image_mode,
1643 artifacts_dir: artifacts_dir.to_string(),
1644 ..HtmlExportOptions::default()
1645 },
1646 )
1647 }
1648
1649 /// HTML rendering the content `layers` — docling-core's
1650 /// `export_to_html(included_content_layers=…)` (#499). The default export
1651 /// is body only; `ContentLayers::BODY.with(ContentLayer::Furniture)` adds
1652 /// page headers/footers, `.with(ContentLayer::Notes)` reviewer comments,
1653 /// [`ContentLayers::ALL`] is Python's `set(ContentLayer)`. An item on a
1654 /// layer outside the set is skipped while its children are still walked,
1655 /// and the items that do render go through the same serializers as the
1656 /// body (a page header is a `<p>`, a comment a `<p>`, a header table a
1657 /// `<table>`), exactly as upstream's `HTMLParams.layers` behaves. Pictures
1658 /// stay placeholders; see [`export_to_html_with`] for the full option set.
1659 ///
1660 /// [`export_to_html_with`]: Self::export_to_html_with
1661 pub fn export_to_html_with_layers(&self, layers: ContentLayers) -> String {
1662 crate::html::to_html(
1663 self,
1664 &HtmlExportOptions {
1665 layers,
1666 ..HtmlExportOptions::default()
1667 },
1668 )
1669 .0
1670 }
1671
1672 /// HTML per `options` — image mode, referenced-image directory and content
1673 /// layers in one call; the other `export_to_html*` methods are
1674 /// shorthands for it. Returns the HTML and, for
1675 /// [`ImageMode::Referenced`], the `(path, bytes)` artifacts.
1676 pub fn export_to_html_with(
1677 &self,
1678 options: &HtmlExportOptions,
1679 ) -> (String, Vec<(String, Vec<u8>)>) {
1680 crate::html::to_html(self, options)
1681 }
1682}
1683
1684#[cfg(test)]
1685mod table_api_tests {
1686 use super::*;
1687
1688 fn cell(
1689 text: &str,
1690 bbox: [f32; 4],
1691 (start_row, start_col): (usize, usize),
1692 (row_span, col_span): (usize, usize),
1693 ) -> TableCell {
1694 TableCell {
1695 text: text.into(),
1696 bbox: Some(bbox),
1697 start_row,
1698 start_col,
1699 row_span,
1700 col_span,
1701 column_header: false,
1702 row_header: false,
1703 row_section: false,
1704 }
1705 }
1706
1707 fn table() -> Table {
1708 Table {
1709 rows: vec![
1710 vec!["Year".into(), "Ducks".into()],
1711 vec!["2019".into(), "120".into()],
1712 ],
1713 cells: Some(vec![
1714 cell("Year", [0.0, 0.0, 50.0, 10.0], (0, 0), (1, 1)),
1715 cell("Ducks", [50.0, 0.0, 100.0, 10.0], (0, 1), (1, 1)),
1716 cell("2019", [0.0, 10.0, 50.0, 20.0], (1, 0), (1, 1)),
1717 cell("120", [50.0, 10.0, 100.0, 20.0], (1, 1), (1, 1)),
1718 ]),
1719 ..Default::default()
1720 }
1721 }
1722
1723 /// Declarative tables derive first-class cells from the structure
1724 /// overlay: continuation grids become span extents, `col_header` (or the
1725 /// row-0 fallback) becomes the header role — the XLSX/DOCX/HTML merge
1726 /// path into real `TableCell`s (#240).
1727 #[test]
1728 fn derive_cells_reads_spans_and_headers_from_structure() {
1729 let t = Table {
1730 rows: vec![
1731 vec!["Wide".into(), "Wide".into(), "C".into()],
1732 vec!["a".into(), "b".into(), "c".into()],
1733 ],
1734 structure: Some(TableStructure {
1735 header_row: vec![true, false],
1736 col_continuation: vec![vec![false, true, false], vec![false; 3]],
1737 row_continuation: vec![vec![false; 3], vec![false; 3]],
1738 row_header: Vec::new(),
1739 col_header: Vec::new(),
1740 }),
1741 ..Default::default()
1742 };
1743 let cells = t.derive_cells();
1744 assert_eq!(cells.len(), 5, "two anchors in row 0, three in row 1");
1745 let wide = &cells[0];
1746 assert_eq!((wide.col_span, wide.row_span), (2, 1));
1747 assert!(wide.column_header, "header_row band");
1748 assert!(cells.iter().skip(2).all(|c| !c.column_header));
1749
1750 // Without any overlay: every position 1x1, row 0 the header
1751 // (docling's declarative default — the old JSON synthesis).
1752 let plain = Table {
1753 rows: vec![vec!["h".into()], vec!["x".into()]],
1754 ..Default::default()
1755 };
1756 let cells = plain.derive_cells();
1757 assert_eq!(cells.len(), 2);
1758 assert!(cells[0].column_header && !cells[1].column_header);
1759 }
1760
1761 /// A spanning cell updates once: the record text and every covered grid
1762 /// position — a repair shows once in Markdown, not once per column.
1763 #[test]
1764 fn span_repair_updates_the_whole_cell() {
1765 let mut t = Table {
1766 rows: vec![
1767 vec!["Wide".into(), "Wide".into(), "C".into()],
1768 vec!["a".into(), "b".into(), "c".into()],
1769 ],
1770 cells: Some(vec![
1771 cell("Wide", [0.0, 0.0, 100.0, 10.0], (0, 0), (1, 2)),
1772 cell("C", [100.0, 0.0, 150.0, 10.0], (0, 2), (1, 1)),
1773 ]),
1774 ..Default::default()
1775 };
1776 // Update through the covered (non-anchor) position.
1777 assert!(t.set_cell_text(0, 1, "Fixed"));
1778 assert_eq!(
1779 t.rows[0],
1780 vec!["Fixed".to_string(), "Fixed".into(), "C".into()]
1781 );
1782 assert_eq!(t.cell_at(0, 1).unwrap().text, "Fixed");
1783 assert_eq!(t.cell_at(0, 1).unwrap().col_span, 2);
1784 }
1785
1786 /// The OCR-repair loop (#238): locate a cell by an external box (best
1787 /// IoU), replace its text, and see the fix in the export — the grid is
1788 /// the single source of truth for every serializer.
1789 #[test]
1790 fn bbox_lookup_and_repair_flow_into_exports() {
1791 let mut doc = DoclingDocument::new("t");
1792 doc.push(Node::Table(table()));
1793 assert_eq!(doc.tables().count(), 1);
1794
1795 let t = doc.tables_mut().next().unwrap();
1796 // A slightly-off OCR box still lands on the (1,1) cell.
1797 assert_eq!(t.find_cell_by_bbox([52.0, 11.0, 98.0, 19.0]), Some((1, 1)));
1798 assert_eq!(
1799 t.update_cell_by_bbox([52.0, 11.0, 98.0, 19.0], "125"),
1800 Some((1, 1))
1801 );
1802 assert_eq!(t.cell_text(1, 1), Some("125"));
1803 assert!(doc.export_to_markdown().contains("125"));
1804
1805 // No overlap → no match, nothing changed.
1806 let t = doc.tables_mut().next().unwrap();
1807 assert_eq!(t.find_cell_by_bbox([500.0, 500.0, 600.0, 600.0]), None);
1808 }
1809
1810 #[test]
1811 fn cell_accessors_bound_check_and_geometry_materializes() {
1812 let mut t = table();
1813 assert_eq!(t.cell_text(0, 0), Some("Year"));
1814 assert_eq!(t.cell_text(5, 0), None);
1815 assert!(!t.set_cell_text(0, 9, "x"), "outside the grid");
1816 assert_eq!(t.cell_bbox(1, 0), Some([0.0, 10.0, 50.0, 20.0]));
1817
1818 // A geometry-less table materializes its box grid on first set.
1819 let mut plain = Table {
1820 rows: vec![vec!["a".into(), "b".into()]],
1821 ..Default::default()
1822 };
1823 assert_eq!(plain.cell_bbox(0, 1), None);
1824 assert!(!plain.set_cell_bbox(0, 5, [0.0; 4]), "outside the grid");
1825 assert!(plain.set_cell_bbox(0, 1, [1.0, 2.0, 3.0, 4.0]));
1826 assert_eq!(plain.cell_bbox(0, 1), Some([1.0, 2.0, 3.0, 4.0]));
1827 assert_eq!(plain.find_cell_by_bbox([1.5, 2.5, 2.5, 3.5]), Some((0, 1)));
1828 }
1829}