Skip to main content

docling_core/
markdown.rs

1//! Markdown serializer for [`DoclingDocument`].
2
3use crate::document::{DoclingDocument, Node, Table};
4
5/// How pictures are rendered (mirrors docling-core's `ImageRefMode`).
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
7pub enum ImageMode {
8    /// `<!-- image -->` (docling's default, and the only mode without image data).
9    #[default]
10    Placeholder,
11    /// `![Image](data:<mime>;base64,…)` — self-contained.
12    Embedded,
13    /// `![Image](<artifacts>/image_NNNNNN.<ext>)`; the bytes are returned for the
14    /// caller to write.
15    Referenced,
16}
17
18/// Serializer state threaded through the render walk.
19struct Ctx {
20    strict: bool,
21    /// Emit compact `| a | b |` tables instead of the padded GitHub serializer.
22    compact_tables: bool,
23    images: ImageMode,
24    artifacts_dir: String,
25    /// (relative path, bytes) for each referenced image — written by the caller.
26    artifacts: Vec<(String, Vec<u8>)>,
27    pic_index: usize,
28    /// Rendering the block content of a rich table cell (docling-core 2.94's
29    /// `in_table_cell`, docling-core#540): a heading has no valid Markdown
30    /// form inside a table, so it renders as plain text without `#` markers.
31    in_table_cell: bool,
32}
33
34/// Render a document to a Markdown string (pictures as placeholders).
35///
36/// `strict` selects the serializer-level behaviours that differ between
37/// docling-legacy output and cleaner Markdown — currently the code-fence
38/// language (legacy drops it, strict keeps it).
39pub fn to_markdown(doc: &DoclingDocument, strict: bool) -> String {
40    to_markdown_images(doc, strict, ImageMode::Placeholder, "artifacts").0
41}
42
43/// Render to Markdown with an explicit picture [`ImageMode`]. Returns the
44/// Markdown and, for [`ImageMode::Referenced`], the `(path, bytes)` of each image
45/// the caller should write (relative to the Markdown file).
46pub fn to_markdown_images(
47    doc: &DoclingDocument,
48    strict: bool,
49    images: ImageMode,
50    artifacts_dir: &str,
51) -> (String, Vec<(String, Vec<u8>)>) {
52    let mut ctx = Ctx {
53        strict,
54        compact_tables: doc.compact_tables,
55        images,
56        artifacts_dir: artifacts_dir.to_string(),
57        artifacts: Vec::new(),
58        pic_index: 0,
59        in_table_cell: false,
60    };
61    let mut blocks: Vec<String> = Vec::new();
62    render(&doc.nodes, &mut blocks, &mut ctx);
63    let mut body = blocks.join("\n\n");
64    // Strict mode only: turn recovered source hyperlinks into Markdown links.
65    // docling's standard pipeline drops them, so doing this in legacy mode would
66    // diverge from docling — hence strict-only, leaving conformance output intact.
67    if strict && !doc.links.is_empty() {
68        body = apply_links(&body, &doc.links);
69    }
70    let md = if body.is_empty() {
71        String::new()
72    } else {
73        format!("{body}\n")
74    };
75    (md, ctx.artifacts)
76}
77
78/// Render the block content of a *rich table cell* to Markdown — what
79/// docling-core's table serializer does for a `RichTableCell`
80/// (`doc_serializer.serialize(item, in_table_cell=True)`): the cell's
81/// paragraphs, lists and flattened nested tables render as in a document, but a
82/// heading loses its `#` markers (docling-core#540 — the Markdown spec has no
83/// headings inside tables). Pictures stay placeholders. The caller flattens the
84/// result into its cell text; the table serializer later turns the newlines
85/// into spaces.
86pub fn to_markdown_table_cell(doc: &DoclingDocument, strict: bool) -> String {
87    let mut ctx = Ctx {
88        strict,
89        compact_tables: doc.compact_tables,
90        images: ImageMode::Placeholder,
91        artifacts_dir: String::new(),
92        artifacts: Vec::new(),
93        pic_index: 0,
94        in_table_cell: true,
95    };
96    let mut blocks: Vec<String> = Vec::new();
97    render(&doc.nodes, &mut blocks, &mut ctx);
98    blocks.join("\n\n")
99}
100
101/// Wrap each recovered link's anchor text in Markdown `[anchor](href)`. Anchors
102/// arrive cleaned (curly quotes/dashes already normalized) but un-escaped, so we
103/// match against the body's HTML-escaped (`&`/`<`/`>`) form, the way prose nodes
104/// were serialized. Links are consumed in document order from a moving cursor, so
105/// a repeated anchor (e.g. two "issues") links its successive occurrences rather
106/// than all pointing at the first. An anchor that can't be located is skipped
107/// (its text may have been split across a line wrap or table cell).
108fn apply_links(body: &str, links: &[(String, String)]) -> String {
109    let mut out = body.to_string();
110    let mut cursor = 0usize;
111    for (anchor, href) in links {
112        let anchor = anchor
113            .replace('&', "&amp;")
114            .replace('<', "&lt;")
115            .replace('>', "&gt;");
116        if anchor.is_empty() {
117            continue;
118        }
119        if let Some(rel) = out[cursor..].find(&anchor) {
120            let at = cursor + rel;
121            // Don't relink inside an already-emitted `](` Markdown link target.
122            let replacement = format!("[{anchor}]({href})");
123            out.replace_range(at..at + anchor.len(), &replacement);
124            cursor = at + replacement.len();
125        }
126    }
127    out
128}
129
130/// Like [`apply_links`] but over a single chunk, consuming from a shared queue so
131/// the same `[anchor](href)` rewriting can be applied incrementally as Markdown is
132/// streamed out. Each queued link is matched (in document order) against `chunk`
133/// and rewritten in place; a link whose anchor is not in this chunk is carried
134/// forward in the queue for a later chunk. Anchors are recovered in document
135/// order and a chunk is always a contiguous run of whole blocks, so this
136/// reproduces [`apply_links`]' single moving cursor: the link lands in whichever
137/// chunk contains its anchor, identically to the buffered path. (A link whose
138/// anchor never appears is carried to the end and dropped — the same no-op
139/// `apply_links` performs for an unlocatable anchor.)
140fn apply_links_chunk(chunk: &str, queue: &mut Vec<(String, String)>) -> String {
141    let mut out = chunk.to_string();
142    let mut cursor = 0usize;
143    let mut carried: Vec<(String, String)> = Vec::new();
144    for (anchor_raw, href) in std::mem::take(queue) {
145        let anchor = anchor_raw
146            .replace('&', "&amp;")
147            .replace('<', "&lt;")
148            .replace('>', "&gt;");
149        if anchor.is_empty() {
150            continue;
151        }
152        if let Some(rel) = out[cursor..].find(&anchor) {
153            let at = cursor + rel;
154            let replacement = format!("[{anchor}]({href})");
155            out.replace_range(at..at + anchor.len(), &replacement);
156            cursor = at + replacement.len();
157        } else {
158            // Not in this chunk; try again when its block is flushed.
159            carried.push((anchor_raw, href));
160        }
161    }
162    *queue = carried;
163    out
164}
165
166/// Incremental Markdown serializer: feed finalized, in-document-order batches of
167/// [`Node`]s and receive Markdown chunks whose concatenation is **byte-identical**
168/// to [`to_markdown_images`] over the same nodes. This is the streaming
169/// counterpart of the buffered serializer — used to emit a document's Markdown in
170/// chunks (e.g. page by page, as the parallel PDF pipeline finishes pages) instead
171/// of building the whole string up front.
172///
173/// [`ImageMode::Placeholder`] and [`ImageMode::Embedded`] render inline.
174/// [`ImageMode::Referenced`] additionally hands each picture's bytes out through
175/// [`take_artifacts`](Self::take_artifacts) — construct with
176/// [`with_artifacts`](Self::with_artifacts) and drain after every push so the
177/// bytes can be written to disk as pages finish instead of accumulating for the
178/// whole document (issue #80's memory-bounded image handling).
179///
180/// Each [`push`](Self::push) must contain whole blocks in reading order: a caller
181/// must not split a run of list items across two pushes (the run would render as
182/// two separate lists). Finalized PDF page batches already satisfy this.
183pub struct MarkdownStreamer {
184    strict: bool,
185    images: ImageMode,
186    compact_tables: bool,
187    /// Whether any non-empty chunk has been emitted yet (drives `\n\n` joins and
188    /// the trailing newline).
189    emitted_any: bool,
190    /// Recovered links not yet placed (strict mode), consumed in document order.
191    links: Vec<(String, String)>,
192    /// Referenced mode: the link prefix, the not-yet-drained `(path, bytes)`
193    /// artifacts, and the running image number (continues across pushes so the
194    /// stream matches the buffered serializer's `image_000000…` numbering).
195    artifacts_dir: String,
196    artifacts: Vec<(String, Vec<u8>)>,
197    pic_index: usize,
198}
199
200impl MarkdownStreamer {
201    /// Create a streamer. `compact_tables` mirrors [`DoclingDocument::compact_tables`].
202    /// For [`ImageMode::Referenced`] use [`with_artifacts`](Self::with_artifacts).
203    pub fn new(strict: bool, images: ImageMode, compact_tables: bool) -> Self {
204        debug_assert!(
205            images != ImageMode::Referenced,
206            "referenced image mode needs an artifacts dir; use with_artifacts"
207        );
208        Self::with_artifacts(strict, images, compact_tables, "artifacts")
209    }
210
211    /// Like [`new`](Self::new) but with the artifacts link prefix, allowing
212    /// [`ImageMode::Referenced`]: pictures render as
213    /// `![Image](<artifacts_dir>/image_NNNNNN.<ext>)` and each push's image
214    /// bytes wait in [`take_artifacts`](Self::take_artifacts) for the caller to
215    /// write. The concatenated chunks and the artifact list match the buffered
216    /// [`to_markdown_images`] byte-for-byte.
217    pub fn with_artifacts(
218        strict: bool,
219        images: ImageMode,
220        compact_tables: bool,
221        artifacts_dir: &str,
222    ) -> Self {
223        Self {
224            strict,
225            images,
226            compact_tables,
227            emitted_any: false,
228            links: Vec::new(),
229            artifacts_dir: artifacts_dir.to_string(),
230            artifacts: Vec::new(),
231            pic_index: 0,
232        }
233    }
234
235    /// The `(relative path, bytes)` of images rendered by pushes since the last
236    /// drain ([`ImageMode::Referenced`] only — empty otherwise). Paths are
237    /// relative to the Markdown file, i.e. they start with the configured
238    /// artifacts dir.
239    pub fn take_artifacts(&mut self) -> Vec<(String, Vec<u8>)> {
240        std::mem::take(&mut self.artifacts)
241    }
242
243    /// Render one finalized batch of nodes (plus any links recovered from the same
244    /// span, in document order) into the next Markdown chunk. Returns an empty
245    /// string when the batch produces no output (e.g. empty tables/pictures), in
246    /// which case nothing should be written.
247    pub fn push(&mut self, nodes: &[Node], links: &[(String, String)]) -> String {
248        self.links.extend(links.iter().cloned());
249        let mut ctx = Ctx {
250            strict: self.strict,
251            compact_tables: self.compact_tables,
252            images: self.images,
253            artifacts_dir: std::mem::take(&mut self.artifacts_dir),
254            artifacts: std::mem::take(&mut self.artifacts),
255            pic_index: self.pic_index,
256            in_table_cell: false,
257        };
258        let mut blocks: Vec<String> = Vec::new();
259        render(nodes, &mut blocks, &mut ctx);
260        self.artifacts_dir = std::mem::take(&mut ctx.artifacts_dir);
261        self.artifacts = std::mem::take(&mut ctx.artifacts);
262        self.pic_index = ctx.pic_index;
263        if blocks.is_empty() {
264            return String::new();
265        }
266        let mut body = blocks.join("\n\n");
267        if self.strict && !self.links.is_empty() {
268            body = apply_links_chunk(&body, &mut self.links);
269        }
270        let chunk = if self.emitted_any {
271            format!("\n\n{body}")
272        } else {
273            body
274        };
275        self.emitted_any = true;
276        chunk
277    }
278
279    /// Emit the trailing newline that finishes the document (empty if no content
280    /// was produced). Call exactly once, after the final [`push`](Self::push).
281    pub fn finish(self) -> String {
282        if self.emitted_any {
283            "\n".to_string()
284        } else {
285            String::new()
286        }
287    }
288}
289
290/// In `strict` mode, rewrite inline text for readability rather than byte-for-byte
291/// docling fidelity: undo the legacy `\_` underscore escaping, and tighten stray
292/// spaces around punctuation (`[ 37 , 36 ]` → `[37, 36]`, `( x )` → `(x)`). This
293/// cleans up both the PDF backend's glyph-split spacing and the space the legacy
294/// emphasis serialization leaves before punctuation (`*a* ,` → `*a*,`).
295/// Legacy/default output keeps docling's spacing untouched. Only inline text
296/// nodes pass through here — code blocks and table cells are left alone.
297fn strict_text(text: &str, strict: bool) -> String {
298    if !strict {
299        return text.to_string();
300    }
301    text.replace("\\_", "_")
302        .replace(" ,", ",")
303        .replace(" .", ".")
304        .replace(" ;", ";")
305        .replace(" )", ")")
306        .replace("( ", "(")
307        .replace(" ]", "]")
308        .replace("[ ", "[")
309}
310
311/// docling-core 2.92's `_md_line_breaks` (docling-core#721): a single `\n`
312/// inside an item's text becomes a GFM hard line break (`"  \n"`, two trailing
313/// spaces) so renderers honour it; a blank line (`\n\n`) is a paragraph break
314/// and stays as is — the document scope already joins blocks with `\n\n`.
315/// Applied to body text, list items and captions, never to code/formulas.
316fn md_line_breaks(text: &str) -> String {
317    if !text.contains('\n') {
318        return text.to_string();
319    }
320    text.split("\n\n")
321        .map(|para| para.replace('\n', "  \n"))
322        .collect::<Vec<_>>()
323        .join("\n\n")
324}
325
326/// Undo [`md_line_breaks`] on a rich table cell's flattened Markdown so the
327/// non-Markdown exports (JSON `text`, LaTeX cells) see the cell's raw line
328/// breaks, as docling's do — a rich cell's text is its Markdown serialization
329/// in our model, and the two trailing spaces are a Markdown-only marker.
330pub(crate) fn strip_hard_breaks(text: &str) -> String {
331    if text.contains("  \n") {
332        text.replace("  \n", "\n")
333    } else {
334        text.to_string()
335    }
336}
337
338/// docling-core's `_heading_line_breaks`: a GFM heading cannot span lines, so a
339/// newline inside heading text collapses to a space (`# Hello World`, not a
340/// broken `# Hello\nWorld`).
341fn heading_line_breaks(text: &str) -> String {
342    text.replace('\n', " ")
343}
344
345fn render(nodes: &[Node], blocks: &mut Vec<String>, ctx: &mut Ctx) {
346    let mut i = 0;
347    while i < nodes.len() {
348        match &nodes[i] {
349            Node::ListItem { .. } => {
350                let start = i;
351                i += 1;
352                loop {
353                    match nodes.get(i) {
354                        Some(Node::ListItem { .. }) => i += 1,
355                        // An empty paragraph between two list items is absorbed
356                        // into the run — docling keeps such a ListGroup
357                        // contiguous rather than splitting it.
358                        Some(Node::Paragraph { text })
359                            if text.is_empty()
360                                && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
361                        {
362                            i += 1
363                        }
364                        _ => break,
365                    }
366                }
367                render_list_run(&nodes[start..i], blocks, ctx.strict);
368            }
369            other => {
370                render_one(other, blocks, ctx);
371                i += 1;
372            }
373        }
374    }
375}
376
377/// Render a contiguous run of list items.
378///
379/// Ordered items use their explicit `number`. A new sibling list (marked by
380/// `first_in_list`) at the same depth is separated by a blank line, matching
381/// docling-core's serializer.
382fn render_list_run(items: &[Node], blocks: &mut Vec<String>, strict: bool) {
383    let mut lines: Vec<String> = Vec::new();
384    // Whether a top-level item has been rendered yet — a fresh-list flag on
385    // the very first item opens nothing.
386    let mut any_top = false;
387
388    for item in items {
389        let Node::ListItem {
390            ordered,
391            number,
392            first_in_list,
393            text,
394            level,
395            marker: _,
396            location: _,
397            dclx: _,
398            href: _,
399            layer,
400        } = item
401        else {
402            continue;
403        };
404        // A non-body (furniture) list item is omitted from Markdown, matching
405        // docling's content-layer filtering.
406        if layer.is_some() {
407            continue;
408        }
409        let level = *level as usize;
410
411        // A new sibling list at the top level gets a blank line — and only the
412        // backend knows where one starts (`first_in_list`: Word's `numId`
413        // changing, an HTML `<ul>` closing, a Markdown bullet switching
414        // `-`→`*`). The serializer used to guess it from a kind flip or a
415        // number gap as well, which split lists docling keeps whole (an
416        // AsciiDoc `1.` … `5.`, mixed `*`/`1.` markers) — #385. Only at the
417        // top level: nested sibling groups are children of a list item, and
418        // docling joins an item's children without blank lines.
419        if level == 0 {
420            if any_top && *first_in_list {
421                lines.push(String::new());
422            }
423            any_top = true;
424        }
425
426        let indent = "    ".repeat(level);
427        let marker = if *ordered {
428            format!("{number}.")
429        } else {
430            "-".to_string()
431        };
432        lines.push(format!("{indent}{marker} {}", list_item_text(text, strict)));
433    }
434
435    // A run consisting only of furniture (content-layer-filtered) items yields no
436    // lines; pushing an empty block here would surface as a stray blank line.
437    if !lines.is_empty() {
438        blocks.push(lines.join("\n"));
439    }
440}
441
442/// A list item's Markdown body. The GFM hard-line-break rule (docling-core#721)
443/// applies to the item's own text; pictures the HTML backend folded into the
444/// item (`"\n[alt\n]<!-- image -->"` per `<img>` inside the `<li>`) are
445/// docling's picture *children* of the item, which its serializer prints after
446/// the item line with plain newlines — so a folded tail keeps its newlines
447/// unmarked. The tail is recognised structurally: every line after the first is
448/// an image marker or an alt caption directly followed by one.
449fn list_item_text(text: &str, strict: bool) -> String {
450    let escaped = strict_text(text, strict);
451    if let Some((own, tail)) = escaped.split_once('\n') {
452        if is_folded_child_tail(tail) {
453            return format!("{}\n{tail}", md_line_breaks(own));
454        }
455    }
456    md_line_breaks(&escaped)
457}
458
459/// Whether everything after a list item's own first line is a folded *child*
460/// block rather than a continuation of the item's text: an image marker
461/// (optionally preceded by its caption/alt line) or a fenced code block. The
462/// AsciiDoc backend indents such a block to the item's own depth (as
463/// docling-core's list serializer does for each part it emits), so a leading
464/// indent is ignored here.
465fn is_folded_child_tail(tail: &str) -> bool {
466    const MARKER: &str = "<!-- image -->";
467    const FENCE: &str = "```";
468    let mut lines = tail.split('\n').peekable();
469    let mut any = false;
470    while let Some(line) = lines.next() {
471        let line = line.trim_start();
472        if line == MARKER {
473            any = true;
474        } else if line == FENCE {
475            // Skip the block's body; an unclosed fence is not a folded child.
476            loop {
477                match lines.next() {
478                    Some(l) if l.trim_start() == FENCE => break,
479                    Some(_) => {}
480                    None => return false,
481                }
482            }
483            any = true;
484        } else if lines.next().map(str::trim_start) == Some(MARKER) {
485            any = true; // an alt caption line, then its marker
486        } else {
487            return false;
488        }
489    }
490    any
491}
492
493fn render_one(node: &Node, blocks: &mut Vec<String>, ctx: &mut Ctx) {
494    match node {
495        Node::Heading { level, text } => {
496            let text = heading_line_breaks(&strict_text(text, ctx.strict));
497            if ctx.in_table_cell {
498                // docling-core#540: no `#` markers inside a table cell.
499                blocks.push(text);
500            } else {
501                let hashes = "#".repeat((*level).clamp(1, 6) as usize);
502                blocks.push(format!("{hashes} {text}"));
503            }
504        }
505        // An empty body paragraph (docling's blank-line text item) contributes
506        // nothing to Markdown — only DocLang/JSON keep it.
507        Node::Paragraph { text } if text.is_empty() => {}
508        Node::Paragraph { text } => blocks.push(md_line_breaks(&strict_text(text, ctx.strict))),
509        // A standalone caption item renders like a text item; its hyperlink
510        // annotation becomes a Markdown link around the whole caption.
511        Node::Caption { text, .. } if text.is_empty() => {}
512        Node::Caption { text, href } => {
513            let body = md_line_breaks(&strict_text(text, ctx.strict));
514            blocks.push(match href {
515                Some(url) => format!("[{body}]({url})"),
516                None => body,
517            });
518        }
519        Node::CheckboxItem { checked, text } => {
520            let mark = if *checked { "- [x] " } else { "- [ ] " };
521            blocks.push(md_line_breaks(&strict_text(
522                &format!("{mark}{text}"),
523                ctx.strict,
524            )));
525        }
526        Node::Code {
527            language,
528            text,
529            pretty,
530            ..
531        } => {
532            // Legacy docling never emits a language on the fence; strict keeps it.
533            let lang = match language {
534                Some(l) if ctx.strict => l.as_str(),
535                _ => "",
536            };
537            // Strict prefers the line-preserving rendering when the backend
538            // supplied one (PDF); legacy stays on docling's flat `text`.
539            let body = match pretty {
540                Some(p) if ctx.strict => p.as_str(),
541                _ => text.as_str(),
542            };
543            blocks.push(format!("```{lang}\n{body}\n```"));
544        }
545        // A CodeFormula-decoded display formula renders as docling's `$$…$$`
546        // (the un-enriched pipeline emits a placeholder paragraph instead).
547        Node::Formula { latex, .. } => blocks.push(format!("$${latex}$$")),
548        Node::Table(table) => {
549            // docling renders a table's caption as a text line before the grid.
550            // `caption` is already escaped (backend convention), like a paragraph.
551            if let Some(cap) = &table.caption {
552                if !cap.is_empty() {
553                    blocks.push(md_line_breaks(&strict_text(cap, ctx.strict)));
554                }
555            }
556            let rendered = render_table(table, ctx.compact_tables);
557            if !rendered.is_empty() {
558                blocks.push(rendered);
559            }
560        }
561        // Classification predictions don't affect docling's Markdown output.
562        Node::Picture { caption, image, .. } => {
563            if let Some(cap) = caption {
564                if !cap.is_empty() {
565                    blocks.push(md_line_breaks(cap));
566                }
567            }
568            blocks.push(picture_marker(image.as_ref(), ctx));
569        }
570        // A chart renders as docling's picture-with-meta markdown: the caption,
571        // the placeholder, the humanized classification ("line_chart" ->
572        // "Line chart"), then the chart's data grid as a regular table.
573        Node::Chart {
574            kind,
575            table,
576            caption,
577            ..
578        } => {
579            if let Some(cap) = caption {
580                if !cap.is_empty() {
581                    blocks.push(md_line_breaks(cap));
582                }
583            }
584            blocks.push(picture_marker(None, ctx));
585            blocks.push(humanize_label(kind));
586            let rendered = render_table(table, false);
587            if !rendered.is_empty() {
588                blocks.push(rendered);
589            }
590        }
591        // A DocLang-only node is omitted from Markdown.
592        Node::DoclangOnly(_) => {}
593        // A group on a non-body layer (a hidden spreadsheet sheet) renders
594        // nothing, like every other non-body item.
595        Node::Group { layer: Some(_), .. } => {}
596        Node::Group { children, .. } => render(children, blocks, ctx),
597        Node::FieldRegion { items } => {
598            // The region container and each field item carry no text of their
599            // own; docling-core 2.93 (#724) serializes them to nothing (older
600            // releases emitted a `<!-- missing-text -->` marker for each), so
601            // only an item's marker/key/value appear, as separate paragraphs.
602            for item in items {
603                for part in [&item.marker, &item.key, &item.value].into_iter().flatten() {
604                    blocks.push(md_line_breaks(&strict_text(part, ctx.strict)));
605                }
606            }
607        }
608        // A rich inline group renders exactly like a paragraph of its Markdown
609        // text — the structured runs are DocLang-only.
610        Node::InlineGroup { md_text, .. } => {
611            blocks.push(md_line_breaks(&strict_text(md_text, ctx.strict)))
612        }
613        // A plain-text backend dump renders verbatim as a single block.
614        Node::TextDump(text) => {
615            if !text.is_empty() {
616                blocks.push(text.clone());
617            }
618        }
619        // Furniture (page headers/footers, HTML `<title>`) is excluded from
620        // Markdown by default, mirroring docling.
621        Node::Furniture { .. } => {}
622        Node::PageFurniture { .. } => {}
623        // A comment lives in the notes layer — omitted like other furniture;
624        // the annotation on a body item is JSON-only, so render the item.
625        Node::CommentSection { .. } => {}
626        Node::Commented { inner, .. } => render_one(inner, blocks, ctx),
627        // Layout provenance is DocLang-only; render the wrapped node.
628        Node::Located { inner, .. } | Node::Prov { inner, .. } => render_one(inner, blocks, ctx),
629        // Page breaks are DocLang-only; docling omits them from Markdown.
630        Node::PageBreak => {}
631        // Page markers feed the JSON export only.
632        Node::PageInfo { .. } => {}
633        // Runs of adjacent list items are merged by `render`; a stray single
634        // item (a hand-built document, or a `Located` wrapper around one)
635        // still renders as its own one-item list instead of panicking —
636        // `nodes` is public API, so every representable tree must serialize.
637        Node::ListItem { .. } => render_list_run(std::slice::from_ref(node), blocks, ctx.strict),
638    }
639}
640
641/// The Markdown for a picture under the active [`ImageMode`]; Referenced mode also
642/// records the bytes in `ctx.artifacts` for the caller to write.
643/// docling-core's `_humanize_text`: underscores to spaces, first letter
644/// capitalized ("line_chart" -> "Line chart").
645fn humanize_label(label: &str) -> String {
646    let text = label.replace('_', " ");
647    let mut chars = text.chars();
648    match chars.next() {
649        Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
650        None => text,
651    }
652}
653
654fn picture_marker(image: Option<&crate::PictureImage>, ctx: &mut Ctx) -> String {
655    match (ctx.images, image) {
656        (ImageMode::Embedded, Some(img)) => format!("![Image]({})", img.data_uri()),
657        (ImageMode::Referenced, Some(img)) => {
658            let path = format!(
659                "{}/image_{:06}.{}",
660                ctx.artifacts_dir,
661                ctx.pic_index,
662                ext_for(&img.mimetype)
663            );
664            ctx.pic_index += 1;
665            ctx.artifacts.push((path.clone(), img.data.clone()));
666            format!("![Image]({})", escape_uri_path(&path))
667        }
668        // Placeholder, or any mode with no extracted image.
669        _ => "<!-- image -->".to_string(),
670    }
671}
672
673/// Encode a URL or filesystem path as a Markdown link destination —
674/// docling-core's `MarkdownPictureSerializer._escape_uri_path`
675/// (docling-core#698, 2.94). Handles URLs of any scheme as well as POSIX and
676/// Windows paths, keeps relative paths relative and never double-encodes:
677/// backslashes become `/` (a backslash is both the Windows separator and a
678/// Markdown escape), a UNC share `//host/…` and an absolute Windows path
679/// `C:/…` become RFC 8089 `file://` URLs (the one spelling a renderer cannot
680/// misread as a scheme-relative URL or a `C:` scheme), a URL keeps its
681/// scheme / authority / delimiters with only the components encoded, and
682/// everything else is percent-encoded as a path. `%` is kept so an
683/// already-encoded destination stays as it is; spaces and parentheses are
684/// encoded because they would end (or unbalance) a Markdown inline link.
685pub(crate) fn escape_uri_path(value: &str) -> String {
686    const KEEP: &str = "/%:@+,;=~$!&'*";
687    let s = value.replace('\\', "/");
688    if let Some(rest) = s.strip_prefix("//") {
689        // A fileshare: `file://<host>/<path>`, the host possibly empty.
690        let rest = rest.trim_start_matches('/');
691        let (host, tail) = rest.split_once('/').unwrap_or((rest, ""));
692        return format!("file://{host}{}", percent_quote(&format!("/{tail}"), KEEP));
693    }
694    let bytes = s.as_bytes();
695    if bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && bytes[2] == b'/' {
696        // A Windows path with a drive letter: `file:///C:/…`.
697        return format!("file:///{}", percent_quote(&s, KEEP));
698    }
699    // A URL keeps its scheme, authority and delimiters; only its components are
700    // encoded. A single-character scheme cannot be real (it is a drive letter,
701    // handled above), so it is read as a path — like `urlsplit`.
702    if let Some((scheme, rest)) = s.split_once(':') {
703        let valid_scheme = scheme.len() > 1
704            && scheme.as_bytes()[0].is_ascii_alphabetic()
705            && scheme
706                .bytes()
707                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'));
708        if valid_scheme {
709            let (authority, rest) = match rest.strip_prefix("//") {
710                Some(r) => {
711                    let end = r.find(['/', '?', '#']).unwrap_or(r.len());
712                    (Some(&r[..end]), &r[end..])
713                }
714                None => (None, rest),
715            };
716            let (before_frag, fragment) = rest.split_once('#').unwrap_or((rest, ""));
717            let (path, query) = before_frag.split_once('?').unwrap_or((before_frag, ""));
718            let mut out = format!("{scheme}:");
719            if let Some(a) = authority {
720                out.push_str("//");
721                out.push_str(a);
722            }
723            out.push_str(&percent_quote(path, KEEP));
724            if !query.is_empty() {
725                out.push('?');
726                out.push_str(&percent_quote(query, KEEP));
727            }
728            if !fragment.is_empty() {
729                out.push('#');
730                out.push_str(&percent_quote(fragment, KEEP));
731            }
732            return out;
733        }
734    }
735    // A relative or root-relative local path.
736    percent_quote(&s, KEEP)
737}
738
739/// `urllib.parse.quote(s, safe)`: unreserved ASCII (`A–Z a–z 0–9 _ . - ~`) and
740/// the `safe` set stay, every other byte of the UTF-8 encoding becomes `%XX`.
741fn percent_quote(s: &str, safe: &str) -> String {
742    let mut out = String::with_capacity(s.len());
743    for &b in s.as_bytes() {
744        let keep = b.is_ascii_alphanumeric()
745            || matches!(b, b'_' | b'.' | b'-' | b'~')
746            || (b.is_ascii() && safe.contains(b as char));
747        if keep {
748            out.push(b as char);
749        } else {
750            out.push_str(&format!("%{b:02X}"));
751        }
752    }
753    out
754}
755
756fn ext_for(mimetype: &str) -> &str {
757    match mimetype {
758        "image/jpeg" => "jpg",
759        "image/gif" => "gif",
760        "image/webp" => "webp",
761        "image/bmp" => "bmp",
762        "image/tiff" => "tif",
763        _ => "png",
764    }
765}
766
767/// Render a table. `compact` selects between two serializers:
768///
769/// - **padded** (default) — docling-core's `tabulate(tablefmt="github")`: columns
770///   are padded to a fixed width (header width + a minimum padding of 2, or the
771///   widest data cell); numeric columns (every data cell parses as a number) are
772///   right-aligned, others left-aligned; separators are plain dashes of
773///   `width + 2`. Matches current published docling (DOCX/HTML conformance).
774/// - **compact** — `| a | b |` cells with single-dash `| - | - |` separators, no
775///   width padding. Matches the committed PDF groundtruth corpus, which predates
776///   the padded serializer.
777///
778/// Each cell is first escaped (`\n` → space, `|` → `&#124;`) so it can't break the
779/// table. The header row is the table's leading `column_header` block flattened
780/// to one row ([`Table::header_row_count`] + [`flatten_header_rows`],
781/// docling-core#723); alignment and widths are computed over the body rows.
782/// Whether a table cell counts as a number for column alignment, matching
783/// `tabulate`'s detection: an ordinary float/int (`f64`-parseable, covering
784/// `1e2`/`inf`/`+1.5`) **or** a thousands-separated number like `7,015`.
785fn is_number_cell(t: &str) -> bool {
786    t.parse::<f64>().is_ok() || is_thousands_number(t)
787}
788
789/// A number with comma thousands-separators, per `tabulate`'s
790/// `_float_with_thousands_separators` regex
791/// (`^(([+-]?[0-9]{1,3})(?:,([0-9]{3}))*)?(?(1)\.[0-9]*|\.[0-9]+)?$`): the
792/// integer part is 1–3 digits then any number of `,ddd` groups; the fraction is
793/// optional (and, without an integer part, must have at least one digit).
794fn is_thousands_number(t: &str) -> bool {
795    let b = t.as_bytes();
796    let mut i = 0;
797    let start = i;
798    if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
799        i += 1;
800    }
801    // First digit chunk: 1–3 digits.
802    let d0 = i;
803    while i < b.len() && b[i].is_ascii_digit() && i - d0 < 3 {
804        i += 1;
805    }
806    let has_int = i > d0;
807    if has_int {
808        // Subsequent `,ddd` groups (exactly three digits each).
809        while i + 3 < b.len() + 1
810            && b.get(i) == Some(&b',')
811            && b.get(i + 1).is_some_and(u8::is_ascii_digit)
812            && b.get(i + 2).is_some_and(u8::is_ascii_digit)
813            && b.get(i + 3).is_some_and(u8::is_ascii_digit)
814        {
815            i += 4;
816        }
817    } else {
818        // A sign only counts with an integer part.
819        i = start;
820    }
821    // Optional fraction.
822    if i < b.len() && b[i] == b'.' {
823        i += 1;
824        let f0 = i;
825        while i < b.len() && b[i].is_ascii_digit() {
826            i += 1;
827        }
828        if !has_int && i == f0 {
829            return false; // `.` with no digits and no integer part
830        }
831    } else if !has_int {
832        return false; // neither integer nor fractional part
833    }
834    i == b.len()
835}
836
837/// The single GFM header row for a table: the leading header rows (see
838/// [`Table::header_row_count`]) flattened per column, texts joined with
839/// `" - "` after dropping consecutive duplicates — docling-core's
840/// `_flatten_header_rows` (docling-core#723). The duplicate rule is what
841/// keeps a row-spanning header from being joined to itself (the grid repeats
842/// its text into every row it covers); it is position-based, so two stacked
843/// levels sharing a label collapse too — GFM has one header row, and upstream
844/// accepts that loss. No header rows → one empty header cell per column.
845fn flatten_header_rows(header_rows: &[Vec<String>], num_cols: usize) -> Vec<String> {
846    (0..num_cols)
847        .map(|c| {
848            let mut parts: Vec<&str> = Vec::new();
849            for row in header_rows {
850                let text = row.get(c).map(String::as_str).unwrap_or("");
851                if !text.is_empty() && parts.last() != Some(&text) {
852                    parts.push(text);
853                }
854            }
855            parts.join(" - ")
856        })
857        .collect()
858}
859
860pub(crate) fn render_table(table: &Table, compact: bool) -> String {
861    if table.rows.is_empty() {
862        return String::new();
863    }
864    let num_cols = table.rows.iter().map(Vec::len).max().unwrap_or(0);
865    if num_cols == 0 {
866        return String::new();
867    }
868
869    // Escaped, rectangular grid (ragged rows padded with empty cells). The
870    // header block is resolved to the one row GFM allows (docling-core#723);
871    // `tabulate` strips data cells of surrounding whitespace but leaves the
872    // header texts as-is.
873    let num_headers = table.header_row_count().min(table.rows.len());
874    let escaped = |r: usize| -> Vec<String> {
875        (0..num_cols)
876            .map(|c| escape_cell(table.rows[r].get(c).map(String::as_str).unwrap_or("")))
877            .collect()
878    };
879    let header_rows: Vec<Vec<String>> = (0..num_headers).map(escaped).collect();
880    let header = flatten_header_rows(&header_rows, num_cols);
881    let body: Vec<Vec<String>> = (num_headers..table.rows.len())
882        .map(|r| {
883            escaped(r)
884                .into_iter()
885                .map(|c| c.trim().to_string())
886                .collect()
887        })
888        .collect();
889
890    if compact {
891        // Compact: cells joined by " | ", no padding, single-dash separators.
892        let render_row = |row: &[String]| -> String { format!("| {} |", row.join(" | ")) };
893        let mut lines = Vec::with_capacity(body.len() + 2);
894        lines.push(render_row(&header));
895        let sep: Vec<&str> = (0..num_cols).map(|_| "-").collect();
896        lines.push(format!("| {} |", sep.join(" | ")));
897        for row in &body {
898            lines.push(render_row(row));
899        }
900        return lines.join("\n");
901    }
902
903    // Display width (Unicode scalar count — good enough for now).
904    let dw = |s: &str| s.chars().count();
905
906    // A column is right-aligned when at least one body cell is numeric and every
907    // non-empty body cell is numeric — matching `tabulate`'s column typing, where
908    // empty cells are "missing" (ignored) and a number may carry thousands
909    // separators (`7,015`), which a plain `f64` parse rejects.
910    let right: Vec<bool> = (0..num_cols)
911        .map(|c| {
912            let mut any = false;
913            for row in &body {
914                let t = row[c].trim();
915                if t.is_empty() {
916                    continue;
917                }
918                if !is_number_cell(t) {
919                    return false;
920                }
921                any = true;
922            }
923            any
924        })
925        .collect();
926
927    // Column width = max(header_width + MIN_PADDING(2), max body-cell width).
928    let width: Vec<usize> = (0..num_cols)
929        .map(|c| {
930            let mut w = dw(&header[c]) + 2;
931            for row in &body {
932                w = w.max(dw(&row[c]));
933            }
934            w
935        })
936        .collect();
937
938    let fmt_cell = |s: &str, c: usize| -> String {
939        let pad = " ".repeat(width[c].saturating_sub(dw(s)));
940        let body = if right[c] {
941            format!("{pad}{s}")
942        } else {
943            format!("{s}{pad}")
944        };
945        format!(" {body} ")
946    };
947    let render_row = |row: &[String]| -> String {
948        let cells: Vec<String> = (0..num_cols).map(|c| fmt_cell(&row[c], c)).collect();
949        format!("|{}|", cells.join("|"))
950    };
951
952    let mut lines = Vec::with_capacity(body.len() + 2);
953    lines.push(render_row(&header));
954    let sep: Vec<String> = (0..num_cols).map(|c| "-".repeat(width[c] + 2)).collect();
955    lines.push(format!("|{}|", sep.join("|")));
956    for row in &body {
957        lines.push(render_row(row));
958    }
959    lines.join("\n")
960}
961
962/// Escape a table cell so it can't break the markdown table: newlines become
963/// spaces and pipes become the `&#124;` HTML entity (matches docling-core).
964fn escape_cell(s: &str) -> String {
965    s.replace('\n', " ").replace('|', "&#124;")
966}
967
968#[cfg(test)]
969mod tests {
970    use super::*;
971    use crate::{PictureImage, TableCell, TableStructure};
972
973    /// #385: where one list ends and the next begins is the backend's call
974    /// (`first_in_list`), never the serializer's. An ordered run `1.` → `5.`
975    /// is one list (an AsciiDoc numbered list around a nested one), and so are
976    /// mixed bullet/ordered items the backend did not separate; only a flagged
977    /// item opens a new list and earns the blank line.
978    #[test]
979    fn list_boundaries_come_from_the_backend_not_the_numbering() {
980        let item = |ordered: bool, number: u64, first_in_list: bool, text: &str| Node::ListItem {
981            ordered,
982            number,
983            first_in_list,
984            text: text.into(),
985            level: 0,
986            marker: None,
987            location: None,
988            dclx: None,
989            href: None,
990            layer: None,
991        };
992        let md = |items: Vec<Node>| {
993            let mut doc = DoclingDocument::new("t");
994            for n in items {
995                doc.push(n);
996            }
997            doc.export_to_markdown()
998        };
999        // A number gap alone is not a boundary.
1000        assert_eq!(
1001            md(vec![
1002                item(true, 1, true, "one"),
1003                item(true, 5, false, "five")
1004            ]),
1005            "1. one\n5. five\n"
1006        );
1007        // Nor is a kind flip the backend did not flag …
1008        assert_eq!(
1009            md(vec![
1010                item(false, 0, true, "bullet"),
1011                item(true, 1, false, "one"),
1012                item(false, 0, false, "bullet two"),
1013            ]),
1014            "- bullet\n1. one\n- bullet two\n"
1015        );
1016        // … while a flagged item is one, whatever its number says.
1017        assert_eq!(
1018            md(vec![
1019                item(true, 1, true, "a"),
1020                item(true, 2, false, "b"),
1021                item(true, 3, true, "new list, continuing count"),
1022            ]),
1023            "1. a\n2. b\n\n3. new list, continuing count\n"
1024        );
1025    }
1026
1027    #[test]
1028    fn renders_headings_paragraphs_and_lists() {
1029        let mut doc = DoclingDocument::new("demo");
1030        doc.add_heading(1, "Title");
1031        doc.add_paragraph("Hello world.");
1032        doc.push(Node::ListItem {
1033            ordered: false,
1034            number: 1,
1035            first_in_list: true,
1036            text: "first".into(),
1037            level: 0,
1038            marker: None,
1039            location: None,
1040            dclx: None,
1041            href: None,
1042            layer: None,
1043        });
1044        doc.push(Node::ListItem {
1045            ordered: false,
1046            number: 2,
1047            first_in_list: false,
1048            text: "second".into(),
1049            level: 0,
1050            marker: None,
1051            location: None,
1052            dclx: None,
1053            href: None,
1054            layer: None,
1055        });
1056        let md = doc.export_to_markdown();
1057        assert_eq!(md, "# Title\n\nHello world.\n\n- first\n- second\n");
1058    }
1059
1060    /// docling-core 2.92 (#721): a single newline inside an item's text is a
1061    /// GFM hard line break, a blank line stays a paragraph break, and a heading
1062    /// collapses its newline to a space. Nested-table dumps stay verbatim.
1063    #[test]
1064    fn single_newlines_become_gfm_hard_line_breaks() {
1065        let mut doc = DoclingDocument::new("t");
1066        doc.push(Node::Heading {
1067            level: 1,
1068            text: "Hello\nWorld".into(),
1069        });
1070        doc.push(Node::Paragraph {
1071            text: "line one\nline two\n\npara two".into(),
1072        });
1073        doc.push(Node::ListItem {
1074            ordered: false,
1075            number: 1,
1076            first_in_list: true,
1077            text: "item\ncontinued".into(),
1078            level: 0,
1079            marker: None,
1080            location: None,
1081            dclx: None,
1082            href: None,
1083            layer: None,
1084        });
1085        doc.push(Node::TextDump("A1 B1 \n\n\nC1".into()));
1086        assert_eq!(
1087            doc.export_to_markdown(),
1088            "# Hello World\n\nline one  \nline two\n\npara two\n\n- item  \ncontinued\n\nA1 B1 \n\n\nC1\n"
1089        );
1090    }
1091
1092    /// docling-core#540: inside a rich table cell a heading is plain text;
1093    /// docling-core#724: a field region renders only its items' key/value text.
1094    #[test]
1095    fn table_cell_mode_and_field_regions() {
1096        let mut doc = DoclingDocument::new("t");
1097        doc.push(Node::Heading {
1098            level: 2,
1099            text: "A  text".into(),
1100        });
1101        doc.push(Node::Paragraph {
1102            text: "body".into(),
1103        });
1104        assert_eq!(to_markdown_table_cell(&doc, false), "A  text\n\nbody");
1105        assert_eq!(doc.export_to_markdown(), "## A  text\n\nbody\n");
1106
1107        let mut doc = DoclingDocument::new("f");
1108        doc.push(Node::FieldRegion {
1109            items: vec![crate::FieldItem {
1110                marker: None,
1111                key: Some("Name:".into()),
1112                value: Some("John Doe".into()),
1113            }],
1114        });
1115        assert_eq!(doc.export_to_markdown(), "Name:\n\nJohn Doe\n");
1116    }
1117
1118    #[test]
1119    fn strict_renders_recovered_links_legacy_does_not() {
1120        let mut doc = DoclingDocument::new("cv");
1121        doc.add_paragraph("Find me on LinkedIn or GitHub.");
1122        doc.links = vec![
1123            ("LinkedIn".into(), "https://www.linkedin.com/in/x/".into()),
1124            ("GitHub".into(), "https://github.com/x/".into()),
1125        ];
1126        // Legacy/docling mode: links are left untouched (conformance preserved).
1127        assert_eq!(doc.export_to_markdown(), "Find me on LinkedIn or GitHub.\n");
1128        // Strict mode: anchors become Markdown links.
1129        assert_eq!(
1130            doc.export_to_markdown_with(true),
1131            "Find me on [LinkedIn](https://www.linkedin.com/in/x/) or [GitHub](https://github.com/x/).\n"
1132        );
1133    }
1134
1135    #[test]
1136    fn strict_links_match_escaped_anchor_and_consume_in_order() {
1137        let mut doc = DoclingDocument::new("d");
1138        // The PDF assembler HTML-escapes prose, so by serialization time the body
1139        // already carries `&amp;`; the anchor is stored un-escaped. The matcher must
1140        // escape the anchor to find it. Two identical anchors link in document order.
1141        doc.add_paragraph("AI &amp; ML here, and issues here, then issues there.");
1142        doc.links = vec![
1143            ("AI & ML".into(), "https://a/".into()),
1144            ("issues".into(), "https://first/".into()),
1145            ("issues".into(), "https://second/".into()),
1146        ];
1147        assert_eq!(
1148            doc.export_to_markdown_with(true),
1149            "[AI &amp; ML](https://a/) here, and [issues](https://first/) here, then [issues](https://second/) there.\n"
1150        );
1151    }
1152
1153    /// docling-core#698: the referenced-image destination is percent-encoded —
1154    /// upstream's own case table (paths, Windows flavours, UNC, URLs) plus
1155    /// idempotency on the encoded result.
1156    #[test]
1157    fn referenced_image_destinations_are_escaped() {
1158        let cases = [
1159            (
1160                "doc_artifacts/image_000001_ab12.png",
1161                "doc_artifacts/image_000001_ab12.png",
1162            ),
1163            (
1164                "My Report_artifacts/img.png",
1165                "My%20Report_artifacts/img.png",
1166            ),
1167            ("artifacts/img (1).png", "artifacts/img%20%281%29.png"),
1168            ("100%_scale/a#b?c.png", "100%_scale/a%23b%3Fc.png"),
1169            ("/home/a b/img.png", "/home/a%20b/img.png"),
1170            (
1171                "My Report_artifacts\\img.png",
1172                "My%20Report_artifacts/img.png",
1173            ),
1174            (
1175                "C:/Users/me/My Docs/img.png",
1176                "file:///C:/Users/me/My%20Docs/img.png",
1177            ),
1178            ("C:\\Users\\me\\img.png", "file:///C:/Users/me/img.png"),
1179            (
1180                "//server/share/My Docs/img.png",
1181                "file://server/share/My%20Docs/img.png",
1182            ),
1183            ("\\\\server\\share\\img.png", "file://server/share/img.png"),
1184            ("file:///home/a b/img.png", "file:///home/a%20b/img.png"),
1185            (
1186                "s3://bucket/My Report_artifacts/img.png",
1187                "s3://bucket/My%20Report_artifacts/img.png",
1188            ),
1189            (
1190                "https://example.com:8080/a b.png?w=1&h=2#frag",
1191                "https://example.com:8080/a%20b.png?w=1&h=2#frag",
1192            ),
1193            (
1194                "https://example.com/img (1).png",
1195                "https://example.com/img%20%281%29.png",
1196            ),
1197            ("caf\u{e9}/im\u{e4}ge.png", "caf%C3%A9/im%C3%A4ge.png"),
1198        ];
1199        for (input, expected) in cases {
1200            assert_eq!(escape_uri_path(input), expected, "input {input:?}");
1201            assert_eq!(
1202                escape_uri_path(expected),
1203                expected,
1204                "idempotent {expected:?}"
1205            );
1206        }
1207        // The whole marker, through the referenced-image export.
1208        let mut doc = DoclingDocument::new("t");
1209        doc.push(Node::Picture {
1210            caption: None,
1211            caption_href: None,
1212            image: Some(PictureImage {
1213                mimetype: "image/png".into(),
1214                width: 1,
1215                height: 1,
1216                data: b"x".to_vec(),
1217            }),
1218            classification: None,
1219        });
1220        let (md, files) = doc
1221            .export_to_markdown_with_images(ImageMode::Referenced, "My Report (final)_artifacts");
1222        assert!(
1223            md.contains("![Image](My%20Report%20%28final%29_artifacts/image_000000.png)"),
1224            "got:\n{md}"
1225        );
1226        // The file path handed back for writing stays unescaped.
1227        assert_eq!(files[0].0, "My Report (final)_artifacts/image_000000.png");
1228    }
1229
1230    /// Pictures the HTML backend folds into a list item print after the item
1231    /// line with plain newlines; a `<br>` newline in the item's own text is
1232    /// still a GFM hard line break.
1233    #[test]
1234    fn folded_list_item_pictures_keep_plain_newlines() {
1235        assert_eq!(
1236            list_item_text("Step\n<!-- image -->", false),
1237            "Step\n<!-- image -->"
1238        );
1239        assert_eq!(
1240            list_item_text("Step\nAlt text\n<!-- image -->\n<!-- image -->", false),
1241            "Step\nAlt text\n<!-- image -->\n<!-- image -->"
1242        );
1243        assert_eq!(
1244            list_item_text("line one\nline two", false),
1245            "line one  \nline two"
1246        );
1247    }
1248
1249    /// docling-core#723: the header block is the leading run of rows on which a
1250    /// `column_header` cell starts, flattened per column with " - ".
1251    #[test]
1252    fn stacked_header_rows_flatten_into_one() {
1253        let mut t = Table {
1254            rows: vec![
1255                vec!["".into(), "% of Total".into(), "% of Total".into()],
1256                vec!["class".into(), "Train".into(), "Test".into()],
1257                vec!["Caption".into(), "2.04".into(), "1.77".into()],
1258            ],
1259            ..Default::default()
1260        };
1261        t.structure = Some(TableStructure {
1262            header_row: vec![true, true, false],
1263            col_continuation: vec![
1264                vec![false, false, true],
1265                vec![false, false, false],
1266                vec![false, false, false],
1267            ],
1268            ..Default::default()
1269        });
1270        assert_eq!(t.header_row_count(), 2);
1271        assert_eq!(
1272            render_table(&t, true),
1273            "| class | % of Total - Train | % of Total - Test |\n| - | - | - |\n| Caption | 2.04 | 1.77 |"
1274        );
1275        // padded: widths from the flattened header, alignment from body rows
1276        assert_eq!(
1277            render_table(&t, false),
1278            "| class   |   % of Total - Train |   % of Total - Test |\n\
1279             |---------|----------------------|---------------------|\n\
1280             | Caption |                 2.04 |                1.77 |"
1281        );
1282    }
1283
1284    /// A header spanning two rows is repeated into the second row by the grid;
1285    /// that row is not a header row unless another header cell starts there.
1286    #[test]
1287    fn vertically_spanning_header_does_not_extend_the_block() {
1288        let mut t = Table {
1289            rows: vec![
1290                vec!["Name".into(), "Value".into()],
1291                vec!["Name".into(), "1".into()],
1292                vec!["x".into(), "2".into()],
1293            ],
1294            ..Default::default()
1295        };
1296        t.structure = Some(TableStructure {
1297            col_header: vec![vec![true, true], vec![true, false], vec![false, false]],
1298            row_continuation: vec![vec![false, false], vec![true, false], vec![false, false]],
1299            ..Default::default()
1300        });
1301        assert_eq!(t.header_row_count(), 1);
1302        assert_eq!(
1303            render_table(&t, true),
1304            "| Name | Value |\n| - | - |\n| Name | 1 |\n| x | 2 |"
1305        );
1306    }
1307
1308    /// Flags that begin on a later row promote nothing: every row stays in the
1309    /// body under an empty header row (tabulate's `headers=["", ""]`).
1310    #[test]
1311    fn header_flags_not_on_row_zero_keep_all_rows_in_the_body() {
1312        let mut t = Table {
1313            rows: vec![
1314                vec!["1".into(), "2".into()],
1315                vec!["a".into(), "b".into()],
1316                vec!["333".into(), "4".into()],
1317            ],
1318            ..Default::default()
1319        };
1320        t.structure = Some(TableStructure {
1321            header_row: vec![false, true, false],
1322            ..Default::default()
1323        });
1324        assert_eq!(t.header_row_count(), 0);
1325        assert_eq!(
1326            render_table(&t, false),
1327            "|     |    |\n|-----|----|\n| 1   | 2  |\n| a   | b  |\n| 333 | 4  |"
1328        );
1329    }
1330
1331    /// A pivot table's row headers (`<th rowspan>`) carry `row_header`, not
1332    /// `column_header` (docling#4216), so the data row beside them is not
1333    /// pulled into the header block — what this port used to reach with a
1334    /// deviation now falls out of the flags themselves.
1335    #[test]
1336    fn pivot_row_headers_do_not_extend_the_header() {
1337        let mut t = Table {
1338            rows: vec![
1339                vec!["Year".into(), "Month".into()],
1340                vec!["2025".into(), "January".into()],
1341                vec!["2025".into(), "February".into()],
1342            ],
1343            ..Default::default()
1344        };
1345        t.structure = Some(TableStructure {
1346            col_header: vec![vec![true, true], vec![false, false], vec![false, false]],
1347            row_header: vec![vec![false, false], vec![true, false], vec![true, false]],
1348            row_continuation: vec![vec![false, false], vec![false, false], vec![true, false]],
1349            ..Default::default()
1350        });
1351        assert_eq!(t.header_row_count(), 1);
1352        assert_eq!(
1353            render_table(&t, true),
1354            "| Year | Month |\n| - | - |\n| 2025 | January |\n| 2025 | February |"
1355        );
1356    }
1357
1358    /// No `column_header` anywhere (first-class cells without flags) → row 0
1359    /// stays the header, as before.
1360    #[test]
1361    fn unflagged_cells_keep_row_zero_as_header() {
1362        let mut t = Table {
1363            rows: vec![vec!["h".into()], vec!["d".into()]],
1364            ..Default::default()
1365        };
1366        t.cells = Some(
1367            [(0usize, "h"), (1, "d")]
1368                .into_iter()
1369                .map(|(r, text)| TableCell {
1370                    text: text.into(),
1371                    bbox: None,
1372                    start_row: r,
1373                    start_col: 0,
1374                    row_span: 1,
1375                    col_span: 1,
1376                    column_header: false,
1377                    row_header: false,
1378                    row_section: false,
1379                })
1380                .collect(),
1381        );
1382        assert_eq!(t.header_row_count(), 1);
1383        assert_eq!(render_table(&t, true), "| h |\n| - |\n| d |");
1384    }
1385
1386    #[test]
1387    fn renders_compact_table() {
1388        let mut doc = DoclingDocument::new("t");
1389        // The compact form is opt-in (the PDF backend sets it); default output uses
1390        // the padded GitHub serializer (covered by the regression fixtures).
1391        doc.compact_tables = true;
1392        doc.push(Node::Table(Table {
1393            rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
1394            location: None,
1395            structure: None,
1396            cell_blocks: None,
1397            cells: None,
1398            caption: None,
1399        }));
1400        let md = doc.export_to_markdown();
1401        assert_eq!(md, "| a | b |\n| - | - |\n| 1 | 2 |\n");
1402    }
1403
1404    #[test]
1405    fn renders_padded_github_table_by_default() {
1406        let mut doc = DoclingDocument::new("t");
1407        doc.push(Node::Table(Table {
1408            rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
1409            location: None,
1410            structure: None,
1411            cell_blocks: None,
1412            cells: None,
1413            caption: None,
1414        }));
1415        let md = doc.export_to_markdown();
1416        // Numeric data columns are right-aligned; columns padded to header+2.
1417        assert_eq!(md, "|   a |   b |\n|-----|-----|\n|   1 |   2 |\n");
1418    }
1419
1420    #[test]
1421    fn strict_unescapes_inline_underscores_legacy_keeps_them() {
1422        let mut doc = DoclingDocument::new("t");
1423        doc.add_heading(1, "a\\_b");
1424        doc.add_paragraph("x\\_y");
1425        doc.push(Node::ListItem {
1426            ordered: false,
1427            number: 1,
1428            first_in_list: true,
1429            text: "i\\_j".into(),
1430            level: 0,
1431            marker: None,
1432            location: None,
1433            dclx: None,
1434            href: None,
1435            layer: None,
1436        });
1437        // Legacy reproduces docling's `\_` escaping byte-for-byte.
1438        assert_eq!(doc.export_to_markdown(), "# a\\_b\n\nx\\_y\n\n- i\\_j\n");
1439        // Strict prefers literal underscores (Rust-only readability mode).
1440        assert_eq!(doc.export_to_markdown_with(true), "# a_b\n\nx_y\n\n- i_j\n");
1441    }
1442
1443    /// Drive a document's nodes through [`MarkdownStreamer`] in the given page
1444    /// splits and assert the concatenated chunks equal the buffered serializer.
1445    fn assert_stream_matches(
1446        doc: &DoclingDocument,
1447        strict: bool,
1448        images: ImageMode,
1449        splits: &[usize],
1450    ) {
1451        let (want, want_artifacts) = to_markdown_images(doc, strict, images, "artifacts");
1452        let mut streamer =
1453            MarkdownStreamer::with_artifacts(strict, images, doc.compact_tables, "artifacts");
1454        let mut got = String::new();
1455        let mut got_artifacts = Vec::new();
1456        let mut start = 0;
1457        for &end in splits {
1458            // Links only matter in strict mode; feed them all with the first batch
1459            // that has content (document order is preserved by the queue).
1460            let links = if start == 0 {
1461                doc.links.as_slice()
1462            } else {
1463                &[]
1464            };
1465            got.push_str(&streamer.push(&doc.nodes[start..end], links));
1466            // Referenced mode: drain per push, as a real caller writing files
1467            // page by page would — numbering must continue across drains.
1468            got_artifacts.extend(streamer.take_artifacts());
1469            start = end;
1470        }
1471        got.push_str(&streamer.push(
1472            &doc.nodes[start..],
1473            if start == 0 {
1474                doc.links.as_slice()
1475            } else {
1476                &[]
1477            },
1478        ));
1479        got_artifacts.extend(streamer.take_artifacts());
1480        got.push_str(&streamer.finish());
1481        assert_eq!(
1482            got, want,
1483            "streamed output diverged (splits={splits:?}, strict={strict})"
1484        );
1485        assert_eq!(
1486            got_artifacts, want_artifacts,
1487            "streamed artifacts diverged (splits={splits:?}, strict={strict})"
1488        );
1489    }
1490
1491    #[test]
1492    fn streaming_is_byte_identical_to_buffered() {
1493        let mut doc = DoclingDocument::new("d");
1494        doc.add_heading(1, "Title");
1495        doc.add_paragraph("First paragraph.");
1496        doc.push(Node::ListItem {
1497            ordered: false,
1498            number: 1,
1499            first_in_list: true,
1500            text: "a".into(),
1501            level: 0,
1502            marker: None,
1503            location: None,
1504            dclx: None,
1505            href: None,
1506            layer: None,
1507        });
1508        doc.push(Node::ListItem {
1509            ordered: false,
1510            number: 2,
1511            first_in_list: false,
1512            text: "b".into(),
1513            level: 0,
1514            marker: None,
1515            location: None,
1516            dclx: None,
1517            href: None,
1518            layer: None,
1519        });
1520        doc.push(Node::Code {
1521            language: Some("rust".into()),
1522            text: "let x = 1;".into(),
1523            orig: None,
1524            pretty: None,
1525        });
1526        doc.push(Node::Table(Table {
1527            rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
1528            location: None,
1529            structure: None,
1530            cell_blocks: None,
1531            cells: None,
1532            caption: None,
1533        }));
1534        doc.push(Node::Picture {
1535            caption: Some("Fig 1".into()),
1536            caption_href: None,
1537            image: Some(PictureImage {
1538                mimetype: "image/png".into(),
1539                width: 2,
1540                height: 2,
1541                data: b"png-one".to_vec(),
1542            }),
1543            classification: None,
1544        });
1545        doc.add_paragraph("Last paragraph.");
1546        // A second embedded picture, so referenced mode must keep numbering
1547        // (`image_000001`) across chunk boundaries.
1548        doc.push(Node::Picture {
1549            caption: None,
1550            caption_href: None,
1551            image: Some(PictureImage {
1552                mimetype: "image/png".into(),
1553                width: 2,
1554                height: 2,
1555                data: b"png-two".to_vec(),
1556            }),
1557            classification: None,
1558        });
1559
1560        // A run of list items must never straddle a split, so try splits that fall
1561        // on safe block boundaries (the streaming PDF assembler guarantees this).
1562        for &strict in &[false, true] {
1563            for &images in &[
1564                ImageMode::Placeholder,
1565                ImageMode::Embedded,
1566                ImageMode::Referenced,
1567            ] {
1568                for splits in [&[][..], &[1][..], &[2][..], &[4][..], &[1, 4, 6, 7][..]] {
1569                    assert_stream_matches(&doc, strict, images, splits);
1570                }
1571            }
1572        }
1573    }
1574
1575    #[test]
1576    fn streaming_applies_recovered_links_in_strict_mode() {
1577        let mut doc = DoclingDocument::new("d");
1578        doc.add_paragraph("See LinkedIn for details.");
1579        doc.add_paragraph("And GitHub too.");
1580        doc.links = vec![
1581            ("LinkedIn".into(), "https://lnkd/".into()),
1582            ("GitHub".into(), "https://gh/".into()),
1583        ];
1584        // The second anchor lives in the second block, so it must be carried across
1585        // the page boundary and placed when that block streams out.
1586        assert_stream_matches(&doc, true, ImageMode::Placeholder, &[1]);
1587    }
1588
1589    #[test]
1590    fn strict_tightens_punctuation_spacing_legacy_keeps_it() {
1591        let mut doc = DoclingDocument::new("t");
1592        doc.add_paragraph("see [ 37 , 36 ] and ( x ) .");
1593        // Legacy keeps docling's spacing byte-for-byte.
1594        assert_eq!(doc.export_to_markdown(), "see [ 37 , 36 ] and ( x ) .\n");
1595        // Strict tightens punctuation for readable Markdown.
1596        assert_eq!(doc.export_to_markdown_with(true), "see [37, 36] and (x).\n");
1597    }
1598}