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 { .. } | Node::ListText { .. }) => 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        if let Node::ListText { level, text, glue } = item {
846            let text = ctx.text(text);
847            match lines.last_mut() {
848                Some(last) if *glue => last.push_str(&text),
849                _ => lines.push(format!("{}{text}", "    ".repeat(*level as usize))),
850            }
851            continue;
852        }
853        let Node::ListItem {
854            ordered,
855            number,
856            first_in_list,
857            text,
858            level,
859            marker: orig_marker,
860            location: _,
861            dclx: _,
862            href: _,
863            layer,
864        } = item
865        else {
866            continue;
867        };
868        // docling's content-layer filtering: an item renders when its layer
869        // — its own, else the layer of the group it sits in — is in the set
870        // (body only by default, so a furniture list item is omitted).
871        if !ctx.layers.contains(layer.or(ctx.current_layer)) {
872            continue;
873        }
874        let level = *level as usize;
875
876        // A new sibling list at the top level gets a blank line — and only the
877        // backend knows where one starts (`first_in_list`: Word's `numId`
878        // changing, an HTML `<ul>` closing, a Markdown bullet switching
879        // `-`→`*`). The serializer used to guess it from a kind flip or a
880        // number gap as well, which split lists docling keeps whole (an
881        // AsciiDoc `1.` … `5.`, mixed `*`/`1.` markers) — #385. Only at the
882        // top level: nested sibling groups are children of a list item, and
883        // docling joins an item's children without blank lines.
884        if level == 0 {
885            if any_top && *first_in_list {
886                lines.push(String::new());
887            }
888            any_top = true;
889        }
890
891        let indent = "    ".repeat(level);
892        // docling-core's `case_already_valid`: a marker of digits and a dot
893        // prints verbatim — Python's `\d+\.` admits every Unicode decimal
894        // digit, so a DOCX `decimalFullWidth` marker (`1.`, docling#4336)
895        // is kept as it is rather than renumbered in ASCII.
896        let verbatim = orig_marker.as_deref().filter(|m| {
897            m.strip_suffix('.')
898                .is_some_and(|d| !d.is_empty() && d.chars().all(char::is_numeric))
899        });
900        let marker = match verbatim {
901            Some(m) if *ordered => m.to_string(),
902            _ if *ordered => format!("{number}."),
903            _ => "-".to_string(),
904        };
905        lines.push(format!("{indent}{marker} {}", list_item_text(text, ctx)));
906    }
907
908    // A run consisting only of furniture (content-layer-filtered) items yields no
909    // lines; pushing an empty block here would surface as a stray blank line.
910    if !lines.is_empty() {
911        blocks.push(lines.join("\n"));
912    }
913}
914
915/// A list item's Markdown body. The GFM hard-line-break rule (docling-core#721)
916/// applies to the item's own text; pictures the HTML backend folded into the
917/// item (`"\n[alt\n]<!-- image -->"` per `<img>` inside the `<li>`) are
918/// docling's picture *children* of the item, which its serializer prints after
919/// the item line with plain newlines — so a folded tail keeps its newlines
920/// unmarked. The tail is recognised structurally: every line after the first is
921/// an image marker or an alt caption directly followed by one.
922fn list_item_text(text: &str, ctx: &Ctx) -> String {
923    let escaped = ctx.text(text);
924    if ctx.plain {
925        return escaped;
926    }
927    if let Some((own, tail)) = escaped.split_once('\n') {
928        if is_folded_child_tail(tail) {
929            return format!("{}\n{tail}", md_line_breaks(own));
930        }
931    }
932    md_line_breaks(&escaped)
933}
934
935/// Whether everything after a list item's own first line is a folded *child*
936/// block rather than a continuation of the item's text: an image marker
937/// (optionally preceded by its caption/alt line) or a fenced code block. The
938/// AsciiDoc backend indents such a block to the item's own depth (as
939/// docling-core's list serializer does for each part it emits), so a leading
940/// indent is ignored here.
941fn is_folded_child_tail(tail: &str) -> bool {
942    const MARKER: &str = "<!-- image -->";
943    const FENCE: &str = "```";
944    let mut lines = tail.split('\n').peekable();
945    let mut any = false;
946    while let Some(line) = lines.next() {
947        let line = line.trim_start();
948        if line == MARKER {
949            any = true;
950        } else if line == FENCE {
951            // Skip the block's body; an unclosed fence is not a folded child.
952            loop {
953                match lines.next() {
954                    Some(l) if l.trim_start() == FENCE => break,
955                    Some(_) => {}
956                    None => return false,
957                }
958            }
959            any = true;
960        } else if lines.next().map(str::trim_start) == Some(MARKER) {
961            any = true; // an alt caption line, then its marker
962        } else {
963            return false;
964        }
965    }
966    any
967}
968
969/// Render one item: docling's content-layer gate first — an item whose layer
970/// (the group's or wrapper's it sits in, else the body) is outside the set
971/// renders nothing, while a container still walks its children — then the
972/// item itself.
973fn render_one(node: &Node, blocks: &mut Vec<String>, ctx: &mut Ctx) {
974    match node {
975        // Containers and layer wrappers decide for their children.
976        Node::Group { .. }
977        | Node::Furniture { .. }
978        | Node::PageFurniture { .. }
979        | Node::FurnitureText { .. }
980        | Node::CommentSection { .. }
981        | Node::PictureChildren(_)
982        | Node::Commented { .. }
983        | Node::Located { .. }
984        | Node::Prov { .. }
985        | Node::Track { .. }
986        | Node::PageBreak
987        | Node::PageInfo { .. }
988        | Node::DoclangOnly(_) => {}
989        _ if !ctx.layer_visible() => return,
990        _ => {}
991    }
992    render_item(node, blocks, ctx)
993}
994
995fn render_item(node: &Node, blocks: &mut Vec<String>, ctx: &mut Ctx) {
996    match node {
997        Node::Heading { level, text } => {
998            if ctx.plain {
999                // `PlainTextTextSerializer`: the heading's text as it is —
1000                // no `#`, its newlines kept.
1001                blocks.push(ctx.text(text));
1002                return;
1003            }
1004            let text = heading_line_breaks(&ctx.text(text));
1005            if ctx.in_table_cell {
1006                // docling-core#540: no `#` markers inside a table cell.
1007                blocks.push(text);
1008            } else {
1009                let hashes = "#".repeat((*level).clamp(1, 6) as usize);
1010                blocks.push(format!("{hashes} {text}"));
1011            }
1012        }
1013        // An empty body paragraph (docling's blank-line text item) contributes
1014        // nothing to Markdown — only DocLang/JSON keep it.
1015        Node::Paragraph { text } if text.is_empty() => {}
1016        Node::Paragraph { text } => blocks.push(ctx.breaks(&ctx.text(text))),
1017        Node::LabeledText { .. } => render_item(&node.labeled_as_paragraph(), blocks, ctx),
1018        // A standalone caption item renders like a text item; its hyperlink
1019        // annotation becomes a Markdown link around the whole caption.
1020        Node::Caption { text, .. } if text.is_empty() => {}
1021        Node::Caption { text, href } => {
1022            let body = ctx.breaks(&ctx.text(text));
1023            blocks.push(match href {
1024                Some(url) if !ctx.plain => format!("[{body}]({url})"),
1025                _ => body,
1026            });
1027        }
1028        Node::CheckboxItem { checked, text } => {
1029            let mark = if *checked { "- [x] " } else { "- [ ] " };
1030            blocks.push(ctx.breaks(&ctx.text(&format!("{mark}{text}"))));
1031        }
1032        Node::Code {
1033            language,
1034            text,
1035            pretty,
1036            ..
1037        } => {
1038            // Legacy docling never emits a language on the fence; strict keeps it.
1039            let lang = match language {
1040                Some(l) if ctx.strict => l.as_str(),
1041                _ => "",
1042            };
1043            // Strict prefers the line-preserving rendering when the backend
1044            // supplied one (PDF); legacy stays on docling's flat `text`.
1045            let body = match pretty {
1046                Some(p) if ctx.strict => p.as_str(),
1047                _ => text.as_str(),
1048            };
1049            // The plain export (`format_code_blocks=False`) prints the code
1050            // as it is.
1051            blocks.push(if ctx.plain {
1052                body.to_string()
1053            } else {
1054                format!("```{lang}\n{body}\n```")
1055            });
1056        }
1057        // A CodeFormula-decoded display formula renders as docling's `$$…$$`
1058        // (the un-enriched pipeline emits a placeholder paragraph instead).
1059        Node::Formula { latex, .. } => blocks.push(format!("$${latex}$$")),
1060        Node::Table(table) => {
1061            // docling renders a table's caption as a text line before the grid.
1062            // `caption` is already escaped (backend convention), like a paragraph.
1063            if let Some(cap) = &table.caption {
1064                if !cap.is_empty() {
1065                    blocks.push(ctx.text(cap));
1066                }
1067            }
1068            let rendered = if ctx.plain {
1069                render_table(&ctx.plain_table(table), ctx.compact_tables)
1070            } else {
1071                render_table(table, ctx.compact_tables)
1072            };
1073            if !rendered.is_empty() {
1074                blocks.push(rendered);
1075            }
1076        }
1077        // Classification predictions don't affect docling's Markdown output;
1078        // a description (the picture-OCR text, #645) prints between the
1079        // caption and the image placeholder — docling's
1080        // `MarkdownPictureSerializer` order: captions, annotations, image.
1081        // Alt text (#676) is rendered only under strict Markdown or the
1082        // document's `picture_alt_text`, and then where Markdown puts it: as
1083        // the `![alt](…)` of an image line, or — with the placeholder, which
1084        // has no alt slot — as the line a description takes.
1085        Node::Picture {
1086            caption,
1087            image,
1088            description,
1089            ..
1090        } => {
1091            if let Some(cap) = caption {
1092                if !cap.is_empty() {
1093                    blocks.push(ctx.caption(cap));
1094                }
1095            }
1096            let alt = description
1097                .as_ref()
1098                .filter(|d| d.is_alt_text() && ctx.alt_text && !d.text.is_empty());
1099            let marker = picture_marker(image.as_ref(), ctx, alt.map(|d| d.text.as_str()));
1100            if let Some(desc) = description {
1101                let shown = !desc.is_alt_text() || (ctx.alt_text && !marker.starts_with("!["));
1102                if !desc.text.is_empty() && shown {
1103                    blocks.push(ctx.breaks(&ctx.text(&desc.text)));
1104                }
1105            }
1106            blocks.push(marker);
1107        }
1108        // A chart renders as docling's picture-with-meta markdown: the caption,
1109        // the placeholder, the humanized classification ("line_chart" ->
1110        // "Line chart"), then the chart's data grid as a regular table.
1111        Node::Chart {
1112            kind,
1113            table,
1114            caption,
1115            ..
1116        } => {
1117            if let Some(cap) = caption {
1118                if !cap.is_empty() {
1119                    blocks.push(ctx.caption(cap));
1120                }
1121            }
1122            blocks.push(picture_marker(None, ctx, None));
1123            blocks.push(humanize_label(kind));
1124            let rendered = if ctx.plain {
1125                render_table(&ctx.plain_table(table), false)
1126            } else {
1127                render_table(table, false)
1128            };
1129            if !rendered.is_empty() {
1130                blocks.push(rendered);
1131            }
1132        }
1133        // A DocLang-only node is omitted from Markdown.
1134        Node::DoclangOnly(_) => {}
1135        // A group on a non-body layer (a hidden spreadsheet sheet): its items
1136        // sit on that layer, as every item of such a sheet does upstream — so
1137        // they render exactly when the set includes it (#599), nothing by
1138        // default.
1139        Node::Group {
1140            layer: Some(layer),
1141            children,
1142            ..
1143        } => {
1144            let outer = ctx.current_layer.replace(*layer);
1145            render(children, blocks, ctx);
1146            ctx.current_layer = outer;
1147        }
1148        Node::Group { children, .. } => render(children, blocks, ctx),
1149        Node::FieldRegion { items } => {
1150            // The region container and each field item carry no text of their
1151            // own; docling-core 2.93 (#724) serializes them to nothing (older
1152            // releases emitted a `<!-- missing-text -->` marker for each), so
1153            // only an item's marker/key/value appear, as separate paragraphs.
1154            for item in items {
1155                for part in [&item.marker, &item.key, &item.value].into_iter().flatten() {
1156                    blocks.push(ctx.breaks(&ctx.text(part)));
1157                }
1158            }
1159        }
1160        // docling's Markdown serializer has no component for a `KeyValueItem`
1161        // and writes its fallback placeholder in the item's place.
1162        Node::KeyValueGraph { .. } => blocks.push(MISSING_KEY_VALUE_ITEM.to_string()),
1163        // A rich inline group renders exactly like a paragraph of its Markdown
1164        // text — the structured runs are DocLang-only.
1165        Node::InlineGroup { md_text, .. } => blocks.push(ctx.breaks(&ctx.text(md_text))),
1166        // A plain-text backend dump renders verbatim as a single block.
1167        Node::TextDump(text) => {
1168            if !text.is_empty() {
1169                blocks.push(text.clone());
1170            }
1171        }
1172        // Furniture (page headers/footers, HTML `<title>`, notes) is out of
1173        // the default body-only export, mirroring docling; a set that
1174        // includes its layer renders the wrapped item like a body item (#599).
1175        Node::Furniture { layer, inner } => {
1176            let outer = ctx.current_layer.replace(*layer);
1177            render_one(inner, blocks, ctx);
1178            ctx.current_layer = outer;
1179        }
1180        // A page header/footer or a `.doc` furniture paragraph: upstream's
1181        // `page_header` / `page_footer` / `footnote` text item, a plain
1182        // paragraph when the furniture layer renders.
1183        Node::PageFurniture { text, .. } | Node::FurnitureText { text, .. } => {
1184            if ctx.layers.furniture && !text.is_empty() {
1185                blocks.push(ctx.breaks(&ctx.text(text)));
1186            }
1187        }
1188        // A picture's contained text: docling's Markdown picture serializer
1189        // prints the caption and the image, never the children — unless the
1190        // export traverses pictures, when the item walk yields them after
1191        // the picture and they render as the text items they are (#599).
1192        Node::PictureChildren(children) => {
1193            if ctx.traverse_pictures {
1194                render(children, blocks, ctx);
1195            }
1196        }
1197        // A comment lives in the notes layer — out like other furniture
1198        // unless that layer renders (the note's `[author: …]: text` as a
1199        // paragraph); the annotation on a body item is JSON-only, so render
1200        // the item.
1201        Node::CommentSection { text, .. } => {
1202            if ctx.layers.notes && !text.is_empty() {
1203                blocks.push(ctx.breaks(&ctx.text(text)));
1204            }
1205        }
1206        Node::Commented { inner, .. } => render_one(inner, blocks, ctx),
1207        // Layout provenance is DocLang-only; render the wrapped node.
1208        Node::Located { inner, .. } | Node::Prov { inner, .. } | Node::Track { inner, .. } => {
1209            render_one(inner, blocks, ctx)
1210        }
1211        // Page breaks are DocLang-only; docling omits them from Markdown.
1212        Node::PageBreak => {}
1213        // Page markers feed the JSON export only.
1214        Node::PageInfo { .. } => {}
1215        // Runs of adjacent list items are merged by `render`; a stray single
1216        // item (a hand-built document, or a `Located` wrapper around one)
1217        // still renders as its own one-item list instead of panicking —
1218        // `nodes` is public API, so every representable tree must serialize.
1219        Node::ListItem { .. } => render_list_run(std::slice::from_ref(node), blocks, ctx),
1220        // Outside a list run (a hand-built document): a paragraph.
1221        Node::ListText { text, .. } if text.is_empty() => {}
1222        Node::ListText { text, .. } => blocks.push(ctx.breaks(&ctx.text(text))),
1223    }
1224}
1225
1226/// The Markdown for a picture under the active [`ImageMode`]; Referenced mode also
1227/// records the bytes in `ctx.artifacts` for the caller to write.
1228/// docling-core's `_humanize_text`: underscores to spaces, first letter
1229/// capitalized ("line_chart" -> "Line chart").
1230fn humanize_label(label: &str) -> String {
1231    let text = label.replace('_', " ");
1232    let mut chars = text.chars();
1233    match chars.next() {
1234        Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
1235        None => text,
1236    }
1237}
1238
1239/// The image line's alt: docling's `Image`, or the picture's alt text (#676)
1240/// on one line with its `]` escaped, so it cannot close the bracket.
1241fn image_alt(alt: Option<&str>) -> String {
1242    match alt {
1243        Some(text) => text
1244            .split_whitespace()
1245            .collect::<Vec<_>>()
1246            .join(" ")
1247            .replace('\\', "\\\\")
1248            .replace(']', "\\]"),
1249        None => "Image".to_string(),
1250    }
1251}
1252
1253fn picture_marker(image: Option<&crate::PictureImage>, ctx: &mut Ctx, alt: Option<&str>) -> String {
1254    match (ctx.images, image) {
1255        // docling embeds the `ImageRef`'s PNG (a JPEG re-encoded).
1256        (ImageMode::Embedded, Some(img)) => {
1257            format!(
1258                "![{}]({})",
1259                image_alt(alt),
1260                crate::pixel_digest::docling_data_uri(img).1
1261            )
1262        }
1263        (ImageMode::Referenced, Some(img)) => {
1264            let path = format!(
1265                "{}/image_{:06}.{}",
1266                ctx.artifacts_dir,
1267                ctx.pic_index,
1268                ext_for(&img.mimetype)
1269            );
1270            ctx.pic_index += 1;
1271            ctx.artifacts.push((path.clone(), img.data.clone()));
1272            format!("![{}]({})", image_alt(alt), escape_uri_path(&path))
1273        }
1274        // Placeholder, or any mode with no extracted image.
1275        _ => ctx.image_placeholder.clone(),
1276    }
1277}
1278
1279/// Encode a URL or filesystem path as a Markdown link destination —
1280/// docling-core's `MarkdownPictureSerializer._escape_uri_path`
1281/// (docling-core#698, 2.94). Handles URLs of any scheme as well as POSIX and
1282/// Windows paths, keeps relative paths relative and never double-encodes:
1283/// backslashes become `/` (a backslash is both the Windows separator and a
1284/// Markdown escape), a UNC share `//host/…` and an absolute Windows path
1285/// `C:/…` become RFC 8089 `file://` URLs (the one spelling a renderer cannot
1286/// misread as a scheme-relative URL or a `C:` scheme), a URL keeps its
1287/// scheme / authority / delimiters with only the components encoded, and
1288/// everything else is percent-encoded as a path. `%` is kept so an
1289/// already-encoded destination stays as it is; spaces and parentheses are
1290/// encoded because they would end (or unbalance) a Markdown inline link.
1291pub(crate) fn escape_uri_path(value: &str) -> String {
1292    const KEEP: &str = "/%:@+,;=~$!&'*";
1293    let s = value.replace('\\', "/");
1294    if let Some(rest) = s.strip_prefix("//") {
1295        // A fileshare: `file://<host>/<path>`, the host possibly empty.
1296        let rest = rest.trim_start_matches('/');
1297        let (host, tail) = rest.split_once('/').unwrap_or((rest, ""));
1298        return format!("file://{host}{}", percent_quote(&format!("/{tail}"), KEEP));
1299    }
1300    let bytes = s.as_bytes();
1301    if bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && bytes[2] == b'/' {
1302        // A Windows path with a drive letter: `file:///C:/…`.
1303        return format!("file:///{}", percent_quote(&s, KEEP));
1304    }
1305    // A URL keeps its scheme, authority and delimiters; only its components are
1306    // encoded. A single-character scheme cannot be real (it is a drive letter,
1307    // handled above), so it is read as a path — like `urlsplit`.
1308    if let Some((scheme, rest)) = s.split_once(':') {
1309        let valid_scheme = scheme.len() > 1
1310            && scheme.as_bytes()[0].is_ascii_alphabetic()
1311            && scheme
1312                .bytes()
1313                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'));
1314        if valid_scheme {
1315            let (authority, rest) = match rest.strip_prefix("//") {
1316                Some(r) => {
1317                    let end = r.find(['/', '?', '#']).unwrap_or(r.len());
1318                    (Some(&r[..end]), &r[end..])
1319                }
1320                None => (None, rest),
1321            };
1322            let (before_frag, fragment) = rest.split_once('#').unwrap_or((rest, ""));
1323            let (path, query) = before_frag.split_once('?').unwrap_or((before_frag, ""));
1324            let mut out = format!("{scheme}:");
1325            if let Some(a) = authority {
1326                out.push_str("//");
1327                out.push_str(a);
1328            }
1329            out.push_str(&percent_quote(path, KEEP));
1330            if !query.is_empty() {
1331                out.push('?');
1332                out.push_str(&percent_quote(query, KEEP));
1333            }
1334            if !fragment.is_empty() {
1335                out.push('#');
1336                out.push_str(&percent_quote(fragment, KEEP));
1337            }
1338            return out;
1339        }
1340    }
1341    // A relative or root-relative local path.
1342    percent_quote(&s, KEEP)
1343}
1344
1345/// `urllib.parse.quote(s, safe)`: unreserved ASCII (`A–Z a–z 0–9 _ . - ~`) and
1346/// the `safe` set stay, every other byte of the UTF-8 encoding becomes `%XX`.
1347fn percent_quote(s: &str, safe: &str) -> String {
1348    let mut out = String::with_capacity(s.len());
1349    for &b in s.as_bytes() {
1350        let keep = b.is_ascii_alphanumeric()
1351            || matches!(b, b'_' | b'.' | b'-' | b'~')
1352            || (b.is_ascii() && safe.contains(b as char));
1353        if keep {
1354            out.push(b as char);
1355        } else {
1356            out.push_str(&format!("%{b:02X}"));
1357        }
1358    }
1359    out
1360}
1361
1362pub(crate) fn ext_for(mimetype: &str) -> &str {
1363    match mimetype {
1364        "image/jpeg" => "jpg",
1365        "image/gif" => "gif",
1366        "image/webp" => "webp",
1367        "image/bmp" => "bmp",
1368        "image/tiff" => "tif",
1369        _ => "png",
1370    }
1371}
1372
1373/// Render a table. `compact` selects between two serializers:
1374///
1375/// - **padded** (default) — docling-core's `tabulate(tablefmt="github")`: columns
1376///   are padded to a fixed width (header width + a minimum padding of 2, or the
1377///   widest data cell); numeric columns (every data cell parses as a number) are
1378///   right-aligned, others left-aligned; separators are plain dashes of
1379///   `width + 2`. Matches current published docling (DOCX/HTML conformance).
1380/// - **compact** — `| a | b |` cells with single-dash `| - | - |` separators, no
1381///   width padding. Matches the committed PDF groundtruth corpus, which predates
1382///   the padded serializer.
1383///
1384/// Each cell is first escaped (`\n` → space, `|` → `&#124;`) so it can't break the
1385/// table. The header row is the table's leading `column_header` block flattened
1386/// to one row ([`Table::header_row_count`] + [`flatten_header_rows`],
1387/// docling-core#723); alignment and widths are computed over the body rows.
1388/// Whether a table cell counts as a number for column alignment, matching
1389/// `tabulate`'s detection: an ordinary float/int (`f64`-parseable, covering
1390/// `1e2`/`inf`/`+1.5`) **or** a thousands-separated number like `7,015`.
1391fn is_number_cell(t: &str) -> bool {
1392    t.parse::<f64>().is_ok() || is_thousands_number(t)
1393}
1394
1395/// A number with comma thousands-separators, per `tabulate`'s
1396/// `_float_with_thousands_separators` regex
1397/// (`^(([+-]?[0-9]{1,3})(?:,([0-9]{3}))*)?(?(1)\.[0-9]*|\.[0-9]+)?$`): the
1398/// integer part is 1–3 digits then any number of `,ddd` groups; the fraction is
1399/// optional (and, without an integer part, must have at least one digit).
1400fn is_thousands_number(t: &str) -> bool {
1401    let b = t.as_bytes();
1402    let mut i = 0;
1403    let start = i;
1404    if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
1405        i += 1;
1406    }
1407    // First digit chunk: 1–3 digits.
1408    let d0 = i;
1409    while i < b.len() && b[i].is_ascii_digit() && i - d0 < 3 {
1410        i += 1;
1411    }
1412    let has_int = i > d0;
1413    if has_int {
1414        // Subsequent `,ddd` groups (exactly three digits each).
1415        while i + 3 < b.len() + 1
1416            && b.get(i) == Some(&b',')
1417            && b.get(i + 1).is_some_and(u8::is_ascii_digit)
1418            && b.get(i + 2).is_some_and(u8::is_ascii_digit)
1419            && b.get(i + 3).is_some_and(u8::is_ascii_digit)
1420        {
1421            i += 4;
1422        }
1423    } else {
1424        // A sign only counts with an integer part.
1425        i = start;
1426    }
1427    // Optional fraction.
1428    if i < b.len() && b[i] == b'.' {
1429        i += 1;
1430        let f0 = i;
1431        while i < b.len() && b[i].is_ascii_digit() {
1432            i += 1;
1433        }
1434        if !has_int && i == f0 {
1435            return false; // `.` with no digits and no integer part
1436        }
1437    } else if !has_int {
1438        return false; // neither integer nor fractional part
1439    }
1440    i == b.len()
1441}
1442
1443/// The single GFM header row for a table: the leading header rows (see
1444/// [`Table::header_row_count`]) flattened per column, texts joined with
1445/// `" - "` after dropping consecutive duplicates — docling-core's
1446/// `_flatten_header_rows` (docling-core#723). The duplicate rule is what
1447/// keeps a row-spanning header from being joined to itself (the grid repeats
1448/// its text into every row it covers); it is position-based, so two stacked
1449/// levels sharing a label collapse too — GFM has one header row, and upstream
1450/// accepts that loss. No header rows → one empty header cell per column.
1451fn flatten_header_rows(header_rows: &[Vec<String>], num_cols: usize) -> Vec<String> {
1452    (0..num_cols)
1453        .map(|c| {
1454            let mut parts: Vec<&str> = Vec::new();
1455            for row in header_rows {
1456                let text = row.get(c).map(String::as_str).unwrap_or("");
1457                if !text.is_empty() && parts.last() != Some(&text) {
1458                    parts.push(text);
1459                }
1460            }
1461            parts.join(" - ")
1462        })
1463        .collect()
1464}
1465
1466pub(crate) fn render_table(table: &Table, compact: bool) -> String {
1467    if table.rows.is_empty() {
1468        return String::new();
1469    }
1470    let num_cols = table.rows.iter().map(Vec::len).max().unwrap_or(0);
1471    if num_cols == 0 {
1472        return String::new();
1473    }
1474
1475    // Escaped, rectangular grid (ragged rows padded with empty cells). The
1476    // header block is resolved to the one row GFM allows (docling-core#723);
1477    // `tabulate` strips data cells of surrounding whitespace but leaves the
1478    // header texts as-is.
1479    let num_headers = table.header_row_count().min(table.rows.len());
1480    let escaped = |r: usize| -> Vec<String> {
1481        (0..num_cols)
1482            .map(|c| escape_cell(table.rows[r].get(c).map(String::as_str).unwrap_or("")))
1483            .collect()
1484    };
1485    let header_rows: Vec<Vec<String>> = (0..num_headers).map(escaped).collect();
1486    let header = flatten_header_rows(&header_rows, num_cols);
1487    let body: Vec<Vec<String>> = (num_headers..table.rows.len())
1488        .map(|r| {
1489            escaped(r)
1490                .into_iter()
1491                .map(|c| c.trim().to_string())
1492                .collect()
1493        })
1494        .collect();
1495
1496    if compact {
1497        // Compact: cells joined by " | ", no padding, single-dash separators.
1498        let render_row = |row: &[String]| -> String { format!("| {} |", row.join(" | ")) };
1499        let mut lines = Vec::with_capacity(body.len() + 2);
1500        lines.push(render_row(&header));
1501        let sep: Vec<&str> = (0..num_cols).map(|_| "-").collect();
1502        lines.push(format!("| {} |", sep.join(" | ")));
1503        for row in &body {
1504            lines.push(render_row(row));
1505        }
1506        return lines.join("\n");
1507    }
1508
1509    // Display width (Unicode scalar count — good enough for now).
1510    let dw = |s: &str| s.chars().count();
1511
1512    // A column is right-aligned when at least one body cell is numeric and every
1513    // non-empty body cell is numeric — matching `tabulate`'s column typing, where
1514    // empty cells are "missing" (ignored) and a number may carry thousands
1515    // separators (`7,015`), which a plain `f64` parse rejects.
1516    let right: Vec<bool> = (0..num_cols)
1517        .map(|c| {
1518            let mut any = false;
1519            for row in &body {
1520                let t = row[c].trim();
1521                if t.is_empty() {
1522                    continue;
1523                }
1524                if !is_number_cell(t) {
1525                    return false;
1526                }
1527                any = true;
1528            }
1529            any
1530        })
1531        .collect();
1532
1533    // Column width = max(header_width + MIN_PADDING(2), max body-cell width).
1534    let width: Vec<usize> = (0..num_cols)
1535        .map(|c| {
1536            let mut w = dw(&header[c]) + 2;
1537            for row in &body {
1538                w = w.max(dw(&row[c]));
1539            }
1540            w
1541        })
1542        .collect();
1543
1544    let fmt_cell = |s: &str, c: usize| -> String {
1545        let pad = " ".repeat(width[c].saturating_sub(dw(s)));
1546        let body = if right[c] {
1547            format!("{pad}{s}")
1548        } else {
1549            format!("{s}{pad}")
1550        };
1551        format!(" {body} ")
1552    };
1553    let render_row = |row: &[String]| -> String {
1554        let cells: Vec<String> = (0..num_cols).map(|c| fmt_cell(&row[c], c)).collect();
1555        format!("|{}|", cells.join("|"))
1556    };
1557
1558    let mut lines = Vec::with_capacity(body.len() + 2);
1559    lines.push(render_row(&header));
1560    let sep: Vec<String> = (0..num_cols).map(|c| "-".repeat(width[c] + 2)).collect();
1561    lines.push(format!("|{}|", sep.join("|")));
1562    for row in &body {
1563        lines.push(render_row(row));
1564    }
1565    lines.join("\n")
1566}
1567
1568/// Escape a table cell so it can't break the markdown table: newlines become
1569/// spaces and pipes become the `&#124;` HTML entity (matches docling-core).
1570fn escape_cell(s: &str) -> String {
1571    s.replace('\n', " ").replace('|', "&#124;")
1572}
1573
1574#[cfg(test)]
1575mod tests {
1576    use super::*;
1577    use crate::{PictureImage, TableCell, TableStructure};
1578
1579    /// #385: where one list ends and the next begins is the backend's call
1580    /// (`first_in_list`), never the serializer's. An ordered run `1.` → `5.`
1581    /// is one list (an AsciiDoc numbered list around a nested one), and so are
1582    /// mixed bullet/ordered items the backend did not separate; only a flagged
1583    /// item opens a new list and earns the blank line.
1584    #[test]
1585    fn list_boundaries_come_from_the_backend_not_the_numbering() {
1586        let item = |ordered: bool, number: u64, first_in_list: bool, text: &str| Node::ListItem {
1587            ordered,
1588            number,
1589            first_in_list,
1590            text: text.into(),
1591            level: 0,
1592            marker: None,
1593            location: None,
1594            dclx: None,
1595            href: None,
1596            layer: None,
1597        };
1598        let md = |items: Vec<Node>| {
1599            let mut doc = DoclingDocument::new("t");
1600            for n in items {
1601                doc.push(n);
1602            }
1603            doc.export_to_markdown()
1604        };
1605        // A number gap alone is not a boundary.
1606        assert_eq!(
1607            md(vec![
1608                item(true, 1, true, "one"),
1609                item(true, 5, false, "five")
1610            ]),
1611            "1. one\n5. five\n"
1612        );
1613        // Nor is a kind flip the backend did not flag …
1614        assert_eq!(
1615            md(vec![
1616                item(false, 0, true, "bullet"),
1617                item(true, 1, false, "one"),
1618                item(false, 0, false, "bullet two"),
1619            ]),
1620            "- bullet\n1. one\n- bullet two\n"
1621        );
1622        // … while a flagged item is one, whatever its number says.
1623        assert_eq!(
1624            md(vec![
1625                item(true, 1, true, "a"),
1626                item(true, 2, false, "b"),
1627                item(true, 3, true, "new list, continuing count"),
1628            ]),
1629            "1. a\n2. b\n\n3. new list, continuing count\n"
1630        );
1631    }
1632
1633    #[test]
1634    fn renders_headings_paragraphs_and_lists() {
1635        let mut doc = DoclingDocument::new("demo");
1636        doc.add_heading(1, "Title");
1637        doc.add_paragraph("Hello world.");
1638        doc.push(Node::ListItem {
1639            ordered: false,
1640            number: 1,
1641            first_in_list: true,
1642            text: "first".into(),
1643            level: 0,
1644            marker: None,
1645            location: None,
1646            dclx: None,
1647            href: None,
1648            layer: None,
1649        });
1650        doc.push(Node::ListItem {
1651            ordered: false,
1652            number: 2,
1653            first_in_list: false,
1654            text: "second".into(),
1655            level: 0,
1656            marker: None,
1657            location: None,
1658            dclx: None,
1659            href: None,
1660            layer: None,
1661        });
1662        let md = doc.export_to_markdown();
1663        assert_eq!(md, "# Title\n\nHello world.\n\n- first\n- second\n");
1664    }
1665
1666    /// docling-core 2.92 (#721): a single newline inside an item's text is a
1667    /// GFM hard line break, a blank line stays a paragraph break, and a heading
1668    /// collapses its newline to a space. Nested-table dumps stay verbatim.
1669    #[test]
1670    fn single_newlines_become_gfm_hard_line_breaks() {
1671        let mut doc = DoclingDocument::new("t");
1672        doc.push(Node::Heading {
1673            level: 1,
1674            text: "Hello\nWorld".into(),
1675        });
1676        doc.push(Node::Paragraph {
1677            text: "line one\nline two\n\npara two".into(),
1678        });
1679        doc.push(Node::ListItem {
1680            ordered: false,
1681            number: 1,
1682            first_in_list: true,
1683            text: "item\ncontinued".into(),
1684            level: 0,
1685            marker: None,
1686            location: None,
1687            dclx: None,
1688            href: None,
1689            layer: None,
1690        });
1691        doc.push(Node::TextDump("A1 B1 \n\n\nC1".into()));
1692        assert_eq!(
1693            doc.export_to_markdown(),
1694            "# Hello World\n\nline one  \nline two\n\npara two\n\n- item  \ncontinued\n\nA1 B1 \n\n\nC1\n"
1695        );
1696    }
1697
1698    /// docling-core#540: inside a rich table cell a heading is plain text;
1699    /// docling-core#724: a field region renders only its items' key/value text.
1700    #[test]
1701    fn table_cell_mode_and_field_regions() {
1702        let mut doc = DoclingDocument::new("t");
1703        doc.push(Node::Heading {
1704            level: 2,
1705            text: "A  text".into(),
1706        });
1707        doc.push(Node::Paragraph {
1708            text: "body".into(),
1709        });
1710        assert_eq!(to_markdown_table_cell(&doc, false), "A  text\n\nbody");
1711        assert_eq!(doc.export_to_markdown(), "## A  text\n\nbody\n");
1712
1713        let mut doc = DoclingDocument::new("f");
1714        doc.push(Node::FieldRegion {
1715            items: vec![crate::FieldItem {
1716                marker: None,
1717                key: Some("Name:".into()),
1718                value: Some("John Doe".into()),
1719                value_kind: None,
1720            }],
1721        });
1722        assert_eq!(doc.export_to_markdown(), "Name:\n\nJohn Doe\n");
1723    }
1724
1725    #[test]
1726    fn strict_renders_recovered_links_legacy_does_not() {
1727        let mut doc = DoclingDocument::new("cv");
1728        doc.add_paragraph("Find me on LinkedIn or GitHub.");
1729        doc.links = vec![
1730            ("LinkedIn".into(), "https://www.linkedin.com/in/x/".into()),
1731            ("GitHub".into(), "https://github.com/x/".into()),
1732        ];
1733        // Legacy/docling mode: links are left untouched (conformance preserved).
1734        assert_eq!(doc.export_to_markdown(), "Find me on LinkedIn or GitHub.\n");
1735        // Strict mode: anchors become Markdown links.
1736        assert_eq!(
1737            doc.export_to_markdown_with(true),
1738            "Find me on [LinkedIn](https://www.linkedin.com/in/x/) or [GitHub](https://github.com/x/).\n"
1739        );
1740    }
1741
1742    #[test]
1743    fn strict_links_match_escaped_anchor_and_consume_in_order() {
1744        let mut doc = DoclingDocument::new("d");
1745        // The PDF assembler HTML-escapes prose, so by serialization time the body
1746        // already carries `&amp;`; the anchor is stored un-escaped. The matcher must
1747        // escape the anchor to find it. Two identical anchors link in document order.
1748        doc.add_paragraph("AI &amp; ML here, and issues here, then issues there.");
1749        doc.links = vec![
1750            ("AI & ML".into(), "https://a/".into()),
1751            ("issues".into(), "https://first/".into()),
1752            ("issues".into(), "https://second/".into()),
1753        ];
1754        assert_eq!(
1755            doc.export_to_markdown_with(true),
1756            "[AI &amp; ML](https://a/) here, and [issues](https://first/) here, then [issues](https://second/) there.\n"
1757        );
1758    }
1759
1760    /// docling-core#698: the referenced-image destination is percent-encoded —
1761    /// upstream's own case table (paths, Windows flavours, UNC, URLs) plus
1762    /// idempotency on the encoded result.
1763    #[test]
1764    fn referenced_image_destinations_are_escaped() {
1765        let cases = [
1766            (
1767                "doc_artifacts/image_000001_ab12.png",
1768                "doc_artifacts/image_000001_ab12.png",
1769            ),
1770            (
1771                "My Report_artifacts/img.png",
1772                "My%20Report_artifacts/img.png",
1773            ),
1774            ("artifacts/img (1).png", "artifacts/img%20%281%29.png"),
1775            ("100%_scale/a#b?c.png", "100%_scale/a%23b%3Fc.png"),
1776            ("/home/a b/img.png", "/home/a%20b/img.png"),
1777            (
1778                "My Report_artifacts\\img.png",
1779                "My%20Report_artifacts/img.png",
1780            ),
1781            (
1782                "C:/Users/me/My Docs/img.png",
1783                "file:///C:/Users/me/My%20Docs/img.png",
1784            ),
1785            ("C:\\Users\\me\\img.png", "file:///C:/Users/me/img.png"),
1786            (
1787                "//server/share/My Docs/img.png",
1788                "file://server/share/My%20Docs/img.png",
1789            ),
1790            ("\\\\server\\share\\img.png", "file://server/share/img.png"),
1791            ("file:///home/a b/img.png", "file:///home/a%20b/img.png"),
1792            (
1793                "s3://bucket/My Report_artifacts/img.png",
1794                "s3://bucket/My%20Report_artifacts/img.png",
1795            ),
1796            (
1797                "https://example.com:8080/a b.png?w=1&h=2#frag",
1798                "https://example.com:8080/a%20b.png?w=1&h=2#frag",
1799            ),
1800            (
1801                "https://example.com/img (1).png",
1802                "https://example.com/img%20%281%29.png",
1803            ),
1804            ("caf\u{e9}/im\u{e4}ge.png", "caf%C3%A9/im%C3%A4ge.png"),
1805        ];
1806        for (input, expected) in cases {
1807            assert_eq!(escape_uri_path(input), expected, "input {input:?}");
1808            assert_eq!(
1809                escape_uri_path(expected),
1810                expected,
1811                "idempotent {expected:?}"
1812            );
1813        }
1814        // The whole marker, through the referenced-image export.
1815        let mut doc = DoclingDocument::new("t");
1816        doc.push(Node::Picture {
1817            caption: None,
1818            caption_href: None,
1819            image: Some(PictureImage {
1820                dpi: PictureImage::DEFAULT_DPI,
1821                mimetype: "image/png".into(),
1822                width: 1,
1823                height: 1,
1824                data: b"x".to_vec(),
1825            }),
1826            classification: None,
1827            description: None,
1828            caption_parent: Default::default(),
1829            caption_location: None,
1830        });
1831        let (md, files) = doc
1832            .export_to_markdown_with_images(ImageMode::Referenced, "My Report (final)_artifacts");
1833        assert!(
1834            md.contains("![Image](My%20Report%20%28final%29_artifacts/image_000000.png)"),
1835            "got:\n{md}"
1836        );
1837        // The file path handed back for writing stays unescaped.
1838        assert_eq!(files[0].0, "My Report (final)_artifacts/image_000000.png");
1839    }
1840
1841    /// Pictures the HTML backend folds into a list item print after the item
1842    /// line with plain newlines; a `<br>` newline in the item's own text is
1843    /// still a GFM hard line break.
1844    #[test]
1845    fn folded_list_item_pictures_keep_plain_newlines() {
1846        let doc = DoclingDocument::new("t");
1847        let ctx = Ctx::new(&doc, false, &MarkdownExportOptions::default());
1848        assert_eq!(
1849            list_item_text("Step\n<!-- image -->", &ctx),
1850            "Step\n<!-- image -->"
1851        );
1852        assert_eq!(
1853            list_item_text("Step\nAlt text\n<!-- image -->\n<!-- image -->", &ctx),
1854            "Step\nAlt text\n<!-- image -->\n<!-- image -->"
1855        );
1856        assert_eq!(
1857            list_item_text("line one\nline two", &ctx),
1858            "line one  \nline two"
1859        );
1860    }
1861
1862    /// docling-core#723: the header block is the leading run of rows on which a
1863    /// `column_header` cell starts, flattened per column with " - ".
1864    #[test]
1865    fn stacked_header_rows_flatten_into_one() {
1866        let mut t = Table {
1867            rows: vec![
1868                vec!["".into(), "% of Total".into(), "% of Total".into()],
1869                vec!["class".into(), "Train".into(), "Test".into()],
1870                vec!["Caption".into(), "2.04".into(), "1.77".into()],
1871            ],
1872            ..Default::default()
1873        };
1874        t.structure = Some(TableStructure {
1875            header_row: vec![true, true, false],
1876            col_continuation: vec![
1877                vec![false, false, true],
1878                vec![false, false, false],
1879                vec![false, false, false],
1880            ],
1881            ..Default::default()
1882        });
1883        assert_eq!(t.header_row_count(), 2);
1884        assert_eq!(
1885            render_table(&t, true),
1886            "| class | % of Total - Train | % of Total - Test |\n| - | - | - |\n| Caption | 2.04 | 1.77 |"
1887        );
1888        // padded: widths from the flattened header, alignment from body rows
1889        assert_eq!(
1890            render_table(&t, false),
1891            "| class   |   % of Total - Train |   % of Total - Test |\n\
1892             |---------|----------------------|---------------------|\n\
1893             | Caption |                 2.04 |                1.77 |"
1894        );
1895    }
1896
1897    /// A header spanning two rows is repeated into the second row by the grid;
1898    /// that row is not a header row unless another header cell starts there.
1899    #[test]
1900    fn vertically_spanning_header_does_not_extend_the_block() {
1901        let mut t = Table {
1902            rows: vec![
1903                vec!["Name".into(), "Value".into()],
1904                vec!["Name".into(), "1".into()],
1905                vec!["x".into(), "2".into()],
1906            ],
1907            ..Default::default()
1908        };
1909        t.structure = Some(TableStructure {
1910            col_header: vec![vec![true, true], vec![true, false], vec![false, false]],
1911            row_continuation: vec![vec![false, false], vec![true, false], vec![false, false]],
1912            ..Default::default()
1913        });
1914        assert_eq!(t.header_row_count(), 1);
1915        assert_eq!(
1916            render_table(&t, true),
1917            "| Name | Value |\n| - | - |\n| Name | 1 |\n| x | 2 |"
1918        );
1919    }
1920
1921    /// Flags that begin on a later row promote nothing: every row stays in the
1922    /// body under an empty header row (tabulate's `headers=["", ""]`).
1923    #[test]
1924    fn header_flags_not_on_row_zero_keep_all_rows_in_the_body() {
1925        let mut t = Table {
1926            rows: vec![
1927                vec!["1".into(), "2".into()],
1928                vec!["a".into(), "b".into()],
1929                vec!["333".into(), "4".into()],
1930            ],
1931            ..Default::default()
1932        };
1933        t.structure = Some(TableStructure {
1934            header_row: vec![false, true, false],
1935            ..Default::default()
1936        });
1937        assert_eq!(t.header_row_count(), 0);
1938        assert_eq!(
1939            render_table(&t, false),
1940            "|     |    |\n|-----|----|\n| 1   | 2  |\n| a   | b  |\n| 333 | 4  |"
1941        );
1942    }
1943
1944    /// A pivot table's row headers (`<th rowspan>`) carry `row_header`, not
1945    /// `column_header` (docling#4216), so the data row beside them is not
1946    /// pulled into the header block — what this port used to reach with a
1947    /// deviation now falls out of the flags themselves.
1948    #[test]
1949    fn pivot_row_headers_do_not_extend_the_header() {
1950        let mut t = Table {
1951            rows: vec![
1952                vec!["Year".into(), "Month".into()],
1953                vec!["2025".into(), "January".into()],
1954                vec!["2025".into(), "February".into()],
1955            ],
1956            ..Default::default()
1957        };
1958        t.structure = Some(TableStructure {
1959            col_header: vec![vec![true, true], vec![false, false], vec![false, false]],
1960            row_header: vec![vec![false, false], vec![true, false], vec![true, false]],
1961            row_continuation: vec![vec![false, false], vec![false, false], vec![true, false]],
1962            ..Default::default()
1963        });
1964        assert_eq!(t.header_row_count(), 1);
1965        assert_eq!(
1966            render_table(&t, true),
1967            "| Year | Month |\n| - | - |\n| 2025 | January |\n| 2025 | February |"
1968        );
1969    }
1970
1971    /// No `column_header` anywhere (first-class cells without flags) → row 0
1972    /// stays the header, as before.
1973    #[test]
1974    fn unflagged_cells_keep_row_zero_as_header() {
1975        let mut t = Table {
1976            rows: vec![vec!["h".into()], vec!["d".into()]],
1977            ..Default::default()
1978        };
1979        t.cells = Some(
1980            [(0usize, "h"), (1, "d")]
1981                .into_iter()
1982                .map(|(r, text)| TableCell {
1983                    text: text.into(),
1984                    bbox: None,
1985                    start_row: r,
1986                    start_col: 0,
1987                    row_span: 1,
1988                    col_span: 1,
1989                    column_header: false,
1990                    row_header: false,
1991                    row_section: false,
1992                })
1993                .collect(),
1994        );
1995        assert_eq!(t.header_row_count(), 1);
1996        assert_eq!(render_table(&t, true), "| h |\n| - |\n| d |");
1997    }
1998
1999    /// A table with first-class 1×1 cells, `column_header` where `ched` says.
2000    fn flagged_table(rows: &[&[&str]], ched: impl Fn(usize, usize) -> bool) -> Table {
2001        let mut cells = Vec::new();
2002        for (r, row) in rows.iter().enumerate() {
2003            for (c, text) in row.iter().enumerate() {
2004                cells.push(TableCell {
2005                    text: (*text).into(),
2006                    bbox: None,
2007                    start_row: r,
2008                    start_col: c,
2009                    row_span: 1,
2010                    col_span: 1,
2011                    column_header: ched(r, c),
2012                    row_header: false,
2013                    row_section: false,
2014                });
2015            }
2016        }
2017        Table {
2018            rows: rows
2019                .iter()
2020                .map(|row| row.iter().map(|t| (*t).to_string()).collect())
2021                .collect(),
2022            cells: Some(cells),
2023            ..Default::default()
2024        }
2025    }
2026
2027    /// #604 (docling-core#766, 2.97): a row whose first-column label is a
2028    /// `column_header` but whose other cells carry body text stops the header
2029    /// block. Expected outputs are docling-core 2.99's, byte for byte.
2030    #[test]
2031    fn rows_with_body_text_stop_the_header_block() {
2032        // The issue's form: labels flagged on every row, a real header on top.
2033        let t = flagged_table(
2034            &[
2035                &["Item", "Q1", "Q2"],
2036                &["Sales", "10", "20"],
2037                &["Costs", "5", "7"],
2038            ],
2039            |r, c| r == 0 || c == 0,
2040        );
2041        assert_eq!(t.header_row_count(), 1);
2042        assert_eq!(
2043            render_table(&t, false),
2044            "| Item   |   Q1 |   Q2 |\n\
2045             |--------|------|------|\n\
2046             | Sales  |   10 |   20 |\n\
2047             | Costs  |    5 |    7 |"
2048        );
2049        // Labels on every row and no header row: row 0 stops, later rows are
2050        // flagged → nothing promotable, the body keeps every row.
2051        let t = flagged_table(&[&["Sales", "10", "20"], &["Costs", "5", "7"]], |_, c| {
2052            c == 0
2053        });
2054        assert_eq!(t.header_row_count(), 0);
2055        assert_eq!(
2056            render_table(&t, false),
2057            "|       |    |    |\n\
2058             |-------|----|----|\n\
2059             | Sales | 10 | 20 |\n\
2060             | Costs |  5 |  7 |"
2061        );
2062        let t = flagged_table(
2063            &[&["a", "1", "2"], &["b", "3", "4"], &["c", "5", "6"]],
2064            |r, c| c == 0 && r < 2,
2065        );
2066        assert_eq!(t.header_row_count(), 0);
2067        // Row 0 stops on its body text, but no later row carries a flag:
2068        // row 0 is the header anyway, as for an unflagged table.
2069        let t = flagged_table(&[&["a", "1", "2"], &["b", "3", "4"]], |r, c| {
2070            r == 0 && c == 0
2071        });
2072        assert_eq!(t.header_row_count(), 1);
2073        assert_eq!(
2074            render_table(&t, false),
2075            "| a   |   1 |   2 |\n\
2076             |-----|-----|-----|\n\
2077             | b   |   3 |   4 |"
2078        );
2079        // Blank cells beside a flagged label are not body text.
2080        let t = flagged_table(&[&["Item", "", ""], &["x", "1", "2"]], |_, c| c == 0);
2081        assert_eq!(t.header_row_count(), 1);
2082        assert_eq!(
2083            render_table(&t, false),
2084            "| Item   |    |    |\n\
2085             |--------|----|----|\n\
2086             | x      |  1 |  2 |"
2087        );
2088    }
2089
2090    #[test]
2091    fn renders_compact_table() {
2092        let mut doc = DoclingDocument::new("t");
2093        // The compact form is opt-in (the PDF backend sets it); default output uses
2094        // the padded GitHub serializer (covered by the regression fixtures).
2095        doc.compact_tables = true;
2096        doc.push(Node::Table(Table {
2097            rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
2098            location: None,
2099            structure: None,
2100            cell_blocks: None,
2101            cells: None,
2102            caption: None,
2103            caption_parent: Default::default(),
2104            caption_location: None,
2105        }));
2106        let md = doc.export_to_markdown();
2107        assert_eq!(md, "| a | b |\n| - | - |\n| 1 | 2 |\n");
2108    }
2109
2110    #[test]
2111    fn renders_padded_github_table_by_default() {
2112        let mut doc = DoclingDocument::new("t");
2113        doc.push(Node::Table(Table {
2114            rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
2115            location: None,
2116            structure: None,
2117            cell_blocks: None,
2118            cells: None,
2119            caption: None,
2120            caption_parent: Default::default(),
2121            caption_location: None,
2122        }));
2123        let md = doc.export_to_markdown();
2124        // Numeric data columns are right-aligned; columns padded to header+2.
2125        assert_eq!(md, "|   a |   b |\n|-----|-----|\n|   1 |   2 |\n");
2126    }
2127
2128    #[test]
2129    fn strict_unescapes_inline_underscores_legacy_keeps_them() {
2130        let mut doc = DoclingDocument::new("t");
2131        doc.add_heading(1, "a\\_b");
2132        doc.add_paragraph("x\\_y");
2133        doc.push(Node::ListItem {
2134            ordered: false,
2135            number: 1,
2136            first_in_list: true,
2137            text: "i\\_j".into(),
2138            level: 0,
2139            marker: None,
2140            location: None,
2141            dclx: None,
2142            href: None,
2143            layer: None,
2144        });
2145        // Legacy reproduces docling's `\_` escaping byte-for-byte.
2146        assert_eq!(doc.export_to_markdown(), "# a\\_b\n\nx\\_y\n\n- i\\_j\n");
2147        // Strict prefers literal underscores (Rust-only readability mode).
2148        assert_eq!(doc.export_to_markdown_with(true), "# a_b\n\nx_y\n\n- i_j\n");
2149    }
2150
2151    /// Drive a document's nodes through [`MarkdownStreamer`] in the given page
2152    /// splits and assert the concatenated chunks equal the buffered serializer.
2153    fn assert_stream_matches(
2154        doc: &DoclingDocument,
2155        strict: bool,
2156        images: ImageMode,
2157        splits: &[usize],
2158    ) {
2159        let (want, want_artifacts) = to_markdown_images(doc, strict, images, "artifacts");
2160        let mut streamer =
2161            MarkdownStreamer::with_artifacts(strict, images, doc.compact_tables, "artifacts")
2162                .with_page_break_placeholder(doc.page_break_placeholder.clone());
2163        let mut got = String::new();
2164        let mut got_artifacts = Vec::new();
2165        let mut start = 0;
2166        for &end in splits {
2167            // Links only matter in strict mode; feed them all with the first batch
2168            // that has content (document order is preserved by the queue).
2169            let links = if start == 0 {
2170                doc.links.as_slice()
2171            } else {
2172                &[]
2173            };
2174            got.push_str(&streamer.push(&doc.nodes[start..end], links));
2175            // Referenced mode: drain per push, as a real caller writing files
2176            // page by page would — numbering must continue across drains.
2177            got_artifacts.extend(streamer.take_artifacts());
2178            start = end;
2179        }
2180        got.push_str(&streamer.push(
2181            &doc.nodes[start..],
2182            if start == 0 {
2183                doc.links.as_slice()
2184            } else {
2185                &[]
2186            },
2187        ));
2188        got_artifacts.extend(streamer.take_artifacts());
2189        got.push_str(&streamer.finish());
2190        assert_eq!(
2191            got, want,
2192            "streamed output diverged (splits={splits:?}, strict={strict})"
2193        );
2194        assert_eq!(
2195            got_artifacts, want_artifacts,
2196            "streamed artifacts diverged (splits={splits:?}, strict={strict})"
2197        );
2198    }
2199
2200    #[test]
2201    fn streaming_is_byte_identical_to_buffered() {
2202        let mut doc = DoclingDocument::new("d");
2203        doc.add_heading(1, "Title");
2204        doc.add_paragraph("First paragraph.");
2205        doc.push(Node::ListItem {
2206            ordered: false,
2207            number: 1,
2208            first_in_list: true,
2209            text: "a".into(),
2210            level: 0,
2211            marker: None,
2212            location: None,
2213            dclx: None,
2214            href: None,
2215            layer: None,
2216        });
2217        doc.push(Node::ListItem {
2218            ordered: false,
2219            number: 2,
2220            first_in_list: false,
2221            text: "b".into(),
2222            level: 0,
2223            marker: None,
2224            location: None,
2225            dclx: None,
2226            href: None,
2227            layer: None,
2228        });
2229        doc.push(Node::Code {
2230            language: Some("rust".into()),
2231            text: "let x = 1;".into(),
2232            orig: None,
2233            pretty: None,
2234        });
2235        doc.push(Node::Table(Table {
2236            rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
2237            location: None,
2238            structure: None,
2239            cell_blocks: None,
2240            cells: None,
2241            caption: None,
2242            caption_parent: Default::default(),
2243            caption_location: None,
2244        }));
2245        doc.push(Node::Picture {
2246            caption: Some("Fig 1".into()),
2247            caption_href: None,
2248            image: Some(PictureImage {
2249                dpi: PictureImage::DEFAULT_DPI,
2250                mimetype: "image/png".into(),
2251                width: 2,
2252                height: 2,
2253                data: b"png-one".to_vec(),
2254            }),
2255            classification: None,
2256            description: None,
2257            caption_parent: Default::default(),
2258            caption_location: None,
2259        });
2260        doc.add_paragraph("Last paragraph.");
2261        // A second embedded picture, so referenced mode must keep numbering
2262        // (`image_000001`) across chunk boundaries.
2263        doc.push(Node::Picture {
2264            caption: None,
2265            caption_href: None,
2266            image: Some(PictureImage {
2267                dpi: PictureImage::DEFAULT_DPI,
2268                mimetype: "image/png".into(),
2269                width: 2,
2270                height: 2,
2271                data: b"png-two".to_vec(),
2272            }),
2273            classification: None,
2274            description: None,
2275            caption_parent: Default::default(),
2276            caption_location: None,
2277        });
2278
2279        // A run of list items must never straddle a split, so try splits that fall
2280        // on safe block boundaries (the streaming PDF assembler guarantees this).
2281        for &strict in &[false, true] {
2282            for &images in &[
2283                ImageMode::Placeholder,
2284                ImageMode::Embedded,
2285                ImageMode::Referenced,
2286            ] {
2287                for splits in [&[][..], &[1][..], &[2][..], &[4][..], &[1, 4, 6, 7][..]] {
2288                    assert_stream_matches(&doc, strict, images, splits);
2289                }
2290            }
2291        }
2292    }
2293
2294    #[test]
2295    fn streaming_applies_recovered_links_in_strict_mode() {
2296        let mut doc = DoclingDocument::new("d");
2297        doc.add_paragraph("See LinkedIn for details.");
2298        doc.add_paragraph("And GitHub too.");
2299        doc.links = vec![
2300            ("LinkedIn".into(), "https://lnkd/".into()),
2301            ("GitHub".into(), "https://gh/".into()),
2302        ];
2303        // The second anchor lives in the second block, so it must be carried across
2304        // the page boundary and placed when that block streams out.
2305        assert_stream_matches(&doc, true, ImageMode::Placeholder, &[1]);
2306    }
2307
2308    /// A three-page document with one empty page in the middle and page
2309    /// markers of both kinds, as the backends emit them.
2310    fn paged_doc() -> DoclingDocument {
2311        let mut doc = DoclingDocument::new("p");
2312        doc.push(Node::PageInfo {
2313            page_no: 1,
2314            width: 100.0,
2315            height: 100.0,
2316        });
2317        doc.add_heading(1, "Title");
2318        doc.add_paragraph("Page one.");
2319        // Page two: a marker plus furniture only — renders nothing.
2320        doc.push(Node::PageBreak);
2321        doc.push(Node::PageInfo {
2322            page_no: 2,
2323            width: 100.0,
2324            height: 100.0,
2325        });
2326        doc.push(Node::PageFurniture {
2327            footer: true,
2328            location: [0, 500, 511, 511],
2329            text: "2".into(),
2330        });
2331        doc.push(Node::PageBreak);
2332        doc.push(Node::PageInfo {
2333            page_no: 3,
2334            width: 100.0,
2335            height: 100.0,
2336        });
2337        doc.add_paragraph("Page three.");
2338        // A trailing boundary with nothing after it.
2339        doc.push(Node::PageBreak);
2340        doc
2341    }
2342
2343    #[test]
2344    fn page_break_placeholder_lands_between_pages_only() {
2345        let mut doc = paged_doc();
2346        // Off by default: docling's Markdown carries no page breaks.
2347        assert_eq!(
2348            doc.export_to_markdown(),
2349            "# Title\n\nPage one.\n\nPage three.\n"
2350        );
2351        doc.page_break_placeholder = Some("<!-- page break -->".into());
2352        // One break for the 1→3 transition (the empty page 2 and the doubled
2353        // PageBreak+PageInfo markers collapse), none before the first block,
2354        // none for the trailing boundary.
2355        assert_eq!(
2356            doc.export_to_markdown(),
2357            "# Title\n\nPage one.\n\n<!-- page break -->\n\nPage three.\n"
2358        );
2359        // An empty placeholder is still a (blank) part, as upstream's
2360        // `str.replace(marker, "")` leaves the delimiters around it.
2361        doc.page_break_placeholder = Some(String::new());
2362        assert_eq!(
2363            doc.export_to_markdown(),
2364            "# Title\n\nPage one.\n\n\n\nPage three.\n"
2365        );
2366    }
2367
2368    #[test]
2369    fn page_break_placeholder_never_leads_a_single_page() {
2370        let mut doc = DoclingDocument::new("one");
2371        doc.page_break_placeholder = Some("---".into());
2372        doc.push(Node::PageBreak);
2373        doc.push(Node::PageInfo {
2374            page_no: 1,
2375            width: 10.0,
2376            height: 10.0,
2377        });
2378        doc.add_paragraph("Only page.");
2379        assert_eq!(doc.export_to_markdown(), "Only page.\n");
2380        // Two boundaries with no content between them: still one break.
2381        doc.push(Node::PageBreak);
2382        doc.push(Node::PageBreak);
2383        doc.add_paragraph("Next.");
2384        assert_eq!(doc.export_to_markdown(), "Only page.\n\n---\n\nNext.\n");
2385    }
2386
2387    #[test]
2388    fn page_break_placeholder_streams_byte_identical() {
2389        let mut doc = paged_doc();
2390        doc.page_break_placeholder = Some("<!-- page break -->".into());
2391        // Split at every page marker (how the PDF pipeline pushes page batches)
2392        // and at odd places inside a page: the pending break must survive a
2393        // push that renders nothing (page two) and land on page three's block.
2394        for splits in [
2395            &[3usize][..],
2396            &[3, 6],
2397            &[3, 6, 8],
2398            &[1, 2, 3, 4, 5, 6, 7, 8, 9],
2399            &[8],
2400        ] {
2401            assert_stream_matches(&doc, false, ImageMode::Placeholder, splits);
2402            assert_stream_matches(&doc, true, ImageMode::Placeholder, splits);
2403        }
2404    }
2405
2406    #[test]
2407    fn strict_tightens_punctuation_spacing_legacy_keeps_it() {
2408        let mut doc = DoclingDocument::new("t");
2409        doc.add_paragraph("see [ 37 , 36 ] and ( x ) .");
2410        // Legacy keeps docling's spacing byte-for-byte.
2411        assert_eq!(doc.export_to_markdown(), "see [ 37 , 36 ] and ( x ) .\n");
2412        // Strict tightens punctuation for readable Markdown.
2413        assert_eq!(doc.export_to_markdown_with(true), "see [37, 36] and (x).\n");
2414    }
2415
2416    // ----- MarkdownExportOptions (#599) ------------------------------------
2417
2418    /// A document touching every option: furniture, a comment, a hidden
2419    /// sheet group, a picture with nested text, escaped text.
2420    fn options_doc() -> DoclingDocument {
2421        use crate::document::ContentLayer;
2422        let mut doc = DoclingDocument::new("opts");
2423        doc.push(Node::PageFurniture {
2424            footer: false,
2425            location: [0, 0, 0, 0],
2426            text: "FAX COVER \\_ R&amp;D".into(),
2427        });
2428        doc.add_heading(1, "R&amp;D \\_ report");
2429        doc.add_paragraph("Body a\\_b &lt;tag&gt;");
2430        doc.push(Node::Picture {
2431            caption: Some("Figure 1".into()),
2432            caption_href: None,
2433            image: None,
2434            classification: None,
2435            description: None,
2436            caption_parent: Default::default(),
2437            caption_location: None,
2438        });
2439        doc.push(Node::PictureChildren(vec![
2440            Node::Paragraph {
2441                text: "Field: Name".into(),
2442            },
2443            Node::Paragraph {
2444                text: "Field: Date".into(),
2445            },
2446        ]));
2447        doc.push(Node::CommentSection {
2448            name: "comment-1".into(),
2449            text: "[author: A]: note".into(),
2450            refs_note_text: false,
2451            grouped: true,
2452        });
2453        doc.push(Node::Group {
2454            label: "section".into(),
2455            name: Some("sheet: Hidden".into()),
2456            layer: Some(ContentLayer::Invisible),
2457            children: vec![Node::Paragraph {
2458                text: "hidden cell".into(),
2459            }],
2460        });
2461        doc.push(Node::Furniture {
2462            layer: ContentLayer::Furniture,
2463            inner: Box::new(Node::Paragraph {
2464                text: "Page 1 of 2".into(),
2465            }),
2466        });
2467        doc.push(Node::FurnitureText {
2468            label: "page_footer".into(),
2469            text: "footer line".into(),
2470        });
2471        doc
2472    }
2473
2474    /// The defaults are docling's: the options export is the plain export,
2475    /// byte for byte — and the plain export is unchanged (furniture, notes,
2476    /// hidden sheets and picture children out; escaping kept).
2477    #[test]
2478    fn default_options_are_the_default_export() {
2479        let doc = options_doc();
2480        let plain = doc.export_to_markdown();
2481        assert_eq!(
2482            plain,
2483            "# R&amp;D \\_ report\n\nBody a\\_b &lt;tag&gt;\n\nFigure 1\n\n<!-- image -->\n"
2484        );
2485        let (with_default, artifacts) =
2486            doc.export_to_markdown_with_options(&MarkdownExportOptions::default());
2487        assert_eq!(with_default, plain);
2488        assert!(artifacts.is_empty());
2489    }
2490
2491    #[test]
2492    fn layers_render_furniture_notes_and_hidden_sheets() {
2493        use crate::document::ContentLayer;
2494        let doc = options_doc();
2495        let md = |layers: ContentLayers| {
2496            doc.export_to_markdown_with_options(&MarkdownExportOptions {
2497                layers,
2498                ..MarkdownExportOptions::default()
2499            })
2500            .0
2501        };
2502        assert_eq!(
2503            md(ContentLayers::BODY.with(ContentLayer::Furniture)),
2504            "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",
2505            "a page header, a furniture-wrapped paragraph and a furniture text item render as paragraphs"
2506        );
2507        assert_eq!(
2508            md(ContentLayers::BODY.with(ContentLayer::Notes)),
2509            "# R&amp;D \\_ report\n\nBody a\\_b &lt;tag&gt;\n\nFigure 1\n\n<!-- image -->\n\n[author: A]: note\n"
2510        );
2511        assert_eq!(
2512            md(ContentLayers::BODY.with(ContentLayer::Invisible)),
2513            "# R&amp;D \\_ report\n\nBody a\\_b &lt;tag&gt;\n\nFigure 1\n\n<!-- image -->\n\nhidden cell\n",
2514            "a hidden sheet's items sit on the sheet's layer"
2515        );
2516        assert_eq!(
2517            md(ContentLayers::NONE.with(ContentLayer::Furniture)),
2518            "FAX COVER \\_ R&amp;D\n\nPage 1 of 2\n\nfooter line\n",
2519            "without the body layer only the furniture prints"
2520        );
2521        assert_eq!(md(ContentLayers::NONE), "");
2522        assert_eq!(
2523            md(ContentLayers::ALL),
2524            "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"
2525        );
2526    }
2527
2528    /// A list item carries its own layer: a furniture list renders with the
2529    /// furniture layer and stays out of the body export.
2530    #[test]
2531    fn layers_apply_to_list_items() {
2532        use crate::document::ContentLayer;
2533        let mut doc = DoclingDocument::new("lists");
2534        doc.push(Node::ListItem {
2535            ordered: false,
2536            number: 1,
2537            first_in_list: true,
2538            text: "nav link".into(),
2539            level: 0,
2540            marker: None,
2541            location: None,
2542            dclx: None,
2543            href: None,
2544            layer: Some(ContentLayer::Furniture),
2545        });
2546        doc.add_paragraph("body");
2547        assert_eq!(doc.export_to_markdown(), "body\n");
2548        let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2549            layers: ContentLayers::BODY.with(ContentLayer::Furniture),
2550            ..MarkdownExportOptions::default()
2551        });
2552        assert_eq!(md, "- nav link\n\nbody\n");
2553    }
2554
2555    #[test]
2556    fn traverse_pictures_prints_the_nested_text_after_the_picture() {
2557        let doc = options_doc();
2558        let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2559            traverse_pictures: true,
2560            ..MarkdownExportOptions::default()
2561        });
2562        assert_eq!(
2563            md,
2564            "# R&amp;D \\_ report\n\nBody a\\_b &lt;tag&gt;\n\nFigure 1\n\n<!-- image -->\n\nField: Name\n\nField: Date\n"
2565        );
2566    }
2567
2568    #[test]
2569    fn escaping_can_be_turned_off_per_kind() {
2570        let doc = options_doc();
2571        let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2572            escape_html: false,
2573            ..MarkdownExportOptions::default()
2574        });
2575        assert_eq!(
2576            md,
2577            "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n"
2578        );
2579        let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2580            escape_underscores: false,
2581            ..MarkdownExportOptions::default()
2582        });
2583        assert_eq!(
2584            md,
2585            "# R&amp;D _ report\n\nBody a_b &lt;tag&gt;\n\nFigure 1\n\n<!-- image -->\n"
2586        );
2587        // Code and table cells are never touched (upstream leaves them
2588        // unescaped too, so nothing was escaped there to undo).
2589        let mut doc = DoclingDocument::new("code");
2590        doc.push(Node::Code {
2591            language: None,
2592            text: "a &amp; b \\_ c".into(),
2593            orig: None,
2594            pretty: None,
2595        });
2596        let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2597            escape_html: false,
2598            escape_underscores: false,
2599            ..MarkdownExportOptions::default()
2600        });
2601        assert_eq!(md, "```\na &amp; b \\_ c\n```\n");
2602    }
2603
2604    #[test]
2605    fn image_placeholder_is_configurable() {
2606        let doc = options_doc();
2607        let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2608            image_placeholder: "[figure]".into(),
2609            ..MarkdownExportOptions::default()
2610        });
2611        assert!(md.contains("Figure 1\n\n[figure]\n"), "{md}");
2612        assert!(!md.contains("<!-- image -->"));
2613    }
2614
2615    /// #605: an empty `image_placeholder` prints nothing — no empty block, so
2616    /// no extra blank lines — while the page-break scan still counts the
2617    /// picture as an item. Every expectation is docling-core 2.99's own
2618    /// `export_to_markdown(image_placeholder="", page_break_placeholder=…)`
2619    /// (plus the trailing newline this port always writes).
2620    #[test]
2621    fn empty_image_placeholder_prints_nothing() {
2622        fn picture(caption: Option<&str>) -> Node {
2623            Node::Picture {
2624                caption: caption.map(Into::into),
2625                caption_href: None,
2626                image: None,
2627                classification: None,
2628                description: None,
2629                caption_parent: Default::default(),
2630                caption_location: None,
2631            }
2632        }
2633        fn page(no: usize) -> Node {
2634            Node::PageInfo {
2635                page_no: no,
2636                width: 100.0,
2637                height: 100.0,
2638            }
2639        }
2640        fn para(text: &str) -> Node {
2641            Node::Paragraph { text: text.into() }
2642        }
2643        let options = MarkdownExportOptions {
2644            image_placeholder: String::new(),
2645            ..MarkdownExportOptions::default()
2646        };
2647        // (nodes, page-break placeholder, expected)
2648        let cases: Vec<(Vec<Node>, Option<&str>, &str)> = vec![
2649            (
2650                vec![page(1), para("a"), picture(None), para("b")],
2651                None,
2652                "a\n\nb\n",
2653            ),
2654            (
2655                vec![page(1), para("a"), picture(Some("Figure 1")), para("b")],
2656                None,
2657                "a\n\nFigure 1\n\nb\n",
2658            ),
2659            (
2660                vec![
2661                    page(1),
2662                    para("a"),
2663                    page(2),
2664                    picture(None),
2665                    page(3),
2666                    para("b"),
2667                ],
2668                Some("<!-- pb -->"),
2669                "a\n\n<!-- pb -->\n\n<!-- pb -->\n\nb\n",
2670            ),
2671            (
2672                vec![
2673                    page(1),
2674                    para("a"),
2675                    page(2),
2676                    picture(None),
2677                    page(3),
2678                    para("b"),
2679                ],
2680                Some(""),
2681                "a\n\n\n\n\n\nb\n",
2682            ),
2683            (
2684                vec![page(1), picture(None), page(2), para("b")],
2685                Some("<!-- pb -->"),
2686                "<!-- pb -->\n\nb\n",
2687            ),
2688            (
2689                vec![page(1), picture(None), page(2), para("b")],
2690                Some(""),
2691                "\n\nb\n",
2692            ),
2693            (
2694                vec![page(1), para("a"), page(2), picture(None)],
2695                Some("<!-- pb -->"),
2696                "a\n\n<!-- pb -->\n",
2697            ),
2698        ];
2699        for (nodes, placeholder, expected) in cases {
2700            let mut doc = DoclingDocument::new("t");
2701            doc.page_break_placeholder = placeholder.map(Into::into);
2702            for node in nodes {
2703                doc.push(node);
2704            }
2705            let (md, _) = doc.export_to_markdown_with_options(&options);
2706            assert_eq!(md, expected, "page break {placeholder:?}");
2707            // The streamer agrees at every chunking, one node per push
2708            // included — an all-empty push still owes the next page break.
2709            for size in 1..=doc.nodes.len() {
2710                let mut streamer = MarkdownStreamer::new(false, ImageMode::Placeholder, false)
2711                    .with_export_options(&options)
2712                    .with_page_break_placeholder(placeholder.map(Into::into));
2713                let mut out = String::new();
2714                for chunk in doc.nodes.chunks(size) {
2715                    out.push_str(&streamer.push(chunk, &[]));
2716                }
2717                out.push_str(&streamer.finish());
2718                assert_eq!(
2719                    out, expected,
2720                    "chunks of {size}, page break {placeholder:?}"
2721                );
2722            }
2723        }
2724        // The default placeholder is untouched.
2725        let mut doc = DoclingDocument::new("t");
2726        doc.push(para("a"));
2727        doc.push(picture(None));
2728        doc.push(para("b"));
2729        assert_eq!(doc.export_to_markdown(), "a\n\n<!-- image -->\n\nb\n");
2730    }
2731
2732    /// The streamer takes the same options and its chunks concatenate to the
2733    /// buffered export.
2734    #[test]
2735    fn streamer_matches_buffered_export_with_options() {
2736        let doc = options_doc();
2737        let options = MarkdownExportOptions {
2738            layers: ContentLayers::ALL,
2739            traverse_pictures: true,
2740            escape_html: false,
2741            escape_underscores: false,
2742            image_placeholder: "(img)".into(),
2743            ..MarkdownExportOptions::default()
2744        };
2745        let (buffered, _) = doc.export_to_markdown_with_options(&options);
2746        let mut streamer = MarkdownStreamer::new(false, ImageMode::Placeholder, false)
2747            .with_export_options(&options);
2748        let mut out = String::new();
2749        for chunk in doc.nodes.chunks(2) {
2750            out.push_str(&streamer.push(chunk, &[]));
2751        }
2752        out.push_str(&streamer.finish());
2753        assert_eq!(out, buffered);
2754        assert!(
2755            buffered.contains("(img)") && buffered.contains("R&D _ report"),
2756            "{buffered}"
2757        );
2758    }
2759
2760    /// #613: the plain export of a document holding every decoration the
2761    /// Markdown export writes, and the streamer agreeing with it.
2762    #[test]
2763    fn plain_text_drops_the_markdown_decoration() {
2764        let item = |text: &str, ordered: bool, number: u64, level: u8| Node::ListItem {
2765            ordered,
2766            number,
2767            first_in_list: number == 1 && level == 0,
2768            text: text.into(),
2769            level,
2770            marker: None,
2771            location: None,
2772            dclx: None,
2773            href: None,
2774            layer: None,
2775        };
2776        let mut doc = DoclingDocument::new("plain");
2777        doc.add_heading(1, "Title with **bold**");
2778        doc.add_heading(2, "Section");
2779        doc.add_paragraph("Some **bold**, *italic*, ~~gone~~ and `code` with a [link](https://x.org).\nNext line.");
2780        doc.push(item("*one*", false, 1, 0));
2781        doc.push(item("[two](https://y.org)", false, 2, 0));
2782        doc.push(item("nested", true, 1, 1));
2783        doc.push(Node::CheckboxItem {
2784            checked: true,
2785            text: "done".into(),
2786        });
2787        doc.push(Node::Code {
2788            language: Some("rust".into()),
2789            text: "let x = **y**;".into(),
2790            orig: None,
2791            pretty: None,
2792        });
2793        doc.push(Node::Picture {
2794            caption: Some("Figure *1*".into()),
2795            caption_href: None,
2796            image: None,
2797            classification: None,
2798            description: None,
2799            caption_parent: Default::default(),
2800            caption_location: None,
2801        });
2802        doc.push(Node::Caption {
2803            text: "Linked caption".into(),
2804            href: Some("https://z.org".into()),
2805        });
2806        doc.push(Node::Table(Table {
2807            rows: vec![
2808                vec!["**n**".into(), "rich".into()],
2809                vec!["**2**".into(), "a  \nb".into()],
2810            ],
2811            ..Default::default()
2812        }));
2813        doc.add_paragraph("R&amp;D \\_ x");
2814        let text = doc.export_to_text();
2815        assert_eq!(
2816            text,
2817            "Title with bold\n\n\
2818             Section\n\n\
2819             Some bold, italic, gone and code with a link.\nNext line.\n\n\
2820             - one\n- two\n    1. nested\n\n\
2821             - [x] done\n\n\
2822             let x = **y**;\n\n\
2823             Figure 1\n\n\
2824             Linked caption\n\n\
2825             |   n | rich   |\n\
2826             |-----|--------|\n\
2827             |   2 | a b    |\n\n\
2828             R&D _ x"
2829        );
2830
2831        let options = MarkdownExportOptions::plain_text();
2832        let (buffered, _) = doc.export_to_markdown_with_options(&options);
2833        assert_eq!(buffered, format!("{text}\n"));
2834        let mut streamer = MarkdownStreamer::new(false, ImageMode::Placeholder, false)
2835            .with_export_options(&options);
2836        let mut out = String::new();
2837        for chunk in doc.nodes.chunks(3) {
2838            out.push_str(&streamer.push(chunk, &[]));
2839        }
2840        out.push_str(&streamer.finish());
2841        assert_eq!(out, buffered);
2842    }
2843
2844    /// #613: text that only looks like Markdown stays as it is.
2845    #[test]
2846    fn plain_inline_keeps_literal_markers() {
2847        for (input, want) in [
2848            ("**bold** and *it* and ***both***", "bold and it and both"),
2849            ("**[label](https://a.b/c_(d))** end", "label end"),
2850            (
2851                "grant *USE and *OBJMGT authority",
2852                "grant *USE and *OBJMGT authority",
2853            ),
2854            ("2 * 3 * 4", "2 * 3 * 4"),
2855            ("a ** b", "a ** b"),
2856            ("the `quoted’ and `x` term", "the `quoted’ and x term"),
2857            ("see [12] and [docs](u)", "see [12] and docs"),
2858            ("formula $[a](b)$ stays", "formula $[a](b)$ stays"),
2859            ("price $5 and **bold**", "price $5 and bold"),
2860            ("[outer [inner] text](u)", "outer [inner] text"),
2861            ("unclosed **bold", "unclosed **bold"),
2862        ] {
2863            assert_eq!(plain_inline(input), want, "{input}");
2864        }
2865    }
2866}