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