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 let Some((prev_ordered, prev_number)) = prev[level] {
321 let new_list = *first_in_list
322 || prev_ordered != *ordered
323 || (*ordered && *number != prev_number + 1);
324 if new_list {
325 lines.push(String::new());
326 }
327 }
328
329 let indent = " ".repeat(level);
330 let marker = if *ordered {
331 format!("{number}.")
332 } else {
333 "-".to_string()
334 };
335 lines.push(format!("{indent}{marker} {}", strict_text(text, strict)));
336 prev[level] = Some((*ordered, *number));
337 }
338
339 if !lines.is_empty() {
342 blocks.push(lines.join("\n"));
343 }
344}
345
346fn render_one(node: &Node, blocks: &mut Vec<String>, ctx: &mut Ctx) {
347 match node {
348 Node::Heading { level, text } => {
349 let hashes = "#".repeat((*level).clamp(1, 6) as usize);
350 blocks.push(format!("{hashes} {}", strict_text(text, ctx.strict)));
351 }
352 Node::Paragraph { text } if text.is_empty() => {}
355 Node::Paragraph { text } => blocks.push(strict_text(text, ctx.strict)),
356 Node::CheckboxItem { checked, text } => {
357 let mark = if *checked { "- [x] " } else { "- [ ] " };
358 blocks.push(strict_text(&format!("{mark}{text}"), ctx.strict));
359 }
360 Node::Code { language, text } => {
361 let lang = match language {
363 Some(l) if ctx.strict => l.as_str(),
364 _ => "",
365 };
366 blocks.push(format!("```{lang}\n{text}\n```"));
367 }
368 Node::Table(table) => {
369 let rendered = render_table(table, ctx.compact_tables);
370 if !rendered.is_empty() {
371 blocks.push(rendered);
372 }
373 }
374 Node::Picture { caption, image } => {
375 if let Some(cap) = caption {
376 if !cap.is_empty() {
377 blocks.push(cap.clone());
378 }
379 }
380 blocks.push(picture_marker(image.as_ref(), ctx));
381 }
382 Node::Chart { .. } => blocks.push(picture_marker(None, ctx)),
385 Node::DoclangOnly(_) => {}
387 Node::Group { children, .. } => render(children, blocks, ctx),
388 Node::FieldRegion { items } => {
389 blocks.push(MISSING_TEXT.to_string());
394 for item in items {
395 blocks.push(MISSING_TEXT.to_string());
396 for part in [&item.marker, &item.key, &item.value].into_iter().flatten() {
397 blocks.push(strict_text(part, ctx.strict));
398 }
399 }
400 }
401 Node::InlineGroup { md_text, .. } => blocks.push(strict_text(md_text, ctx.strict)),
404 Node::Furniture { .. } => {}
407 Node::Located { inner, .. } => render_one(inner, blocks, ctx),
409 Node::PageBreak => {}
411 Node::ListItem { .. } => unreachable!("list items are rendered in runs"),
413 }
414}
415
416const MISSING_TEXT: &str = "<!-- missing-text -->";
419
420fn picture_marker(image: Option<&crate::PictureImage>, ctx: &mut Ctx) -> String {
423 match (ctx.images, image) {
424 (ImageMode::Embedded, Some(img)) => format!("", img.data_uri()),
425 (ImageMode::Referenced, Some(img)) => {
426 let path = format!(
427 "{}/image_{:06}.{}",
428 ctx.artifacts_dir,
429 ctx.pic_index,
430 ext_for(&img.mimetype)
431 );
432 ctx.pic_index += 1;
433 ctx.artifacts.push((path.clone(), img.data.clone()));
434 format!("")
435 }
436 _ => "<!-- image -->".to_string(),
438 }
439}
440
441fn ext_for(mimetype: &str) -> &str {
442 match mimetype {
443 "image/jpeg" => "jpg",
444 "image/gif" => "gif",
445 "image/webp" => "webp",
446 "image/bmp" => "bmp",
447 "image/tiff" => "tif",
448 _ => "png",
449 }
450}
451
452fn is_number_cell(t: &str) -> bool {
469 t.parse::<f64>().is_ok() || is_thousands_number(t)
470}
471
472fn is_thousands_number(t: &str) -> bool {
478 let b = t.as_bytes();
479 let mut i = 0;
480 let start = i;
481 if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
482 i += 1;
483 }
484 let d0 = i;
486 while i < b.len() && b[i].is_ascii_digit() && i - d0 < 3 {
487 i += 1;
488 }
489 let has_int = i > d0;
490 if has_int {
491 while i + 3 < b.len() + 1
493 && b.get(i) == Some(&b',')
494 && b.get(i + 1).is_some_and(u8::is_ascii_digit)
495 && b.get(i + 2).is_some_and(u8::is_ascii_digit)
496 && b.get(i + 3).is_some_and(u8::is_ascii_digit)
497 {
498 i += 4;
499 }
500 } else {
501 i = start;
503 }
504 if i < b.len() && b[i] == b'.' {
506 i += 1;
507 let f0 = i;
508 while i < b.len() && b[i].is_ascii_digit() {
509 i += 1;
510 }
511 if !has_int && i == f0 {
512 return false; }
514 } else if !has_int {
515 return false; }
517 i == b.len()
518}
519
520fn render_table(table: &Table, compact: bool) -> String {
521 if table.rows.is_empty() {
522 return String::new();
523 }
524 let num_cols = table.rows.iter().map(Vec::len).max().unwrap_or(0);
525 if num_cols == 0 {
526 return String::new();
527 }
528
529 let grid: Vec<Vec<String>> = table
532 .rows
533 .iter()
534 .enumerate()
535 .map(|(r, row)| {
536 (0..num_cols)
537 .map(|c| {
538 let cell = escape_cell(row.get(c).map(String::as_str).unwrap_or(""));
539 if r == 0 {
540 cell
541 } else {
542 cell.trim().to_string()
543 }
544 })
545 .collect()
546 })
547 .collect();
548
549 if compact {
550 let render_row = |r: usize| -> String { format!("| {} |", grid[r].join(" | ")) };
552 let mut lines = Vec::with_capacity(grid.len() + 1);
553 lines.push(render_row(0));
554 let sep: Vec<&str> = (0..num_cols).map(|_| "-").collect();
555 lines.push(format!("| {} |", sep.join(" | ")));
556 for r in 1..grid.len() {
557 lines.push(render_row(r));
558 }
559 return lines.join("\n");
560 }
561
562 let dw = |s: &str| s.chars().count();
564 let data_rows = 1..grid.len();
565
566 let right: Vec<bool> = (0..num_cols)
571 .map(|c| {
572 let mut any = false;
573 for r in data_rows.clone() {
574 let t = grid[r][c].trim();
575 if t.is_empty() {
576 continue;
577 }
578 if !is_number_cell(t) {
579 return false;
580 }
581 any = true;
582 }
583 any
584 })
585 .collect();
586
587 let width: Vec<usize> = (0..num_cols)
589 .map(|c| {
590 let mut w = dw(&grid[0][c]) + 2;
591 for r in data_rows.clone() {
592 w = w.max(dw(&grid[r][c]));
593 }
594 w
595 })
596 .collect();
597
598 let fmt_cell = |s: &str, c: usize| -> String {
599 let pad = " ".repeat(width[c].saturating_sub(dw(s)));
600 let body = if right[c] {
601 format!("{pad}{s}")
602 } else {
603 format!("{s}{pad}")
604 };
605 format!(" {body} ")
606 };
607 let render_row = |r: usize| -> String {
608 let cells: Vec<String> = (0..num_cols).map(|c| fmt_cell(&grid[r][c], c)).collect();
609 format!("|{}|", cells.join("|"))
610 };
611
612 let mut lines = Vec::with_capacity(grid.len() + 1);
613 lines.push(render_row(0));
614 let sep: Vec<String> = (0..num_cols).map(|c| "-".repeat(width[c] + 2)).collect();
615 lines.push(format!("|{}|", sep.join("|")));
616 for r in data_rows {
617 lines.push(render_row(r));
618 }
619 lines.join("\n")
620}
621
622fn escape_cell(s: &str) -> String {
625 s.replace('\n', " ").replace('|', "|")
626}
627
628#[cfg(test)]
629mod tests {
630 use super::*;
631
632 #[test]
633 fn renders_headings_paragraphs_and_lists() {
634 let mut doc = DoclingDocument::new("demo");
635 doc.add_heading(1, "Title");
636 doc.add_paragraph("Hello world.");
637 doc.push(Node::ListItem {
638 ordered: false,
639 number: 1,
640 first_in_list: true,
641 text: "first".into(),
642 level: 0,
643 marker: None,
644 location: None,
645 dclx: None,
646 href: None,
647 layer: None,
648 });
649 doc.push(Node::ListItem {
650 ordered: false,
651 number: 2,
652 first_in_list: false,
653 text: "second".into(),
654 level: 0,
655 marker: None,
656 location: None,
657 dclx: None,
658 href: None,
659 layer: None,
660 });
661 let md = doc.export_to_markdown();
662 assert_eq!(md, "# Title\n\nHello world.\n\n- first\n- second\n");
663 }
664
665 #[test]
666 fn strict_renders_recovered_links_legacy_does_not() {
667 let mut doc = DoclingDocument::new("cv");
668 doc.add_paragraph("Find me on LinkedIn or GitHub.");
669 doc.links = vec![
670 ("LinkedIn".into(), "https://www.linkedin.com/in/x/".into()),
671 ("GitHub".into(), "https://github.com/x/".into()),
672 ];
673 assert_eq!(doc.export_to_markdown(), "Find me on LinkedIn or GitHub.\n");
675 assert_eq!(
677 doc.export_to_markdown_with(true),
678 "Find me on [LinkedIn](https://www.linkedin.com/in/x/) or [GitHub](https://github.com/x/).\n"
679 );
680 }
681
682 #[test]
683 fn strict_links_match_escaped_anchor_and_consume_in_order() {
684 let mut doc = DoclingDocument::new("d");
685 doc.add_paragraph("AI & ML here, and issues here, then issues there.");
689 doc.links = vec![
690 ("AI & ML".into(), "https://a/".into()),
691 ("issues".into(), "https://first/".into()),
692 ("issues".into(), "https://second/".into()),
693 ];
694 assert_eq!(
695 doc.export_to_markdown_with(true),
696 "[AI & ML](https://a/) here, and [issues](https://first/) here, then [issues](https://second/) there.\n"
697 );
698 }
699
700 #[test]
701 fn renders_compact_table() {
702 let mut doc = DoclingDocument::new("t");
703 doc.compact_tables = true;
706 doc.push(Node::Table(Table {
707 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
708 location: None,
709 structure: None,
710 cell_blocks: None,
711 }));
712 let md = doc.export_to_markdown();
713 assert_eq!(md, "| a | b |\n| - | - |\n| 1 | 2 |\n");
714 }
715
716 #[test]
717 fn renders_padded_github_table_by_default() {
718 let mut doc = DoclingDocument::new("t");
719 doc.push(Node::Table(Table {
720 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
721 location: None,
722 structure: None,
723 cell_blocks: None,
724 }));
725 let md = doc.export_to_markdown();
726 assert_eq!(md, "| a | b |\n|-----|-----|\n| 1 | 2 |\n");
728 }
729
730 #[test]
731 fn strict_unescapes_inline_underscores_legacy_keeps_them() {
732 let mut doc = DoclingDocument::new("t");
733 doc.add_heading(1, "a\\_b");
734 doc.add_paragraph("x\\_y");
735 doc.push(Node::ListItem {
736 ordered: false,
737 number: 1,
738 first_in_list: true,
739 text: "i\\_j".into(),
740 level: 0,
741 marker: None,
742 location: None,
743 dclx: None,
744 href: None,
745 layer: None,
746 });
747 assert_eq!(doc.export_to_markdown(), "# a\\_b\n\nx\\_y\n\n- i\\_j\n");
749 assert_eq!(doc.export_to_markdown_with(true), "# a_b\n\nx_y\n\n- i_j\n");
751 }
752
753 fn assert_stream_matches(
756 doc: &DoclingDocument,
757 strict: bool,
758 images: ImageMode,
759 splits: &[usize],
760 ) {
761 let want = to_markdown_images(doc, strict, images, "artifacts").0;
762 let mut streamer = MarkdownStreamer::new(strict, images, doc.compact_tables);
763 let mut got = String::new();
764 let mut start = 0;
765 for &end in splits {
766 let links = if start == 0 {
769 doc.links.as_slice()
770 } else {
771 &[]
772 };
773 got.push_str(&streamer.push(&doc.nodes[start..end], links));
774 start = end;
775 }
776 got.push_str(&streamer.push(
777 &doc.nodes[start..],
778 if start == 0 {
779 doc.links.as_slice()
780 } else {
781 &[]
782 },
783 ));
784 got.push_str(&streamer.finish());
785 assert_eq!(
786 got, want,
787 "streamed output diverged (splits={splits:?}, strict={strict})"
788 );
789 }
790
791 #[test]
792 fn streaming_is_byte_identical_to_buffered() {
793 let mut doc = DoclingDocument::new("d");
794 doc.add_heading(1, "Title");
795 doc.add_paragraph("First paragraph.");
796 doc.push(Node::ListItem {
797 ordered: false,
798 number: 1,
799 first_in_list: true,
800 text: "a".into(),
801 level: 0,
802 marker: None,
803 location: None,
804 dclx: None,
805 href: None,
806 layer: None,
807 });
808 doc.push(Node::ListItem {
809 ordered: false,
810 number: 2,
811 first_in_list: false,
812 text: "b".into(),
813 level: 0,
814 marker: None,
815 location: None,
816 dclx: None,
817 href: None,
818 layer: None,
819 });
820 doc.push(Node::Code {
821 language: Some("rust".into()),
822 text: "let x = 1;".into(),
823 });
824 doc.push(Node::Table(Table {
825 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
826 location: None,
827 structure: None,
828 cell_blocks: None,
829 }));
830 doc.push(Node::Picture {
831 caption: Some("Fig 1".into()),
832 image: None,
833 });
834 doc.add_paragraph("Last paragraph.");
835
836 for &strict in &[false, true] {
839 for &images in &[ImageMode::Placeholder, ImageMode::Embedded] {
840 for splits in [&[][..], &[1][..], &[2][..], &[4][..], &[1, 4, 6][..]] {
841 assert_stream_matches(&doc, strict, images, splits);
842 }
843 }
844 }
845 }
846
847 #[test]
848 fn streaming_applies_recovered_links_in_strict_mode() {
849 let mut doc = DoclingDocument::new("d");
850 doc.add_paragraph("See LinkedIn for details.");
851 doc.add_paragraph("And GitHub too.");
852 doc.links = vec![
853 ("LinkedIn".into(), "https://lnkd/".into()),
854 ("GitHub".into(), "https://gh/".into()),
855 ];
856 assert_stream_matches(&doc, true, ImageMode::Placeholder, &[1]);
859 }
860
861 #[test]
862 fn strict_tightens_punctuation_spacing_legacy_keeps_it() {
863 let mut doc = DoclingDocument::new("t");
864 doc.add_paragraph("see [ 37 , 36 ] and ( x ) .");
865 assert_eq!(doc.export_to_markdown(), "see [ 37 , 36 ] and ( x ) .\n");
867 assert_eq!(doc.export_to_markdown_with(true), "see [37, 36] and (x).\n");
869 }
870}