Skip to main content

docling_core/
markdown.rs

1//! Markdown serializer for [`DoclingDocument`].
2
3use crate::document::{
4    ContentLayer, ContentLayers, DoclingDocument, MarkdownExportOptions, Node, Table,
5};
6
7/// What docling's Markdown serializer writes for an item it has no component
8/// for — a `KeyValueItem` (the XBRL fact graph) is the one such item a backend
9/// produces.
10const MISSING_KEY_VALUE_ITEM: &str = "<!-- missing-key-value-item -->";
11
12/// How pictures are rendered (mirrors docling-core's `ImageRefMode`).
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14pub enum ImageMode {
15    /// `<!-- image -->` (docling's default, and the only mode without image data).
16    #[default]
17    Placeholder,
18    /// `![Image](data:<mime>;base64,…)` — self-contained.
19    Embedded,
20    /// `![Image](<artifacts>/image_NNNNNN.<ext>)`; the bytes are returned for the
21    /// caller to write.
22    Referenced,
23}
24
25/// Serializer state threaded through the render walk.
26struct Ctx {
27    strict: bool,
28    /// Render pictures' alt text (#676): strict Markdown, or the document's
29    /// `picture_alt_text`.
30    alt_text: bool,
31    /// Emit compact `| a | b |` tables instead of the padded GitHub serializer.
32    compact_tables: bool,
33    images: ImageMode,
34    artifacts_dir: String,
35    /// (relative path, bytes) for each referenced image — written by the caller.
36    artifacts: Vec<(String, Vec<u8>)>,
37    pic_index: usize,
38    /// Rendering the block content of a rich table cell (docling-core 2.94's
39    /// `in_table_cell`, docling-core#540): a heading has no valid Markdown
40    /// form inside a table, so it renders as plain text without `#` markers.
41    in_table_cell: bool,
42    /// docling-core's `MarkdownParams.page_break_placeholder`: the text that
43    /// separates two pages ([`DoclingDocument::page_break_placeholder`]).
44    /// `None` omits page breaks, docling's default.
45    page_break: Option<String>,
46    /// A page boundary has been crossed since the last rendered block, so the
47    /// next block is preceded by the placeholder. docling yields its
48    /// `_PageBreakNode` between two *items* whose `prov.page_no` differ, so a
49    /// boundary before the first block or after the last one emits nothing,
50    /// and a run of empty pages collapses into a single break.
51    pending_page_break: bool,
52    /// Whether any block has been rendered yet — for a streamer, across every
53    /// earlier push too — which is what makes a boundary a *pending* break.
54    emitted_any: bool,
55    /// The content layers rendered ([`MarkdownExportOptions::layers`], #599).
56    layers: ContentLayers,
57    /// The layer the items being rendered sit on: `None` (body) at the
58    /// root, the group's or wrapper's layer inside a non-body group or a
59    /// [`Node::Furniture`] — what the layer gate compares against the set,
60    /// as every item of a hidden sheet carries that sheet's layer upstream.
61    current_layer: Option<ContentLayer>,
62    /// Render a picture's nested text items ([`MarkdownExportOptions::traverse_pictures`]).
63    traverse_pictures: bool,
64    /// Keep the backends' HTML-entity escaping (`&amp;` …) in the output;
65    /// off, it is undone ([`MarkdownExportOptions::escape_html`]).
66    escape_html: bool,
67    /// Keep the backends' `\_` escaping; off, it is undone.
68    escape_underscores: bool,
69    /// What a picture prints as without image data.
70    image_placeholder: String,
71    /// The plain-text export ([`MarkdownExportOptions::plain_text`], #613).
72    plain: bool,
73}
74
75impl Ctx {
76    /// Serializer state for `options` (the page-break setting is the
77    /// document's, the strictness the caller's).
78    fn new(doc: &DoclingDocument, strict: bool, options: &MarkdownExportOptions) -> Self {
79        Ctx {
80            strict,
81            alt_text: strict || doc.picture_alt_text,
82            compact_tables: doc.compact_tables,
83            images: options.image_mode,
84            artifacts_dir: options.artifacts_dir.clone(),
85            artifacts: Vec::new(),
86            pic_index: 0,
87            in_table_cell: false,
88            page_break: doc.page_break_placeholder.clone(),
89            pending_page_break: false,
90            emitted_any: false,
91            layers: options.layers,
92            current_layer: None,
93            traverse_pictures: options.traverse_pictures,
94            escape_html: options.escape_html,
95            escape_underscores: options.escape_underscores,
96            image_placeholder: options.image_placeholder.clone(),
97            plain: options.plain_text,
98        }
99    }
100
101    /// Whether an item on the layer being rendered is in the chosen set.
102    fn layer_visible(&self) -> bool {
103        self.layers.contains(self.current_layer)
104    }
105
106    /// The backends escape inline text for Markdown when they build the
107    /// nodes (`&` → `&amp;`, `_` → `\_`, what docling-core's `post_process`
108    /// does at serialization time); an export that turns an escaping off
109    /// undoes it here, the way the JSON export recovers the raw text. Code,
110    /// formulas and table cells never pass through — upstream leaves those
111    /// unescaped too.
112    fn unescape(&self, text: &str) -> String {
113        let mut out = std::borrow::Cow::Borrowed(text);
114        if !self.escape_html
115            && (out.contains("&amp;") || out.contains("&lt;") || out.contains("&gt;"))
116        {
117            out = std::borrow::Cow::Owned(
118                out.replace("&lt;", "<")
119                    .replace("&gt;", ">")
120                    .replace("&amp;", "&"),
121            );
122        }
123        if !self.escape_underscores && out.contains("\\_") {
124            out = std::borrow::Cow::Owned(out.replace("\\_", "_"));
125        }
126        out.into_owned()
127    }
128
129    /// A text item's inline text: the strict-mode cleanup, then the
130    /// escaping the options turn off undone.
131    fn text(&self, text: &str) -> String {
132        let text = strict_text(text, self.strict);
133        if self.plain {
134            self.unescape(&plain_inline(&self.drop_image_markers(&text)))
135        } else {
136            self.unescape(&text)
137        }
138    }
139
140    /// A caption's text (the backends escape it, but strict mode leaves it
141    /// alone): the escaping the options turn off undone, and, for the plain
142    /// export, its inline markup dropped.
143    fn caption(&self, text: &str) -> String {
144        if self.plain {
145            self.unescape(&plain_inline(text))
146        } else {
147            self.unescape(text)
148        }
149    }
150
151    /// docling-core's `_md_line_breaks` for the Markdown export; the plain
152    /// export's `PlainTextTextSerializer` keeps the text's own newlines.
153    fn breaks(&self, text: &str) -> String {
154        if self.plain {
155            text.to_string()
156        } else {
157            md_line_breaks(text)
158        }
159    }
160
161    /// A table for the plain export: a rich cell's text is its Markdown
162    /// serialization in our model (bold runs, links, hard line breaks),
163    /// where upstream serializes the cell with the plain serializer — so
164    /// the markup goes before the grid is laid out, which also lets a
165    /// once-bold number right-align like a plain one. A simple cell holds
166    /// raw text and passes through unchanged.
167    fn plain_table(&self, table: &Table) -> Table {
168        let mut plain = table.clone();
169        for cell in plain.rows.iter_mut().flatten() {
170            if cell.contains(['*', '~', '`', '[', '\n', '<']) {
171                let text = self.drop_image_markers(&strip_hard_breaks(cell));
172                *cell = plain_inline(&text);
173            }
174        }
175        plain
176    }
177
178    /// Pictures some backends fold into an item's text (an HTML `<img>`
179    /// inside a `<li>`, a LaTeX figure in a paragraph) arrive as baked
180    /// `<!-- image -->` lines — docling's picture *children* of the item,
181    /// which its serializer prints with the active image placeholder. The
182    /// plain export's placeholder is empty, so such a line goes, as a
183    /// picture item would.
184    fn drop_image_markers(&self, text: &str) -> String {
185        const MARKER: &str = "<!-- image -->";
186        if !text.contains(MARKER) && !text.contains("```") {
187            return text.to_string();
188        }
189        // Block by block (`\n\n`, the serializer's part delimiter): a block
190        // left empty goes with its delimiter, as docling joins only the parts
191        // that carry text.
192        text.split("\n\n")
193            .filter_map(|block| {
194                let lines: Vec<String> = block
195                    .split('\n')
196                    .filter_map(|line| {
197                        // A folded code block's fences go too: the plain
198                        // export prints code unfenced.
199                        if line.trim() == MARKER || line.trim() == "```" {
200                            return None;
201                        }
202                        Some(line.replace(MARKER, &self.image_placeholder))
203                    })
204                    .collect();
205                (!lines.is_empty()).then(|| lines.join("\n"))
206            })
207            .collect::<Vec<_>>()
208            .join("\n\n")
209    }
210}
211
212/// Render a document to a Markdown string (pictures as placeholders).
213///
214/// `strict` selects the serializer-level behaviours that differ between
215/// docling-legacy output and cleaner Markdown — currently the code-fence
216/// language (legacy drops it, strict keeps it).
217pub fn to_markdown(doc: &DoclingDocument, strict: bool) -> String {
218    to_markdown_images(doc, strict, ImageMode::Placeholder, "artifacts").0
219}
220
221/// Render to Markdown with an explicit picture [`ImageMode`]. Returns the
222/// Markdown and, for [`ImageMode::Referenced`], the `(path, bytes)` of each image
223/// the caller should write (relative to the Markdown file).
224pub fn to_markdown_images(
225    doc: &DoclingDocument,
226    strict: bool,
227    images: ImageMode,
228    artifacts_dir: &str,
229) -> (String, Vec<(String, Vec<u8>)>) {
230    to_markdown_with_options(
231        doc,
232        strict,
233        &MarkdownExportOptions {
234            image_mode: images,
235            artifacts_dir: artifacts_dir.to_string(),
236            ..MarkdownExportOptions::default()
237        },
238    )
239}
240
241/// Render to Markdown per `options` ([`MarkdownExportOptions`], #599):
242/// content layers, picture traversal, escaping, the image placeholder and
243/// the image mode. Returns the Markdown and the referenced-image artifacts.
244pub fn to_markdown_with_options(
245    doc: &DoclingDocument,
246    strict: bool,
247    options: &MarkdownExportOptions,
248) -> (String, Vec<(String, Vec<u8>)>) {
249    let mut ctx = Ctx::new(doc, strict, options);
250    let mut blocks: Vec<String> = Vec::new();
251    render(&doc.nodes, &mut blocks, &mut ctx);
252    let mut body = blocks.join("\n\n");
253    // Strict mode only: turn recovered source hyperlinks into Markdown links.
254    // docling's standard pipeline drops them, so doing this in legacy mode would
255    // diverge from docling — hence strict-only, leaving conformance output intact.
256    if strict && !options.plain_text && !doc.links.is_empty() {
257        body = apply_links(&body, &doc.links);
258    }
259    // The YAML front matter (#679) opens the document when its output mode
260    // asks for it; never in the plain-text export.
261    let front = if doc.metadata_output.front_matter() && !options.plain_text {
262        doc.metadata.to_front_matter()
263    } else {
264        String::new()
265    };
266    let md = match (front.is_empty(), body.is_empty()) {
267        (true, true) => String::new(),
268        (true, false) => format!("{body}\n"),
269        (false, true) => front,
270        (false, false) => format!("{front}\n{body}\n"),
271    };
272    (md, ctx.artifacts)
273}
274
275/// Render the block content of a *rich table cell* to Markdown — what
276/// docling-core's table serializer does for a `RichTableCell`
277/// (`doc_serializer.serialize(item, in_table_cell=True)`): the cell's
278/// paragraphs, lists and flattened nested tables render as in a document, but a
279/// heading loses its `#` markers (docling-core#540 — the Markdown spec has no
280/// headings inside tables). Pictures stay placeholders. The caller flattens the
281/// result into its cell text; the table serializer later turns the newlines
282/// into spaces.
283pub fn to_markdown_table_cell(doc: &DoclingDocument, strict: bool) -> String {
284    let mut ctx = Ctx::new(doc, strict, &MarkdownExportOptions::default());
285    ctx.in_table_cell = true;
286    ctx.artifacts_dir = String::new();
287    // A rich cell is one page's content; its sub-document carries no page
288    // boundaries and docling's `_iterate_items` runs the page-break scan
289    // over the document root only.
290    ctx.page_break = None;
291    let mut blocks: Vec<String> = Vec::new();
292    render(&doc.nodes, &mut blocks, &mut ctx);
293    blocks.join("\n\n")
294}
295
296/// Wrap each recovered link's anchor text in Markdown `[anchor](href)`. Anchors
297/// arrive cleaned (curly quotes/dashes already normalized) but un-escaped, so we
298/// match against the body's HTML-escaped (`&`/`<`/`>`) form, the way prose nodes
299/// were serialized. Links are consumed in document order from a moving cursor, so
300/// a repeated anchor (e.g. two "issues") links its successive occurrences rather
301/// than all pointing at the first. An anchor that can't be located is skipped
302/// (its text may have been split across a line wrap or table cell).
303fn apply_links(body: &str, links: &[(String, String)]) -> String {
304    let mut out = body.to_string();
305    let mut cursor = 0usize;
306    for (anchor, href) in links {
307        let anchor = anchor
308            .replace('&', "&amp;")
309            .replace('<', "&lt;")
310            .replace('>', "&gt;");
311        if anchor.is_empty() {
312            continue;
313        }
314        if let Some(rel) = out[cursor..].find(&anchor) {
315            let at = cursor + rel;
316            // Don't relink inside an already-emitted `](` Markdown link target.
317            let replacement = format!("[{anchor}]({href})");
318            out.replace_range(at..at + anchor.len(), &replacement);
319            cursor = at + replacement.len();
320        }
321    }
322    out
323}
324
325/// Like [`apply_links`] but over a single chunk, consuming from a shared queue so
326/// the same `[anchor](href)` rewriting can be applied incrementally as Markdown is
327/// streamed out. Each queued link is matched (in document order) against `chunk`
328/// and rewritten in place; a link whose anchor is not in this chunk is carried
329/// forward in the queue for a later chunk. Anchors are recovered in document
330/// order and a chunk is always a contiguous run of whole blocks, so this
331/// reproduces [`apply_links`]' single moving cursor: the link lands in whichever
332/// chunk contains its anchor, identically to the buffered path. (A link whose
333/// anchor never appears is carried to the end and dropped — the same no-op
334/// `apply_links` performs for an unlocatable anchor.)
335fn apply_links_chunk(chunk: &str, queue: &mut Vec<(String, String)>) -> String {
336    let mut out = chunk.to_string();
337    let mut cursor = 0usize;
338    let mut carried: Vec<(String, String)> = Vec::new();
339    for (anchor_raw, href) in std::mem::take(queue) {
340        let anchor = anchor_raw
341            .replace('&', "&amp;")
342            .replace('<', "&lt;")
343            .replace('>', "&gt;");
344        if anchor.is_empty() {
345            continue;
346        }
347        if let Some(rel) = out[cursor..].find(&anchor) {
348            let at = cursor + rel;
349            let replacement = format!("[{anchor}]({href})");
350            out.replace_range(at..at + anchor.len(), &replacement);
351            cursor = at + replacement.len();
352        } else {
353            // Not in this chunk; try again when its block is flushed.
354            carried.push((anchor_raw, href));
355        }
356    }
357    *queue = carried;
358    out
359}
360
361/// Incremental Markdown serializer: feed finalized, in-document-order batches of
362/// [`Node`]s and receive Markdown chunks whose concatenation is **byte-identical**
363/// to [`to_markdown_images`] over the same nodes. This is the streaming
364/// counterpart of the buffered serializer — used to emit a document's Markdown in
365/// chunks (e.g. page by page, as the parallel PDF pipeline finishes pages) instead
366/// of building the whole string up front.
367///
368/// [`ImageMode::Placeholder`] and [`ImageMode::Embedded`] render inline.
369/// [`ImageMode::Referenced`] additionally hands each picture's bytes out through
370/// [`take_artifacts`](Self::take_artifacts) — construct with
371/// [`with_artifacts`](Self::with_artifacts) and drain after every push so the
372/// bytes can be written to disk as pages finish instead of accumulating for the
373/// whole document (issue #80's memory-bounded image handling).
374///
375/// Each [`push`](Self::push) must contain whole blocks in reading order: a caller
376/// must not split a run of list items across two pushes (the run would render as
377/// two separate lists). Finalized PDF page batches already satisfy this.
378pub struct MarkdownStreamer {
379    strict: bool,
380    images: ImageMode,
381    compact_tables: bool,
382    /// [`DoclingDocument::picture_alt_text`] (#676).
383    picture_alt_text: bool,
384    /// The YAML front matter (#679) still to be written, ahead of the first
385    /// chunk — or alone, from [`finish`](Self::finish), when nothing else
386    /// comes.
387    front_matter: Option<String>,
388    /// Whether any non-empty chunk has been emitted yet (drives `\n\n` joins and
389    /// the trailing newline).
390    emitted_any: bool,
391    /// Recovered links not yet placed (strict mode), consumed in document order.
392    links: Vec<(String, String)>,
393    /// Referenced mode: the link prefix, the not-yet-drained `(path, bytes)`
394    /// artifacts, and the running image number (continues across pushes so the
395    /// stream matches the buffered serializer's `image_000000…` numbering).
396    artifacts_dir: String,
397    artifacts: Vec<(String, Vec<u8>)>,
398    pic_index: usize,
399    /// [`DoclingDocument::page_break_placeholder`] and the boundary carried
400    /// over from the previous push (a page batch opens with its page marker,
401    /// so the break it implies is paid by that batch's first block).
402    page_break: Option<String>,
403    pending_page_break: bool,
404    /// Whether an earlier push rendered an *item* — the page-break scan's
405    /// state ([`Ctx`]'s `emitted_any`). It differs from `emitted_any` (text
406    /// written) only when every block of the earlier pushes was empty and
407    /// dropped (#605): a page break before the next item is still owed then,
408    /// exactly as in the buffered export.
409    items_emitted: bool,
410    /// The export options beyond the image mode (#599): layers, picture
411    /// traversal, escaping, the placeholder — [`with_export_options`](Self::with_export_options).
412    layers: ContentLayers,
413    traverse_pictures: bool,
414    escape_html: bool,
415    escape_underscores: bool,
416    image_placeholder: String,
417    plain: bool,
418}
419
420impl MarkdownStreamer {
421    /// Create a streamer. `compact_tables` mirrors [`DoclingDocument::compact_tables`].
422    /// For [`ImageMode::Referenced`] use [`with_artifacts`](Self::with_artifacts).
423    pub fn new(strict: bool, images: ImageMode, compact_tables: bool) -> Self {
424        debug_assert!(
425            images != ImageMode::Referenced,
426            "referenced image mode needs an artifacts dir; use with_artifacts"
427        );
428        Self::with_artifacts(strict, images, compact_tables, "artifacts")
429    }
430
431    /// Like [`new`](Self::new) but with the artifacts link prefix, allowing
432    /// [`ImageMode::Referenced`]: pictures render as
433    /// `![Image](<artifacts_dir>/image_NNNNNN.<ext>)` and each push's image
434    /// bytes wait in [`take_artifacts`](Self::take_artifacts) for the caller to
435    /// write. The concatenated chunks and the artifact list match the buffered
436    /// [`to_markdown_images`] byte-for-byte.
437    pub fn with_artifacts(
438        strict: bool,
439        images: ImageMode,
440        compact_tables: bool,
441        artifacts_dir: &str,
442    ) -> Self {
443        Self {
444            strict,
445            images,
446            compact_tables,
447            picture_alt_text: false,
448            front_matter: None,
449            emitted_any: false,
450            links: Vec::new(),
451            artifacts_dir: artifacts_dir.to_string(),
452            artifacts: Vec::new(),
453            pic_index: 0,
454            page_break: None,
455            pending_page_break: false,
456            items_emitted: false,
457            layers: ContentLayers::BODY,
458            traverse_pictures: false,
459            escape_html: true,
460            escape_underscores: true,
461            image_placeholder: "<!-- image -->".to_string(),
462            plain: false,
463        }
464    }
465
466    /// Take every setting of `options` ([`MarkdownExportOptions`], #599):
467    /// the image mode and artifacts directory the constructors took, plus the
468    /// content layers, picture traversal, escaping and image placeholder.
469    /// The concatenated chunks match the buffered
470    /// [`to_markdown_with_options`] byte-for-byte. Set before the first
471    /// [`push`](Self::push).
472    pub fn with_export_options(mut self, options: &MarkdownExportOptions) -> Self {
473        self.images = options.image_mode;
474        self.artifacts_dir = options.artifacts_dir.clone();
475        self.layers = options.layers;
476        self.traverse_pictures = options.traverse_pictures;
477        self.escape_html = options.escape_html;
478        self.escape_underscores = options.escape_underscores;
479        self.image_placeholder = options.image_placeholder.clone();
480        self.plain = options.plain_text;
481        self
482    }
483
484    /// Insert `placeholder` between pages, mirroring
485    /// [`DoclingDocument::page_break_placeholder`] for the buffered path (the
486    /// concatenated chunks stay byte-identical to it). `None` — the default —
487    /// omits page breaks. Set before the first [`push`](Self::push).
488    pub fn with_page_break_placeholder(mut self, placeholder: Option<String>) -> Self {
489        self.page_break = placeholder;
490        self
491    }
492
493    /// Render pictures' alt text (#676) — [`DoclingDocument::picture_alt_text`]
494    /// for the stream; strict Markdown renders it regardless. Set before the
495    /// first [`push`](Self::push).
496    pub fn with_picture_alt_text(mut self, on: bool) -> Self {
497        self.picture_alt_text = on;
498        self
499    }
500
501    /// Open the stream with the YAML front matter of `metadata` (#679) —
502    /// what the buffered export writes for a document whose
503    /// [`DoclingDocument::metadata_output`] is `Frontmatter`. Empty
504    /// metadata writes nothing; the plain-text export never writes it.
505    pub fn with_metadata(mut self, metadata: &crate::metadata::DocumentMetadata) -> Self {
506        self.front_matter = (!self.plain)
507            .then(|| metadata.to_front_matter())
508            .filter(|f| !f.is_empty());
509        self
510    }
511
512    /// The `(relative path, bytes)` of images rendered by pushes since the last
513    /// drain ([`ImageMode::Referenced`] only — empty otherwise). Paths are
514    /// relative to the Markdown file, i.e. they start with the configured
515    /// artifacts dir.
516    pub fn take_artifacts(&mut self) -> Vec<(String, Vec<u8>)> {
517        std::mem::take(&mut self.artifacts)
518    }
519
520    /// Render one finalized batch of nodes (plus any links recovered from the same
521    /// span, in document order) into the next Markdown chunk. Returns an empty
522    /// string when the batch produces no output (e.g. empty tables/pictures), in
523    /// which case nothing should be written.
524    pub fn push(&mut self, nodes: &[Node], links: &[(String, String)]) -> String {
525        self.links.extend(links.iter().cloned());
526        let mut ctx = Ctx {
527            strict: self.strict,
528            alt_text: self.strict || self.picture_alt_text,
529            compact_tables: self.compact_tables,
530            images: self.images,
531            artifacts_dir: std::mem::take(&mut self.artifacts_dir),
532            artifacts: std::mem::take(&mut self.artifacts),
533            pic_index: self.pic_index,
534            in_table_cell: false,
535            page_break: std::mem::take(&mut self.page_break),
536            pending_page_break: self.pending_page_break,
537            emitted_any: self.items_emitted,
538            layers: self.layers,
539            current_layer: None,
540            traverse_pictures: self.traverse_pictures,
541            escape_html: self.escape_html,
542            escape_underscores: self.escape_underscores,
543            image_placeholder: std::mem::take(&mut self.image_placeholder),
544            plain: self.plain,
545        };
546        let mut blocks: Vec<String> = Vec::new();
547        render(nodes, &mut blocks, &mut ctx);
548        self.image_placeholder = std::mem::take(&mut ctx.image_placeholder);
549        self.artifacts_dir = std::mem::take(&mut ctx.artifacts_dir);
550        self.artifacts = std::mem::take(&mut ctx.artifacts);
551        self.pic_index = ctx.pic_index;
552        self.page_break = std::mem::take(&mut ctx.page_break);
553        self.pending_page_break = ctx.pending_page_break;
554        self.items_emitted = ctx.emitted_any;
555        if blocks.is_empty() {
556            return String::new();
557        }
558        let mut body = blocks.join("\n\n");
559        if self.strict && !self.plain && !self.links.is_empty() {
560            body = apply_links_chunk(&body, &mut self.links);
561        }
562        let chunk = if let Some(front) = self.front_matter.take() {
563            format!("{front}\n{body}")
564        } else if self.emitted_any {
565            format!("\n\n{body}")
566        } else {
567            body
568        };
569        self.emitted_any = true;
570        chunk
571    }
572
573    /// Emit the trailing newline that finishes the document (empty if no content
574    /// was produced). Call exactly once, after the final [`push`](Self::push).
575    pub fn finish(self) -> String {
576        if let Some(front) = self.front_matter {
577            front
578        } else if self.emitted_any {
579            "\n".to_string()
580        } else {
581            String::new()
582        }
583    }
584}
585
586/// In `strict` mode, rewrite inline text for readability rather than byte-for-byte
587/// docling fidelity: undo the legacy `\_` underscore escaping, and tighten stray
588/// spaces around punctuation (`[ 37 , 36 ]` → `[37, 36]`, `( x )` → `(x)`). This
589/// cleans up both the PDF backend's glyph-split spacing and the space the legacy
590/// emphasis serialization leaves before punctuation (`*a* ,` → `*a*,`).
591/// Legacy/default output keeps docling's spacing untouched. Only inline text
592/// nodes pass through here — code blocks and table cells are left alone.
593fn strict_text(text: &str, strict: bool) -> String {
594    if !strict {
595        return text.to_string();
596    }
597    text.replace("\\_", "_")
598        .replace(" ,", ",")
599        .replace(" .", ".")
600        .replace(" ;", ";")
601        .replace(" )", ")")
602        .replace("( ", "(")
603        .replace(" ]", "]")
604        .replace("[ ", "[")
605}
606
607/// The plain export's inline text (#613): the Markdown markers docling-core's
608/// `PlainTextDocSerializer` never writes — `serialize_bold` / `_italic` /
609/// `_strikethrough` return the text, `serialize_hyperlink` the label, and
610/// `format_code_blocks=False` drops inline code's backticks. The backends
611/// bake those markers into an item's Markdown text (`***x***`, `**x**`,
612/// `*x*`, `~~x~~`, `` `x` ``, `[label](url)`, the set DocLang's run parser
613/// reads too), so they are taken out here, nested ones included. A marker
614/// counts only when it closes and its content is tight against both
615/// markers (CommonMark's flanking rule): `2 * 3 * 4` is arithmetic and IBM
616/// i's `*USE … have *OBJMGT` are special values, not emphasis, and stay as
617/// they are — docling's own emphasis around a space (WebVTT's `* *`) stays
618/// literal too. Inline `$…$` formulas pass through untouched.
619pub(crate) fn plain_inline(text: &str) -> String {
620    if !text.contains(['*', '~', '`', '[']) {
621        return text.to_string();
622    }
623    let chars: Vec<char> = text.chars().collect();
624    let mut out = String::with_capacity(text.len());
625    plain_inline_into(&chars, &mut out);
626    out
627}
628
629fn plain_inline_into(chars: &[char], out: &mut String) {
630    let find = |open: usize, pat: &[char]| -> Option<usize> {
631        chars
632            .get(open..)?
633            .windows(pat.len())
634            .position(|w| w == pat)
635            .map(|p| open + p)
636    };
637    // An emphasis span opening at `i` with marker `pat`: its closing index
638    // when the content is non-empty and tight against both markers.
639    let span = |i: usize, pat: &[char]| -> Option<usize> {
640        if !chars[i..].starts_with(pat) {
641            return None;
642        }
643        let open = i + pat.len();
644        let end = find(open, pat)?;
645        (end > open && !chars[open].is_whitespace() && !chars[end - 1].is_whitespace())
646            .then_some(end)
647    };
648    let mut i = 0;
649    while i < chars.len() {
650        let mut matched = false;
651        for pat in [&['*', '*', '*'][..], &['*', '*'], &['~', '~'], &['*']] {
652            if let Some(end) = span(i, pat) {
653                plain_inline_into(&chars[i + pat.len()..end], out);
654                i = end + pat.len();
655                matched = true;
656                break;
657            }
658        }
659        if matched {
660            continue;
661        }
662        // Inline code: content tight against both backticks, as docling
663        // writes it — a backtick opening a quotation (`` `like this’ ``,
664        // JATS prose) stays.
665        if chars[i] == '`' {
666            if let Some(end) = find(i + 1, &['`']).filter(|&e| {
667                e > i + 1 && !chars[i + 1].is_whitespace() && !chars[e - 1].is_whitespace()
668            }) {
669                out.extend(&chars[i + 1..end]);
670                i = end + 1;
671                continue;
672            }
673        }
674        // An inline formula is LaTeX, printed as it is — its brackets and
675        // stars are not Markdown.
676        if chars[i] == '$' {
677            if let Some(end) = find(i + 1, &['$']) {
678                out.extend(&chars[i..=end]);
679                i = end + 1;
680                continue;
681            }
682        }
683        // A link: the `]` closing this `[` (brackets nest) directly followed
684        // by `(` — a citation `[23,24]` before a later link is no anchor.
685        if chars[i] == '[' {
686            if let Some(close) = closing_bracket(chars, i) {
687                if chars.get(close + 1) == Some(&'(') {
688                    if let Some(endp) = crate::doclang::link_dest_end(chars, close + 2) {
689                        plain_inline_into(&chars[i + 1..close], out);
690                        i = endp + 1;
691                        continue;
692                    }
693                }
694            }
695        }
696        // A run of the same marker that opened nothing stays literal as a
697        // whole, so `***` before a lone `*` is not re-read from its middle.
698        let c = chars[i];
699        out.push(c);
700        i += 1;
701        if matches!(c, '*' | '~') {
702            while i < chars.len() && chars[i] == c {
703                out.push(c);
704                i += 1;
705            }
706        }
707    }
708}
709
710/// The index of the `]` matching the `[` at `open`, nested brackets
711/// balanced; `None` when it never closes.
712fn closing_bracket(chars: &[char], open: usize) -> Option<usize> {
713    let mut depth = 0usize;
714    for (k, c) in chars.iter().enumerate().skip(open + 1) {
715        match c {
716            '[' => depth += 1,
717            ']' if depth == 0 => return Some(k),
718            ']' => depth -= 1,
719            _ => {}
720        }
721    }
722    None
723}
724
725/// docling-core 2.92's `_md_line_breaks` (docling-core#721): a single `\n`
726/// inside an item's text becomes a GFM hard line break (`"  \n"`, two trailing
727/// spaces) so renderers honour it; a blank line (`\n\n`) is a paragraph break
728/// and stays as is — the document scope already joins blocks with `\n\n`.
729/// Applied to body text, list items and standalone caption items, never to
730/// code/formulas, nor to the captions a table or picture carries: docling-core's
731/// `serialize_captions` prints those as they are (#769).
732fn md_line_breaks(text: &str) -> String {
733    if !text.contains('\n') {
734        return text.to_string();
735    }
736    text.split("\n\n")
737        .map(|para| para.replace('\n', "  \n"))
738        .collect::<Vec<_>>()
739        .join("\n\n")
740}
741
742/// Undo [`md_line_breaks`] on a rich table cell's flattened Markdown so the
743/// non-Markdown exports (JSON `text`, LaTeX cells) see the cell's raw line
744/// breaks, as docling's do — a rich cell's text is its Markdown serialization
745/// in our model, and the two trailing spaces are a Markdown-only marker.
746pub(crate) fn strip_hard_breaks(text: &str) -> String {
747    if text.contains("  \n") {
748        text.replace("  \n", "\n")
749    } else {
750        text.to_string()
751    }
752}
753
754/// docling-core's `_heading_line_breaks`: a GFM heading cannot span lines, so a
755/// newline inside heading text collapses to a space (`# Hello World`, not a
756/// broken `# Hello\nWorld`).
757fn heading_line_breaks(text: &str) -> String {
758    text.replace('\n', " ")
759}
760
761fn render(nodes: &[Node], blocks: &mut Vec<String>, ctx: &mut Ctx) {
762    let mut i = 0;
763    while i < nodes.len() {
764        let before = blocks.len();
765        match &nodes[i] {
766            // A page boundary: the explicit `PageBreak` (slides, DjVu / DocTags
767            // pages) or the `PageInfo` marker that opens every PDF page and
768            // spreadsheet sheet — a sheet boundary carries both, and the flag
769            // absorbs the pair into one break. docling's `_iterate_items`
770            // yields a `_PageBreakNode` only between two items on different
771            // pages (a group's leading item counts for the group), which is
772            // exactly "a boundary between two rendered blocks": nothing before
773            // the first block, nothing after the last, consecutive boundaries
774            // — empty or furniture-only pages — collapsed into one.
775            Node::PageBreak | Node::PageInfo { .. } => {
776                if ctx.page_break.is_some() && ctx.emitted_any {
777                    ctx.pending_page_break = true;
778                }
779                i += 1;
780            }
781            Node::ListItem { .. } => {
782                let start = i;
783                i += 1;
784                loop {
785                    match nodes.get(i) {
786                        Some(Node::ListItem { .. }) => i += 1,
787                        // An empty paragraph between two list items is absorbed
788                        // into the run — docling keeps such a ListGroup
789                        // contiguous rather than splitting it.
790                        Some(Node::Paragraph { text })
791                            if text.is_empty()
792                                && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
793                        {
794                            i += 1
795                        }
796                        _ => break,
797                    }
798                }
799                render_list_run(&nodes[start..i], blocks, ctx);
800            }
801            other => {
802                render_one(other, blocks, ctx);
803                i += 1;
804            }
805        }
806        if blocks.len() > before {
807            // docling-core joins only the parts that carry text
808            // (`"\n\n".join(p.text for p in parts if p.text)`, at the
809            // document and every group scope), so an item that renders an
810            // empty block — a picture or chart under `image_placeholder: ""`,
811            // an empty field part or inline group — adds no blank lines
812            // (#605). It still counts as an item for the page-break scan:
813            // upstream's page-break marker sits between the *items* of two
814            // pages and is never empty itself, so the placeholder below still
815            // goes in (an empty placeholder keeps its doubled delimiter).
816            let kept: Vec<String> = blocks.drain(before..).filter(|b| !b.is_empty()).collect();
817            blocks.extend(kept);
818            if ctx.pending_page_break {
819                // The placeholder is a block of its own, joined by the document
820                // delimiter like docling's `_PageBreakSerResult` part — an
821                // empty placeholder therefore leaves the doubled `\n\n`
822                // upstream leaves too.
823                if let Some(placeholder) = &ctx.page_break {
824                    blocks.insert(before, placeholder.clone());
825                }
826                ctx.pending_page_break = false;
827            }
828            ctx.emitted_any = true;
829        }
830    }
831}
832
833/// Render a contiguous run of list items.
834///
835/// Ordered items use their explicit `number`. A new sibling list (marked by
836/// `first_in_list`) at the same depth is separated by a blank line, matching
837/// docling-core's serializer.
838fn render_list_run(items: &[Node], blocks: &mut Vec<String>, ctx: &Ctx) {
839    let mut lines: Vec<String> = Vec::new();
840    // Whether a top-level item has been rendered yet — a fresh-list flag on
841    // the very first item opens nothing.
842    let mut any_top = false;
843
844    for item in items {
845        let Node::ListItem {
846            ordered,
847            number,
848            first_in_list,
849            text,
850            level,
851            marker: orig_marker,
852            location: _,
853            dclx: _,
854            href: _,
855            layer,
856        } = item
857        else {
858            continue;
859        };
860        // docling's content-layer filtering: an item renders when its layer
861        // — its own, else the layer of the group it sits in — is in the set
862        // (body only by default, so a furniture list item is omitted).
863        if !ctx.layers.contains(layer.or(ctx.current_layer)) {
864            continue;
865        }
866        let level = *level as usize;
867
868        // A new sibling list at the top level gets a blank line — and only the
869        // backend knows where one starts (`first_in_list`: Word's `numId`
870        // changing, an HTML `<ul>` closing, a Markdown bullet switching
871        // `-`→`*`). The serializer used to guess it from a kind flip or a
872        // number gap as well, which split lists docling keeps whole (an
873        // AsciiDoc `1.` … `5.`, mixed `*`/`1.` markers) — #385. Only at the
874        // top level: nested sibling groups are children of a list item, and
875        // docling joins an item's children without blank lines.
876        if level == 0 {
877            if any_top && *first_in_list {
878                lines.push(String::new());
879            }
880            any_top = true;
881        }
882
883        let indent = "    ".repeat(level);
884        // docling-core's `case_already_valid`: a marker of digits and a dot
885        // prints verbatim — Python's `\d+\.` admits every Unicode decimal
886        // digit, so a DOCX `decimalFullWidth` marker (`1.`, docling#4336)
887        // is kept as it is rather than renumbered in ASCII.
888        let verbatim = orig_marker.as_deref().filter(|m| {
889            m.strip_suffix('.')
890                .is_some_and(|d| !d.is_empty() && d.chars().all(char::is_numeric))
891        });
892        let marker = match verbatim {
893            Some(m) if *ordered => m.to_string(),
894            _ if *ordered => format!("{number}."),
895            _ => "-".to_string(),
896        };
897        lines.push(format!("{indent}{marker} {}", list_item_text(text, ctx)));
898    }
899
900    // A run consisting only of furniture (content-layer-filtered) items yields no
901    // lines; pushing an empty block here would surface as a stray blank line.
902    if !lines.is_empty() {
903        blocks.push(lines.join("\n"));
904    }
905}
906
907/// A list item's Markdown body. The GFM hard-line-break rule (docling-core#721)
908/// applies to the item's own text; pictures the HTML backend folded into the
909/// item (`"\n[alt\n]<!-- image -->"` per `<img>` inside the `<li>`) are
910/// docling's picture *children* of the item, which its serializer prints after
911/// the item line with plain newlines — so a folded tail keeps its newlines
912/// unmarked. The tail is recognised structurally: every line after the first is
913/// an image marker or an alt caption directly followed by one.
914fn list_item_text(text: &str, ctx: &Ctx) -> String {
915    let escaped = ctx.text(text);
916    if ctx.plain {
917        return escaped;
918    }
919    if let Some((own, tail)) = escaped.split_once('\n') {
920        if is_folded_child_tail(tail) {
921            return format!("{}\n{tail}", md_line_breaks(own));
922        }
923    }
924    md_line_breaks(&escaped)
925}
926
927/// Whether everything after a list item's own first line is a folded *child*
928/// block rather than a continuation of the item's text: an image marker
929/// (optionally preceded by its caption/alt line) or a fenced code block. The
930/// AsciiDoc backend indents such a block to the item's own depth (as
931/// docling-core's list serializer does for each part it emits), so a leading
932/// indent is ignored here.
933fn is_folded_child_tail(tail: &str) -> bool {
934    const MARKER: &str = "<!-- image -->";
935    const FENCE: &str = "```";
936    let mut lines = tail.split('\n').peekable();
937    let mut any = false;
938    while let Some(line) = lines.next() {
939        let line = line.trim_start();
940        if line == MARKER {
941            any = true;
942        } else if line == FENCE {
943            // Skip the block's body; an unclosed fence is not a folded child.
944            loop {
945                match lines.next() {
946                    Some(l) if l.trim_start() == FENCE => break,
947                    Some(_) => {}
948                    None => return false,
949                }
950            }
951            any = true;
952        } else if lines.next().map(str::trim_start) == Some(MARKER) {
953            any = true; // an alt caption line, then its marker
954        } else {
955            return false;
956        }
957    }
958    any
959}
960
961/// Render one item: docling's content-layer gate first — an item whose layer
962/// (the group's or wrapper's it sits in, else the body) is outside the set
963/// renders nothing, while a container still walks its children — then the
964/// item itself.
965fn render_one(node: &Node, blocks: &mut Vec<String>, ctx: &mut Ctx) {
966    match node {
967        // Containers and layer wrappers decide for their children.
968        Node::Group { .. }
969        | Node::Furniture { .. }
970        | Node::PageFurniture { .. }
971        | Node::FurnitureText { .. }
972        | Node::CommentSection { .. }
973        | Node::PictureChildren(_)
974        | Node::Commented { .. }
975        | Node::Located { .. }
976        | Node::Prov { .. }
977        | Node::Track { .. }
978        | Node::PageBreak
979        | Node::PageInfo { .. }
980        | Node::DoclangOnly(_) => {}
981        _ if !ctx.layer_visible() => return,
982        _ => {}
983    }
984    render_item(node, blocks, ctx)
985}
986
987fn render_item(node: &Node, blocks: &mut Vec<String>, ctx: &mut Ctx) {
988    match node {
989        Node::Heading { level, text } => {
990            if ctx.plain {
991                // `PlainTextTextSerializer`: the heading's text as it is —
992                // no `#`, its newlines kept.
993                blocks.push(ctx.text(text));
994                return;
995            }
996            let text = heading_line_breaks(&ctx.text(text));
997            if ctx.in_table_cell {
998                // docling-core#540: no `#` markers inside a table cell.
999                blocks.push(text);
1000            } else {
1001                let hashes = "#".repeat((*level).clamp(1, 6) as usize);
1002                blocks.push(format!("{hashes} {text}"));
1003            }
1004        }
1005        // An empty body paragraph (docling's blank-line text item) contributes
1006        // nothing to Markdown — only DocLang/JSON keep it.
1007        Node::Paragraph { text } if text.is_empty() => {}
1008        Node::Paragraph { text } => blocks.push(ctx.breaks(&ctx.text(text))),
1009        Node::LabeledText { .. } => render_item(&node.labeled_as_paragraph(), blocks, ctx),
1010        // A standalone caption item renders like a text item; its hyperlink
1011        // annotation becomes a Markdown link around the whole caption.
1012        Node::Caption { text, .. } if text.is_empty() => {}
1013        Node::Caption { text, href } => {
1014            let body = ctx.breaks(&ctx.text(text));
1015            blocks.push(match href {
1016                Some(url) if !ctx.plain => format!("[{body}]({url})"),
1017                _ => body,
1018            });
1019        }
1020        Node::CheckboxItem { checked, text } => {
1021            let mark = if *checked { "- [x] " } else { "- [ ] " };
1022            blocks.push(ctx.breaks(&ctx.text(&format!("{mark}{text}"))));
1023        }
1024        Node::Code {
1025            language,
1026            text,
1027            pretty,
1028            ..
1029        } => {
1030            // Legacy docling never emits a language on the fence; strict keeps it.
1031            let lang = match language {
1032                Some(l) if ctx.strict => l.as_str(),
1033                _ => "",
1034            };
1035            // Strict prefers the line-preserving rendering when the backend
1036            // supplied one (PDF); legacy stays on docling's flat `text`.
1037            let body = match pretty {
1038                Some(p) if ctx.strict => p.as_str(),
1039                _ => text.as_str(),
1040            };
1041            // The plain export (`format_code_blocks=False`) prints the code
1042            // as it is.
1043            blocks.push(if ctx.plain {
1044                body.to_string()
1045            } else {
1046                format!("```{lang}\n{body}\n```")
1047            });
1048        }
1049        // A CodeFormula-decoded display formula renders as docling's `$$…$$`
1050        // (the un-enriched pipeline emits a placeholder paragraph instead).
1051        Node::Formula { latex, .. } => blocks.push(format!("$${latex}$$")),
1052        Node::Table(table) => {
1053            // docling renders a table's caption as a text line before the grid.
1054            // `caption` is already escaped (backend convention), like a paragraph.
1055            if let Some(cap) = &table.caption {
1056                if !cap.is_empty() {
1057                    blocks.push(ctx.text(cap));
1058                }
1059            }
1060            let rendered = if ctx.plain {
1061                render_table(&ctx.plain_table(table), ctx.compact_tables)
1062            } else {
1063                render_table(table, ctx.compact_tables)
1064            };
1065            if !rendered.is_empty() {
1066                blocks.push(rendered);
1067            }
1068        }
1069        // Classification predictions don't affect docling's Markdown output;
1070        // a description (the picture-OCR text, #645) prints between the
1071        // caption and the image placeholder — docling's
1072        // `MarkdownPictureSerializer` order: captions, annotations, image.
1073        // Alt text (#676) is rendered only under strict Markdown or the
1074        // document's `picture_alt_text`, and then where Markdown puts it: as
1075        // the `![alt](…)` of an image line, or — with the placeholder, which
1076        // has no alt slot — as the line a description takes.
1077        Node::Picture {
1078            caption,
1079            image,
1080            description,
1081            ..
1082        } => {
1083            if let Some(cap) = caption {
1084                if !cap.is_empty() {
1085                    blocks.push(ctx.caption(cap));
1086                }
1087            }
1088            let alt = description
1089                .as_ref()
1090                .filter(|d| d.is_alt_text() && ctx.alt_text && !d.text.is_empty());
1091            let marker = picture_marker(image.as_ref(), ctx, alt.map(|d| d.text.as_str()));
1092            if let Some(desc) = description {
1093                let shown = !desc.is_alt_text() || (ctx.alt_text && !marker.starts_with("!["));
1094                if !desc.text.is_empty() && shown {
1095                    blocks.push(ctx.breaks(&ctx.text(&desc.text)));
1096                }
1097            }
1098            blocks.push(marker);
1099        }
1100        // A chart renders as docling's picture-with-meta markdown: the caption,
1101        // the placeholder, the humanized classification ("line_chart" ->
1102        // "Line chart"), then the chart's data grid as a regular table.
1103        Node::Chart {
1104            kind,
1105            table,
1106            caption,
1107            ..
1108        } => {
1109            if let Some(cap) = caption {
1110                if !cap.is_empty() {
1111                    blocks.push(ctx.caption(cap));
1112                }
1113            }
1114            blocks.push(picture_marker(None, ctx, None));
1115            blocks.push(humanize_label(kind));
1116            let rendered = if ctx.plain {
1117                render_table(&ctx.plain_table(table), false)
1118            } else {
1119                render_table(table, false)
1120            };
1121            if !rendered.is_empty() {
1122                blocks.push(rendered);
1123            }
1124        }
1125        // A DocLang-only node is omitted from Markdown.
1126        Node::DoclangOnly(_) => {}
1127        // A group on a non-body layer (a hidden spreadsheet sheet): its items
1128        // sit on that layer, as every item of such a sheet does upstream — so
1129        // they render exactly when the set includes it (#599), nothing by
1130        // default.
1131        Node::Group {
1132            layer: Some(layer),
1133            children,
1134            ..
1135        } => {
1136            let outer = ctx.current_layer.replace(*layer);
1137            render(children, blocks, ctx);
1138            ctx.current_layer = outer;
1139        }
1140        Node::Group { children, .. } => render(children, blocks, ctx),
1141        Node::FieldRegion { items } => {
1142            // The region container and each field item carry no text of their
1143            // own; docling-core 2.93 (#724) serializes them to nothing (older
1144            // releases emitted a `<!-- missing-text -->` marker for each), so
1145            // only an item's marker/key/value appear, as separate paragraphs.
1146            for item in items {
1147                for part in [&item.marker, &item.key, &item.value].into_iter().flatten() {
1148                    blocks.push(ctx.breaks(&ctx.text(part)));
1149                }
1150            }
1151        }
1152        // docling's Markdown serializer has no component for a `KeyValueItem`
1153        // and writes its fallback placeholder in the item's place.
1154        Node::KeyValueGraph { .. } => blocks.push(MISSING_KEY_VALUE_ITEM.to_string()),
1155        // A rich inline group renders exactly like a paragraph of its Markdown
1156        // text — the structured runs are DocLang-only.
1157        Node::InlineGroup { md_text, .. } => blocks.push(ctx.breaks(&ctx.text(md_text))),
1158        // A plain-text backend dump renders verbatim as a single block.
1159        Node::TextDump(text) => {
1160            if !text.is_empty() {
1161                blocks.push(text.clone());
1162            }
1163        }
1164        // Furniture (page headers/footers, HTML `<title>`, notes) is out of
1165        // the default body-only export, mirroring docling; a set that
1166        // includes its layer renders the wrapped item like a body item (#599).
1167        Node::Furniture { layer, inner } => {
1168            let outer = ctx.current_layer.replace(*layer);
1169            render_one(inner, blocks, ctx);
1170            ctx.current_layer = outer;
1171        }
1172        // A page header/footer or a `.doc` furniture paragraph: upstream's
1173        // `page_header` / `page_footer` / `footnote` text item, a plain
1174        // paragraph when the furniture layer renders.
1175        Node::PageFurniture { text, .. } | Node::FurnitureText { text, .. } => {
1176            if ctx.layers.furniture && !text.is_empty() {
1177                blocks.push(ctx.breaks(&ctx.text(text)));
1178            }
1179        }
1180        // A picture's contained text: docling's Markdown picture serializer
1181        // prints the caption and the image, never the children — unless the
1182        // export traverses pictures, when the item walk yields them after
1183        // the picture and they render as the text items they are (#599).
1184        Node::PictureChildren(children) => {
1185            if ctx.traverse_pictures {
1186                render(children, blocks, ctx);
1187            }
1188        }
1189        // A comment lives in the notes layer — out like other furniture
1190        // unless that layer renders (the note's `[author: …]: text` as a
1191        // paragraph); the annotation on a body item is JSON-only, so render
1192        // the item.
1193        Node::CommentSection { text, .. } => {
1194            if ctx.layers.notes && !text.is_empty() {
1195                blocks.push(ctx.breaks(&ctx.text(text)));
1196            }
1197        }
1198        Node::Commented { inner, .. } => render_one(inner, blocks, ctx),
1199        // Layout provenance is DocLang-only; render the wrapped node.
1200        Node::Located { inner, .. } | Node::Prov { inner, .. } | Node::Track { inner, .. } => {
1201            render_one(inner, blocks, ctx)
1202        }
1203        // Page breaks are DocLang-only; docling omits them from Markdown.
1204        Node::PageBreak => {}
1205        // Page markers feed the JSON export only.
1206        Node::PageInfo { .. } => {}
1207        // Runs of adjacent list items are merged by `render`; a stray single
1208        // item (a hand-built document, or a `Located` wrapper around one)
1209        // still renders as its own one-item list instead of panicking —
1210        // `nodes` is public API, so every representable tree must serialize.
1211        Node::ListItem { .. } => render_list_run(std::slice::from_ref(node), blocks, ctx),
1212    }
1213}
1214
1215/// The Markdown for a picture under the active [`ImageMode`]; Referenced mode also
1216/// records the bytes in `ctx.artifacts` for the caller to write.
1217/// docling-core's `_humanize_text`: underscores to spaces, first letter
1218/// capitalized ("line_chart" -> "Line chart").
1219fn humanize_label(label: &str) -> String {
1220    let text = label.replace('_', " ");
1221    let mut chars = text.chars();
1222    match chars.next() {
1223        Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
1224        None => text,
1225    }
1226}
1227
1228/// The image line's alt: docling's `Image`, or the picture's alt text (#676)
1229/// on one line with its `]` escaped, so it cannot close the bracket.
1230fn image_alt(alt: Option<&str>) -> String {
1231    match alt {
1232        Some(text) => text
1233            .split_whitespace()
1234            .collect::<Vec<_>>()
1235            .join(" ")
1236            .replace('\\', "\\\\")
1237            .replace(']', "\\]"),
1238        None => "Image".to_string(),
1239    }
1240}
1241
1242fn picture_marker(image: Option<&crate::PictureImage>, ctx: &mut Ctx, alt: Option<&str>) -> String {
1243    match (ctx.images, image) {
1244        // docling embeds the `ImageRef`'s PNG (a JPEG re-encoded).
1245        (ImageMode::Embedded, Some(img)) => {
1246            format!(
1247                "![{}]({})",
1248                image_alt(alt),
1249                crate::pixel_digest::docling_data_uri(img).1
1250            )
1251        }
1252        (ImageMode::Referenced, Some(img)) => {
1253            let path = format!(
1254                "{}/image_{:06}.{}",
1255                ctx.artifacts_dir,
1256                ctx.pic_index,
1257                ext_for(&img.mimetype)
1258            );
1259            ctx.pic_index += 1;
1260            ctx.artifacts.push((path.clone(), img.data.clone()));
1261            format!("![{}]({})", image_alt(alt), escape_uri_path(&path))
1262        }
1263        // Placeholder, or any mode with no extracted image.
1264        _ => ctx.image_placeholder.clone(),
1265    }
1266}
1267
1268/// Encode a URL or filesystem path as a Markdown link destination —
1269/// docling-core's `MarkdownPictureSerializer._escape_uri_path`
1270/// (docling-core#698, 2.94). Handles URLs of any scheme as well as POSIX and
1271/// Windows paths, keeps relative paths relative and never double-encodes:
1272/// backslashes become `/` (a backslash is both the Windows separator and a
1273/// Markdown escape), a UNC share `//host/…` and an absolute Windows path
1274/// `C:/…` become RFC 8089 `file://` URLs (the one spelling a renderer cannot
1275/// misread as a scheme-relative URL or a `C:` scheme), a URL keeps its
1276/// scheme / authority / delimiters with only the components encoded, and
1277/// everything else is percent-encoded as a path. `%` is kept so an
1278/// already-encoded destination stays as it is; spaces and parentheses are
1279/// encoded because they would end (or unbalance) a Markdown inline link.
1280pub(crate) fn escape_uri_path(value: &str) -> String {
1281    const KEEP: &str = "/%:@+,;=~$!&'*";
1282    let s = value.replace('\\', "/");
1283    if let Some(rest) = s.strip_prefix("//") {
1284        // A fileshare: `file://<host>/<path>`, the host possibly empty.
1285        let rest = rest.trim_start_matches('/');
1286        let (host, tail) = rest.split_once('/').unwrap_or((rest, ""));
1287        return format!("file://{host}{}", percent_quote(&format!("/{tail}"), KEEP));
1288    }
1289    let bytes = s.as_bytes();
1290    if bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && bytes[2] == b'/' {
1291        // A Windows path with a drive letter: `file:///C:/…`.
1292        return format!("file:///{}", percent_quote(&s, KEEP));
1293    }
1294    // A URL keeps its scheme, authority and delimiters; only its components are
1295    // encoded. A single-character scheme cannot be real (it is a drive letter,
1296    // handled above), so it is read as a path — like `urlsplit`.
1297    if let Some((scheme, rest)) = s.split_once(':') {
1298        let valid_scheme = scheme.len() > 1
1299            && scheme.as_bytes()[0].is_ascii_alphabetic()
1300            && scheme
1301                .bytes()
1302                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'));
1303        if valid_scheme {
1304            let (authority, rest) = match rest.strip_prefix("//") {
1305                Some(r) => {
1306                    let end = r.find(['/', '?', '#']).unwrap_or(r.len());
1307                    (Some(&r[..end]), &r[end..])
1308                }
1309                None => (None, rest),
1310            };
1311            let (before_frag, fragment) = rest.split_once('#').unwrap_or((rest, ""));
1312            let (path, query) = before_frag.split_once('?').unwrap_or((before_frag, ""));
1313            let mut out = format!("{scheme}:");
1314            if let Some(a) = authority {
1315                out.push_str("//");
1316                out.push_str(a);
1317            }
1318            out.push_str(&percent_quote(path, KEEP));
1319            if !query.is_empty() {
1320                out.push('?');
1321                out.push_str(&percent_quote(query, KEEP));
1322            }
1323            if !fragment.is_empty() {
1324                out.push('#');
1325                out.push_str(&percent_quote(fragment, KEEP));
1326            }
1327            return out;
1328        }
1329    }
1330    // A relative or root-relative local path.
1331    percent_quote(&s, KEEP)
1332}
1333
1334/// `urllib.parse.quote(s, safe)`: unreserved ASCII (`A–Z a–z 0–9 _ . - ~`) and
1335/// the `safe` set stay, every other byte of the UTF-8 encoding becomes `%XX`.
1336fn percent_quote(s: &str, safe: &str) -> String {
1337    let mut out = String::with_capacity(s.len());
1338    for &b in s.as_bytes() {
1339        let keep = b.is_ascii_alphanumeric()
1340            || matches!(b, b'_' | b'.' | b'-' | b'~')
1341            || (b.is_ascii() && safe.contains(b as char));
1342        if keep {
1343            out.push(b as char);
1344        } else {
1345            out.push_str(&format!("%{b:02X}"));
1346        }
1347    }
1348    out
1349}
1350
1351pub(crate) fn ext_for(mimetype: &str) -> &str {
1352    match mimetype {
1353        "image/jpeg" => "jpg",
1354        "image/gif" => "gif",
1355        "image/webp" => "webp",
1356        "image/bmp" => "bmp",
1357        "image/tiff" => "tif",
1358        _ => "png",
1359    }
1360}
1361
1362/// Render a table. `compact` selects between two serializers:
1363///
1364/// - **padded** (default) — docling-core's `tabulate(tablefmt="github")`: columns
1365///   are padded to a fixed width (header width + a minimum padding of 2, or the
1366///   widest data cell); numeric columns (every data cell parses as a number) are
1367///   right-aligned, others left-aligned; separators are plain dashes of
1368///   `width + 2`. Matches current published docling (DOCX/HTML conformance).
1369/// - **compact** — `| a | b |` cells with single-dash `| - | - |` separators, no
1370///   width padding. Matches the committed PDF groundtruth corpus, which predates
1371///   the padded serializer.
1372///
1373/// Each cell is first escaped (`\n` → space, `|` → `&#124;`) so it can't break the
1374/// table. The header row is the table's leading `column_header` block flattened
1375/// to one row ([`Table::header_row_count`] + [`flatten_header_rows`],
1376/// docling-core#723); alignment and widths are computed over the body rows.
1377/// Whether a table cell counts as a number for column alignment, matching
1378/// `tabulate`'s detection: an ordinary float/int (`f64`-parseable, covering
1379/// `1e2`/`inf`/`+1.5`) **or** a thousands-separated number like `7,015`.
1380fn is_number_cell(t: &str) -> bool {
1381    t.parse::<f64>().is_ok() || is_thousands_number(t)
1382}
1383
1384/// A number with comma thousands-separators, per `tabulate`'s
1385/// `_float_with_thousands_separators` regex
1386/// (`^(([+-]?[0-9]{1,3})(?:,([0-9]{3}))*)?(?(1)\.[0-9]*|\.[0-9]+)?$`): the
1387/// integer part is 1–3 digits then any number of `,ddd` groups; the fraction is
1388/// optional (and, without an integer part, must have at least one digit).
1389fn is_thousands_number(t: &str) -> bool {
1390    let b = t.as_bytes();
1391    let mut i = 0;
1392    let start = i;
1393    if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
1394        i += 1;
1395    }
1396    // First digit chunk: 1–3 digits.
1397    let d0 = i;
1398    while i < b.len() && b[i].is_ascii_digit() && i - d0 < 3 {
1399        i += 1;
1400    }
1401    let has_int = i > d0;
1402    if has_int {
1403        // Subsequent `,ddd` groups (exactly three digits each).
1404        while i + 3 < b.len() + 1
1405            && b.get(i) == Some(&b',')
1406            && b.get(i + 1).is_some_and(u8::is_ascii_digit)
1407            && b.get(i + 2).is_some_and(u8::is_ascii_digit)
1408            && b.get(i + 3).is_some_and(u8::is_ascii_digit)
1409        {
1410            i += 4;
1411        }
1412    } else {
1413        // A sign only counts with an integer part.
1414        i = start;
1415    }
1416    // Optional fraction.
1417    if i < b.len() && b[i] == b'.' {
1418        i += 1;
1419        let f0 = i;
1420        while i < b.len() && b[i].is_ascii_digit() {
1421            i += 1;
1422        }
1423        if !has_int && i == f0 {
1424            return false; // `.` with no digits and no integer part
1425        }
1426    } else if !has_int {
1427        return false; // neither integer nor fractional part
1428    }
1429    i == b.len()
1430}
1431
1432/// The single GFM header row for a table: the leading header rows (see
1433/// [`Table::header_row_count`]) flattened per column, texts joined with
1434/// `" - "` after dropping consecutive duplicates — docling-core's
1435/// `_flatten_header_rows` (docling-core#723). The duplicate rule is what
1436/// keeps a row-spanning header from being joined to itself (the grid repeats
1437/// its text into every row it covers); it is position-based, so two stacked
1438/// levels sharing a label collapse too — GFM has one header row, and upstream
1439/// accepts that loss. No header rows → one empty header cell per column.
1440fn flatten_header_rows(header_rows: &[Vec<String>], num_cols: usize) -> Vec<String> {
1441    (0..num_cols)
1442        .map(|c| {
1443            let mut parts: Vec<&str> = Vec::new();
1444            for row in header_rows {
1445                let text = row.get(c).map(String::as_str).unwrap_or("");
1446                if !text.is_empty() && parts.last() != Some(&text) {
1447                    parts.push(text);
1448                }
1449            }
1450            parts.join(" - ")
1451        })
1452        .collect()
1453}
1454
1455pub(crate) fn render_table(table: &Table, compact: bool) -> String {
1456    if table.rows.is_empty() {
1457        return String::new();
1458    }
1459    let num_cols = table.rows.iter().map(Vec::len).max().unwrap_or(0);
1460    if num_cols == 0 {
1461        return String::new();
1462    }
1463
1464    // Escaped, rectangular grid (ragged rows padded with empty cells). The
1465    // header block is resolved to the one row GFM allows (docling-core#723);
1466    // `tabulate` strips data cells of surrounding whitespace but leaves the
1467    // header texts as-is.
1468    let num_headers = table.header_row_count().min(table.rows.len());
1469    let escaped = |r: usize| -> Vec<String> {
1470        (0..num_cols)
1471            .map(|c| escape_cell(table.rows[r].get(c).map(String::as_str).unwrap_or("")))
1472            .collect()
1473    };
1474    let header_rows: Vec<Vec<String>> = (0..num_headers).map(escaped).collect();
1475    let header = flatten_header_rows(&header_rows, num_cols);
1476    let body: Vec<Vec<String>> = (num_headers..table.rows.len())
1477        .map(|r| {
1478            escaped(r)
1479                .into_iter()
1480                .map(|c| c.trim().to_string())
1481                .collect()
1482        })
1483        .collect();
1484
1485    if compact {
1486        // Compact: cells joined by " | ", no padding, single-dash separators.
1487        let render_row = |row: &[String]| -> String { format!("| {} |", row.join(" | ")) };
1488        let mut lines = Vec::with_capacity(body.len() + 2);
1489        lines.push(render_row(&header));
1490        let sep: Vec<&str> = (0..num_cols).map(|_| "-").collect();
1491        lines.push(format!("| {} |", sep.join(" | ")));
1492        for row in &body {
1493            lines.push(render_row(row));
1494        }
1495        return lines.join("\n");
1496    }
1497
1498    // Display width (Unicode scalar count — good enough for now).
1499    let dw = |s: &str| s.chars().count();
1500
1501    // A column is right-aligned when at least one body cell is numeric and every
1502    // non-empty body cell is numeric — matching `tabulate`'s column typing, where
1503    // empty cells are "missing" (ignored) and a number may carry thousands
1504    // separators (`7,015`), which a plain `f64` parse rejects.
1505    let right: Vec<bool> = (0..num_cols)
1506        .map(|c| {
1507            let mut any = false;
1508            for row in &body {
1509                let t = row[c].trim();
1510                if t.is_empty() {
1511                    continue;
1512                }
1513                if !is_number_cell(t) {
1514                    return false;
1515                }
1516                any = true;
1517            }
1518            any
1519        })
1520        .collect();
1521
1522    // Column width = max(header_width + MIN_PADDING(2), max body-cell width).
1523    let width: Vec<usize> = (0..num_cols)
1524        .map(|c| {
1525            let mut w = dw(&header[c]) + 2;
1526            for row in &body {
1527                w = w.max(dw(&row[c]));
1528            }
1529            w
1530        })
1531        .collect();
1532
1533    let fmt_cell = |s: &str, c: usize| -> String {
1534        let pad = " ".repeat(width[c].saturating_sub(dw(s)));
1535        let body = if right[c] {
1536            format!("{pad}{s}")
1537        } else {
1538            format!("{s}{pad}")
1539        };
1540        format!(" {body} ")
1541    };
1542    let render_row = |row: &[String]| -> String {
1543        let cells: Vec<String> = (0..num_cols).map(|c| fmt_cell(&row[c], c)).collect();
1544        format!("|{}|", cells.join("|"))
1545    };
1546
1547    let mut lines = Vec::with_capacity(body.len() + 2);
1548    lines.push(render_row(&header));
1549    let sep: Vec<String> = (0..num_cols).map(|c| "-".repeat(width[c] + 2)).collect();
1550    lines.push(format!("|{}|", sep.join("|")));
1551    for row in &body {
1552        lines.push(render_row(row));
1553    }
1554    lines.join("\n")
1555}
1556
1557/// Escape a table cell so it can't break the markdown table: newlines become
1558/// spaces and pipes become the `&#124;` HTML entity (matches docling-core).
1559fn escape_cell(s: &str) -> String {
1560    s.replace('\n', " ").replace('|', "&#124;")
1561}
1562
1563#[cfg(test)]
1564mod tests {
1565    use super::*;
1566    use crate::{PictureImage, TableCell, TableStructure};
1567
1568    /// #385: where one list ends and the next begins is the backend's call
1569    /// (`first_in_list`), never the serializer's. An ordered run `1.` → `5.`
1570    /// is one list (an AsciiDoc numbered list around a nested one), and so are
1571    /// mixed bullet/ordered items the backend did not separate; only a flagged
1572    /// item opens a new list and earns the blank line.
1573    #[test]
1574    fn list_boundaries_come_from_the_backend_not_the_numbering() {
1575        let item = |ordered: bool, number: u64, first_in_list: bool, text: &str| Node::ListItem {
1576            ordered,
1577            number,
1578            first_in_list,
1579            text: text.into(),
1580            level: 0,
1581            marker: None,
1582            location: None,
1583            dclx: None,
1584            href: None,
1585            layer: None,
1586        };
1587        let md = |items: Vec<Node>| {
1588            let mut doc = DoclingDocument::new("t");
1589            for n in items {
1590                doc.push(n);
1591            }
1592            doc.export_to_markdown()
1593        };
1594        // A number gap alone is not a boundary.
1595        assert_eq!(
1596            md(vec![
1597                item(true, 1, true, "one"),
1598                item(true, 5, false, "five")
1599            ]),
1600            "1. one\n5. five\n"
1601        );
1602        // Nor is a kind flip the backend did not flag …
1603        assert_eq!(
1604            md(vec![
1605                item(false, 0, true, "bullet"),
1606                item(true, 1, false, "one"),
1607                item(false, 0, false, "bullet two"),
1608            ]),
1609            "- bullet\n1. one\n- bullet two\n"
1610        );
1611        // … while a flagged item is one, whatever its number says.
1612        assert_eq!(
1613            md(vec![
1614                item(true, 1, true, "a"),
1615                item(true, 2, false, "b"),
1616                item(true, 3, true, "new list, continuing count"),
1617            ]),
1618            "1. a\n2. b\n\n3. new list, continuing count\n"
1619        );
1620    }
1621
1622    #[test]
1623    fn renders_headings_paragraphs_and_lists() {
1624        let mut doc = DoclingDocument::new("demo");
1625        doc.add_heading(1, "Title");
1626        doc.add_paragraph("Hello world.");
1627        doc.push(Node::ListItem {
1628            ordered: false,
1629            number: 1,
1630            first_in_list: true,
1631            text: "first".into(),
1632            level: 0,
1633            marker: None,
1634            location: None,
1635            dclx: None,
1636            href: None,
1637            layer: None,
1638        });
1639        doc.push(Node::ListItem {
1640            ordered: false,
1641            number: 2,
1642            first_in_list: false,
1643            text: "second".into(),
1644            level: 0,
1645            marker: None,
1646            location: None,
1647            dclx: None,
1648            href: None,
1649            layer: None,
1650        });
1651        let md = doc.export_to_markdown();
1652        assert_eq!(md, "# Title\n\nHello world.\n\n- first\n- second\n");
1653    }
1654
1655    /// docling-core 2.92 (#721): a single newline inside an item's text is a
1656    /// GFM hard line break, a blank line stays a paragraph break, and a heading
1657    /// collapses its newline to a space. Nested-table dumps stay verbatim.
1658    #[test]
1659    fn single_newlines_become_gfm_hard_line_breaks() {
1660        let mut doc = DoclingDocument::new("t");
1661        doc.push(Node::Heading {
1662            level: 1,
1663            text: "Hello\nWorld".into(),
1664        });
1665        doc.push(Node::Paragraph {
1666            text: "line one\nline two\n\npara two".into(),
1667        });
1668        doc.push(Node::ListItem {
1669            ordered: false,
1670            number: 1,
1671            first_in_list: true,
1672            text: "item\ncontinued".into(),
1673            level: 0,
1674            marker: None,
1675            location: None,
1676            dclx: None,
1677            href: None,
1678            layer: None,
1679        });
1680        doc.push(Node::TextDump("A1 B1 \n\n\nC1".into()));
1681        assert_eq!(
1682            doc.export_to_markdown(),
1683            "# Hello World\n\nline one  \nline two\n\npara two\n\n- item  \ncontinued\n\nA1 B1 \n\n\nC1\n"
1684        );
1685    }
1686
1687    /// docling-core#540: inside a rich table cell a heading is plain text;
1688    /// docling-core#724: a field region renders only its items' key/value text.
1689    #[test]
1690    fn table_cell_mode_and_field_regions() {
1691        let mut doc = DoclingDocument::new("t");
1692        doc.push(Node::Heading {
1693            level: 2,
1694            text: "A  text".into(),
1695        });
1696        doc.push(Node::Paragraph {
1697            text: "body".into(),
1698        });
1699        assert_eq!(to_markdown_table_cell(&doc, false), "A  text\n\nbody");
1700        assert_eq!(doc.export_to_markdown(), "## A  text\n\nbody\n");
1701
1702        let mut doc = DoclingDocument::new("f");
1703        doc.push(Node::FieldRegion {
1704            items: vec![crate::FieldItem {
1705                marker: None,
1706                key: Some("Name:".into()),
1707                value: Some("John Doe".into()),
1708                value_kind: None,
1709            }],
1710        });
1711        assert_eq!(doc.export_to_markdown(), "Name:\n\nJohn Doe\n");
1712    }
1713
1714    #[test]
1715    fn strict_renders_recovered_links_legacy_does_not() {
1716        let mut doc = DoclingDocument::new("cv");
1717        doc.add_paragraph("Find me on LinkedIn or GitHub.");
1718        doc.links = vec![
1719            ("LinkedIn".into(), "https://www.linkedin.com/in/x/".into()),
1720            ("GitHub".into(), "https://github.com/x/".into()),
1721        ];
1722        // Legacy/docling mode: links are left untouched (conformance preserved).
1723        assert_eq!(doc.export_to_markdown(), "Find me on LinkedIn or GitHub.\n");
1724        // Strict mode: anchors become Markdown links.
1725        assert_eq!(
1726            doc.export_to_markdown_with(true),
1727            "Find me on [LinkedIn](https://www.linkedin.com/in/x/) or [GitHub](https://github.com/x/).\n"
1728        );
1729    }
1730
1731    #[test]
1732    fn strict_links_match_escaped_anchor_and_consume_in_order() {
1733        let mut doc = DoclingDocument::new("d");
1734        // The PDF assembler HTML-escapes prose, so by serialization time the body
1735        // already carries `&amp;`; the anchor is stored un-escaped. The matcher must
1736        // escape the anchor to find it. Two identical anchors link in document order.
1737        doc.add_paragraph("AI &amp; ML here, and issues here, then issues there.");
1738        doc.links = vec![
1739            ("AI & ML".into(), "https://a/".into()),
1740            ("issues".into(), "https://first/".into()),
1741            ("issues".into(), "https://second/".into()),
1742        ];
1743        assert_eq!(
1744            doc.export_to_markdown_with(true),
1745            "[AI &amp; ML](https://a/) here, and [issues](https://first/) here, then [issues](https://second/) there.\n"
1746        );
1747    }
1748
1749    /// docling-core#698: the referenced-image destination is percent-encoded —
1750    /// upstream's own case table (paths, Windows flavours, UNC, URLs) plus
1751    /// idempotency on the encoded result.
1752    #[test]
1753    fn referenced_image_destinations_are_escaped() {
1754        let cases = [
1755            (
1756                "doc_artifacts/image_000001_ab12.png",
1757                "doc_artifacts/image_000001_ab12.png",
1758            ),
1759            (
1760                "My Report_artifacts/img.png",
1761                "My%20Report_artifacts/img.png",
1762            ),
1763            ("artifacts/img (1).png", "artifacts/img%20%281%29.png"),
1764            ("100%_scale/a#b?c.png", "100%_scale/a%23b%3Fc.png"),
1765            ("/home/a b/img.png", "/home/a%20b/img.png"),
1766            (
1767                "My Report_artifacts\\img.png",
1768                "My%20Report_artifacts/img.png",
1769            ),
1770            (
1771                "C:/Users/me/My Docs/img.png",
1772                "file:///C:/Users/me/My%20Docs/img.png",
1773            ),
1774            ("C:\\Users\\me\\img.png", "file:///C:/Users/me/img.png"),
1775            (
1776                "//server/share/My Docs/img.png",
1777                "file://server/share/My%20Docs/img.png",
1778            ),
1779            ("\\\\server\\share\\img.png", "file://server/share/img.png"),
1780            ("file:///home/a b/img.png", "file:///home/a%20b/img.png"),
1781            (
1782                "s3://bucket/My Report_artifacts/img.png",
1783                "s3://bucket/My%20Report_artifacts/img.png",
1784            ),
1785            (
1786                "https://example.com:8080/a b.png?w=1&h=2#frag",
1787                "https://example.com:8080/a%20b.png?w=1&h=2#frag",
1788            ),
1789            (
1790                "https://example.com/img (1).png",
1791                "https://example.com/img%20%281%29.png",
1792            ),
1793            ("caf\u{e9}/im\u{e4}ge.png", "caf%C3%A9/im%C3%A4ge.png"),
1794        ];
1795        for (input, expected) in cases {
1796            assert_eq!(escape_uri_path(input), expected, "input {input:?}");
1797            assert_eq!(
1798                escape_uri_path(expected),
1799                expected,
1800                "idempotent {expected:?}"
1801            );
1802        }
1803        // The whole marker, through the referenced-image export.
1804        let mut doc = DoclingDocument::new("t");
1805        doc.push(Node::Picture {
1806            caption: None,
1807            caption_href: None,
1808            image: Some(PictureImage {
1809                dpi: PictureImage::DEFAULT_DPI,
1810                mimetype: "image/png".into(),
1811                width: 1,
1812                height: 1,
1813                data: b"x".to_vec(),
1814            }),
1815            classification: None,
1816            description: None,
1817            caption_parent: Default::default(),
1818            caption_location: None,
1819        });
1820        let (md, files) = doc
1821            .export_to_markdown_with_images(ImageMode::Referenced, "My Report (final)_artifacts");
1822        assert!(
1823            md.contains("![Image](My%20Report%20%28final%29_artifacts/image_000000.png)"),
1824            "got:\n{md}"
1825        );
1826        // The file path handed back for writing stays unescaped.
1827        assert_eq!(files[0].0, "My Report (final)_artifacts/image_000000.png");
1828    }
1829
1830    /// Pictures the HTML backend folds into a list item print after the item
1831    /// line with plain newlines; a `<br>` newline in the item's own text is
1832    /// still a GFM hard line break.
1833    #[test]
1834    fn folded_list_item_pictures_keep_plain_newlines() {
1835        let doc = DoclingDocument::new("t");
1836        let ctx = Ctx::new(&doc, false, &MarkdownExportOptions::default());
1837        assert_eq!(
1838            list_item_text("Step\n<!-- image -->", &ctx),
1839            "Step\n<!-- image -->"
1840        );
1841        assert_eq!(
1842            list_item_text("Step\nAlt text\n<!-- image -->\n<!-- image -->", &ctx),
1843            "Step\nAlt text\n<!-- image -->\n<!-- image -->"
1844        );
1845        assert_eq!(
1846            list_item_text("line one\nline two", &ctx),
1847            "line one  \nline two"
1848        );
1849    }
1850
1851    /// docling-core#723: the header block is the leading run of rows on which a
1852    /// `column_header` cell starts, flattened per column with " - ".
1853    #[test]
1854    fn stacked_header_rows_flatten_into_one() {
1855        let mut t = Table {
1856            rows: vec![
1857                vec!["".into(), "% of Total".into(), "% of Total".into()],
1858                vec!["class".into(), "Train".into(), "Test".into()],
1859                vec!["Caption".into(), "2.04".into(), "1.77".into()],
1860            ],
1861            ..Default::default()
1862        };
1863        t.structure = Some(TableStructure {
1864            header_row: vec![true, true, false],
1865            col_continuation: vec![
1866                vec![false, false, true],
1867                vec![false, false, false],
1868                vec![false, false, false],
1869            ],
1870            ..Default::default()
1871        });
1872        assert_eq!(t.header_row_count(), 2);
1873        assert_eq!(
1874            render_table(&t, true),
1875            "| class | % of Total - Train | % of Total - Test |\n| - | - | - |\n| Caption | 2.04 | 1.77 |"
1876        );
1877        // padded: widths from the flattened header, alignment from body rows
1878        assert_eq!(
1879            render_table(&t, false),
1880            "| class   |   % of Total - Train |   % of Total - Test |\n\
1881             |---------|----------------------|---------------------|\n\
1882             | Caption |                 2.04 |                1.77 |"
1883        );
1884    }
1885
1886    /// A header spanning two rows is repeated into the second row by the grid;
1887    /// that row is not a header row unless another header cell starts there.
1888    #[test]
1889    fn vertically_spanning_header_does_not_extend_the_block() {
1890        let mut t = Table {
1891            rows: vec![
1892                vec!["Name".into(), "Value".into()],
1893                vec!["Name".into(), "1".into()],
1894                vec!["x".into(), "2".into()],
1895            ],
1896            ..Default::default()
1897        };
1898        t.structure = Some(TableStructure {
1899            col_header: vec![vec![true, true], vec![true, false], vec![false, false]],
1900            row_continuation: vec![vec![false, false], vec![true, false], vec![false, false]],
1901            ..Default::default()
1902        });
1903        assert_eq!(t.header_row_count(), 1);
1904        assert_eq!(
1905            render_table(&t, true),
1906            "| Name | Value |\n| - | - |\n| Name | 1 |\n| x | 2 |"
1907        );
1908    }
1909
1910    /// Flags that begin on a later row promote nothing: every row stays in the
1911    /// body under an empty header row (tabulate's `headers=["", ""]`).
1912    #[test]
1913    fn header_flags_not_on_row_zero_keep_all_rows_in_the_body() {
1914        let mut t = Table {
1915            rows: vec![
1916                vec!["1".into(), "2".into()],
1917                vec!["a".into(), "b".into()],
1918                vec!["333".into(), "4".into()],
1919            ],
1920            ..Default::default()
1921        };
1922        t.structure = Some(TableStructure {
1923            header_row: vec![false, true, false],
1924            ..Default::default()
1925        });
1926        assert_eq!(t.header_row_count(), 0);
1927        assert_eq!(
1928            render_table(&t, false),
1929            "|     |    |\n|-----|----|\n| 1   | 2  |\n| a   | b  |\n| 333 | 4  |"
1930        );
1931    }
1932
1933    /// A pivot table's row headers (`<th rowspan>`) carry `row_header`, not
1934    /// `column_header` (docling#4216), so the data row beside them is not
1935    /// pulled into the header block — what this port used to reach with a
1936    /// deviation now falls out of the flags themselves.
1937    #[test]
1938    fn pivot_row_headers_do_not_extend_the_header() {
1939        let mut t = Table {
1940            rows: vec![
1941                vec!["Year".into(), "Month".into()],
1942                vec!["2025".into(), "January".into()],
1943                vec!["2025".into(), "February".into()],
1944            ],
1945            ..Default::default()
1946        };
1947        t.structure = Some(TableStructure {
1948            col_header: vec![vec![true, true], vec![false, false], vec![false, false]],
1949            row_header: vec![vec![false, false], vec![true, false], vec![true, false]],
1950            row_continuation: vec![vec![false, false], vec![false, false], vec![true, false]],
1951            ..Default::default()
1952        });
1953        assert_eq!(t.header_row_count(), 1);
1954        assert_eq!(
1955            render_table(&t, true),
1956            "| Year | Month |\n| - | - |\n| 2025 | January |\n| 2025 | February |"
1957        );
1958    }
1959
1960    /// No `column_header` anywhere (first-class cells without flags) → row 0
1961    /// stays the header, as before.
1962    #[test]
1963    fn unflagged_cells_keep_row_zero_as_header() {
1964        let mut t = Table {
1965            rows: vec![vec!["h".into()], vec!["d".into()]],
1966            ..Default::default()
1967        };
1968        t.cells = Some(
1969            [(0usize, "h"), (1, "d")]
1970                .into_iter()
1971                .map(|(r, text)| TableCell {
1972                    text: text.into(),
1973                    bbox: None,
1974                    start_row: r,
1975                    start_col: 0,
1976                    row_span: 1,
1977                    col_span: 1,
1978                    column_header: false,
1979                    row_header: false,
1980                    row_section: false,
1981                })
1982                .collect(),
1983        );
1984        assert_eq!(t.header_row_count(), 1);
1985        assert_eq!(render_table(&t, true), "| h |\n| - |\n| d |");
1986    }
1987
1988    /// A table with first-class 1×1 cells, `column_header` where `ched` says.
1989    fn flagged_table(rows: &[&[&str]], ched: impl Fn(usize, usize) -> bool) -> Table {
1990        let mut cells = Vec::new();
1991        for (r, row) in rows.iter().enumerate() {
1992            for (c, text) in row.iter().enumerate() {
1993                cells.push(TableCell {
1994                    text: (*text).into(),
1995                    bbox: None,
1996                    start_row: r,
1997                    start_col: c,
1998                    row_span: 1,
1999                    col_span: 1,
2000                    column_header: ched(r, c),
2001                    row_header: false,
2002                    row_section: false,
2003                });
2004            }
2005        }
2006        Table {
2007            rows: rows
2008                .iter()
2009                .map(|row| row.iter().map(|t| (*t).to_string()).collect())
2010                .collect(),
2011            cells: Some(cells),
2012            ..Default::default()
2013        }
2014    }
2015
2016    /// #604 (docling-core#766, 2.97): a row whose first-column label is a
2017    /// `column_header` but whose other cells carry body text stops the header
2018    /// block. Expected outputs are docling-core 2.99's, byte for byte.
2019    #[test]
2020    fn rows_with_body_text_stop_the_header_block() {
2021        // The issue's form: labels flagged on every row, a real header on top.
2022        let t = flagged_table(
2023            &[
2024                &["Item", "Q1", "Q2"],
2025                &["Sales", "10", "20"],
2026                &["Costs", "5", "7"],
2027            ],
2028            |r, c| r == 0 || c == 0,
2029        );
2030        assert_eq!(t.header_row_count(), 1);
2031        assert_eq!(
2032            render_table(&t, false),
2033            "| Item   |   Q1 |   Q2 |\n\
2034             |--------|------|------|\n\
2035             | Sales  |   10 |   20 |\n\
2036             | Costs  |    5 |    7 |"
2037        );
2038        // Labels on every row and no header row: row 0 stops, later rows are
2039        // flagged → nothing promotable, the body keeps every row.
2040        let t = flagged_table(&[&["Sales", "10", "20"], &["Costs", "5", "7"]], |_, c| {
2041            c == 0
2042        });
2043        assert_eq!(t.header_row_count(), 0);
2044        assert_eq!(
2045            render_table(&t, false),
2046            "|       |    |    |\n\
2047             |-------|----|----|\n\
2048             | Sales | 10 | 20 |\n\
2049             | Costs |  5 |  7 |"
2050        );
2051        let t = flagged_table(
2052            &[&["a", "1", "2"], &["b", "3", "4"], &["c", "5", "6"]],
2053            |r, c| c == 0 && r < 2,
2054        );
2055        assert_eq!(t.header_row_count(), 0);
2056        // Row 0 stops on its body text, but no later row carries a flag:
2057        // row 0 is the header anyway, as for an unflagged table.
2058        let t = flagged_table(&[&["a", "1", "2"], &["b", "3", "4"]], |r, c| {
2059            r == 0 && c == 0
2060        });
2061        assert_eq!(t.header_row_count(), 1);
2062        assert_eq!(
2063            render_table(&t, false),
2064            "| a   |   1 |   2 |\n\
2065             |-----|-----|-----|\n\
2066             | b   |   3 |   4 |"
2067        );
2068        // Blank cells beside a flagged label are not body text.
2069        let t = flagged_table(&[&["Item", "", ""], &["x", "1", "2"]], |_, c| c == 0);
2070        assert_eq!(t.header_row_count(), 1);
2071        assert_eq!(
2072            render_table(&t, false),
2073            "| Item   |    |    |\n\
2074             |--------|----|----|\n\
2075             | x      |  1 |  2 |"
2076        );
2077    }
2078
2079    #[test]
2080    fn renders_compact_table() {
2081        let mut doc = DoclingDocument::new("t");
2082        // The compact form is opt-in (the PDF backend sets it); default output uses
2083        // the padded GitHub serializer (covered by the regression fixtures).
2084        doc.compact_tables = true;
2085        doc.push(Node::Table(Table {
2086            rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
2087            location: None,
2088            structure: None,
2089            cell_blocks: None,
2090            cells: None,
2091            caption: None,
2092            caption_parent: Default::default(),
2093            caption_location: None,
2094        }));
2095        let md = doc.export_to_markdown();
2096        assert_eq!(md, "| a | b |\n| - | - |\n| 1 | 2 |\n");
2097    }
2098
2099    #[test]
2100    fn renders_padded_github_table_by_default() {
2101        let mut doc = DoclingDocument::new("t");
2102        doc.push(Node::Table(Table {
2103            rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
2104            location: None,
2105            structure: None,
2106            cell_blocks: None,
2107            cells: None,
2108            caption: None,
2109            caption_parent: Default::default(),
2110            caption_location: None,
2111        }));
2112        let md = doc.export_to_markdown();
2113        // Numeric data columns are right-aligned; columns padded to header+2.
2114        assert_eq!(md, "|   a |   b |\n|-----|-----|\n|   1 |   2 |\n");
2115    }
2116
2117    #[test]
2118    fn strict_unescapes_inline_underscores_legacy_keeps_them() {
2119        let mut doc = DoclingDocument::new("t");
2120        doc.add_heading(1, "a\\_b");
2121        doc.add_paragraph("x\\_y");
2122        doc.push(Node::ListItem {
2123            ordered: false,
2124            number: 1,
2125            first_in_list: true,
2126            text: "i\\_j".into(),
2127            level: 0,
2128            marker: None,
2129            location: None,
2130            dclx: None,
2131            href: None,
2132            layer: None,
2133        });
2134        // Legacy reproduces docling's `\_` escaping byte-for-byte.
2135        assert_eq!(doc.export_to_markdown(), "# a\\_b\n\nx\\_y\n\n- i\\_j\n");
2136        // Strict prefers literal underscores (Rust-only readability mode).
2137        assert_eq!(doc.export_to_markdown_with(true), "# a_b\n\nx_y\n\n- i_j\n");
2138    }
2139
2140    /// Drive a document's nodes through [`MarkdownStreamer`] in the given page
2141    /// splits and assert the concatenated chunks equal the buffered serializer.
2142    fn assert_stream_matches(
2143        doc: &DoclingDocument,
2144        strict: bool,
2145        images: ImageMode,
2146        splits: &[usize],
2147    ) {
2148        let (want, want_artifacts) = to_markdown_images(doc, strict, images, "artifacts");
2149        let mut streamer =
2150            MarkdownStreamer::with_artifacts(strict, images, doc.compact_tables, "artifacts")
2151                .with_page_break_placeholder(doc.page_break_placeholder.clone());
2152        let mut got = String::new();
2153        let mut got_artifacts = Vec::new();
2154        let mut start = 0;
2155        for &end in splits {
2156            // Links only matter in strict mode; feed them all with the first batch
2157            // that has content (document order is preserved by the queue).
2158            let links = if start == 0 {
2159                doc.links.as_slice()
2160            } else {
2161                &[]
2162            };
2163            got.push_str(&streamer.push(&doc.nodes[start..end], links));
2164            // Referenced mode: drain per push, as a real caller writing files
2165            // page by page would — numbering must continue across drains.
2166            got_artifacts.extend(streamer.take_artifacts());
2167            start = end;
2168        }
2169        got.push_str(&streamer.push(
2170            &doc.nodes[start..],
2171            if start == 0 {
2172                doc.links.as_slice()
2173            } else {
2174                &[]
2175            },
2176        ));
2177        got_artifacts.extend(streamer.take_artifacts());
2178        got.push_str(&streamer.finish());
2179        assert_eq!(
2180            got, want,
2181            "streamed output diverged (splits={splits:?}, strict={strict})"
2182        );
2183        assert_eq!(
2184            got_artifacts, want_artifacts,
2185            "streamed artifacts diverged (splits={splits:?}, strict={strict})"
2186        );
2187    }
2188
2189    #[test]
2190    fn streaming_is_byte_identical_to_buffered() {
2191        let mut doc = DoclingDocument::new("d");
2192        doc.add_heading(1, "Title");
2193        doc.add_paragraph("First paragraph.");
2194        doc.push(Node::ListItem {
2195            ordered: false,
2196            number: 1,
2197            first_in_list: true,
2198            text: "a".into(),
2199            level: 0,
2200            marker: None,
2201            location: None,
2202            dclx: None,
2203            href: None,
2204            layer: None,
2205        });
2206        doc.push(Node::ListItem {
2207            ordered: false,
2208            number: 2,
2209            first_in_list: false,
2210            text: "b".into(),
2211            level: 0,
2212            marker: None,
2213            location: None,
2214            dclx: None,
2215            href: None,
2216            layer: None,
2217        });
2218        doc.push(Node::Code {
2219            language: Some("rust".into()),
2220            text: "let x = 1;".into(),
2221            orig: None,
2222            pretty: None,
2223        });
2224        doc.push(Node::Table(Table {
2225            rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
2226            location: None,
2227            structure: None,
2228            cell_blocks: None,
2229            cells: None,
2230            caption: None,
2231            caption_parent: Default::default(),
2232            caption_location: None,
2233        }));
2234        doc.push(Node::Picture {
2235            caption: Some("Fig 1".into()),
2236            caption_href: None,
2237            image: Some(PictureImage {
2238                dpi: PictureImage::DEFAULT_DPI,
2239                mimetype: "image/png".into(),
2240                width: 2,
2241                height: 2,
2242                data: b"png-one".to_vec(),
2243            }),
2244            classification: None,
2245            description: None,
2246            caption_parent: Default::default(),
2247            caption_location: None,
2248        });
2249        doc.add_paragraph("Last paragraph.");
2250        // A second embedded picture, so referenced mode must keep numbering
2251        // (`image_000001`) across chunk boundaries.
2252        doc.push(Node::Picture {
2253            caption: None,
2254            caption_href: None,
2255            image: Some(PictureImage {
2256                dpi: PictureImage::DEFAULT_DPI,
2257                mimetype: "image/png".into(),
2258                width: 2,
2259                height: 2,
2260                data: b"png-two".to_vec(),
2261            }),
2262            classification: None,
2263            description: None,
2264            caption_parent: Default::default(),
2265            caption_location: None,
2266        });
2267
2268        // A run of list items must never straddle a split, so try splits that fall
2269        // on safe block boundaries (the streaming PDF assembler guarantees this).
2270        for &strict in &[false, true] {
2271            for &images in &[
2272                ImageMode::Placeholder,
2273                ImageMode::Embedded,
2274                ImageMode::Referenced,
2275            ] {
2276                for splits in [&[][..], &[1][..], &[2][..], &[4][..], &[1, 4, 6, 7][..]] {
2277                    assert_stream_matches(&doc, strict, images, splits);
2278                }
2279            }
2280        }
2281    }
2282
2283    #[test]
2284    fn streaming_applies_recovered_links_in_strict_mode() {
2285        let mut doc = DoclingDocument::new("d");
2286        doc.add_paragraph("See LinkedIn for details.");
2287        doc.add_paragraph("And GitHub too.");
2288        doc.links = vec![
2289            ("LinkedIn".into(), "https://lnkd/".into()),
2290            ("GitHub".into(), "https://gh/".into()),
2291        ];
2292        // The second anchor lives in the second block, so it must be carried across
2293        // the page boundary and placed when that block streams out.
2294        assert_stream_matches(&doc, true, ImageMode::Placeholder, &[1]);
2295    }
2296
2297    /// A three-page document with one empty page in the middle and page
2298    /// markers of both kinds, as the backends emit them.
2299    fn paged_doc() -> DoclingDocument {
2300        let mut doc = DoclingDocument::new("p");
2301        doc.push(Node::PageInfo {
2302            page_no: 1,
2303            width: 100.0,
2304            height: 100.0,
2305        });
2306        doc.add_heading(1, "Title");
2307        doc.add_paragraph("Page one.");
2308        // Page two: a marker plus furniture only — renders nothing.
2309        doc.push(Node::PageBreak);
2310        doc.push(Node::PageInfo {
2311            page_no: 2,
2312            width: 100.0,
2313            height: 100.0,
2314        });
2315        doc.push(Node::PageFurniture {
2316            footer: true,
2317            location: [0, 500, 511, 511],
2318            text: "2".into(),
2319        });
2320        doc.push(Node::PageBreak);
2321        doc.push(Node::PageInfo {
2322            page_no: 3,
2323            width: 100.0,
2324            height: 100.0,
2325        });
2326        doc.add_paragraph("Page three.");
2327        // A trailing boundary with nothing after it.
2328        doc.push(Node::PageBreak);
2329        doc
2330    }
2331
2332    #[test]
2333    fn page_break_placeholder_lands_between_pages_only() {
2334        let mut doc = paged_doc();
2335        // Off by default: docling's Markdown carries no page breaks.
2336        assert_eq!(
2337            doc.export_to_markdown(),
2338            "# Title\n\nPage one.\n\nPage three.\n"
2339        );
2340        doc.page_break_placeholder = Some("<!-- page break -->".into());
2341        // One break for the 1→3 transition (the empty page 2 and the doubled
2342        // PageBreak+PageInfo markers collapse), none before the first block,
2343        // none for the trailing boundary.
2344        assert_eq!(
2345            doc.export_to_markdown(),
2346            "# Title\n\nPage one.\n\n<!-- page break -->\n\nPage three.\n"
2347        );
2348        // An empty placeholder is still a (blank) part, as upstream's
2349        // `str.replace(marker, "")` leaves the delimiters around it.
2350        doc.page_break_placeholder = Some(String::new());
2351        assert_eq!(
2352            doc.export_to_markdown(),
2353            "# Title\n\nPage one.\n\n\n\nPage three.\n"
2354        );
2355    }
2356
2357    #[test]
2358    fn page_break_placeholder_never_leads_a_single_page() {
2359        let mut doc = DoclingDocument::new("one");
2360        doc.page_break_placeholder = Some("---".into());
2361        doc.push(Node::PageBreak);
2362        doc.push(Node::PageInfo {
2363            page_no: 1,
2364            width: 10.0,
2365            height: 10.0,
2366        });
2367        doc.add_paragraph("Only page.");
2368        assert_eq!(doc.export_to_markdown(), "Only page.\n");
2369        // Two boundaries with no content between them: still one break.
2370        doc.push(Node::PageBreak);
2371        doc.push(Node::PageBreak);
2372        doc.add_paragraph("Next.");
2373        assert_eq!(doc.export_to_markdown(), "Only page.\n\n---\n\nNext.\n");
2374    }
2375
2376    #[test]
2377    fn page_break_placeholder_streams_byte_identical() {
2378        let mut doc = paged_doc();
2379        doc.page_break_placeholder = Some("<!-- page break -->".into());
2380        // Split at every page marker (how the PDF pipeline pushes page batches)
2381        // and at odd places inside a page: the pending break must survive a
2382        // push that renders nothing (page two) and land on page three's block.
2383        for splits in [
2384            &[3usize][..],
2385            &[3, 6],
2386            &[3, 6, 8],
2387            &[1, 2, 3, 4, 5, 6, 7, 8, 9],
2388            &[8],
2389        ] {
2390            assert_stream_matches(&doc, false, ImageMode::Placeholder, splits);
2391            assert_stream_matches(&doc, true, ImageMode::Placeholder, splits);
2392        }
2393    }
2394
2395    #[test]
2396    fn strict_tightens_punctuation_spacing_legacy_keeps_it() {
2397        let mut doc = DoclingDocument::new("t");
2398        doc.add_paragraph("see [ 37 , 36 ] and ( x ) .");
2399        // Legacy keeps docling's spacing byte-for-byte.
2400        assert_eq!(doc.export_to_markdown(), "see [ 37 , 36 ] and ( x ) .\n");
2401        // Strict tightens punctuation for readable Markdown.
2402        assert_eq!(doc.export_to_markdown_with(true), "see [37, 36] and (x).\n");
2403    }
2404
2405    // ----- MarkdownExportOptions (#599) ------------------------------------
2406
2407    /// A document touching every option: furniture, a comment, a hidden
2408    /// sheet group, a picture with nested text, escaped text.
2409    fn options_doc() -> DoclingDocument {
2410        use crate::document::ContentLayer;
2411        let mut doc = DoclingDocument::new("opts");
2412        doc.push(Node::PageFurniture {
2413            footer: false,
2414            location: [0, 0, 0, 0],
2415            text: "FAX COVER \\_ R&amp;D".into(),
2416        });
2417        doc.add_heading(1, "R&amp;D \\_ report");
2418        doc.add_paragraph("Body a\\_b &lt;tag&gt;");
2419        doc.push(Node::Picture {
2420            caption: Some("Figure 1".into()),
2421            caption_href: None,
2422            image: None,
2423            classification: None,
2424            description: None,
2425            caption_parent: Default::default(),
2426            caption_location: None,
2427        });
2428        doc.push(Node::PictureChildren(vec![
2429            Node::Paragraph {
2430                text: "Field: Name".into(),
2431            },
2432            Node::Paragraph {
2433                text: "Field: Date".into(),
2434            },
2435        ]));
2436        doc.push(Node::CommentSection {
2437            name: "comment-1".into(),
2438            text: "[author: A]: note".into(),
2439            refs_note_text: false,
2440            grouped: true,
2441        });
2442        doc.push(Node::Group {
2443            label: "section".into(),
2444            name: Some("sheet: Hidden".into()),
2445            layer: Some(ContentLayer::Invisible),
2446            children: vec![Node::Paragraph {
2447                text: "hidden cell".into(),
2448            }],
2449        });
2450        doc.push(Node::Furniture {
2451            layer: ContentLayer::Furniture,
2452            inner: Box::new(Node::Paragraph {
2453                text: "Page 1 of 2".into(),
2454            }),
2455        });
2456        doc.push(Node::FurnitureText {
2457            label: "page_footer".into(),
2458            text: "footer line".into(),
2459        });
2460        doc
2461    }
2462
2463    /// The defaults are docling's: the options export is the plain export,
2464    /// byte for byte — and the plain export is unchanged (furniture, notes,
2465    /// hidden sheets and picture children out; escaping kept).
2466    #[test]
2467    fn default_options_are_the_default_export() {
2468        let doc = options_doc();
2469        let plain = doc.export_to_markdown();
2470        assert_eq!(
2471            plain,
2472            "# R&amp;D \\_ report\n\nBody a\\_b &lt;tag&gt;\n\nFigure 1\n\n<!-- image -->\n"
2473        );
2474        let (with_default, artifacts) =
2475            doc.export_to_markdown_with_options(&MarkdownExportOptions::default());
2476        assert_eq!(with_default, plain);
2477        assert!(artifacts.is_empty());
2478    }
2479
2480    #[test]
2481    fn layers_render_furniture_notes_and_hidden_sheets() {
2482        use crate::document::ContentLayer;
2483        let doc = options_doc();
2484        let md = |layers: ContentLayers| {
2485            doc.export_to_markdown_with_options(&MarkdownExportOptions {
2486                layers,
2487                ..MarkdownExportOptions::default()
2488            })
2489            .0
2490        };
2491        assert_eq!(
2492            md(ContentLayers::BODY.with(ContentLayer::Furniture)),
2493            "FAX COVER \\_ R&amp;D\n\n# R&amp;D \\_ report\n\nBody a\\_b &lt;tag&gt;\n\nFigure 1\n\n<!-- image -->\n\nPage 1 of 2\n\nfooter line\n",
2494            "a page header, a furniture-wrapped paragraph and a furniture text item render as paragraphs"
2495        );
2496        assert_eq!(
2497            md(ContentLayers::BODY.with(ContentLayer::Notes)),
2498            "# R&amp;D \\_ report\n\nBody a\\_b &lt;tag&gt;\n\nFigure 1\n\n<!-- image -->\n\n[author: A]: note\n"
2499        );
2500        assert_eq!(
2501            md(ContentLayers::BODY.with(ContentLayer::Invisible)),
2502            "# R&amp;D \\_ report\n\nBody a\\_b &lt;tag&gt;\n\nFigure 1\n\n<!-- image -->\n\nhidden cell\n",
2503            "a hidden sheet's items sit on the sheet's layer"
2504        );
2505        assert_eq!(
2506            md(ContentLayers::NONE.with(ContentLayer::Furniture)),
2507            "FAX COVER \\_ R&amp;D\n\nPage 1 of 2\n\nfooter line\n",
2508            "without the body layer only the furniture prints"
2509        );
2510        assert_eq!(md(ContentLayers::NONE), "");
2511        assert_eq!(
2512            md(ContentLayers::ALL),
2513            "FAX COVER \\_ R&amp;D\n\n# R&amp;D \\_ report\n\nBody a\\_b &lt;tag&gt;\n\nFigure 1\n\n<!-- image -->\n\n[author: A]: note\n\nhidden cell\n\nPage 1 of 2\n\nfooter line\n"
2514        );
2515    }
2516
2517    /// A list item carries its own layer: a furniture list renders with the
2518    /// furniture layer and stays out of the body export.
2519    #[test]
2520    fn layers_apply_to_list_items() {
2521        use crate::document::ContentLayer;
2522        let mut doc = DoclingDocument::new("lists");
2523        doc.push(Node::ListItem {
2524            ordered: false,
2525            number: 1,
2526            first_in_list: true,
2527            text: "nav link".into(),
2528            level: 0,
2529            marker: None,
2530            location: None,
2531            dclx: None,
2532            href: None,
2533            layer: Some(ContentLayer::Furniture),
2534        });
2535        doc.add_paragraph("body");
2536        assert_eq!(doc.export_to_markdown(), "body\n");
2537        let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2538            layers: ContentLayers::BODY.with(ContentLayer::Furniture),
2539            ..MarkdownExportOptions::default()
2540        });
2541        assert_eq!(md, "- nav link\n\nbody\n");
2542    }
2543
2544    #[test]
2545    fn traverse_pictures_prints_the_nested_text_after_the_picture() {
2546        let doc = options_doc();
2547        let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2548            traverse_pictures: true,
2549            ..MarkdownExportOptions::default()
2550        });
2551        assert_eq!(
2552            md,
2553            "# R&amp;D \\_ report\n\nBody a\\_b &lt;tag&gt;\n\nFigure 1\n\n<!-- image -->\n\nField: Name\n\nField: Date\n"
2554        );
2555    }
2556
2557    #[test]
2558    fn escaping_can_be_turned_off_per_kind() {
2559        let doc = options_doc();
2560        let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2561            escape_html: false,
2562            ..MarkdownExportOptions::default()
2563        });
2564        assert_eq!(
2565            md,
2566            "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n"
2567        );
2568        let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2569            escape_underscores: false,
2570            ..MarkdownExportOptions::default()
2571        });
2572        assert_eq!(
2573            md,
2574            "# R&amp;D _ report\n\nBody a_b &lt;tag&gt;\n\nFigure 1\n\n<!-- image -->\n"
2575        );
2576        // Code and table cells are never touched (upstream leaves them
2577        // unescaped too, so nothing was escaped there to undo).
2578        let mut doc = DoclingDocument::new("code");
2579        doc.push(Node::Code {
2580            language: None,
2581            text: "a &amp; b \\_ c".into(),
2582            orig: None,
2583            pretty: None,
2584        });
2585        let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2586            escape_html: false,
2587            escape_underscores: false,
2588            ..MarkdownExportOptions::default()
2589        });
2590        assert_eq!(md, "```\na &amp; b \\_ c\n```\n");
2591    }
2592
2593    #[test]
2594    fn image_placeholder_is_configurable() {
2595        let doc = options_doc();
2596        let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2597            image_placeholder: "[figure]".into(),
2598            ..MarkdownExportOptions::default()
2599        });
2600        assert!(md.contains("Figure 1\n\n[figure]\n"), "{md}");
2601        assert!(!md.contains("<!-- image -->"));
2602    }
2603
2604    /// #605: an empty `image_placeholder` prints nothing — no empty block, so
2605    /// no extra blank lines — while the page-break scan still counts the
2606    /// picture as an item. Every expectation is docling-core 2.99's own
2607    /// `export_to_markdown(image_placeholder="", page_break_placeholder=…)`
2608    /// (plus the trailing newline this port always writes).
2609    #[test]
2610    fn empty_image_placeholder_prints_nothing() {
2611        fn picture(caption: Option<&str>) -> Node {
2612            Node::Picture {
2613                caption: caption.map(Into::into),
2614                caption_href: None,
2615                image: None,
2616                classification: None,
2617                description: None,
2618                caption_parent: Default::default(),
2619                caption_location: None,
2620            }
2621        }
2622        fn page(no: usize) -> Node {
2623            Node::PageInfo {
2624                page_no: no,
2625                width: 100.0,
2626                height: 100.0,
2627            }
2628        }
2629        fn para(text: &str) -> Node {
2630            Node::Paragraph { text: text.into() }
2631        }
2632        let options = MarkdownExportOptions {
2633            image_placeholder: String::new(),
2634            ..MarkdownExportOptions::default()
2635        };
2636        // (nodes, page-break placeholder, expected)
2637        let cases: Vec<(Vec<Node>, Option<&str>, &str)> = vec![
2638            (
2639                vec![page(1), para("a"), picture(None), para("b")],
2640                None,
2641                "a\n\nb\n",
2642            ),
2643            (
2644                vec![page(1), para("a"), picture(Some("Figure 1")), para("b")],
2645                None,
2646                "a\n\nFigure 1\n\nb\n",
2647            ),
2648            (
2649                vec![
2650                    page(1),
2651                    para("a"),
2652                    page(2),
2653                    picture(None),
2654                    page(3),
2655                    para("b"),
2656                ],
2657                Some("<!-- pb -->"),
2658                "a\n\n<!-- pb -->\n\n<!-- pb -->\n\nb\n",
2659            ),
2660            (
2661                vec![
2662                    page(1),
2663                    para("a"),
2664                    page(2),
2665                    picture(None),
2666                    page(3),
2667                    para("b"),
2668                ],
2669                Some(""),
2670                "a\n\n\n\n\n\nb\n",
2671            ),
2672            (
2673                vec![page(1), picture(None), page(2), para("b")],
2674                Some("<!-- pb -->"),
2675                "<!-- pb -->\n\nb\n",
2676            ),
2677            (
2678                vec![page(1), picture(None), page(2), para("b")],
2679                Some(""),
2680                "\n\nb\n",
2681            ),
2682            (
2683                vec![page(1), para("a"), page(2), picture(None)],
2684                Some("<!-- pb -->"),
2685                "a\n\n<!-- pb -->\n",
2686            ),
2687        ];
2688        for (nodes, placeholder, expected) in cases {
2689            let mut doc = DoclingDocument::new("t");
2690            doc.page_break_placeholder = placeholder.map(Into::into);
2691            for node in nodes {
2692                doc.push(node);
2693            }
2694            let (md, _) = doc.export_to_markdown_with_options(&options);
2695            assert_eq!(md, expected, "page break {placeholder:?}");
2696            // The streamer agrees at every chunking, one node per push
2697            // included — an all-empty push still owes the next page break.
2698            for size in 1..=doc.nodes.len() {
2699                let mut streamer = MarkdownStreamer::new(false, ImageMode::Placeholder, false)
2700                    .with_export_options(&options)
2701                    .with_page_break_placeholder(placeholder.map(Into::into));
2702                let mut out = String::new();
2703                for chunk in doc.nodes.chunks(size) {
2704                    out.push_str(&streamer.push(chunk, &[]));
2705                }
2706                out.push_str(&streamer.finish());
2707                assert_eq!(
2708                    out, expected,
2709                    "chunks of {size}, page break {placeholder:?}"
2710                );
2711            }
2712        }
2713        // The default placeholder is untouched.
2714        let mut doc = DoclingDocument::new("t");
2715        doc.push(para("a"));
2716        doc.push(picture(None));
2717        doc.push(para("b"));
2718        assert_eq!(doc.export_to_markdown(), "a\n\n<!-- image -->\n\nb\n");
2719    }
2720
2721    /// The streamer takes the same options and its chunks concatenate to the
2722    /// buffered export.
2723    #[test]
2724    fn streamer_matches_buffered_export_with_options() {
2725        let doc = options_doc();
2726        let options = MarkdownExportOptions {
2727            layers: ContentLayers::ALL,
2728            traverse_pictures: true,
2729            escape_html: false,
2730            escape_underscores: false,
2731            image_placeholder: "(img)".into(),
2732            ..MarkdownExportOptions::default()
2733        };
2734        let (buffered, _) = doc.export_to_markdown_with_options(&options);
2735        let mut streamer = MarkdownStreamer::new(false, ImageMode::Placeholder, false)
2736            .with_export_options(&options);
2737        let mut out = String::new();
2738        for chunk in doc.nodes.chunks(2) {
2739            out.push_str(&streamer.push(chunk, &[]));
2740        }
2741        out.push_str(&streamer.finish());
2742        assert_eq!(out, buffered);
2743        assert!(
2744            buffered.contains("(img)") && buffered.contains("R&D _ report"),
2745            "{buffered}"
2746        );
2747    }
2748
2749    /// #613: the plain export of a document holding every decoration the
2750    /// Markdown export writes, and the streamer agreeing with it.
2751    #[test]
2752    fn plain_text_drops_the_markdown_decoration() {
2753        let item = |text: &str, ordered: bool, number: u64, level: u8| Node::ListItem {
2754            ordered,
2755            number,
2756            first_in_list: number == 1 && level == 0,
2757            text: text.into(),
2758            level,
2759            marker: None,
2760            location: None,
2761            dclx: None,
2762            href: None,
2763            layer: None,
2764        };
2765        let mut doc = DoclingDocument::new("plain");
2766        doc.add_heading(1, "Title with **bold**");
2767        doc.add_heading(2, "Section");
2768        doc.add_paragraph("Some **bold**, *italic*, ~~gone~~ and `code` with a [link](https://x.org).\nNext line.");
2769        doc.push(item("*one*", false, 1, 0));
2770        doc.push(item("[two](https://y.org)", false, 2, 0));
2771        doc.push(item("nested", true, 1, 1));
2772        doc.push(Node::CheckboxItem {
2773            checked: true,
2774            text: "done".into(),
2775        });
2776        doc.push(Node::Code {
2777            language: Some("rust".into()),
2778            text: "let x = **y**;".into(),
2779            orig: None,
2780            pretty: None,
2781        });
2782        doc.push(Node::Picture {
2783            caption: Some("Figure *1*".into()),
2784            caption_href: None,
2785            image: None,
2786            classification: None,
2787            description: None,
2788            caption_parent: Default::default(),
2789            caption_location: None,
2790        });
2791        doc.push(Node::Caption {
2792            text: "Linked caption".into(),
2793            href: Some("https://z.org".into()),
2794        });
2795        doc.push(Node::Table(Table {
2796            rows: vec![
2797                vec!["**n**".into(), "rich".into()],
2798                vec!["**2**".into(), "a  \nb".into()],
2799            ],
2800            ..Default::default()
2801        }));
2802        doc.add_paragraph("R&amp;D \\_ x");
2803        let text = doc.export_to_text();
2804        assert_eq!(
2805            text,
2806            "Title with bold\n\n\
2807             Section\n\n\
2808             Some bold, italic, gone and code with a link.\nNext line.\n\n\
2809             - one\n- two\n    1. nested\n\n\
2810             - [x] done\n\n\
2811             let x = **y**;\n\n\
2812             Figure 1\n\n\
2813             Linked caption\n\n\
2814             |   n | rich   |\n\
2815             |-----|--------|\n\
2816             |   2 | a b    |\n\n\
2817             R&D _ x"
2818        );
2819
2820        let options = MarkdownExportOptions::plain_text();
2821        let (buffered, _) = doc.export_to_markdown_with_options(&options);
2822        assert_eq!(buffered, format!("{text}\n"));
2823        let mut streamer = MarkdownStreamer::new(false, ImageMode::Placeholder, false)
2824            .with_export_options(&options);
2825        let mut out = String::new();
2826        for chunk in doc.nodes.chunks(3) {
2827            out.push_str(&streamer.push(chunk, &[]));
2828        }
2829        out.push_str(&streamer.finish());
2830        assert_eq!(out, buffered);
2831    }
2832
2833    /// #613: text that only looks like Markdown stays as it is.
2834    #[test]
2835    fn plain_inline_keeps_literal_markers() {
2836        for (input, want) in [
2837            ("**bold** and *it* and ***both***", "bold and it and both"),
2838            ("**[label](https://a.b/c_(d))** end", "label end"),
2839            (
2840                "grant *USE and *OBJMGT authority",
2841                "grant *USE and *OBJMGT authority",
2842            ),
2843            ("2 * 3 * 4", "2 * 3 * 4"),
2844            ("a ** b", "a ** b"),
2845            ("the `quoted’ and `x` term", "the `quoted’ and x term"),
2846            ("see [12] and [docs](u)", "see [12] and docs"),
2847            ("formula $[a](b)$ stays", "formula $[a](b)$ stays"),
2848            ("price $5 and **bold**", "price $5 and bold"),
2849            ("[outer [inner] text](u)", "outer [inner] text"),
2850            ("unclosed **bold", "unclosed **bold"),
2851        ] {
2852            assert_eq!(plain_inline(input), want, "{input}");
2853        }
2854    }
2855}