Skip to main content

docling_core/
markdown.rs

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