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 } = item
298 else {
299 continue;
300 };
301 let level = *level as usize;
302
303 prev.truncate(level + 1);
305 while prev.len() <= level {
306 prev.push(None);
307 }
308
309 if let Some((prev_ordered, prev_number)) = prev[level] {
313 let new_list = *first_in_list
314 || prev_ordered != *ordered
315 || (*ordered && *number != prev_number + 1);
316 if new_list {
317 lines.push(String::new());
318 }
319 }
320
321 let indent = " ".repeat(level);
322 let marker = if *ordered {
323 format!("{number}.")
324 } else {
325 "-".to_string()
326 };
327 lines.push(format!("{indent}{marker} {}", strict_text(text, strict)));
328 prev[level] = Some((*ordered, *number));
329 }
330
331 blocks.push(lines.join("\n"));
332}
333
334fn render_one(node: &Node, blocks: &mut Vec<String>, ctx: &mut Ctx) {
335 match node {
336 Node::Heading { level, text } => {
337 let hashes = "#".repeat((*level).clamp(1, 6) as usize);
338 blocks.push(format!("{hashes} {}", strict_text(text, ctx.strict)));
339 }
340 Node::Paragraph { text } if text.is_empty() => {}
343 Node::Paragraph { text } => blocks.push(strict_text(text, ctx.strict)),
344 Node::Code { language, text } => {
345 let lang = match language {
347 Some(l) if ctx.strict => l.as_str(),
348 _ => "",
349 };
350 blocks.push(format!("```{lang}\n{text}\n```"));
351 }
352 Node::Table(table) => {
353 let rendered = render_table(table, ctx.compact_tables);
354 if !rendered.is_empty() {
355 blocks.push(rendered);
356 }
357 }
358 Node::Picture { caption, image } => {
359 if let Some(cap) = caption {
360 if !cap.is_empty() {
361 blocks.push(cap.clone());
362 }
363 }
364 blocks.push(picture_marker(image.as_ref(), ctx));
365 }
366 Node::Group { children, .. } => render(children, blocks, ctx),
367 Node::FieldRegion { items } => {
368 blocks.push(MISSING_TEXT.to_string());
373 for item in items {
374 blocks.push(MISSING_TEXT.to_string());
375 for part in [&item.marker, &item.key, &item.value].into_iter().flatten() {
376 blocks.push(strict_text(part, ctx.strict));
377 }
378 }
379 }
380 Node::InlineGroup { md_text, .. } => blocks.push(strict_text(md_text, ctx.strict)),
383 Node::Furniture(_) => {}
386 Node::Located { inner, .. } => render_one(inner, blocks, ctx),
388 Node::PageBreak => {}
390 Node::ListItem { .. } => unreachable!("list items are rendered in runs"),
392 }
393}
394
395const MISSING_TEXT: &str = "<!-- missing-text -->";
398
399fn picture_marker(image: Option<&crate::PictureImage>, ctx: &mut Ctx) -> String {
402 match (ctx.images, image) {
403 (ImageMode::Embedded, Some(img)) => format!("", img.data_uri()),
404 (ImageMode::Referenced, Some(img)) => {
405 let path = format!(
406 "{}/image_{:06}.{}",
407 ctx.artifacts_dir,
408 ctx.pic_index,
409 ext_for(&img.mimetype)
410 );
411 ctx.pic_index += 1;
412 ctx.artifacts.push((path.clone(), img.data.clone()));
413 format!("")
414 }
415 _ => "<!-- image -->".to_string(),
417 }
418}
419
420fn ext_for(mimetype: &str) -> &str {
421 match mimetype {
422 "image/jpeg" => "jpg",
423 "image/gif" => "gif",
424 "image/webp" => "webp",
425 "image/bmp" => "bmp",
426 "image/tiff" => "tif",
427 _ => "png",
428 }
429}
430
431fn is_number_cell(t: &str) -> bool {
448 t.parse::<f64>().is_ok() || is_thousands_number(t)
449}
450
451fn is_thousands_number(t: &str) -> bool {
457 let b = t.as_bytes();
458 let mut i = 0;
459 let start = i;
460 if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
461 i += 1;
462 }
463 let d0 = i;
465 while i < b.len() && b[i].is_ascii_digit() && i - d0 < 3 {
466 i += 1;
467 }
468 let has_int = i > d0;
469 if has_int {
470 while i + 3 < b.len() + 1
472 && b.get(i) == Some(&b',')
473 && b.get(i + 1).is_some_and(u8::is_ascii_digit)
474 && b.get(i + 2).is_some_and(u8::is_ascii_digit)
475 && b.get(i + 3).is_some_and(u8::is_ascii_digit)
476 {
477 i += 4;
478 }
479 } else {
480 i = start;
482 }
483 if i < b.len() && b[i] == b'.' {
485 i += 1;
486 let f0 = i;
487 while i < b.len() && b[i].is_ascii_digit() {
488 i += 1;
489 }
490 if !has_int && i == f0 {
491 return false; }
493 } else if !has_int {
494 return false; }
496 i == b.len()
497}
498
499fn render_table(table: &Table, compact: bool) -> String {
500 if table.rows.is_empty() {
501 return String::new();
502 }
503 let num_cols = table.rows.iter().map(Vec::len).max().unwrap_or(0);
504 if num_cols == 0 {
505 return String::new();
506 }
507
508 let grid: Vec<Vec<String>> = table
511 .rows
512 .iter()
513 .enumerate()
514 .map(|(r, row)| {
515 (0..num_cols)
516 .map(|c| {
517 let cell = escape_cell(row.get(c).map(String::as_str).unwrap_or(""));
518 if r == 0 {
519 cell
520 } else {
521 cell.trim().to_string()
522 }
523 })
524 .collect()
525 })
526 .collect();
527
528 if compact {
529 let render_row = |r: usize| -> String { format!("| {} |", grid[r].join(" | ")) };
531 let mut lines = Vec::with_capacity(grid.len() + 1);
532 lines.push(render_row(0));
533 let sep: Vec<&str> = (0..num_cols).map(|_| "-").collect();
534 lines.push(format!("| {} |", sep.join(" | ")));
535 for r in 1..grid.len() {
536 lines.push(render_row(r));
537 }
538 return lines.join("\n");
539 }
540
541 let dw = |s: &str| s.chars().count();
543 let data_rows = 1..grid.len();
544
545 let right: Vec<bool> = (0..num_cols)
550 .map(|c| {
551 let mut any = false;
552 for r in data_rows.clone() {
553 let t = grid[r][c].trim();
554 if t.is_empty() {
555 continue;
556 }
557 if !is_number_cell(t) {
558 return false;
559 }
560 any = true;
561 }
562 any
563 })
564 .collect();
565
566 let width: Vec<usize> = (0..num_cols)
568 .map(|c| {
569 let mut w = dw(&grid[0][c]) + 2;
570 for r in data_rows.clone() {
571 w = w.max(dw(&grid[r][c]));
572 }
573 w
574 })
575 .collect();
576
577 let fmt_cell = |s: &str, c: usize| -> String {
578 let pad = " ".repeat(width[c].saturating_sub(dw(s)));
579 let body = if right[c] {
580 format!("{pad}{s}")
581 } else {
582 format!("{s}{pad}")
583 };
584 format!(" {body} ")
585 };
586 let render_row = |r: usize| -> String {
587 let cells: Vec<String> = (0..num_cols).map(|c| fmt_cell(&grid[r][c], c)).collect();
588 format!("|{}|", cells.join("|"))
589 };
590
591 let mut lines = Vec::with_capacity(grid.len() + 1);
592 lines.push(render_row(0));
593 let sep: Vec<String> = (0..num_cols).map(|c| "-".repeat(width[c] + 2)).collect();
594 lines.push(format!("|{}|", sep.join("|")));
595 for r in data_rows {
596 lines.push(render_row(r));
597 }
598 lines.join("\n")
599}
600
601fn escape_cell(s: &str) -> String {
604 s.replace('\n', " ").replace('|', "|")
605}
606
607#[cfg(test)]
608mod tests {
609 use super::*;
610
611 #[test]
612 fn renders_headings_paragraphs_and_lists() {
613 let mut doc = DoclingDocument::new("demo");
614 doc.add_heading(1, "Title");
615 doc.add_paragraph("Hello world.");
616 doc.push(Node::ListItem {
617 ordered: false,
618 number: 1,
619 first_in_list: true,
620 text: "first".into(),
621 level: 0,
622 marker: None,
623 location: None,
624 });
625 doc.push(Node::ListItem {
626 ordered: false,
627 number: 2,
628 first_in_list: false,
629 text: "second".into(),
630 level: 0,
631 marker: None,
632 location: None,
633 });
634 let md = doc.export_to_markdown();
635 assert_eq!(md, "# Title\n\nHello world.\n\n- first\n- second\n");
636 }
637
638 #[test]
639 fn strict_renders_recovered_links_legacy_does_not() {
640 let mut doc = DoclingDocument::new("cv");
641 doc.add_paragraph("Find me on LinkedIn or GitHub.");
642 doc.links = vec![
643 ("LinkedIn".into(), "https://www.linkedin.com/in/x/".into()),
644 ("GitHub".into(), "https://github.com/x/".into()),
645 ];
646 assert_eq!(doc.export_to_markdown(), "Find me on LinkedIn or GitHub.\n");
648 assert_eq!(
650 doc.export_to_markdown_with(true),
651 "Find me on [LinkedIn](https://www.linkedin.com/in/x/) or [GitHub](https://github.com/x/).\n"
652 );
653 }
654
655 #[test]
656 fn strict_links_match_escaped_anchor_and_consume_in_order() {
657 let mut doc = DoclingDocument::new("d");
658 doc.add_paragraph("AI & ML here, and issues here, then issues there.");
662 doc.links = vec![
663 ("AI & ML".into(), "https://a/".into()),
664 ("issues".into(), "https://first/".into()),
665 ("issues".into(), "https://second/".into()),
666 ];
667 assert_eq!(
668 doc.export_to_markdown_with(true),
669 "[AI & ML](https://a/) here, and [issues](https://first/) here, then [issues](https://second/) there.\n"
670 );
671 }
672
673 #[test]
674 fn renders_compact_table() {
675 let mut doc = DoclingDocument::new("t");
676 doc.compact_tables = true;
679 doc.push(Node::Table(Table {
680 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
681 location: None,
682 structure: None,
683 }));
684 let md = doc.export_to_markdown();
685 assert_eq!(md, "| a | b |\n| - | - |\n| 1 | 2 |\n");
686 }
687
688 #[test]
689 fn renders_padded_github_table_by_default() {
690 let mut doc = DoclingDocument::new("t");
691 doc.push(Node::Table(Table {
692 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
693 location: None,
694 structure: None,
695 }));
696 let md = doc.export_to_markdown();
697 assert_eq!(md, "| a | b |\n|-----|-----|\n| 1 | 2 |\n");
699 }
700
701 #[test]
702 fn strict_unescapes_inline_underscores_legacy_keeps_them() {
703 let mut doc = DoclingDocument::new("t");
704 doc.add_heading(1, "a\\_b");
705 doc.add_paragraph("x\\_y");
706 doc.push(Node::ListItem {
707 ordered: false,
708 number: 1,
709 first_in_list: true,
710 text: "i\\_j".into(),
711 level: 0,
712 marker: None,
713 location: None,
714 });
715 assert_eq!(doc.export_to_markdown(), "# a\\_b\n\nx\\_y\n\n- i\\_j\n");
717 assert_eq!(doc.export_to_markdown_with(true), "# a_b\n\nx_y\n\n- i_j\n");
719 }
720
721 fn assert_stream_matches(
724 doc: &DoclingDocument,
725 strict: bool,
726 images: ImageMode,
727 splits: &[usize],
728 ) {
729 let want = to_markdown_images(doc, strict, images, "artifacts").0;
730 let mut streamer = MarkdownStreamer::new(strict, images, doc.compact_tables);
731 let mut got = String::new();
732 let mut start = 0;
733 for &end in splits {
734 let links = if start == 0 {
737 doc.links.as_slice()
738 } else {
739 &[]
740 };
741 got.push_str(&streamer.push(&doc.nodes[start..end], links));
742 start = end;
743 }
744 got.push_str(&streamer.push(
745 &doc.nodes[start..],
746 if start == 0 {
747 doc.links.as_slice()
748 } else {
749 &[]
750 },
751 ));
752 got.push_str(&streamer.finish());
753 assert_eq!(
754 got, want,
755 "streamed output diverged (splits={splits:?}, strict={strict})"
756 );
757 }
758
759 #[test]
760 fn streaming_is_byte_identical_to_buffered() {
761 let mut doc = DoclingDocument::new("d");
762 doc.add_heading(1, "Title");
763 doc.add_paragraph("First paragraph.");
764 doc.push(Node::ListItem {
765 ordered: false,
766 number: 1,
767 first_in_list: true,
768 text: "a".into(),
769 level: 0,
770 marker: None,
771 location: None,
772 });
773 doc.push(Node::ListItem {
774 ordered: false,
775 number: 2,
776 first_in_list: false,
777 text: "b".into(),
778 level: 0,
779 marker: None,
780 location: None,
781 });
782 doc.push(Node::Code {
783 language: Some("rust".into()),
784 text: "let x = 1;".into(),
785 });
786 doc.push(Node::Table(Table {
787 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
788 location: None,
789 structure: None,
790 }));
791 doc.push(Node::Picture {
792 caption: Some("Fig 1".into()),
793 image: None,
794 });
795 doc.add_paragraph("Last paragraph.");
796
797 for &strict in &[false, true] {
800 for &images in &[ImageMode::Placeholder, ImageMode::Embedded] {
801 for splits in [&[][..], &[1][..], &[2][..], &[4][..], &[1, 4, 6][..]] {
802 assert_stream_matches(&doc, strict, images, splits);
803 }
804 }
805 }
806 }
807
808 #[test]
809 fn streaming_applies_recovered_links_in_strict_mode() {
810 let mut doc = DoclingDocument::new("d");
811 doc.add_paragraph("See LinkedIn for details.");
812 doc.add_paragraph("And GitHub too.");
813 doc.links = vec![
814 ("LinkedIn".into(), "https://lnkd/".into()),
815 ("GitHub".into(), "https://gh/".into()),
816 ];
817 assert_stream_matches(&doc, true, ImageMode::Placeholder, &[1]);
820 }
821
822 #[test]
823 fn strict_tightens_punctuation_spacing_legacy_keeps_it() {
824 let mut doc = DoclingDocument::new("t");
825 doc.add_paragraph("see [ 37 , 36 ] and ( x ) .");
826 assert_eq!(doc.export_to_markdown(), "see [ 37 , 36 ] and ( x ) .\n");
828 assert_eq!(doc.export_to_markdown_with(true), "see [37, 36] and (x).\n");
830 }
831}