Skip to main content

docling_core/
document.rs

1//! The unified document representation.
2
3use crate::markdown::{to_markdown, to_markdown_images};
4use crate::ImageMode;
5
6/// The unified, format-agnostic document produced by every backend.
7///
8/// This is the heart of docling: backends parse their source format into a
9/// `DoclingDocument`, and serializers turn it back into Markdown, HTML, JSON,
10/// etc. Phase 0 uses a flat sequence of [`Node`]s; the production schema will
11/// match docling-core's body-tree-with-references layout.
12#[derive(Debug, Clone, PartialEq)]
13pub struct DoclingDocument {
14    /// Logical document name (usually the input file stem).
15    pub name: String,
16    /// Top-level content, in reading order.
17    pub nodes: Vec<Node>,
18    /// Default Markdown export mode for [`Self::export_to_markdown`]. `false`
19    /// (the default) reproduces docling's legacy output byte-for-byte; `true`
20    /// emits cleaner, more conformant Markdown. Set by `DocumentConverter`.
21    pub strict_markdown: bool,
22    /// Emit tables in the compact `| a | b |` / `| - | - |` form rather than
23    /// docling-core's width-padded GitHub serializer. The PDF backend sets this
24    /// (its committed groundtruth corpus predates the padded serializer); DOCX/HTML
25    /// leave it `false` to match current published docling.
26    pub compact_tables: bool,
27    /// Hyperlinks recovered from the source, as `(anchor_text, href)` pairs in
28    /// document order. docling's standard pipeline drops PDF link annotations, so
29    /// these are rendered as Markdown `[anchor](href)` **only in strict mode**
30    /// (legacy/docling output is left byte-for-byte unchanged). The PDF backend
31    /// populates this from pdfium link annotations; other backends leave it empty.
32    pub links: Vec<(String, String)>,
33}
34
35/// A single piece of document content.
36#[derive(Debug, Clone, PartialEq)]
37pub enum Node {
38    /// A heading. `level` is 1-6.
39    Heading { level: u8, text: String },
40    /// A run of body text.
41    Paragraph { text: String },
42    /// A form checkbox (docling's `checkbox_selected`/`checkbox_unselected`): its
43    /// clean label `text` with the checked state. DocLang emits a `<checkbox>`
44    /// element head; Markdown/JSON render the task-list form (`- [x] `/`- [ ] `).
45    CheckboxItem { checked: bool, text: String },
46    /// A single list item at the given nesting `level` (0 = top). For ordered
47    /// items, `number` is the display number (honoring the list's `start`); it
48    /// is unused for unordered items. `first_in_list` marks the first item of a
49    /// list so the serializer can blank-line-separate adjacent sibling lists.
50    ///
51    /// `marker` is the DocLang enumeration marker (`"1."`, `"1.1."`, …) when the
52    /// backend provides one — HTML and DOCX set it for enumerated items, so
53    /// DocLang emits `<ldiv><marker>…</marker></ldiv>`; Markdown and the other
54    /// declarative backends leave it `None`, giving a bare `<ldiv/>` (matching
55    /// docling, whose Markdown backend passes no marker).
56    ListItem {
57        ordered: bool,
58        number: u64,
59        first_in_list: bool,
60        text: String,
61        level: u8,
62        marker: Option<String>,
63        /// Optional layout provenance (`x0,y0,x1,y1`, normalized to 0–511): the
64        /// four DocLang `<location>` values emitted inside the `<list>` right
65        /// after the item's `<ldiv>`. Set only by backends with real geometry
66        /// (e.g. PPTX shapes); `None` for the declarative backends. Kept on the
67        /// item itself (rather than a [`Node::Located`] wrapper) so consecutive
68        /// items still group into one `<list>`.
69        location: Option<[u16; 4]>,
70        /// DocLang-only override for items whose DocLang form diverges from their
71        /// flat Markdown `text`. Markdown/JSON always render the fields above; the
72        /// DocLang serializer, when this is `Some`, takes the list kind, marker,
73        /// and content from here instead. Used for docx multilevel numbering
74        /// (Markdown shows `- 1.1. x`, DocLang an ordered `<marker>1.1.</marker>`
75        /// with clean text) and inline equations/formatting in list items.
76        dclx: Option<ListItemDclx>,
77        /// The item's hyperlink target, when its content is a link — docling's
78        /// HTML backend emits it as an `<href uri=…/>` in the item head, and the
79        /// anchor's Markdown link markup is stripped from the rendered content.
80        /// `None` for a plain item; ignored by Markdown/JSON.
81        href: Option<String>,
82        /// Non-body content layer (docling's HTML site chrome before the first
83        /// heading → `furniture`). DocLang emits a `<layer value=…/>` in the item
84        /// head; Markdown/JSON drop a non-body item entirely.
85        layer: Option<ContentLayer>,
86    },
87    /// A fenced code block.
88    Code {
89        language: Option<String>,
90        text: String,
91    },
92    /// A table. The first row is treated as the header.
93    Table(Table),
94    /// A picture/figure, with an optional caption and (when a backend extracts
95    /// it) the embedded image itself.
96    Picture {
97        caption: Option<String>,
98        image: Option<PictureImage>,
99    },
100    /// A chart (docling's `PictureItem` classified as a chart, carrying a
101    /// `PictureTabularChartData` annotation). Markdown and JSON render it exactly
102    /// like a [`Node::Picture`] placeholder (an `<!-- image -->` / `picture`
103    /// item); the DocLang serializer emits `<picture class="chart">` with a
104    /// `<label value="{kind}"/>` and the data `table` as a `<tabular>`.
105    Chart {
106        /// docling's classification label, e.g. `bar_chart`, `line_chart`.
107        kind: String,
108        /// The chart's data grid (row 0 is the header band).
109        table: Table,
110    },
111    /// A logical grouping of child nodes (e.g. a list, a section).
112    Group { label: String, children: Vec<Node> },
113    /// A form key-value region (docling's `field_region`): a set of form fields,
114    /// each pairing an optional marker, key, and value. Backends detect these
115    /// from form structure (e.g. HTML's `keyN` / `keyN_valueM` / `keyN_marker`
116    /// `id`-convention); the serializers render each item's parts as separate
117    /// labelled texts (`marker` / `field_key` / `field_value`).
118    FieldRegion { items: Vec<FieldItem> },
119    /// Rich inline content — docling's `InlineGroup`: a run of styled text
120    /// segments that a backend captured with formatting (`<bold>`, `<italic>`,
121    /// `<underline>`, `<strikethrough>`, sub/superscript, inline `<code>`) the
122    /// flat Markdown text cannot represent. Markdown/JSON render this exactly
123    /// like `Paragraph { text: md_text }` (so their output is unchanged); the
124    /// DocLang serializer uses the structured `runs`. `unwrapped` is set when the
125    /// group's docling parent is a heading/text (no enclosing `<text>` wrapper).
126    InlineGroup {
127        unwrapped: bool,
128        runs: Vec<InlineRun>,
129        md_text: String,
130    },
131    /// A node in a non-body content layer — `furniture` (page headers/footers,
132    /// the HTML `<title>`, site navigation/chrome) or `notes` (docx comments).
133    /// Markdown and JSON omit these layers by default; DocLang renders the wrapped
134    /// node with a `<layer value="{layer}"/>` head.
135    Furniture {
136        layer: ContentLayer,
137        inner: Box<Node>,
138    },
139    /// A node carrying layout provenance — the four DocLang `<location>` values
140    /// (`x0,y0,x1,y1`, normalized to 0–511) docling attaches to elements from
141    /// backends with real geometry (e.g. the slide shapes in PPTX). Markdown and
142    /// JSON render the wrapped node unchanged; DocLang emits the `<location>`
143    /// tokens as the element's first children.
144    Located {
145        location: [u16; 4],
146        inner: Box<Node>,
147    },
148    /// A page boundary — docling's implicit page break between pages. The PPTX
149    /// backend emits one between consecutive slides. DocLang renders it as
150    /// `<page_break/>`; Markdown and JSON omit it (matching docling's default
151    /// exports, which carry page breaks only in the document model).
152    PageBreak,
153    /// A node docling keeps in the document model (and DocLang) but leaves out
154    /// of the Markdown and JSON exports — e.g. an ODF *presentation*'s pictures
155    /// and charts, which appear in the `.dclx` body but not in its `.md`/`.json`.
156    /// DocLang renders the wrapped node in place; Markdown and JSON skip it.
157    DoclangOnly(Box<Node>),
158}
159
160/// Vertical text position of an [`InlineRun`] — docling's `Script`.
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
162pub enum Script {
163    #[default]
164    Baseline,
165    Sub,
166    Super,
167}
168
169/// One styled segment of a [`Node::InlineGroup`] — the docling.rs analogue of a
170/// `TextItem` inside an `InlineGroup`, carrying the ancestor formatting docling
171/// tracks. `text` is already whitespace-normalized/trimmed (one segment per
172/// source text node). A hyperlink is intentionally not stored: DocLang drops the
173/// target inside inline scope, keeping only the anchor text.
174#[derive(Debug, Clone, PartialEq, Eq, Default)]
175pub struct InlineRun {
176    pub text: String,
177    pub bold: bool,
178    pub italic: bool,
179    pub underline: bool,
180    pub strike: bool,
181    pub script: Script,
182    pub code: bool,
183    /// An inline equation (`text` holds LaTeX): DocLang renders `<formula>…`,
184    /// Markdown/JSON keep the `$…$` already baked into the group's `md_text`.
185    pub formula: bool,
186}
187
188/// A DocLang content layer other than the default `body` (see [`Node::Furniture`]).
189#[derive(Debug, Clone, Copy, PartialEq, Eq)]
190pub enum ContentLayer {
191    /// Page headers/footers, HTML `<title>`, site navigation/chrome.
192    Furniture,
193    /// Editorial notes (docx reviewer comments).
194    Notes,
195}
196
197impl ContentLayer {
198    /// The `<layer value="…"/>` token value.
199    pub fn value(self) -> &'static str {
200        match self {
201            ContentLayer::Furniture => "furniture",
202            ContentLayer::Notes => "notes",
203        }
204    }
205}
206
207/// DocLang-only content for a [`Node::ListItem`] whose DocLang form differs from
208/// its flat Markdown `text` (see [`Node::ListItem::dclx`]). `ordered` picks the
209/// enclosing `<list>` kind, `marker` the `<ldiv><marker>`; content is `runs`
210/// (structured equations/formatting) when non-empty, else `text` re-parsed for
211/// inline markers.
212#[derive(Debug, Clone, PartialEq, Eq, Default)]
213pub struct ListItemDclx {
214    pub ordered: bool,
215    pub marker: Option<String>,
216    pub text: String,
217    pub runs: Vec<InlineRun>,
218}
219
220impl InlineRun {
221    /// A run with no active formatting (renders as bare inline text).
222    pub fn is_plain(&self) -> bool {
223        !self.bold
224            && !self.italic
225            && !self.underline
226            && !self.strike
227            && !self.code
228            && !self.formula
229            && self.script == Script::Baseline
230    }
231}
232
233/// Build the [`Node`] for a paragraph of inline content from its structured
234/// `runs` and Markdown text, applying docling's `InlineGroup` boundary:
235///
236/// * a single plain run (or none) → a plain [`Node::Paragraph`] (which the
237///   serializers render as `<text>…</text>`, and a lone hyperlink via `<href>`);
238/// * a single uniformly-formatted run, or two or more runs → a
239///   [`Node::InlineGroup`]. `unwrapped` (the group's docling parent is a
240///   heading, so no enclosing `<text>`) only applies to multi-run groups.
241///
242/// Markdown/JSON render the group's `md_text`, so their output is identical to
243/// emitting a `Paragraph` — the structured runs are DocLang-only.
244pub fn inline_paragraph_node(md_text: String, runs: Vec<InlineRun>, unwrapped: bool) -> Node {
245    let single_plain = runs.len() <= 1 && runs.first().map_or(true, |r| r.is_plain());
246    if single_plain {
247        Node::Paragraph { text: md_text }
248    } else {
249        Node::InlineGroup {
250            unwrapped: unwrapped && runs.len() >= 2,
251            runs,
252            md_text,
253        }
254    }
255}
256
257/// One entry of a [`Node::FieldRegion`]: a marker/key/value triple, any of which
258/// may be absent. Mirrors docling's `field_item` with its `marker` / `field_key`
259/// / `field_value` child texts.
260#[derive(Debug, Clone, PartialEq, Default)]
261pub struct FieldItem {
262    pub marker: Option<String>,
263    pub key: Option<String>,
264    pub value: Option<String>,
265}
266
267/// An extracted picture's raw encoded bytes plus its mimetype and pixel size —
268/// the docling.rs analogue of docling-core's `ImageRef`.
269#[derive(Debug, Clone, PartialEq)]
270pub struct PictureImage {
271    /// e.g. `image/png`, `image/jpeg`.
272    pub mimetype: String,
273    pub width: u32,
274    pub height: u32,
275    /// The image file bytes, exactly as embedded (PNG/JPEG/…).
276    pub data: Vec<u8>,
277}
278
279impl PictureImage {
280    /// A `data:` URI for the image (`data:<mimetype>;base64,<…>`).
281    pub fn data_uri(&self) -> String {
282        format!(
283            "data:{};base64,{}",
284            self.mimetype,
285            crate::base64::encode(&self.data)
286        )
287    }
288}
289
290/// A simple row-major table. By default `rows[0]` is the header row; a
291/// [`TableStructure`] overlay overrides that and adds column spans.
292#[derive(Debug, Clone, PartialEq, Default)]
293pub struct Table {
294    pub rows: Vec<Vec<String>>,
295    /// Optional layout provenance: the four DocLang `<location>` values
296    /// (`x0,y0,x1,y1`, each already normalized to the 0–511 resolution) emitted
297    /// before the table's cells. Set only by backends with real geometry (e.g.
298    /// the spreadsheet backend, whose cell grid yields a bounding box); left
299    /// `None` by declarative backends, which have no coordinates.
300    pub location: Option<[u16; 4]>,
301    /// Optional OTSL structure overlay for backends that parse real table
302    /// geometry (USPTO CALS): explicit header-row count and horizontal-span
303    /// continuations. `None` → the default (row 0 is the header, no spans).
304    /// `rows` still carries the full text grid (span text replicated) for
305    /// Markdown/JSON; DocLang uses this overlay to emit `<ched/>`/`<lcel/>`.
306    pub structure: Option<TableStructure>,
307    /// Optional per-cell block content, parallel to `rows`. A *rich* cell (an
308    /// ODF cell holding a list, several paragraphs, or a nested table) carries
309    /// its DocLang blocks here; the DocLang serializer emits them after the
310    /// cell token instead of the flat `rows` text. Markdown/JSON ignore this
311    /// and render `rows`, so their output is unchanged. `None` (or an empty
312    /// `Vec` for a given cell) → the flat text is used everywhere.
313    pub cell_blocks: Option<Vec<Vec<Vec<Node>>>>,
314}
315
316/// OTSL structure overlay for a [`Table`], parallel to [`Table::rows`].
317#[derive(Debug, Clone, PartialEq, Default)]
318pub struct TableStructure {
319    /// Per-row: `true` if the row's non-empty cells are column headers
320    /// (emitted as `<ched/>` rather than `<fcel/>`).
321    pub header_row: Vec<bool>,
322    /// Same shape as [`Table::rows`]; `true` where a cell continues a
323    /// horizontal span from its left neighbour (emitted as `<lcel/>`).
324    pub col_continuation: Vec<Vec<bool>>,
325    /// Same shape as [`Table::rows`]; `true` where a cell continues a
326    /// vertical span from the cell above (emitted as `<ucel/>`). Empty or all
327    /// `false` when the backend has no vertical spans (e.g. USPTO CALS).
328    pub row_continuation: Vec<Vec<bool>>,
329}
330
331impl DoclingDocument {
332    /// Create an empty document with the given name.
333    pub fn new(name: impl Into<String>) -> Self {
334        Self {
335            name: name.into(),
336            nodes: Vec::new(),
337            strict_markdown: false,
338            compact_tables: false,
339            links: Vec::new(),
340        }
341    }
342
343    /// Append a node.
344    pub fn push(&mut self, node: Node) {
345        self.nodes.push(node);
346    }
347
348    /// Convenience: append a heading.
349    pub fn add_heading(&mut self, level: u8, text: impl Into<String>) {
350        self.push(Node::Heading {
351            level,
352            text: text.into(),
353        });
354    }
355
356    /// Convenience: append a paragraph.
357    pub fn add_paragraph(&mut self, text: impl Into<String>) {
358        self.push(Node::Paragraph { text: text.into() });
359    }
360
361    /// Serialize the document to Markdown.
362    ///
363    /// The Rust equivalent of docling-core's
364    /// `DoclingDocument.export_to_markdown()`. Uses [`Self::strict_markdown`] to
365    /// pick between docling-legacy output (default) and the cleaner, more
366    /// conformant variant.
367    pub fn export_to_markdown(&self) -> String {
368        to_markdown(self, self.strict_markdown)
369    }
370
371    /// Serialize to Markdown, explicitly choosing the mode regardless of
372    /// [`Self::strict_markdown`]. `strict = true` produces cleaner, more
373    /// conformant Markdown (code-fence languages preserved, no inline-run
374    /// spacing artifacts); `strict = false` reproduces docling's legacy output.
375    pub fn export_to_markdown_with(&self, strict: bool) -> String {
376        to_markdown(self, strict)
377    }
378
379    /// Serialize to docling-core's native JSON wire format (`DoclingDocument`
380    /// schema), pretty-printed — the Rust equivalent of
381    /// `DoclingDocument.export_to_dict()` / `save_as_json()`. The output loads
382    /// back into Python docling-core and round-trips to the same Markdown.
383    pub fn export_to_json(&self) -> String {
384        serde_json::to_string_pretty(&crate::json::to_json(self))
385            .expect("DoclingDocument JSON is always serializable")
386    }
387
388    /// Serialize to DocLang XML (`<doclang version="0.7">…`), the markup that
389    /// lives inside a `.dclx` archive — the Rust counterpart of docling-core's
390    /// `export_to_doclang()` with default parameters. No trailing newline; the
391    /// archive writer appends exactly one.
392    pub fn export_to_doclang(&self) -> String {
393        crate::doclang::export_to_doclang(&self.nodes)
394    }
395
396    /// Serialize to Markdown with an explicit picture [`ImageMode`] (mirrors
397    /// docling's `image_mode`). Returns the Markdown and, for
398    /// [`ImageMode::Referenced`], the `(relative-path, bytes)` of each image the
399    /// caller should write next to the Markdown file. `artifacts_dir` is the
400    /// directory name used in referenced links.
401    pub fn export_to_markdown_with_images(
402        &self,
403        image_mode: ImageMode,
404        artifacts_dir: &str,
405    ) -> (String, Vec<(String, Vec<u8>)>) {
406        to_markdown_images(self, self.strict_markdown, image_mode, artifacts_dir)
407    }
408}