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/// [`ImageMode::Placeholder`] and [`ImageMode::Embedded`] render inline.
146/// [`ImageMode::Referenced`] additionally hands each picture's bytes out through
147/// [`take_artifacts`](Self::take_artifacts) — construct with
148/// [`with_artifacts`](Self::with_artifacts) and drain after every push so the
149/// bytes can be written to disk as pages finish instead of accumulating for the
150/// whole document (issue #80's memory-bounded image handling).
151///
152/// Each [`push`](Self::push) must contain whole blocks in reading order: a caller
153/// must not split a run of list items across two pushes (the run would render as
154/// two separate lists). Finalized PDF page batches already satisfy this.
155pub struct MarkdownStreamer {
156    strict: bool,
157    images: ImageMode,
158    compact_tables: bool,
159    /// Whether any non-empty chunk has been emitted yet (drives `\n\n` joins and
160    /// the trailing newline).
161    emitted_any: bool,
162    /// Recovered links not yet placed (strict mode), consumed in document order.
163    links: Vec<(String, String)>,
164    /// Referenced mode: the link prefix, the not-yet-drained `(path, bytes)`
165    /// artifacts, and the running image number (continues across pushes so the
166    /// stream matches the buffered serializer's `image_000000…` numbering).
167    artifacts_dir: String,
168    artifacts: Vec<(String, Vec<u8>)>,
169    pic_index: usize,
170}
171
172impl MarkdownStreamer {
173    /// Create a streamer. `compact_tables` mirrors [`DoclingDocument::compact_tables`].
174    /// For [`ImageMode::Referenced`] use [`with_artifacts`](Self::with_artifacts).
175    pub fn new(strict: bool, images: ImageMode, compact_tables: bool) -> Self {
176        debug_assert!(
177            images != ImageMode::Referenced,
178            "referenced image mode needs an artifacts dir; use with_artifacts"
179        );
180        Self::with_artifacts(strict, images, compact_tables, "artifacts")
181    }
182
183    /// Like [`new`](Self::new) but with the artifacts link prefix, allowing
184    /// [`ImageMode::Referenced`]: pictures render as
185    /// `![Image](<artifacts_dir>/image_NNNNNN.<ext>)` and each push's image
186    /// bytes wait in [`take_artifacts`](Self::take_artifacts) for the caller to
187    /// write. The concatenated chunks and the artifact list match the buffered
188    /// [`to_markdown_images`] byte-for-byte.
189    pub fn with_artifacts(
190        strict: bool,
191        images: ImageMode,
192        compact_tables: bool,
193        artifacts_dir: &str,
194    ) -> Self {
195        Self {
196            strict,
197            images,
198            compact_tables,
199            emitted_any: false,
200            links: Vec::new(),
201            artifacts_dir: artifacts_dir.to_string(),
202            artifacts: Vec::new(),
203            pic_index: 0,
204        }
205    }
206
207    /// The `(relative path, bytes)` of images rendered by pushes since the last
208    /// drain ([`ImageMode::Referenced`] only — empty otherwise). Paths are
209    /// relative to the Markdown file, i.e. they start with the configured
210    /// artifacts dir.
211    pub fn take_artifacts(&mut self) -> Vec<(String, Vec<u8>)> {
212        std::mem::take(&mut self.artifacts)
213    }
214
215    /// Render one finalized batch of nodes (plus any links recovered from the same
216    /// span, in document order) into the next Markdown chunk. Returns an empty
217    /// string when the batch produces no output (e.g. empty tables/pictures), in
218    /// which case nothing should be written.
219    pub fn push(&mut self, nodes: &[Node], links: &[(String, String)]) -> String {
220        self.links.extend(links.iter().cloned());
221        let mut ctx = Ctx {
222            strict: self.strict,
223            compact_tables: self.compact_tables,
224            images: self.images,
225            artifacts_dir: std::mem::take(&mut self.artifacts_dir),
226            artifacts: std::mem::take(&mut self.artifacts),
227            pic_index: self.pic_index,
228        };
229        let mut blocks: Vec<String> = Vec::new();
230        render(nodes, &mut blocks, &mut ctx);
231        self.artifacts_dir = std::mem::take(&mut ctx.artifacts_dir);
232        self.artifacts = std::mem::take(&mut ctx.artifacts);
233        self.pic_index = ctx.pic_index;
234        if blocks.is_empty() {
235            return String::new();
236        }
237        let mut body = blocks.join("\n\n");
238        if self.strict && !self.links.is_empty() {
239            body = apply_links_chunk(&body, &mut self.links);
240        }
241        let chunk = if self.emitted_any {
242            format!("\n\n{body}")
243        } else {
244            body
245        };
246        self.emitted_any = true;
247        chunk
248    }
249
250    /// Emit the trailing newline that finishes the document (empty if no content
251    /// was produced). Call exactly once, after the final [`push`](Self::push).
252    pub fn finish(self) -> String {
253        if self.emitted_any {
254            "\n".to_string()
255        } else {
256            String::new()
257        }
258    }
259}
260
261/// In `strict` mode, rewrite inline text for readability rather than byte-for-byte
262/// docling fidelity: undo the legacy `\_` underscore escaping, and tighten stray
263/// spaces around punctuation (`[ 37 , 36 ]` → `[37, 36]`, `( x )` → `(x)`). This
264/// cleans up both the PDF backend's glyph-split spacing and the space the legacy
265/// emphasis serialization leaves before punctuation (`*a* ,` → `*a*,`).
266/// Legacy/default output keeps docling's spacing untouched. Only inline text
267/// nodes pass through here — code blocks and table cells are left alone.
268fn strict_text(text: &str, strict: bool) -> String {
269    if !strict {
270        return text.to_string();
271    }
272    text.replace("\\_", "_")
273        .replace(" ,", ",")
274        .replace(" .", ".")
275        .replace(" ;", ";")
276        .replace(" )", ")")
277        .replace("( ", "(")
278        .replace(" ]", "]")
279        .replace("[ ", "[")
280}
281
282fn render(nodes: &[Node], blocks: &mut Vec<String>, ctx: &mut Ctx) {
283    let mut i = 0;
284    while i < nodes.len() {
285        match &nodes[i] {
286            Node::ListItem { .. } => {
287                let start = i;
288                i += 1;
289                loop {
290                    match nodes.get(i) {
291                        Some(Node::ListItem { .. }) => i += 1,
292                        // An empty paragraph between two list items is absorbed
293                        // into the run — docling keeps such a ListGroup
294                        // contiguous rather than splitting it.
295                        Some(Node::Paragraph { text })
296                            if text.is_empty()
297                                && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
298                        {
299                            i += 1
300                        }
301                        _ => break,
302                    }
303                }
304                render_list_run(&nodes[start..i], blocks, ctx.strict);
305            }
306            other => {
307                render_one(other, blocks, ctx);
308                i += 1;
309            }
310        }
311    }
312}
313
314/// Render a contiguous run of list items.
315///
316/// Ordered items use their explicit `number`. A new sibling list (marked by
317/// `first_in_list`) at the same depth is separated by a blank line, matching
318/// docling-core's serializer.
319fn render_list_run(items: &[Node], blocks: &mut Vec<String>, strict: bool) {
320    let mut lines: Vec<String> = Vec::new();
321    // Per level, the previous item's (ordered, number) so we can detect a new
322    // sibling list.
323    let mut prev: Vec<Option<(bool, u64)>> = Vec::new();
324    // Whether the previous top-level item was a multilevel projection — an
325    // ordered `1.2.`-style item rendered as a Markdown bullet (docx's DocLang
326    // overlay says ordered, the flat field says bullet). Word numbers such an
327    // item and its parent-level successor within one list (same `numId`), and
328    // docling keeps them in one group — so the kind-flip / number-continuity
329    // breaks below must not fire across it (docling#3902's
330    // docx_list_blank_spacer: `- 1.2. Sub two` directly followed by
331    // `2. Second section`, no blank line).
332    let mut prev_projected = false;
333
334    for item in items {
335        let Node::ListItem {
336            ordered,
337            number,
338            first_in_list,
339            text,
340            level,
341            marker: _,
342            location: _,
343            dclx,
344            href: _,
345            layer,
346        } = item
347        else {
348            continue;
349        };
350        // A non-body (furniture) list item is omitted from Markdown, matching
351        // docling's content-layer filtering.
352        if layer.is_some() {
353            continue;
354        }
355        let level = *level as usize;
356
357        // Returning to a shallower level ends the deeper sibling lists.
358        prev.truncate(level + 1);
359        while prev.len() <= level {
360            prev.push(None);
361        }
362
363        // A new sibling list at the same depth gets a blank line: the kind flips
364        // (`<ul>`↔`<ol>`), an ordered run breaks (`1, 2` then `42`), or the
365        // backend flagged a fresh list (e.g. Markdown's bullet changing `-`→`*`).
366        // Only at the top level: nested sibling groups are children of a list
367        // item, and docling joins an item's children without blank lines.
368        let eff_ordered = dclx.as_ref().map_or(*ordered, |d| d.ordered);
369        if level == 0 {
370            if let Some((prev_ordered, prev_number)) = prev[level] {
371                // A projected predecessor suppresses both heuristics for an
372                // ordered successor: the flat kind flip is an artifact of the
373                // bullet projection, and the numbering continues the deeper
374                // sequence (`1.2.` → `2.`), not this level's.
375                let same_word_list = prev_projected && eff_ordered;
376                let new_list = *first_in_list
377                    || (!same_word_list
378                        && (prev_ordered != *ordered || (*ordered && *number != prev_number + 1)));
379                if new_list {
380                    lines.push(String::new());
381                }
382            }
383            prev_projected = eff_ordered && !*ordered;
384        }
385
386        let indent = "    ".repeat(level);
387        let marker = if *ordered {
388            format!("{number}.")
389        } else {
390            "-".to_string()
391        };
392        lines.push(format!("{indent}{marker} {}", strict_text(text, strict)));
393        prev[level] = Some((*ordered, *number));
394    }
395
396    // A run consisting only of furniture (content-layer-filtered) items yields no
397    // lines; pushing an empty block here would surface as a stray blank line.
398    if !lines.is_empty() {
399        blocks.push(lines.join("\n"));
400    }
401}
402
403fn render_one(node: &Node, blocks: &mut Vec<String>, ctx: &mut Ctx) {
404    match node {
405        Node::Heading { level, text } => {
406            let hashes = "#".repeat((*level).clamp(1, 6) as usize);
407            blocks.push(format!("{hashes} {}", strict_text(text, ctx.strict)));
408        }
409        // An empty body paragraph (docling's blank-line text item) contributes
410        // nothing to Markdown — only DocLang/JSON keep it.
411        Node::Paragraph { text } if text.is_empty() => {}
412        Node::Paragraph { text } => blocks.push(strict_text(text, ctx.strict)),
413        Node::CheckboxItem { checked, text } => {
414            let mark = if *checked { "- [x] " } else { "- [ ] " };
415            blocks.push(strict_text(&format!("{mark}{text}"), ctx.strict));
416        }
417        Node::Code {
418            language,
419            text,
420            pretty,
421            ..
422        } => {
423            // Legacy docling never emits a language on the fence; strict keeps it.
424            let lang = match language {
425                Some(l) if ctx.strict => l.as_str(),
426                _ => "",
427            };
428            // Strict prefers the line-preserving rendering when the backend
429            // supplied one (PDF); legacy stays on docling's flat `text`.
430            let body = match pretty {
431                Some(p) if ctx.strict => p.as_str(),
432                _ => text.as_str(),
433            };
434            blocks.push(format!("```{lang}\n{body}\n```"));
435        }
436        // A CodeFormula-decoded display formula renders as docling's `$$…$$`
437        // (the un-enriched pipeline emits a placeholder paragraph instead).
438        Node::Formula { latex, .. } => blocks.push(format!("$${latex}$$")),
439        Node::Table(table) => {
440            // docling renders a table's caption as a text line before the grid.
441            // `caption` is already escaped (backend convention), like a paragraph.
442            if let Some(cap) = &table.caption {
443                if !cap.is_empty() {
444                    blocks.push(strict_text(cap, ctx.strict));
445                }
446            }
447            let rendered = render_table(table, ctx.compact_tables);
448            if !rendered.is_empty() {
449                blocks.push(rendered);
450            }
451        }
452        // Classification predictions don't affect docling's Markdown output.
453        Node::Picture { caption, image, .. } => {
454            if let Some(cap) = caption {
455                if !cap.is_empty() {
456                    blocks.push(cap.clone());
457                }
458            }
459            blocks.push(picture_marker(image.as_ref(), ctx));
460        }
461        // A chart renders as docling's picture-with-meta markdown: the caption,
462        // the placeholder, the humanized classification ("line_chart" ->
463        // "Line chart"), then the chart's data grid as a regular table.
464        Node::Chart {
465            kind,
466            table,
467            caption,
468            ..
469        } => {
470            if let Some(cap) = caption {
471                if !cap.is_empty() {
472                    blocks.push(cap.clone());
473                }
474            }
475            blocks.push(picture_marker(None, ctx));
476            blocks.push(humanize_label(kind));
477            let rendered = render_table(table, false);
478            if !rendered.is_empty() {
479                blocks.push(rendered);
480            }
481        }
482        // A DocLang-only node is omitted from Markdown.
483        Node::DoclangOnly(_) => {}
484        Node::Group { children, .. } => render(children, blocks, ctx),
485        Node::FieldRegion { items } => {
486            // docling renders the region container (which carries no text of its
487            // own) as a `<!-- missing-text -->` marker, then each field item the
488            // same way, followed by that item's marker/key/value as separate
489            // paragraphs.
490            blocks.push(MISSING_TEXT.to_string());
491            for item in items {
492                blocks.push(MISSING_TEXT.to_string());
493                for part in [&item.marker, &item.key, &item.value].into_iter().flatten() {
494                    blocks.push(strict_text(part, ctx.strict));
495                }
496            }
497        }
498        // A rich inline group renders exactly like a paragraph of its Markdown
499        // text — the structured runs are DocLang-only.
500        Node::InlineGroup { md_text, .. } => blocks.push(strict_text(md_text, ctx.strict)),
501        // A plain-text backend dump renders verbatim as a single block.
502        Node::TextDump(text) => {
503            if !text.is_empty() {
504                blocks.push(text.clone());
505            }
506        }
507        // Furniture (page headers/footers, HTML `<title>`) is excluded from
508        // Markdown by default, mirroring docling.
509        Node::Furniture { .. } => {}
510        Node::PageFurniture { .. } => {}
511        // Layout provenance is DocLang-only; render the wrapped node.
512        Node::Located { inner, .. } => render_one(inner, blocks, ctx),
513        // Page breaks are DocLang-only; docling omits them from Markdown.
514        Node::PageBreak => {}
515        // Page markers feed the JSON export only.
516        Node::PageInfo { .. } => {}
517        // Runs of adjacent list items are merged by `render`; a stray single
518        // item (a hand-built document, or a `Located` wrapper around one)
519        // still renders as its own one-item list instead of panicking —
520        // `nodes` is public API, so every representable tree must serialize.
521        Node::ListItem { .. } => render_list_run(std::slice::from_ref(node), blocks, ctx.strict),
522    }
523}
524
525/// docling's placeholder for a structural node (a field region / item) that has
526/// no text of its own.
527const MISSING_TEXT: &str = "<!-- missing-text -->";
528
529/// The Markdown for a picture under the active [`ImageMode`]; Referenced mode also
530/// records the bytes in `ctx.artifacts` for the caller to write.
531/// docling-core's `_humanize_text`: underscores to spaces, first letter
532/// capitalized ("line_chart" -> "Line chart").
533fn humanize_label(label: &str) -> String {
534    let text = label.replace('_', " ");
535    let mut chars = text.chars();
536    match chars.next() {
537        Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
538        None => text,
539    }
540}
541
542fn picture_marker(image: Option<&crate::PictureImage>, ctx: &mut Ctx) -> String {
543    match (ctx.images, image) {
544        (ImageMode::Embedded, Some(img)) => format!("![Image]({})", img.data_uri()),
545        (ImageMode::Referenced, Some(img)) => {
546            let path = format!(
547                "{}/image_{:06}.{}",
548                ctx.artifacts_dir,
549                ctx.pic_index,
550                ext_for(&img.mimetype)
551            );
552            ctx.pic_index += 1;
553            ctx.artifacts.push((path.clone(), img.data.clone()));
554            format!("![Image]({path})")
555        }
556        // Placeholder, or any mode with no extracted image.
557        _ => "<!-- image -->".to_string(),
558    }
559}
560
561fn ext_for(mimetype: &str) -> &str {
562    match mimetype {
563        "image/jpeg" => "jpg",
564        "image/gif" => "gif",
565        "image/webp" => "webp",
566        "image/bmp" => "bmp",
567        "image/tiff" => "tif",
568        _ => "png",
569    }
570}
571
572/// Render a table. `compact` selects between two serializers:
573///
574/// - **padded** (default) — docling-core's `tabulate(tablefmt="github")`: columns
575///   are padded to a fixed width (header width + a minimum padding of 2, or the
576///   widest data cell); numeric columns (every data cell parses as a number) are
577///   right-aligned, others left-aligned; separators are plain dashes of
578///   `width + 2`. Matches current published docling (DOCX/HTML conformance).
579/// - **compact** — `| a | b |` cells with single-dash `| - | - |` separators, no
580///   width padding. Matches the committed PDF groundtruth corpus, which predates
581///   the padded serializer.
582///
583/// Each cell is first escaped (`\n` → space, `|` → `&#124;`) so it can't break the
584/// table. Row 0 is the header.
585/// Whether a table cell counts as a number for column alignment, matching
586/// `tabulate`'s detection: an ordinary float/int (`f64`-parseable, covering
587/// `1e2`/`inf`/`+1.5`) **or** a thousands-separated number like `7,015`.
588fn is_number_cell(t: &str) -> bool {
589    t.parse::<f64>().is_ok() || is_thousands_number(t)
590}
591
592/// A number with comma thousands-separators, per `tabulate`'s
593/// `_float_with_thousands_separators` regex
594/// (`^(([+-]?[0-9]{1,3})(?:,([0-9]{3}))*)?(?(1)\.[0-9]*|\.[0-9]+)?$`): the
595/// integer part is 1–3 digits then any number of `,ddd` groups; the fraction is
596/// optional (and, without an integer part, must have at least one digit).
597fn is_thousands_number(t: &str) -> bool {
598    let b = t.as_bytes();
599    let mut i = 0;
600    let start = i;
601    if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
602        i += 1;
603    }
604    // First digit chunk: 1–3 digits.
605    let d0 = i;
606    while i < b.len() && b[i].is_ascii_digit() && i - d0 < 3 {
607        i += 1;
608    }
609    let has_int = i > d0;
610    if has_int {
611        // Subsequent `,ddd` groups (exactly three digits each).
612        while i + 3 < b.len() + 1
613            && b.get(i) == Some(&b',')
614            && b.get(i + 1).is_some_and(u8::is_ascii_digit)
615            && b.get(i + 2).is_some_and(u8::is_ascii_digit)
616            && b.get(i + 3).is_some_and(u8::is_ascii_digit)
617        {
618            i += 4;
619        }
620    } else {
621        // A sign only counts with an integer part.
622        i = start;
623    }
624    // Optional fraction.
625    if i < b.len() && b[i] == b'.' {
626        i += 1;
627        let f0 = i;
628        while i < b.len() && b[i].is_ascii_digit() {
629            i += 1;
630        }
631        if !has_int && i == f0 {
632            return false; // `.` with no digits and no integer part
633        }
634    } else if !has_int {
635        return false; // neither integer nor fractional part
636    }
637    i == b.len()
638}
639
640pub(crate) fn render_table(table: &Table, compact: bool) -> String {
641    if table.rows.is_empty() {
642        return String::new();
643    }
644    let num_cols = table.rows.iter().map(Vec::len).max().unwrap_or(0);
645    if num_cols == 0 {
646        return String::new();
647    }
648
649    // Escaped, rectangular grid (ragged rows padded with empty cells). `tabulate`
650    // strips data cells of surrounding whitespace but leaves the header row as-is.
651    let grid: Vec<Vec<String>> = table
652        .rows
653        .iter()
654        .enumerate()
655        .map(|(r, row)| {
656            (0..num_cols)
657                .map(|c| {
658                    let cell = escape_cell(row.get(c).map(String::as_str).unwrap_or(""));
659                    if r == 0 {
660                        cell
661                    } else {
662                        cell.trim().to_string()
663                    }
664                })
665                .collect()
666        })
667        .collect();
668
669    if compact {
670        // Compact: cells joined by " | ", no padding, single-dash separators.
671        let render_row = |r: usize| -> String { format!("| {} |", grid[r].join(" | ")) };
672        let mut lines = Vec::with_capacity(grid.len() + 1);
673        lines.push(render_row(0));
674        let sep: Vec<&str> = (0..num_cols).map(|_| "-").collect();
675        lines.push(format!("| {} |", sep.join(" | ")));
676        for r in 1..grid.len() {
677            lines.push(render_row(r));
678        }
679        return lines.join("\n");
680    }
681
682    // Display width (Unicode scalar count — good enough for now).
683    let dw = |s: &str| s.chars().count();
684    let data_rows = 1..grid.len();
685
686    // A column is right-aligned when at least one data cell is numeric and every
687    // non-empty data cell is numeric — matching `tabulate`'s column typing, where
688    // empty cells are "missing" (ignored) and a number may carry thousands
689    // separators (`7,015`), which a plain `f64` parse rejects.
690    let right: Vec<bool> = (0..num_cols)
691        .map(|c| {
692            let mut any = false;
693            for r in data_rows.clone() {
694                let t = grid[r][c].trim();
695                if t.is_empty() {
696                    continue;
697                }
698                if !is_number_cell(t) {
699                    return false;
700                }
701                any = true;
702            }
703            any
704        })
705        .collect();
706
707    // Column width = max(header_width + MIN_PADDING(2), max data-cell width).
708    let width: Vec<usize> = (0..num_cols)
709        .map(|c| {
710            let mut w = dw(&grid[0][c]) + 2;
711            for r in data_rows.clone() {
712                w = w.max(dw(&grid[r][c]));
713            }
714            w
715        })
716        .collect();
717
718    let fmt_cell = |s: &str, c: usize| -> String {
719        let pad = " ".repeat(width[c].saturating_sub(dw(s)));
720        let body = if right[c] {
721            format!("{pad}{s}")
722        } else {
723            format!("{s}{pad}")
724        };
725        format!(" {body} ")
726    };
727    let render_row = |r: usize| -> String {
728        let cells: Vec<String> = (0..num_cols).map(|c| fmt_cell(&grid[r][c], c)).collect();
729        format!("|{}|", cells.join("|"))
730    };
731
732    let mut lines = Vec::with_capacity(grid.len() + 1);
733    lines.push(render_row(0));
734    let sep: Vec<String> = (0..num_cols).map(|c| "-".repeat(width[c] + 2)).collect();
735    lines.push(format!("|{}|", sep.join("|")));
736    for r in data_rows {
737        lines.push(render_row(r));
738    }
739    lines.join("\n")
740}
741
742/// Escape a table cell so it can't break the markdown table: newlines become
743/// spaces and pipes become the `&#124;` HTML entity (matches docling-core).
744fn escape_cell(s: &str) -> String {
745    s.replace('\n', " ").replace('|', "&#124;")
746}
747
748#[cfg(test)]
749mod tests {
750    use super::*;
751    use crate::PictureImage;
752
753    #[test]
754    fn renders_headings_paragraphs_and_lists() {
755        let mut doc = DoclingDocument::new("demo");
756        doc.add_heading(1, "Title");
757        doc.add_paragraph("Hello world.");
758        doc.push(Node::ListItem {
759            ordered: false,
760            number: 1,
761            first_in_list: true,
762            text: "first".into(),
763            level: 0,
764            marker: None,
765            location: None,
766            dclx: None,
767            href: None,
768            layer: None,
769        });
770        doc.push(Node::ListItem {
771            ordered: false,
772            number: 2,
773            first_in_list: false,
774            text: "second".into(),
775            level: 0,
776            marker: None,
777            location: None,
778            dclx: None,
779            href: None,
780            layer: None,
781        });
782        let md = doc.export_to_markdown();
783        assert_eq!(md, "# Title\n\nHello world.\n\n- first\n- second\n");
784    }
785
786    #[test]
787    fn strict_renders_recovered_links_legacy_does_not() {
788        let mut doc = DoclingDocument::new("cv");
789        doc.add_paragraph("Find me on LinkedIn or GitHub.");
790        doc.links = vec![
791            ("LinkedIn".into(), "https://www.linkedin.com/in/x/".into()),
792            ("GitHub".into(), "https://github.com/x/".into()),
793        ];
794        // Legacy/docling mode: links are left untouched (conformance preserved).
795        assert_eq!(doc.export_to_markdown(), "Find me on LinkedIn or GitHub.\n");
796        // Strict mode: anchors become Markdown links.
797        assert_eq!(
798            doc.export_to_markdown_with(true),
799            "Find me on [LinkedIn](https://www.linkedin.com/in/x/) or [GitHub](https://github.com/x/).\n"
800        );
801    }
802
803    #[test]
804    fn strict_links_match_escaped_anchor_and_consume_in_order() {
805        let mut doc = DoclingDocument::new("d");
806        // The PDF assembler HTML-escapes prose, so by serialization time the body
807        // already carries `&amp;`; the anchor is stored un-escaped. The matcher must
808        // escape the anchor to find it. Two identical anchors link in document order.
809        doc.add_paragraph("AI &amp; ML here, and issues here, then issues there.");
810        doc.links = vec![
811            ("AI & ML".into(), "https://a/".into()),
812            ("issues".into(), "https://first/".into()),
813            ("issues".into(), "https://second/".into()),
814        ];
815        assert_eq!(
816            doc.export_to_markdown_with(true),
817            "[AI &amp; ML](https://a/) here, and [issues](https://first/) here, then [issues](https://second/) there.\n"
818        );
819    }
820
821    #[test]
822    fn renders_compact_table() {
823        let mut doc = DoclingDocument::new("t");
824        // The compact form is opt-in (the PDF backend sets it); default output uses
825        // the padded GitHub serializer (covered by the regression fixtures).
826        doc.compact_tables = true;
827        doc.push(Node::Table(Table {
828            rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
829            location: None,
830            structure: None,
831            cell_blocks: None,
832            cells: None,
833            caption: None,
834        }));
835        let md = doc.export_to_markdown();
836        assert_eq!(md, "| a | b |\n| - | - |\n| 1 | 2 |\n");
837    }
838
839    #[test]
840    fn renders_padded_github_table_by_default() {
841        let mut doc = DoclingDocument::new("t");
842        doc.push(Node::Table(Table {
843            rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
844            location: None,
845            structure: None,
846            cell_blocks: None,
847            cells: None,
848            caption: None,
849        }));
850        let md = doc.export_to_markdown();
851        // Numeric data columns are right-aligned; columns padded to header+2.
852        assert_eq!(md, "|   a |   b |\n|-----|-----|\n|   1 |   2 |\n");
853    }
854
855    #[test]
856    fn strict_unescapes_inline_underscores_legacy_keeps_them() {
857        let mut doc = DoclingDocument::new("t");
858        doc.add_heading(1, "a\\_b");
859        doc.add_paragraph("x\\_y");
860        doc.push(Node::ListItem {
861            ordered: false,
862            number: 1,
863            first_in_list: true,
864            text: "i\\_j".into(),
865            level: 0,
866            marker: None,
867            location: None,
868            dclx: None,
869            href: None,
870            layer: None,
871        });
872        // Legacy reproduces docling's `\_` escaping byte-for-byte.
873        assert_eq!(doc.export_to_markdown(), "# a\\_b\n\nx\\_y\n\n- i\\_j\n");
874        // Strict prefers literal underscores (Rust-only readability mode).
875        assert_eq!(doc.export_to_markdown_with(true), "# a_b\n\nx_y\n\n- i_j\n");
876    }
877
878    /// Drive a document's nodes through [`MarkdownStreamer`] in the given page
879    /// splits and assert the concatenated chunks equal the buffered serializer.
880    fn assert_stream_matches(
881        doc: &DoclingDocument,
882        strict: bool,
883        images: ImageMode,
884        splits: &[usize],
885    ) {
886        let (want, want_artifacts) = to_markdown_images(doc, strict, images, "artifacts");
887        let mut streamer =
888            MarkdownStreamer::with_artifacts(strict, images, doc.compact_tables, "artifacts");
889        let mut got = String::new();
890        let mut got_artifacts = Vec::new();
891        let mut start = 0;
892        for &end in splits {
893            // Links only matter in strict mode; feed them all with the first batch
894            // that has content (document order is preserved by the queue).
895            let links = if start == 0 {
896                doc.links.as_slice()
897            } else {
898                &[]
899            };
900            got.push_str(&streamer.push(&doc.nodes[start..end], links));
901            // Referenced mode: drain per push, as a real caller writing files
902            // page by page would — numbering must continue across drains.
903            got_artifacts.extend(streamer.take_artifacts());
904            start = end;
905        }
906        got.push_str(&streamer.push(
907            &doc.nodes[start..],
908            if start == 0 {
909                doc.links.as_slice()
910            } else {
911                &[]
912            },
913        ));
914        got_artifacts.extend(streamer.take_artifacts());
915        got.push_str(&streamer.finish());
916        assert_eq!(
917            got, want,
918            "streamed output diverged (splits={splits:?}, strict={strict})"
919        );
920        assert_eq!(
921            got_artifacts, want_artifacts,
922            "streamed artifacts diverged (splits={splits:?}, strict={strict})"
923        );
924    }
925
926    #[test]
927    fn streaming_is_byte_identical_to_buffered() {
928        let mut doc = DoclingDocument::new("d");
929        doc.add_heading(1, "Title");
930        doc.add_paragraph("First paragraph.");
931        doc.push(Node::ListItem {
932            ordered: false,
933            number: 1,
934            first_in_list: true,
935            text: "a".into(),
936            level: 0,
937            marker: None,
938            location: None,
939            dclx: None,
940            href: None,
941            layer: None,
942        });
943        doc.push(Node::ListItem {
944            ordered: false,
945            number: 2,
946            first_in_list: false,
947            text: "b".into(),
948            level: 0,
949            marker: None,
950            location: None,
951            dclx: None,
952            href: None,
953            layer: None,
954        });
955        doc.push(Node::Code {
956            language: Some("rust".into()),
957            text: "let x = 1;".into(),
958            orig: None,
959            pretty: None,
960        });
961        doc.push(Node::Table(Table {
962            rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
963            location: None,
964            structure: None,
965            cell_blocks: None,
966            cells: None,
967            caption: None,
968        }));
969        doc.push(Node::Picture {
970            caption: Some("Fig 1".into()),
971            image: Some(PictureImage {
972                mimetype: "image/png".into(),
973                width: 2,
974                height: 2,
975                data: b"png-one".to_vec(),
976            }),
977            classification: None,
978        });
979        doc.add_paragraph("Last paragraph.");
980        // A second embedded picture, so referenced mode must keep numbering
981        // (`image_000001`) across chunk boundaries.
982        doc.push(Node::Picture {
983            caption: None,
984            image: Some(PictureImage {
985                mimetype: "image/png".into(),
986                width: 2,
987                height: 2,
988                data: b"png-two".to_vec(),
989            }),
990            classification: None,
991        });
992
993        // A run of list items must never straddle a split, so try splits that fall
994        // on safe block boundaries (the streaming PDF assembler guarantees this).
995        for &strict in &[false, true] {
996            for &images in &[
997                ImageMode::Placeholder,
998                ImageMode::Embedded,
999                ImageMode::Referenced,
1000            ] {
1001                for splits in [&[][..], &[1][..], &[2][..], &[4][..], &[1, 4, 6, 7][..]] {
1002                    assert_stream_matches(&doc, strict, images, splits);
1003                }
1004            }
1005        }
1006    }
1007
1008    #[test]
1009    fn streaming_applies_recovered_links_in_strict_mode() {
1010        let mut doc = DoclingDocument::new("d");
1011        doc.add_paragraph("See LinkedIn for details.");
1012        doc.add_paragraph("And GitHub too.");
1013        doc.links = vec![
1014            ("LinkedIn".into(), "https://lnkd/".into()),
1015            ("GitHub".into(), "https://gh/".into()),
1016        ];
1017        // The second anchor lives in the second block, so it must be carried across
1018        // the page boundary and placed when that block streams out.
1019        assert_stream_matches(&doc, true, ImageMode::Placeholder, &[1]);
1020    }
1021
1022    #[test]
1023    fn strict_tightens_punctuation_spacing_legacy_keeps_it() {
1024        let mut doc = DoclingDocument::new("t");
1025        doc.add_paragraph("see [ 37 , 36 ] and ( x ) .");
1026        // Legacy keeps docling's spacing byte-for-byte.
1027        assert_eq!(doc.export_to_markdown(), "see [ 37 , 36 ] and ( x ) .\n");
1028        // Strict tightens punctuation for readable Markdown.
1029        assert_eq!(doc.export_to_markdown_with(true), "see [37, 36] and (x).\n");
1030    }
1031}