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}
29
30/// Render a document to a Markdown string (pictures as placeholders).
31///
32/// `strict` selects the serializer-level behaviours that differ between
33/// docling-legacy output and cleaner Markdown — currently the code-fence
34/// language (legacy drops it, strict keeps it).
35pub fn to_markdown(doc: &DoclingDocument, strict: bool) -> String {
36    to_markdown_images(doc, strict, ImageMode::Placeholder, "artifacts").0
37}
38
39/// Render to Markdown with an explicit picture [`ImageMode`]. Returns the
40/// Markdown and, for [`ImageMode::Referenced`], the `(path, bytes)` of each image
41/// the caller should write (relative to the Markdown file).
42pub fn to_markdown_images(
43    doc: &DoclingDocument,
44    strict: bool,
45    images: ImageMode,
46    artifacts_dir: &str,
47) -> (String, Vec<(String, Vec<u8>)>) {
48    let mut ctx = Ctx {
49        strict,
50        compact_tables: doc.compact_tables,
51        images,
52        artifacts_dir: artifacts_dir.to_string(),
53        artifacts: Vec::new(),
54        pic_index: 0,
55    };
56    let mut blocks: Vec<String> = Vec::new();
57    render(&doc.nodes, &mut blocks, &mut ctx);
58    let mut body = blocks.join("\n\n");
59    // Strict mode only: turn recovered source hyperlinks into Markdown links.
60    // docling's standard pipeline drops them, so doing this in legacy mode would
61    // diverge from docling — hence strict-only, leaving conformance output intact.
62    if strict && !doc.links.is_empty() {
63        body = apply_links(&body, &doc.links);
64    }
65    let md = if body.is_empty() {
66        String::new()
67    } else {
68        format!("{body}\n")
69    };
70    (md, ctx.artifacts)
71}
72
73/// Wrap each recovered link's anchor text in Markdown `[anchor](href)`. Anchors
74/// arrive cleaned (curly quotes/dashes already normalized) but un-escaped, so we
75/// match against the body's HTML-escaped (`&`/`<`/`>`) form, the way prose nodes
76/// were serialized. Links are consumed in document order from a moving cursor, so
77/// a repeated anchor (e.g. two "issues") links its successive occurrences rather
78/// than all pointing at the first. An anchor that can't be located is skipped
79/// (its text may have been split across a line wrap or table cell).
80fn apply_links(body: &str, links: &[(String, String)]) -> String {
81    let mut out = body.to_string();
82    let mut cursor = 0usize;
83    for (anchor, href) in links {
84        let anchor = anchor
85            .replace('&', "&amp;")
86            .replace('<', "&lt;")
87            .replace('>', "&gt;");
88        if anchor.is_empty() {
89            continue;
90        }
91        if let Some(rel) = out[cursor..].find(&anchor) {
92            let at = cursor + rel;
93            // Don't relink inside an already-emitted `](` Markdown link target.
94            let replacement = format!("[{anchor}]({href})");
95            out.replace_range(at..at + anchor.len(), &replacement);
96            cursor = at + replacement.len();
97        }
98    }
99    out
100}
101
102/// Like [`apply_links`] but over a single chunk, consuming from a shared queue so
103/// the same `[anchor](href)` rewriting can be applied incrementally as Markdown is
104/// streamed out. Each queued link is matched (in document order) against `chunk`
105/// and rewritten in place; a link whose anchor is not in this chunk is carried
106/// forward in the queue for a later chunk. Anchors are recovered in document
107/// order and a chunk is always a contiguous run of whole blocks, so this
108/// reproduces [`apply_links`]' single moving cursor: the link lands in whichever
109/// chunk contains its anchor, identically to the buffered path. (A link whose
110/// anchor never appears is carried to the end and dropped — the same no-op
111/// `apply_links` performs for an unlocatable anchor.)
112fn apply_links_chunk(chunk: &str, queue: &mut Vec<(String, String)>) -> String {
113    let mut out = chunk.to_string();
114    let mut cursor = 0usize;
115    let mut carried: Vec<(String, String)> = Vec::new();
116    for (anchor_raw, href) in std::mem::take(queue) {
117        let anchor = anchor_raw
118            .replace('&', "&amp;")
119            .replace('<', "&lt;")
120            .replace('>', "&gt;");
121        if anchor.is_empty() {
122            continue;
123        }
124        if let Some(rel) = out[cursor..].find(&anchor) {
125            let at = cursor + rel;
126            let replacement = format!("[{anchor}]({href})");
127            out.replace_range(at..at + anchor.len(), &replacement);
128            cursor = at + replacement.len();
129        } else {
130            // Not in this chunk; try again when its block is flushed.
131            carried.push((anchor_raw, href));
132        }
133    }
134    *queue = carried;
135    out
136}
137
138/// Incremental Markdown serializer: feed finalized, in-document-order batches of
139/// [`Node`]s and receive Markdown chunks whose concatenation is **byte-identical**
140/// to [`to_markdown_images`] over the same nodes. This is the streaming
141/// counterpart of the buffered serializer — used to emit a document's Markdown in
142/// chunks (e.g. page by page, as the parallel PDF pipeline finishes pages) instead
143/// of building the whole string up front.
144///
145/// Only [`ImageMode::Placeholder`] and [`ImageMode::Embedded`] are streamable:
146/// [`ImageMode::Referenced`] needs a side-channel for the image bytes, which only
147/// the buffered [`to_markdown_images`] provides.
148///
149/// Each [`push`](Self::push) must contain whole blocks in reading order: a caller
150/// must not split a run of list items across two pushes (the run would render as
151/// two separate lists). Finalized PDF page batches already satisfy this.
152pub struct MarkdownStreamer {
153    strict: bool,
154    images: ImageMode,
155    compact_tables: bool,
156    /// Whether any non-empty chunk has been emitted yet (drives `\n\n` joins and
157    /// the trailing newline).
158    emitted_any: bool,
159    /// Recovered links not yet placed (strict mode), consumed in document order.
160    links: Vec<(String, String)>,
161}
162
163impl MarkdownStreamer {
164    /// Create a streamer. `compact_tables` mirrors [`DoclingDocument::compact_tables`].
165    pub fn new(strict: bool, images: ImageMode, compact_tables: bool) -> Self {
166        debug_assert!(
167            images != ImageMode::Referenced,
168            "referenced image mode is not streamable; use to_markdown_images"
169        );
170        Self {
171            strict,
172            images,
173            compact_tables,
174            emitted_any: false,
175            links: Vec::new(),
176        }
177    }
178
179    /// Render one finalized batch of nodes (plus any links recovered from the same
180    /// span, in document order) into the next Markdown chunk. Returns an empty
181    /// string when the batch produces no output (e.g. empty tables/pictures), in
182    /// which case nothing should be written.
183    pub fn push(&mut self, nodes: &[Node], links: &[(String, String)]) -> String {
184        self.links.extend(links.iter().cloned());
185        let mut ctx = Ctx {
186            strict: self.strict,
187            compact_tables: self.compact_tables,
188            images: self.images,
189            // Referenced mode is rejected at construction, so the artifact sink is
190            // never touched.
191            artifacts_dir: String::new(),
192            artifacts: Vec::new(),
193            pic_index: 0,
194        };
195        let mut blocks: Vec<String> = Vec::new();
196        render(nodes, &mut blocks, &mut ctx);
197        if blocks.is_empty() {
198            return String::new();
199        }
200        let mut body = blocks.join("\n\n");
201        if self.strict && !self.links.is_empty() {
202            body = apply_links_chunk(&body, &mut self.links);
203        }
204        let chunk = if self.emitted_any {
205            format!("\n\n{body}")
206        } else {
207            body
208        };
209        self.emitted_any = true;
210        chunk
211    }
212
213    /// Emit the trailing newline that finishes the document (empty if no content
214    /// was produced). Call exactly once, after the final [`push`](Self::push).
215    pub fn finish(self) -> String {
216        if self.emitted_any {
217            "\n".to_string()
218        } else {
219            String::new()
220        }
221    }
222}
223
224/// In `strict` mode, rewrite inline text for readability rather than byte-for-byte
225/// docling fidelity: undo the legacy `\_` underscore escaping, and tighten stray
226/// spaces around punctuation (`[ 37 , 36 ]` → `[37, 36]`, `( x )` → `(x)`). This
227/// cleans up both the PDF backend's glyph-split spacing and the space the legacy
228/// emphasis serialization leaves before punctuation (`*a* ,` → `*a*,`).
229/// Legacy/default output keeps docling's spacing untouched. Only inline text
230/// nodes pass through here — code blocks and table cells are left alone.
231fn strict_text(text: &str, strict: bool) -> String {
232    if !strict {
233        return text.to_string();
234    }
235    text.replace("\\_", "_")
236        .replace(" ,", ",")
237        .replace(" .", ".")
238        .replace(" ;", ";")
239        .replace(" )", ")")
240        .replace("( ", "(")
241        .replace(" ]", "]")
242        .replace("[ ", "[")
243}
244
245fn render(nodes: &[Node], blocks: &mut Vec<String>, ctx: &mut Ctx) {
246    let mut i = 0;
247    while i < nodes.len() {
248        match &nodes[i] {
249            Node::ListItem { .. } => {
250                let start = i;
251                i += 1;
252                loop {
253                    match nodes.get(i) {
254                        Some(Node::ListItem { .. }) => i += 1,
255                        // An empty paragraph between two list items is absorbed
256                        // into the run — docling keeps such a ListGroup
257                        // contiguous rather than splitting it.
258                        Some(Node::Paragraph { text })
259                            if text.is_empty()
260                                && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
261                        {
262                            i += 1
263                        }
264                        _ => break,
265                    }
266                }
267                render_list_run(&nodes[start..i], blocks, ctx.strict);
268            }
269            other => {
270                render_one(other, blocks, ctx);
271                i += 1;
272            }
273        }
274    }
275}
276
277/// Render a contiguous run of list items.
278///
279/// Ordered items use their explicit `number`. A new sibling list (marked by
280/// `first_in_list`) at the same depth is separated by a blank line, matching
281/// docling-core's serializer.
282fn render_list_run(items: &[Node], blocks: &mut Vec<String>, strict: bool) {
283    let mut lines: Vec<String> = Vec::new();
284    // Per level, the previous item's (ordered, number) so we can detect a new
285    // sibling list.
286    let mut prev: Vec<Option<(bool, u64)>> = Vec::new();
287
288    for item in items {
289        let Node::ListItem {
290            ordered,
291            number,
292            first_in_list,
293            text,
294            level,
295            marker: _,
296            location: _,
297            dclx: _,
298            href: _,
299            layer,
300        } = item
301        else {
302            continue;
303        };
304        // A non-body (furniture) list item is omitted from Markdown, matching
305        // docling's content-layer filtering.
306        if layer.is_some() {
307            continue;
308        }
309        let level = *level as usize;
310
311        // Returning to a shallower level ends the deeper sibling lists.
312        prev.truncate(level + 1);
313        while prev.len() <= level {
314            prev.push(None);
315        }
316
317        // A new sibling list at the same depth gets a blank line: the kind flips
318        // (`<ul>`↔`<ol>`), an ordered run breaks (`1, 2` then `42`), or the
319        // backend flagged a fresh list (e.g. Markdown's bullet changing `-`→`*`).
320        // Only at the top level: nested sibling groups are children of a list
321        // item, and docling joins an item's children without blank lines.
322        if level == 0 {
323            if let Some((prev_ordered, prev_number)) = prev[level] {
324                let new_list = *first_in_list
325                    || prev_ordered != *ordered
326                    || (*ordered && *number != prev_number + 1);
327                if new_list {
328                    lines.push(String::new());
329                }
330            }
331        }
332
333        let indent = "    ".repeat(level);
334        let marker = if *ordered {
335            format!("{number}.")
336        } else {
337            "-".to_string()
338        };
339        lines.push(format!("{indent}{marker} {}", strict_text(text, strict)));
340        prev[level] = Some((*ordered, *number));
341    }
342
343    // A run consisting only of furniture (content-layer-filtered) items yields no
344    // lines; pushing an empty block here would surface as a stray blank line.
345    if !lines.is_empty() {
346        blocks.push(lines.join("\n"));
347    }
348}
349
350fn render_one(node: &Node, blocks: &mut Vec<String>, ctx: &mut Ctx) {
351    match node {
352        Node::Heading { level, text } => {
353            let hashes = "#".repeat((*level).clamp(1, 6) as usize);
354            blocks.push(format!("{hashes} {}", strict_text(text, ctx.strict)));
355        }
356        // An empty body paragraph (docling's blank-line text item) contributes
357        // nothing to Markdown — only DocLang/JSON keep it.
358        Node::Paragraph { text } if text.is_empty() => {}
359        Node::Paragraph { text } => blocks.push(strict_text(text, ctx.strict)),
360        Node::CheckboxItem { checked, text } => {
361            let mark = if *checked { "- [x] " } else { "- [ ] " };
362            blocks.push(strict_text(&format!("{mark}{text}"), ctx.strict));
363        }
364        Node::Code { language, text } => {
365            // Legacy docling never emits a language on the fence; strict keeps it.
366            let lang = match language {
367                Some(l) if ctx.strict => l.as_str(),
368                _ => "",
369            };
370            blocks.push(format!("```{lang}\n{text}\n```"));
371        }
372        Node::Table(table) => {
373            let rendered = render_table(table, ctx.compact_tables);
374            if !rendered.is_empty() {
375                blocks.push(rendered);
376            }
377        }
378        Node::Picture { caption, image } => {
379            if let Some(cap) = caption {
380                if !cap.is_empty() {
381                    blocks.push(cap.clone());
382                }
383            }
384            blocks.push(picture_marker(image.as_ref(), ctx));
385        }
386        // A chart renders as docling's picture-with-meta markdown: the caption,
387        // the placeholder, the humanized classification ("line_chart" ->
388        // "Line chart"), then the chart's data grid as a regular table.
389        Node::Chart {
390            kind,
391            table,
392            caption,
393            ..
394        } => {
395            if let Some(cap) = caption {
396                if !cap.is_empty() {
397                    blocks.push(cap.clone());
398                }
399            }
400            blocks.push(picture_marker(None, ctx));
401            blocks.push(humanize_label(kind));
402            let rendered = render_table(table, false);
403            if !rendered.is_empty() {
404                blocks.push(rendered);
405            }
406        }
407        // A DocLang-only node is omitted from Markdown.
408        Node::DoclangOnly(_) => {}
409        Node::Group { children, .. } => render(children, blocks, ctx),
410        Node::FieldRegion { items } => {
411            // docling renders the region container (which carries no text of its
412            // own) as a `<!-- missing-text -->` marker, then each field item the
413            // same way, followed by that item's marker/key/value as separate
414            // paragraphs.
415            blocks.push(MISSING_TEXT.to_string());
416            for item in items {
417                blocks.push(MISSING_TEXT.to_string());
418                for part in [&item.marker, &item.key, &item.value].into_iter().flatten() {
419                    blocks.push(strict_text(part, ctx.strict));
420                }
421            }
422        }
423        // A rich inline group renders exactly like a paragraph of its Markdown
424        // text — the structured runs are DocLang-only.
425        Node::InlineGroup { md_text, .. } => blocks.push(strict_text(md_text, ctx.strict)),
426        // A plain-text backend dump renders verbatim as a single block.
427        Node::TextDump(text) => {
428            if !text.is_empty() {
429                blocks.push(text.clone());
430            }
431        }
432        // Furniture (page headers/footers, HTML `<title>`) is excluded from
433        // Markdown by default, mirroring docling.
434        Node::Furniture { .. } => {}
435        Node::PageFurniture { .. } => {}
436        // Layout provenance is DocLang-only; render the wrapped node.
437        Node::Located { inner, .. } => render_one(inner, blocks, ctx),
438        // Page breaks are DocLang-only; docling omits them from Markdown.
439        Node::PageBreak => {}
440        // Handled by the run-merging branch in `render`.
441        Node::ListItem { .. } => unreachable!("list items are rendered in runs"),
442    }
443}
444
445/// docling's placeholder for a structural node (a field region / item) that has
446/// no text of its own.
447const MISSING_TEXT: &str = "<!-- missing-text -->";
448
449/// The Markdown for a picture under the active [`ImageMode`]; Referenced mode also
450/// records the bytes in `ctx.artifacts` for the caller to write.
451/// docling-core's `_humanize_text`: underscores to spaces, first letter
452/// capitalized ("line_chart" -> "Line chart").
453fn humanize_label(label: &str) -> String {
454    let text = label.replace('_', " ");
455    let mut chars = text.chars();
456    match chars.next() {
457        Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
458        None => text,
459    }
460}
461
462fn picture_marker(image: Option<&crate::PictureImage>, ctx: &mut Ctx) -> String {
463    match (ctx.images, image) {
464        (ImageMode::Embedded, Some(img)) => format!("![Image]({})", img.data_uri()),
465        (ImageMode::Referenced, Some(img)) => {
466            let path = format!(
467                "{}/image_{:06}.{}",
468                ctx.artifacts_dir,
469                ctx.pic_index,
470                ext_for(&img.mimetype)
471            );
472            ctx.pic_index += 1;
473            ctx.artifacts.push((path.clone(), img.data.clone()));
474            format!("![Image]({path})")
475        }
476        // Placeholder, or any mode with no extracted image.
477        _ => "<!-- image -->".to_string(),
478    }
479}
480
481fn ext_for(mimetype: &str) -> &str {
482    match mimetype {
483        "image/jpeg" => "jpg",
484        "image/gif" => "gif",
485        "image/webp" => "webp",
486        "image/bmp" => "bmp",
487        "image/tiff" => "tif",
488        _ => "png",
489    }
490}
491
492/// Render a table. `compact` selects between two serializers:
493///
494/// - **padded** (default) — docling-core's `tabulate(tablefmt="github")`: columns
495///   are padded to a fixed width (header width + a minimum padding of 2, or the
496///   widest data cell); numeric columns (every data cell parses as a number) are
497///   right-aligned, others left-aligned; separators are plain dashes of
498///   `width + 2`. Matches current published docling (DOCX/HTML conformance).
499/// - **compact** — `| a | b |` cells with single-dash `| - | - |` separators, no
500///   width padding. Matches the committed PDF groundtruth corpus, which predates
501///   the padded serializer.
502///
503/// Each cell is first escaped (`\n` → space, `|` → `&#124;`) so it can't break the
504/// table. Row 0 is the header.
505/// Whether a table cell counts as a number for column alignment, matching
506/// `tabulate`'s detection: an ordinary float/int (`f64`-parseable, covering
507/// `1e2`/`inf`/`+1.5`) **or** a thousands-separated number like `7,015`.
508fn is_number_cell(t: &str) -> bool {
509    t.parse::<f64>().is_ok() || is_thousands_number(t)
510}
511
512/// A number with comma thousands-separators, per `tabulate`'s
513/// `_float_with_thousands_separators` regex
514/// (`^(([+-]?[0-9]{1,3})(?:,([0-9]{3}))*)?(?(1)\.[0-9]*|\.[0-9]+)?$`): the
515/// integer part is 1–3 digits then any number of `,ddd` groups; the fraction is
516/// optional (and, without an integer part, must have at least one digit).
517fn is_thousands_number(t: &str) -> bool {
518    let b = t.as_bytes();
519    let mut i = 0;
520    let start = i;
521    if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
522        i += 1;
523    }
524    // First digit chunk: 1–3 digits.
525    let d0 = i;
526    while i < b.len() && b[i].is_ascii_digit() && i - d0 < 3 {
527        i += 1;
528    }
529    let has_int = i > d0;
530    if has_int {
531        // Subsequent `,ddd` groups (exactly three digits each).
532        while i + 3 < b.len() + 1
533            && b.get(i) == Some(&b',')
534            && b.get(i + 1).is_some_and(u8::is_ascii_digit)
535            && b.get(i + 2).is_some_and(u8::is_ascii_digit)
536            && b.get(i + 3).is_some_and(u8::is_ascii_digit)
537        {
538            i += 4;
539        }
540    } else {
541        // A sign only counts with an integer part.
542        i = start;
543    }
544    // Optional fraction.
545    if i < b.len() && b[i] == b'.' {
546        i += 1;
547        let f0 = i;
548        while i < b.len() && b[i].is_ascii_digit() {
549            i += 1;
550        }
551        if !has_int && i == f0 {
552            return false; // `.` with no digits and no integer part
553        }
554    } else if !has_int {
555        return false; // neither integer nor fractional part
556    }
557    i == b.len()
558}
559
560pub(crate) fn render_table(table: &Table, compact: bool) -> String {
561    if table.rows.is_empty() {
562        return String::new();
563    }
564    let num_cols = table.rows.iter().map(Vec::len).max().unwrap_or(0);
565    if num_cols == 0 {
566        return String::new();
567    }
568
569    // Escaped, rectangular grid (ragged rows padded with empty cells). `tabulate`
570    // strips data cells of surrounding whitespace but leaves the header row as-is.
571    let grid: Vec<Vec<String>> = table
572        .rows
573        .iter()
574        .enumerate()
575        .map(|(r, row)| {
576            (0..num_cols)
577                .map(|c| {
578                    let cell = escape_cell(row.get(c).map(String::as_str).unwrap_or(""));
579                    if r == 0 {
580                        cell
581                    } else {
582                        cell.trim().to_string()
583                    }
584                })
585                .collect()
586        })
587        .collect();
588
589    if compact {
590        // Compact: cells joined by " | ", no padding, single-dash separators.
591        let render_row = |r: usize| -> String { format!("| {} |", grid[r].join(" | ")) };
592        let mut lines = Vec::with_capacity(grid.len() + 1);
593        lines.push(render_row(0));
594        let sep: Vec<&str> = (0..num_cols).map(|_| "-").collect();
595        lines.push(format!("| {} |", sep.join(" | ")));
596        for r in 1..grid.len() {
597            lines.push(render_row(r));
598        }
599        return lines.join("\n");
600    }
601
602    // Display width (Unicode scalar count — good enough for now).
603    let dw = |s: &str| s.chars().count();
604    let data_rows = 1..grid.len();
605
606    // A column is right-aligned when at least one data cell is numeric and every
607    // non-empty data cell is numeric — matching `tabulate`'s column typing, where
608    // empty cells are "missing" (ignored) and a number may carry thousands
609    // separators (`7,015`), which a plain `f64` parse rejects.
610    let right: Vec<bool> = (0..num_cols)
611        .map(|c| {
612            let mut any = false;
613            for r in data_rows.clone() {
614                let t = grid[r][c].trim();
615                if t.is_empty() {
616                    continue;
617                }
618                if !is_number_cell(t) {
619                    return false;
620                }
621                any = true;
622            }
623            any
624        })
625        .collect();
626
627    // Column width = max(header_width + MIN_PADDING(2), max data-cell width).
628    let width: Vec<usize> = (0..num_cols)
629        .map(|c| {
630            let mut w = dw(&grid[0][c]) + 2;
631            for r in data_rows.clone() {
632                w = w.max(dw(&grid[r][c]));
633            }
634            w
635        })
636        .collect();
637
638    let fmt_cell = |s: &str, c: usize| -> String {
639        let pad = " ".repeat(width[c].saturating_sub(dw(s)));
640        let body = if right[c] {
641            format!("{pad}{s}")
642        } else {
643            format!("{s}{pad}")
644        };
645        format!(" {body} ")
646    };
647    let render_row = |r: usize| -> String {
648        let cells: Vec<String> = (0..num_cols).map(|c| fmt_cell(&grid[r][c], c)).collect();
649        format!("|{}|", cells.join("|"))
650    };
651
652    let mut lines = Vec::with_capacity(grid.len() + 1);
653    lines.push(render_row(0));
654    let sep: Vec<String> = (0..num_cols).map(|c| "-".repeat(width[c] + 2)).collect();
655    lines.push(format!("|{}|", sep.join("|")));
656    for r in data_rows {
657        lines.push(render_row(r));
658    }
659    lines.join("\n")
660}
661
662/// Escape a table cell so it can't break the markdown table: newlines become
663/// spaces and pipes become the `&#124;` HTML entity (matches docling-core).
664fn escape_cell(s: &str) -> String {
665    s.replace('\n', " ").replace('|', "&#124;")
666}
667
668#[cfg(test)]
669mod tests {
670    use super::*;
671
672    #[test]
673    fn renders_headings_paragraphs_and_lists() {
674        let mut doc = DoclingDocument::new("demo");
675        doc.add_heading(1, "Title");
676        doc.add_paragraph("Hello world.");
677        doc.push(Node::ListItem {
678            ordered: false,
679            number: 1,
680            first_in_list: true,
681            text: "first".into(),
682            level: 0,
683            marker: None,
684            location: None,
685            dclx: None,
686            href: None,
687            layer: None,
688        });
689        doc.push(Node::ListItem {
690            ordered: false,
691            number: 2,
692            first_in_list: false,
693            text: "second".into(),
694            level: 0,
695            marker: None,
696            location: None,
697            dclx: None,
698            href: None,
699            layer: None,
700        });
701        let md = doc.export_to_markdown();
702        assert_eq!(md, "# Title\n\nHello world.\n\n- first\n- second\n");
703    }
704
705    #[test]
706    fn strict_renders_recovered_links_legacy_does_not() {
707        let mut doc = DoclingDocument::new("cv");
708        doc.add_paragraph("Find me on LinkedIn or GitHub.");
709        doc.links = vec![
710            ("LinkedIn".into(), "https://www.linkedin.com/in/x/".into()),
711            ("GitHub".into(), "https://github.com/x/".into()),
712        ];
713        // Legacy/docling mode: links are left untouched (conformance preserved).
714        assert_eq!(doc.export_to_markdown(), "Find me on LinkedIn or GitHub.\n");
715        // Strict mode: anchors become Markdown links.
716        assert_eq!(
717            doc.export_to_markdown_with(true),
718            "Find me on [LinkedIn](https://www.linkedin.com/in/x/) or [GitHub](https://github.com/x/).\n"
719        );
720    }
721
722    #[test]
723    fn strict_links_match_escaped_anchor_and_consume_in_order() {
724        let mut doc = DoclingDocument::new("d");
725        // The PDF assembler HTML-escapes prose, so by serialization time the body
726        // already carries `&amp;`; the anchor is stored un-escaped. The matcher must
727        // escape the anchor to find it. Two identical anchors link in document order.
728        doc.add_paragraph("AI &amp; ML here, and issues here, then issues there.");
729        doc.links = vec![
730            ("AI & ML".into(), "https://a/".into()),
731            ("issues".into(), "https://first/".into()),
732            ("issues".into(), "https://second/".into()),
733        ];
734        assert_eq!(
735            doc.export_to_markdown_with(true),
736            "[AI &amp; ML](https://a/) here, and [issues](https://first/) here, then [issues](https://second/) there.\n"
737        );
738    }
739
740    #[test]
741    fn renders_compact_table() {
742        let mut doc = DoclingDocument::new("t");
743        // The compact form is opt-in (the PDF backend sets it); default output uses
744        // the padded GitHub serializer (covered by the regression fixtures).
745        doc.compact_tables = true;
746        doc.push(Node::Table(Table {
747            rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
748            location: None,
749            structure: None,
750            cell_blocks: None,
751        }));
752        let md = doc.export_to_markdown();
753        assert_eq!(md, "| a | b |\n| - | - |\n| 1 | 2 |\n");
754    }
755
756    #[test]
757    fn renders_padded_github_table_by_default() {
758        let mut doc = DoclingDocument::new("t");
759        doc.push(Node::Table(Table {
760            rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
761            location: None,
762            structure: None,
763            cell_blocks: None,
764        }));
765        let md = doc.export_to_markdown();
766        // Numeric data columns are right-aligned; columns padded to header+2.
767        assert_eq!(md, "|   a |   b |\n|-----|-----|\n|   1 |   2 |\n");
768    }
769
770    #[test]
771    fn strict_unescapes_inline_underscores_legacy_keeps_them() {
772        let mut doc = DoclingDocument::new("t");
773        doc.add_heading(1, "a\\_b");
774        doc.add_paragraph("x\\_y");
775        doc.push(Node::ListItem {
776            ordered: false,
777            number: 1,
778            first_in_list: true,
779            text: "i\\_j".into(),
780            level: 0,
781            marker: None,
782            location: None,
783            dclx: None,
784            href: None,
785            layer: None,
786        });
787        // Legacy reproduces docling's `\_` escaping byte-for-byte.
788        assert_eq!(doc.export_to_markdown(), "# a\\_b\n\nx\\_y\n\n- i\\_j\n");
789        // Strict prefers literal underscores (Rust-only readability mode).
790        assert_eq!(doc.export_to_markdown_with(true), "# a_b\n\nx_y\n\n- i_j\n");
791    }
792
793    /// Drive a document's nodes through [`MarkdownStreamer`] in the given page
794    /// splits and assert the concatenated chunks equal the buffered serializer.
795    fn assert_stream_matches(
796        doc: &DoclingDocument,
797        strict: bool,
798        images: ImageMode,
799        splits: &[usize],
800    ) {
801        let want = to_markdown_images(doc, strict, images, "artifacts").0;
802        let mut streamer = MarkdownStreamer::new(strict, images, doc.compact_tables);
803        let mut got = String::new();
804        let mut start = 0;
805        for &end in splits {
806            // Links only matter in strict mode; feed them all with the first batch
807            // that has content (document order is preserved by the queue).
808            let links = if start == 0 {
809                doc.links.as_slice()
810            } else {
811                &[]
812            };
813            got.push_str(&streamer.push(&doc.nodes[start..end], links));
814            start = end;
815        }
816        got.push_str(&streamer.push(
817            &doc.nodes[start..],
818            if start == 0 {
819                doc.links.as_slice()
820            } else {
821                &[]
822            },
823        ));
824        got.push_str(&streamer.finish());
825        assert_eq!(
826            got, want,
827            "streamed output diverged (splits={splits:?}, strict={strict})"
828        );
829    }
830
831    #[test]
832    fn streaming_is_byte_identical_to_buffered() {
833        let mut doc = DoclingDocument::new("d");
834        doc.add_heading(1, "Title");
835        doc.add_paragraph("First paragraph.");
836        doc.push(Node::ListItem {
837            ordered: false,
838            number: 1,
839            first_in_list: true,
840            text: "a".into(),
841            level: 0,
842            marker: None,
843            location: None,
844            dclx: None,
845            href: None,
846            layer: None,
847        });
848        doc.push(Node::ListItem {
849            ordered: false,
850            number: 2,
851            first_in_list: false,
852            text: "b".into(),
853            level: 0,
854            marker: None,
855            location: None,
856            dclx: None,
857            href: None,
858            layer: None,
859        });
860        doc.push(Node::Code {
861            language: Some("rust".into()),
862            text: "let x = 1;".into(),
863        });
864        doc.push(Node::Table(Table {
865            rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
866            location: None,
867            structure: None,
868            cell_blocks: None,
869        }));
870        doc.push(Node::Picture {
871            caption: Some("Fig 1".into()),
872            image: None,
873        });
874        doc.add_paragraph("Last paragraph.");
875
876        // A run of list items must never straddle a split, so try splits that fall
877        // on safe block boundaries (the streaming PDF assembler guarantees this).
878        for &strict in &[false, true] {
879            for &images in &[ImageMode::Placeholder, ImageMode::Embedded] {
880                for splits in [&[][..], &[1][..], &[2][..], &[4][..], &[1, 4, 6][..]] {
881                    assert_stream_matches(&doc, strict, images, splits);
882                }
883            }
884        }
885    }
886
887    #[test]
888    fn streaming_applies_recovered_links_in_strict_mode() {
889        let mut doc = DoclingDocument::new("d");
890        doc.add_paragraph("See LinkedIn for details.");
891        doc.add_paragraph("And GitHub too.");
892        doc.links = vec![
893            ("LinkedIn".into(), "https://lnkd/".into()),
894            ("GitHub".into(), "https://gh/".into()),
895        ];
896        // The second anchor lives in the second block, so it must be carried across
897        // the page boundary and placed when that block streams out.
898        assert_stream_matches(&doc, true, ImageMode::Placeholder, &[1]);
899    }
900
901    #[test]
902    fn strict_tightens_punctuation_spacing_legacy_keeps_it() {
903        let mut doc = DoclingDocument::new("t");
904        doc.add_paragraph("see [ 37 , 36 ] and ( x ) .");
905        // Legacy keeps docling's spacing byte-for-byte.
906        assert_eq!(doc.export_to_markdown(), "see [ 37 , 36 ] and ( x ) .\n");
907        // Strict tightens punctuation for readable Markdown.
908        assert_eq!(doc.export_to_markdown_with(true), "see [37, 36] and (x).\n");
909    }
910}