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