Skip to main content

docling_core/
markdown.rs

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