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