1use crate::document::{DoclingDocument, Node, Table};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
7pub enum ImageMode {
8 #[default]
10 Placeholder,
11 Embedded,
13 Referenced,
16}
17
18struct Ctx {
20 strict: bool,
21 compact_tables: bool,
23 images: ImageMode,
24 artifacts_dir: String,
25 artifacts: Vec<(String, Vec<u8>)>,
27 pic_index: usize,
28}
29
30pub fn to_markdown(doc: &DoclingDocument, strict: bool) -> String {
36 to_markdown_images(doc, strict, ImageMode::Placeholder, "artifacts").0
37}
38
39pub fn to_markdown_images(
43 doc: &DoclingDocument,
44 strict: bool,
45 images: ImageMode,
46 artifacts_dir: &str,
47) -> (String, Vec<(String, Vec<u8>)>) {
48 let mut ctx = Ctx {
49 strict,
50 compact_tables: doc.compact_tables,
51 images,
52 artifacts_dir: artifacts_dir.to_string(),
53 artifacts: Vec::new(),
54 pic_index: 0,
55 };
56 let mut blocks: Vec<String> = Vec::new();
57 render(&doc.nodes, &mut blocks, &mut ctx);
58 let mut body = blocks.join("\n\n");
59 if strict && !doc.links.is_empty() {
63 body = apply_links(&body, &doc.links);
64 }
65 let md = if body.is_empty() {
66 String::new()
67 } else {
68 format!("{body}\n")
69 };
70 (md, ctx.artifacts)
71}
72
73fn apply_links(body: &str, links: &[(String, String)]) -> String {
81 let mut out = body.to_string();
82 let mut cursor = 0usize;
83 for (anchor, href) in links {
84 let anchor = anchor
85 .replace('&', "&")
86 .replace('<', "<")
87 .replace('>', ">");
88 if anchor.is_empty() {
89 continue;
90 }
91 if let Some(rel) = out[cursor..].find(&anchor) {
92 let at = cursor + rel;
93 let replacement = format!("[{anchor}]({href})");
95 out.replace_range(at..at + anchor.len(), &replacement);
96 cursor = at + replacement.len();
97 }
98 }
99 out
100}
101
102fn apply_links_chunk(chunk: &str, queue: &mut Vec<(String, String)>) -> String {
113 let mut out = chunk.to_string();
114 let mut cursor = 0usize;
115 let mut carried: Vec<(String, String)> = Vec::new();
116 for (anchor_raw, href) in std::mem::take(queue) {
117 let anchor = anchor_raw
118 .replace('&', "&")
119 .replace('<', "<")
120 .replace('>', ">");
121 if anchor.is_empty() {
122 continue;
123 }
124 if let Some(rel) = out[cursor..].find(&anchor) {
125 let at = cursor + rel;
126 let replacement = format!("[{anchor}]({href})");
127 out.replace_range(at..at + anchor.len(), &replacement);
128 cursor = at + replacement.len();
129 } else {
130 carried.push((anchor_raw, href));
132 }
133 }
134 *queue = carried;
135 out
136}
137
138pub struct MarkdownStreamer {
153 strict: bool,
154 images: ImageMode,
155 compact_tables: bool,
156 emitted_any: bool,
159 links: Vec<(String, String)>,
161}
162
163impl MarkdownStreamer {
164 pub fn new(strict: bool, images: ImageMode, compact_tables: bool) -> Self {
166 debug_assert!(
167 images != ImageMode::Referenced,
168 "referenced image mode is not streamable; use to_markdown_images"
169 );
170 Self {
171 strict,
172 images,
173 compact_tables,
174 emitted_any: false,
175 links: Vec::new(),
176 }
177 }
178
179 pub fn push(&mut self, nodes: &[Node], links: &[(String, String)]) -> String {
184 self.links.extend(links.iter().cloned());
185 let mut ctx = Ctx {
186 strict: self.strict,
187 compact_tables: self.compact_tables,
188 images: self.images,
189 artifacts_dir: String::new(),
192 artifacts: Vec::new(),
193 pic_index: 0,
194 };
195 let mut blocks: Vec<String> = Vec::new();
196 render(nodes, &mut blocks, &mut ctx);
197 if blocks.is_empty() {
198 return String::new();
199 }
200 let mut body = blocks.join("\n\n");
201 if self.strict && !self.links.is_empty() {
202 body = apply_links_chunk(&body, &mut self.links);
203 }
204 let chunk = if self.emitted_any {
205 format!("\n\n{body}")
206 } else {
207 body
208 };
209 self.emitted_any = true;
210 chunk
211 }
212
213 pub fn finish(self) -> String {
216 if self.emitted_any {
217 "\n".to_string()
218 } else {
219 String::new()
220 }
221 }
222}
223
224fn strict_text(text: &str, strict: bool) -> String {
232 if !strict {
233 return text.to_string();
234 }
235 text.replace("\\_", "_")
236 .replace(" ,", ",")
237 .replace(" .", ".")
238 .replace(" ;", ";")
239 .replace(" )", ")")
240 .replace("( ", "(")
241 .replace(" ]", "]")
242 .replace("[ ", "[")
243}
244
245fn render(nodes: &[Node], blocks: &mut Vec<String>, ctx: &mut Ctx) {
246 let mut i = 0;
247 while i < nodes.len() {
248 match &nodes[i] {
249 Node::ListItem { .. } => {
250 let start = i;
251 i += 1;
252 loop {
253 match nodes.get(i) {
254 Some(Node::ListItem { .. }) => i += 1,
255 Some(Node::Paragraph { text })
259 if text.is_empty()
260 && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
261 {
262 i += 1
263 }
264 _ => break,
265 }
266 }
267 render_list_run(&nodes[start..i], blocks, ctx.strict);
268 }
269 other => {
270 render_one(other, blocks, ctx);
271 i += 1;
272 }
273 }
274 }
275}
276
277fn render_list_run(items: &[Node], blocks: &mut Vec<String>, strict: bool) {
283 let mut lines: Vec<String> = Vec::new();
284 let mut prev: Vec<Option<(bool, u64)>> = Vec::new();
287
288 for item in items {
289 let Node::ListItem {
290 ordered,
291 number,
292 first_in_list,
293 text,
294 level,
295 marker: _,
296 location: _,
297 dclx: _,
298 href: _,
299 layer,
300 } = item
301 else {
302 continue;
303 };
304 if layer.is_some() {
307 continue;
308 }
309 let level = *level as usize;
310
311 prev.truncate(level + 1);
313 while prev.len() <= level {
314 prev.push(None);
315 }
316
317 if level == 0 {
323 if let Some((prev_ordered, prev_number)) = prev[level] {
324 let new_list = *first_in_list
325 || prev_ordered != *ordered
326 || (*ordered && *number != prev_number + 1);
327 if new_list {
328 lines.push(String::new());
329 }
330 }
331 }
332
333 let indent = " ".repeat(level);
334 let marker = if *ordered {
335 format!("{number}.")
336 } else {
337 "-".to_string()
338 };
339 lines.push(format!("{indent}{marker} {}", strict_text(text, strict)));
340 prev[level] = Some((*ordered, *number));
341 }
342
343 if !lines.is_empty() {
346 blocks.push(lines.join("\n"));
347 }
348}
349
350fn render_one(node: &Node, blocks: &mut Vec<String>, ctx: &mut Ctx) {
351 match node {
352 Node::Heading { level, text } => {
353 let hashes = "#".repeat((*level).clamp(1, 6) as usize);
354 blocks.push(format!("{hashes} {}", strict_text(text, ctx.strict)));
355 }
356 Node::Paragraph { text } if text.is_empty() => {}
359 Node::Paragraph { text } => blocks.push(strict_text(text, ctx.strict)),
360 Node::CheckboxItem { checked, text } => {
361 let mark = if *checked { "- [x] " } else { "- [ ] " };
362 blocks.push(strict_text(&format!("{mark}{text}"), ctx.strict));
363 }
364 Node::Code { language, text, .. } => {
365 let lang = match language {
367 Some(l) if ctx.strict => l.as_str(),
368 _ => "",
369 };
370 blocks.push(format!("```{lang}\n{text}\n```"));
371 }
372 Node::Formula { latex, .. } => blocks.push(format!("$${latex}$$")),
375 Node::Table(table) => {
376 let rendered = render_table(table, ctx.compact_tables);
377 if !rendered.is_empty() {
378 blocks.push(rendered);
379 }
380 }
381 Node::Picture { caption, image, .. } => {
383 if let Some(cap) = caption {
384 if !cap.is_empty() {
385 blocks.push(cap.clone());
386 }
387 }
388 blocks.push(picture_marker(image.as_ref(), ctx));
389 }
390 Node::Chart {
394 kind,
395 table,
396 caption,
397 ..
398 } => {
399 if let Some(cap) = caption {
400 if !cap.is_empty() {
401 blocks.push(cap.clone());
402 }
403 }
404 blocks.push(picture_marker(None, ctx));
405 blocks.push(humanize_label(kind));
406 let rendered = render_table(table, false);
407 if !rendered.is_empty() {
408 blocks.push(rendered);
409 }
410 }
411 Node::DoclangOnly(_) => {}
413 Node::Group { children, .. } => render(children, blocks, ctx),
414 Node::FieldRegion { items } => {
415 blocks.push(MISSING_TEXT.to_string());
420 for item in items {
421 blocks.push(MISSING_TEXT.to_string());
422 for part in [&item.marker, &item.key, &item.value].into_iter().flatten() {
423 blocks.push(strict_text(part, ctx.strict));
424 }
425 }
426 }
427 Node::InlineGroup { md_text, .. } => blocks.push(strict_text(md_text, ctx.strict)),
430 Node::TextDump(text) => {
432 if !text.is_empty() {
433 blocks.push(text.clone());
434 }
435 }
436 Node::Furniture { .. } => {}
439 Node::PageFurniture { .. } => {}
440 Node::Located { inner, .. } => render_one(inner, blocks, ctx),
442 Node::PageBreak => {}
444 Node::ListItem { .. } => unreachable!("list items are rendered in runs"),
446 }
447}
448
449const MISSING_TEXT: &str = "<!-- missing-text -->";
452
453fn humanize_label(label: &str) -> String {
458 let text = label.replace('_', " ");
459 let mut chars = text.chars();
460 match chars.next() {
461 Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
462 None => text,
463 }
464}
465
466fn picture_marker(image: Option<&crate::PictureImage>, ctx: &mut Ctx) -> String {
467 match (ctx.images, image) {
468 (ImageMode::Embedded, Some(img)) => format!("", img.data_uri()),
469 (ImageMode::Referenced, Some(img)) => {
470 let path = format!(
471 "{}/image_{:06}.{}",
472 ctx.artifacts_dir,
473 ctx.pic_index,
474 ext_for(&img.mimetype)
475 );
476 ctx.pic_index += 1;
477 ctx.artifacts.push((path.clone(), img.data.clone()));
478 format!("")
479 }
480 _ => "<!-- image -->".to_string(),
482 }
483}
484
485fn ext_for(mimetype: &str) -> &str {
486 match mimetype {
487 "image/jpeg" => "jpg",
488 "image/gif" => "gif",
489 "image/webp" => "webp",
490 "image/bmp" => "bmp",
491 "image/tiff" => "tif",
492 _ => "png",
493 }
494}
495
496fn is_number_cell(t: &str) -> bool {
513 t.parse::<f64>().is_ok() || is_thousands_number(t)
514}
515
516fn is_thousands_number(t: &str) -> bool {
522 let b = t.as_bytes();
523 let mut i = 0;
524 let start = i;
525 if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
526 i += 1;
527 }
528 let d0 = i;
530 while i < b.len() && b[i].is_ascii_digit() && i - d0 < 3 {
531 i += 1;
532 }
533 let has_int = i > d0;
534 if has_int {
535 while i + 3 < b.len() + 1
537 && b.get(i) == Some(&b',')
538 && b.get(i + 1).is_some_and(u8::is_ascii_digit)
539 && b.get(i + 2).is_some_and(u8::is_ascii_digit)
540 && b.get(i + 3).is_some_and(u8::is_ascii_digit)
541 {
542 i += 4;
543 }
544 } else {
545 i = start;
547 }
548 if i < b.len() && b[i] == b'.' {
550 i += 1;
551 let f0 = i;
552 while i < b.len() && b[i].is_ascii_digit() {
553 i += 1;
554 }
555 if !has_int && i == f0 {
556 return false; }
558 } else if !has_int {
559 return false; }
561 i == b.len()
562}
563
564pub(crate) fn render_table(table: &Table, compact: bool) -> String {
565 if table.rows.is_empty() {
566 return String::new();
567 }
568 let num_cols = table.rows.iter().map(Vec::len).max().unwrap_or(0);
569 if num_cols == 0 {
570 return String::new();
571 }
572
573 let grid: Vec<Vec<String>> = table
576 .rows
577 .iter()
578 .enumerate()
579 .map(|(r, row)| {
580 (0..num_cols)
581 .map(|c| {
582 let cell = escape_cell(row.get(c).map(String::as_str).unwrap_or(""));
583 if r == 0 {
584 cell
585 } else {
586 cell.trim().to_string()
587 }
588 })
589 .collect()
590 })
591 .collect();
592
593 if compact {
594 let render_row = |r: usize| -> String { format!("| {} |", grid[r].join(" | ")) };
596 let mut lines = Vec::with_capacity(grid.len() + 1);
597 lines.push(render_row(0));
598 let sep: Vec<&str> = (0..num_cols).map(|_| "-").collect();
599 lines.push(format!("| {} |", sep.join(" | ")));
600 for r in 1..grid.len() {
601 lines.push(render_row(r));
602 }
603 return lines.join("\n");
604 }
605
606 let dw = |s: &str| s.chars().count();
608 let data_rows = 1..grid.len();
609
610 let right: Vec<bool> = (0..num_cols)
615 .map(|c| {
616 let mut any = false;
617 for r in data_rows.clone() {
618 let t = grid[r][c].trim();
619 if t.is_empty() {
620 continue;
621 }
622 if !is_number_cell(t) {
623 return false;
624 }
625 any = true;
626 }
627 any
628 })
629 .collect();
630
631 let width: Vec<usize> = (0..num_cols)
633 .map(|c| {
634 let mut w = dw(&grid[0][c]) + 2;
635 for r in data_rows.clone() {
636 w = w.max(dw(&grid[r][c]));
637 }
638 w
639 })
640 .collect();
641
642 let fmt_cell = |s: &str, c: usize| -> String {
643 let pad = " ".repeat(width[c].saturating_sub(dw(s)));
644 let body = if right[c] {
645 format!("{pad}{s}")
646 } else {
647 format!("{s}{pad}")
648 };
649 format!(" {body} ")
650 };
651 let render_row = |r: usize| -> String {
652 let cells: Vec<String> = (0..num_cols).map(|c| fmt_cell(&grid[r][c], c)).collect();
653 format!("|{}|", cells.join("|"))
654 };
655
656 let mut lines = Vec::with_capacity(grid.len() + 1);
657 lines.push(render_row(0));
658 let sep: Vec<String> = (0..num_cols).map(|c| "-".repeat(width[c] + 2)).collect();
659 lines.push(format!("|{}|", sep.join("|")));
660 for r in data_rows {
661 lines.push(render_row(r));
662 }
663 lines.join("\n")
664}
665
666fn escape_cell(s: &str) -> String {
669 s.replace('\n', " ").replace('|', "|")
670}
671
672#[cfg(test)]
673mod tests {
674 use super::*;
675
676 #[test]
677 fn renders_headings_paragraphs_and_lists() {
678 let mut doc = DoclingDocument::new("demo");
679 doc.add_heading(1, "Title");
680 doc.add_paragraph("Hello world.");
681 doc.push(Node::ListItem {
682 ordered: false,
683 number: 1,
684 first_in_list: true,
685 text: "first".into(),
686 level: 0,
687 marker: None,
688 location: None,
689 dclx: None,
690 href: None,
691 layer: None,
692 });
693 doc.push(Node::ListItem {
694 ordered: false,
695 number: 2,
696 first_in_list: false,
697 text: "second".into(),
698 level: 0,
699 marker: None,
700 location: None,
701 dclx: None,
702 href: None,
703 layer: None,
704 });
705 let md = doc.export_to_markdown();
706 assert_eq!(md, "# Title\n\nHello world.\n\n- first\n- second\n");
707 }
708
709 #[test]
710 fn strict_renders_recovered_links_legacy_does_not() {
711 let mut doc = DoclingDocument::new("cv");
712 doc.add_paragraph("Find me on LinkedIn or GitHub.");
713 doc.links = vec![
714 ("LinkedIn".into(), "https://www.linkedin.com/in/x/".into()),
715 ("GitHub".into(), "https://github.com/x/".into()),
716 ];
717 assert_eq!(doc.export_to_markdown(), "Find me on LinkedIn or GitHub.\n");
719 assert_eq!(
721 doc.export_to_markdown_with(true),
722 "Find me on [LinkedIn](https://www.linkedin.com/in/x/) or [GitHub](https://github.com/x/).\n"
723 );
724 }
725
726 #[test]
727 fn strict_links_match_escaped_anchor_and_consume_in_order() {
728 let mut doc = DoclingDocument::new("d");
729 doc.add_paragraph("AI & ML here, and issues here, then issues there.");
733 doc.links = vec![
734 ("AI & ML".into(), "https://a/".into()),
735 ("issues".into(), "https://first/".into()),
736 ("issues".into(), "https://second/".into()),
737 ];
738 assert_eq!(
739 doc.export_to_markdown_with(true),
740 "[AI & ML](https://a/) here, and [issues](https://first/) here, then [issues](https://second/) there.\n"
741 );
742 }
743
744 #[test]
745 fn renders_compact_table() {
746 let mut doc = DoclingDocument::new("t");
747 doc.compact_tables = true;
750 doc.push(Node::Table(Table {
751 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
752 location: None,
753 structure: None,
754 cell_blocks: None,
755 }));
756 let md = doc.export_to_markdown();
757 assert_eq!(md, "| a | b |\n| - | - |\n| 1 | 2 |\n");
758 }
759
760 #[test]
761 fn renders_padded_github_table_by_default() {
762 let mut doc = DoclingDocument::new("t");
763 doc.push(Node::Table(Table {
764 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
765 location: None,
766 structure: None,
767 cell_blocks: None,
768 }));
769 let md = doc.export_to_markdown();
770 assert_eq!(md, "| a | b |\n|-----|-----|\n| 1 | 2 |\n");
772 }
773
774 #[test]
775 fn strict_unescapes_inline_underscores_legacy_keeps_them() {
776 let mut doc = DoclingDocument::new("t");
777 doc.add_heading(1, "a\\_b");
778 doc.add_paragraph("x\\_y");
779 doc.push(Node::ListItem {
780 ordered: false,
781 number: 1,
782 first_in_list: true,
783 text: "i\\_j".into(),
784 level: 0,
785 marker: None,
786 location: None,
787 dclx: None,
788 href: None,
789 layer: None,
790 });
791 assert_eq!(doc.export_to_markdown(), "# a\\_b\n\nx\\_y\n\n- i\\_j\n");
793 assert_eq!(doc.export_to_markdown_with(true), "# a_b\n\nx_y\n\n- i_j\n");
795 }
796
797 fn assert_stream_matches(
800 doc: &DoclingDocument,
801 strict: bool,
802 images: ImageMode,
803 splits: &[usize],
804 ) {
805 let want = to_markdown_images(doc, strict, images, "artifacts").0;
806 let mut streamer = MarkdownStreamer::new(strict, images, doc.compact_tables);
807 let mut got = String::new();
808 let mut start = 0;
809 for &end in splits {
810 let links = if start == 0 {
813 doc.links.as_slice()
814 } else {
815 &[]
816 };
817 got.push_str(&streamer.push(&doc.nodes[start..end], links));
818 start = end;
819 }
820 got.push_str(&streamer.push(
821 &doc.nodes[start..],
822 if start == 0 {
823 doc.links.as_slice()
824 } else {
825 &[]
826 },
827 ));
828 got.push_str(&streamer.finish());
829 assert_eq!(
830 got, want,
831 "streamed output diverged (splits={splits:?}, strict={strict})"
832 );
833 }
834
835 #[test]
836 fn streaming_is_byte_identical_to_buffered() {
837 let mut doc = DoclingDocument::new("d");
838 doc.add_heading(1, "Title");
839 doc.add_paragraph("First paragraph.");
840 doc.push(Node::ListItem {
841 ordered: false,
842 number: 1,
843 first_in_list: true,
844 text: "a".into(),
845 level: 0,
846 marker: None,
847 location: None,
848 dclx: None,
849 href: None,
850 layer: None,
851 });
852 doc.push(Node::ListItem {
853 ordered: false,
854 number: 2,
855 first_in_list: false,
856 text: "b".into(),
857 level: 0,
858 marker: None,
859 location: None,
860 dclx: None,
861 href: None,
862 layer: None,
863 });
864 doc.push(Node::Code {
865 language: Some("rust".into()),
866 text: "let x = 1;".into(),
867 orig: None,
868 });
869 doc.push(Node::Table(Table {
870 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
871 location: None,
872 structure: None,
873 cell_blocks: None,
874 }));
875 doc.push(Node::Picture {
876 caption: Some("Fig 1".into()),
877 image: None,
878 classification: None,
879 });
880 doc.add_paragraph("Last paragraph.");
881
882 for &strict in &[false, true] {
885 for &images in &[ImageMode::Placeholder, ImageMode::Embedded] {
886 for splits in [&[][..], &[1][..], &[2][..], &[4][..], &[1, 4, 6][..]] {
887 assert_stream_matches(&doc, strict, images, splits);
888 }
889 }
890 }
891 }
892
893 #[test]
894 fn streaming_applies_recovered_links_in_strict_mode() {
895 let mut doc = DoclingDocument::new("d");
896 doc.add_paragraph("See LinkedIn for details.");
897 doc.add_paragraph("And GitHub too.");
898 doc.links = vec![
899 ("LinkedIn".into(), "https://lnkd/".into()),
900 ("GitHub".into(), "https://gh/".into()),
901 ];
902 assert_stream_matches(&doc, true, ImageMode::Placeholder, &[1]);
905 }
906
907 #[test]
908 fn strict_tightens_punctuation_spacing_legacy_keeps_it() {
909 let mut doc = DoclingDocument::new("t");
910 doc.add_paragraph("see [ 37 , 36 ] and ( x ) .");
911 assert_eq!(doc.export_to_markdown(), "see [ 37 , 36 ] and ( x ) .\n");
913 assert_eq!(doc.export_to_markdown_with(true), "see [37, 36] and (x).\n");
915 }
916}