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