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