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