1use crate::document::{
4 ContentLayer, ContentLayers, DoclingDocument, MarkdownExportOptions, Node, Table,
5};
6
7const MISSING_KEY_VALUE_ITEM: &str = "<!-- missing-key-value-item -->";
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14pub enum ImageMode {
15 #[default]
17 Placeholder,
18 Embedded,
20 Referenced,
23}
24
25struct Ctx {
27 strict: bool,
28 alt_text: bool,
31 compact_tables: bool,
33 images: ImageMode,
34 artifacts_dir: String,
35 artifacts: Vec<(String, Vec<u8>)>,
37 pic_index: usize,
38 in_table_cell: bool,
42 page_break: Option<String>,
46 pending_page_break: bool,
52 emitted_any: bool,
55 layers: ContentLayers,
57 current_layer: Option<ContentLayer>,
62 traverse_pictures: bool,
64 escape_html: bool,
67 escape_underscores: bool,
69 image_placeholder: String,
71 plain: bool,
73}
74
75impl Ctx {
76 fn new(doc: &DoclingDocument, strict: bool, options: &MarkdownExportOptions) -> Self {
79 Ctx {
80 strict,
81 alt_text: strict || doc.picture_alt_text,
82 compact_tables: doc.compact_tables,
83 images: options.image_mode,
84 artifacts_dir: options.artifacts_dir.clone(),
85 artifacts: Vec::new(),
86 pic_index: 0,
87 in_table_cell: false,
88 page_break: doc.page_break_placeholder.clone(),
89 pending_page_break: false,
90 emitted_any: false,
91 layers: options.layers,
92 current_layer: None,
93 traverse_pictures: options.traverse_pictures,
94 escape_html: options.escape_html,
95 escape_underscores: options.escape_underscores,
96 image_placeholder: options.image_placeholder.clone(),
97 plain: options.plain_text,
98 }
99 }
100
101 fn layer_visible(&self) -> bool {
103 self.layers.contains(self.current_layer)
104 }
105
106 fn unescape(&self, text: &str) -> String {
113 let mut out = std::borrow::Cow::Borrowed(text);
114 if !self.escape_html
115 && (out.contains("&") || out.contains("<") || out.contains(">"))
116 {
117 out = std::borrow::Cow::Owned(
118 out.replace("<", "<")
119 .replace(">", ">")
120 .replace("&", "&"),
121 );
122 }
123 if !self.escape_underscores && out.contains("\\_") {
124 out = std::borrow::Cow::Owned(out.replace("\\_", "_"));
125 }
126 out.into_owned()
127 }
128
129 fn text(&self, text: &str) -> String {
132 let text = strict_text(text, self.strict);
133 if self.plain {
134 self.unescape(&plain_inline(&self.drop_image_markers(&text)))
135 } else {
136 self.unescape(&text)
137 }
138 }
139
140 fn caption(&self, text: &str) -> String {
144 if self.plain {
145 self.unescape(&plain_inline(text))
146 } else {
147 self.unescape(text)
148 }
149 }
150
151 fn breaks(&self, text: &str) -> String {
154 if self.plain {
155 text.to_string()
156 } else {
157 md_line_breaks(text)
158 }
159 }
160
161 fn plain_table(&self, table: &Table) -> Table {
168 let mut plain = table.clone();
169 for cell in plain.rows.iter_mut().flatten() {
170 if cell.contains(['*', '~', '`', '[', '\n', '<']) {
171 let text = self.drop_image_markers(&strip_hard_breaks(cell));
172 *cell = plain_inline(&text);
173 }
174 }
175 plain
176 }
177
178 fn drop_image_markers(&self, text: &str) -> String {
185 const MARKER: &str = "<!-- image -->";
186 if !text.contains(MARKER) && !text.contains("```") {
187 return text.to_string();
188 }
189 text.split("\n\n")
193 .filter_map(|block| {
194 let lines: Vec<String> = block
195 .split('\n')
196 .filter_map(|line| {
197 if line.trim() == MARKER || line.trim() == "```" {
200 return None;
201 }
202 Some(line.replace(MARKER, &self.image_placeholder))
203 })
204 .collect();
205 (!lines.is_empty()).then(|| lines.join("\n"))
206 })
207 .collect::<Vec<_>>()
208 .join("\n\n")
209 }
210}
211
212pub fn to_markdown(doc: &DoclingDocument, strict: bool) -> String {
218 to_markdown_images(doc, strict, ImageMode::Placeholder, "artifacts").0
219}
220
221pub fn to_markdown_images(
225 doc: &DoclingDocument,
226 strict: bool,
227 images: ImageMode,
228 artifacts_dir: &str,
229) -> (String, Vec<(String, Vec<u8>)>) {
230 to_markdown_with_options(
231 doc,
232 strict,
233 &MarkdownExportOptions {
234 image_mode: images,
235 artifacts_dir: artifacts_dir.to_string(),
236 ..MarkdownExportOptions::default()
237 },
238 )
239}
240
241pub fn to_markdown_with_options(
245 doc: &DoclingDocument,
246 strict: bool,
247 options: &MarkdownExportOptions,
248) -> (String, Vec<(String, Vec<u8>)>) {
249 let mut ctx = Ctx::new(doc, strict, options);
250 let mut blocks: Vec<String> = Vec::new();
251 render(&doc.nodes, &mut blocks, &mut ctx);
252 let mut body = blocks.join("\n\n");
253 if strict && !options.plain_text && !doc.links.is_empty() {
257 body = apply_links(&body, &doc.links);
258 }
259 let front = if doc.metadata_output.front_matter() && !options.plain_text {
262 doc.metadata.to_front_matter()
263 } else {
264 String::new()
265 };
266 let md = match (front.is_empty(), body.is_empty()) {
267 (true, true) => String::new(),
268 (true, false) => format!("{body}\n"),
269 (false, true) => front,
270 (false, false) => format!("{front}\n{body}\n"),
271 };
272 (md, ctx.artifacts)
273}
274
275pub fn to_markdown_table_cell(doc: &DoclingDocument, strict: bool) -> String {
284 let mut ctx = Ctx::new(doc, strict, &MarkdownExportOptions::default());
285 ctx.in_table_cell = true;
286 ctx.artifacts_dir = String::new();
287 ctx.page_break = None;
291 let mut blocks: Vec<String> = Vec::new();
292 render(&doc.nodes, &mut blocks, &mut ctx);
293 blocks.join("\n\n")
294}
295
296fn apply_links(body: &str, links: &[(String, String)]) -> String {
304 let mut out = body.to_string();
305 let mut cursor = 0usize;
306 for (anchor, href) in links {
307 let anchor = anchor
308 .replace('&', "&")
309 .replace('<', "<")
310 .replace('>', ">");
311 if anchor.is_empty() {
312 continue;
313 }
314 if let Some(rel) = out[cursor..].find(&anchor) {
315 let at = cursor + rel;
316 let replacement = format!("[{anchor}]({href})");
318 out.replace_range(at..at + anchor.len(), &replacement);
319 cursor = at + replacement.len();
320 }
321 }
322 out
323}
324
325fn apply_links_chunk(chunk: &str, queue: &mut Vec<(String, String)>) -> String {
336 let mut out = chunk.to_string();
337 let mut cursor = 0usize;
338 let mut carried: Vec<(String, String)> = Vec::new();
339 for (anchor_raw, href) in std::mem::take(queue) {
340 let anchor = anchor_raw
341 .replace('&', "&")
342 .replace('<', "<")
343 .replace('>', ">");
344 if anchor.is_empty() {
345 continue;
346 }
347 if let Some(rel) = out[cursor..].find(&anchor) {
348 let at = cursor + rel;
349 let replacement = format!("[{anchor}]({href})");
350 out.replace_range(at..at + anchor.len(), &replacement);
351 cursor = at + replacement.len();
352 } else {
353 carried.push((anchor_raw, href));
355 }
356 }
357 *queue = carried;
358 out
359}
360
361pub struct MarkdownStreamer {
379 strict: bool,
380 images: ImageMode,
381 compact_tables: bool,
382 picture_alt_text: bool,
384 front_matter: Option<String>,
388 emitted_any: bool,
391 links: Vec<(String, String)>,
393 artifacts_dir: String,
397 artifacts: Vec<(String, Vec<u8>)>,
398 pic_index: usize,
399 page_break: Option<String>,
403 pending_page_break: bool,
404 items_emitted: bool,
410 layers: ContentLayers,
413 traverse_pictures: bool,
414 escape_html: bool,
415 escape_underscores: bool,
416 image_placeholder: String,
417 plain: bool,
418}
419
420impl MarkdownStreamer {
421 pub fn new(strict: bool, images: ImageMode, compact_tables: bool) -> Self {
424 debug_assert!(
425 images != ImageMode::Referenced,
426 "referenced image mode needs an artifacts dir; use with_artifacts"
427 );
428 Self::with_artifacts(strict, images, compact_tables, "artifacts")
429 }
430
431 pub fn with_artifacts(
438 strict: bool,
439 images: ImageMode,
440 compact_tables: bool,
441 artifacts_dir: &str,
442 ) -> Self {
443 Self {
444 strict,
445 images,
446 compact_tables,
447 picture_alt_text: false,
448 front_matter: None,
449 emitted_any: false,
450 links: Vec::new(),
451 artifacts_dir: artifacts_dir.to_string(),
452 artifacts: Vec::new(),
453 pic_index: 0,
454 page_break: None,
455 pending_page_break: false,
456 items_emitted: false,
457 layers: ContentLayers::BODY,
458 traverse_pictures: false,
459 escape_html: true,
460 escape_underscores: true,
461 image_placeholder: "<!-- image -->".to_string(),
462 plain: false,
463 }
464 }
465
466 pub fn with_export_options(mut self, options: &MarkdownExportOptions) -> Self {
473 self.images = options.image_mode;
474 self.artifacts_dir = options.artifacts_dir.clone();
475 self.layers = options.layers;
476 self.traverse_pictures = options.traverse_pictures;
477 self.escape_html = options.escape_html;
478 self.escape_underscores = options.escape_underscores;
479 self.image_placeholder = options.image_placeholder.clone();
480 self.plain = options.plain_text;
481 self
482 }
483
484 pub fn with_page_break_placeholder(mut self, placeholder: Option<String>) -> Self {
489 self.page_break = placeholder;
490 self
491 }
492
493 pub fn with_picture_alt_text(mut self, on: bool) -> Self {
497 self.picture_alt_text = on;
498 self
499 }
500
501 pub fn with_metadata(mut self, metadata: &crate::metadata::DocumentMetadata) -> Self {
506 self.front_matter = (!self.plain)
507 .then(|| metadata.to_front_matter())
508 .filter(|f| !f.is_empty());
509 self
510 }
511
512 pub fn take_artifacts(&mut self) -> Vec<(String, Vec<u8>)> {
517 std::mem::take(&mut self.artifacts)
518 }
519
520 pub fn push(&mut self, nodes: &[Node], links: &[(String, String)]) -> String {
525 self.links.extend(links.iter().cloned());
526 let mut ctx = Ctx {
527 strict: self.strict,
528 alt_text: self.strict || self.picture_alt_text,
529 compact_tables: self.compact_tables,
530 images: self.images,
531 artifacts_dir: std::mem::take(&mut self.artifacts_dir),
532 artifacts: std::mem::take(&mut self.artifacts),
533 pic_index: self.pic_index,
534 in_table_cell: false,
535 page_break: std::mem::take(&mut self.page_break),
536 pending_page_break: self.pending_page_break,
537 emitted_any: self.items_emitted,
538 layers: self.layers,
539 current_layer: None,
540 traverse_pictures: self.traverse_pictures,
541 escape_html: self.escape_html,
542 escape_underscores: self.escape_underscores,
543 image_placeholder: std::mem::take(&mut self.image_placeholder),
544 plain: self.plain,
545 };
546 let mut blocks: Vec<String> = Vec::new();
547 render(nodes, &mut blocks, &mut ctx);
548 self.image_placeholder = std::mem::take(&mut ctx.image_placeholder);
549 self.artifacts_dir = std::mem::take(&mut ctx.artifacts_dir);
550 self.artifacts = std::mem::take(&mut ctx.artifacts);
551 self.pic_index = ctx.pic_index;
552 self.page_break = std::mem::take(&mut ctx.page_break);
553 self.pending_page_break = ctx.pending_page_break;
554 self.items_emitted = ctx.emitted_any;
555 if blocks.is_empty() {
556 return String::new();
557 }
558 let mut body = blocks.join("\n\n");
559 if self.strict && !self.plain && !self.links.is_empty() {
560 body = apply_links_chunk(&body, &mut self.links);
561 }
562 let chunk = if let Some(front) = self.front_matter.take() {
563 format!("{front}\n{body}")
564 } else if self.emitted_any {
565 format!("\n\n{body}")
566 } else {
567 body
568 };
569 self.emitted_any = true;
570 chunk
571 }
572
573 pub fn finish(self) -> String {
576 if let Some(front) = self.front_matter {
577 front
578 } else if self.emitted_any {
579 "\n".to_string()
580 } else {
581 String::new()
582 }
583 }
584}
585
586fn strict_text(text: &str, strict: bool) -> String {
594 if !strict {
595 return text.to_string();
596 }
597 text.replace("\\_", "_")
598 .replace(" ,", ",")
599 .replace(" .", ".")
600 .replace(" ;", ";")
601 .replace(" )", ")")
602 .replace("( ", "(")
603 .replace(" ]", "]")
604 .replace("[ ", "[")
605}
606
607pub(crate) fn plain_inline(text: &str) -> String {
620 if !text.contains(['*', '~', '`', '[']) {
621 return text.to_string();
622 }
623 let chars: Vec<char> = text.chars().collect();
624 let mut out = String::with_capacity(text.len());
625 plain_inline_into(&chars, &mut out);
626 out
627}
628
629fn plain_inline_into(chars: &[char], out: &mut String) {
630 let find = |open: usize, pat: &[char]| -> Option<usize> {
631 chars
632 .get(open..)?
633 .windows(pat.len())
634 .position(|w| w == pat)
635 .map(|p| open + p)
636 };
637 let span = |i: usize, pat: &[char]| -> Option<usize> {
640 if !chars[i..].starts_with(pat) {
641 return None;
642 }
643 let open = i + pat.len();
644 let end = find(open, pat)?;
645 (end > open && !chars[open].is_whitespace() && !chars[end - 1].is_whitespace())
646 .then_some(end)
647 };
648 let mut i = 0;
649 while i < chars.len() {
650 let mut matched = false;
651 for pat in [&['*', '*', '*'][..], &['*', '*'], &['~', '~'], &['*']] {
652 if let Some(end) = span(i, pat) {
653 plain_inline_into(&chars[i + pat.len()..end], out);
654 i = end + pat.len();
655 matched = true;
656 break;
657 }
658 }
659 if matched {
660 continue;
661 }
662 if chars[i] == '`' {
666 if let Some(end) = find(i + 1, &['`']).filter(|&e| {
667 e > i + 1 && !chars[i + 1].is_whitespace() && !chars[e - 1].is_whitespace()
668 }) {
669 out.extend(&chars[i + 1..end]);
670 i = end + 1;
671 continue;
672 }
673 }
674 if chars[i] == '$' {
677 if let Some(end) = find(i + 1, &['$']) {
678 out.extend(&chars[i..=end]);
679 i = end + 1;
680 continue;
681 }
682 }
683 if chars[i] == '[' {
686 if let Some(close) = closing_bracket(chars, i) {
687 if chars.get(close + 1) == Some(&'(') {
688 if let Some(endp) = crate::doclang::link_dest_end(chars, close + 2) {
689 plain_inline_into(&chars[i + 1..close], out);
690 i = endp + 1;
691 continue;
692 }
693 }
694 }
695 }
696 let c = chars[i];
699 out.push(c);
700 i += 1;
701 if matches!(c, '*' | '~') {
702 while i < chars.len() && chars[i] == c {
703 out.push(c);
704 i += 1;
705 }
706 }
707 }
708}
709
710fn closing_bracket(chars: &[char], open: usize) -> Option<usize> {
713 let mut depth = 0usize;
714 for (k, c) in chars.iter().enumerate().skip(open + 1) {
715 match c {
716 '[' => depth += 1,
717 ']' if depth == 0 => return Some(k),
718 ']' => depth -= 1,
719 _ => {}
720 }
721 }
722 None
723}
724
725fn md_line_breaks(text: &str) -> String {
733 if !text.contains('\n') {
734 return text.to_string();
735 }
736 text.split("\n\n")
737 .map(|para| para.replace('\n', " \n"))
738 .collect::<Vec<_>>()
739 .join("\n\n")
740}
741
742pub(crate) fn strip_hard_breaks(text: &str) -> String {
747 if text.contains(" \n") {
748 text.replace(" \n", "\n")
749 } else {
750 text.to_string()
751 }
752}
753
754fn heading_line_breaks(text: &str) -> String {
758 text.replace('\n', " ")
759}
760
761fn render(nodes: &[Node], blocks: &mut Vec<String>, ctx: &mut Ctx) {
762 let mut i = 0;
763 while i < nodes.len() {
764 let before = blocks.len();
765 match &nodes[i] {
766 Node::PageBreak | Node::PageInfo { .. } => {
776 if ctx.page_break.is_some() && ctx.emitted_any {
777 ctx.pending_page_break = true;
778 }
779 i += 1;
780 }
781 Node::ListItem { .. } => {
782 let start = i;
783 i += 1;
784 loop {
785 match nodes.get(i) {
786 Some(Node::ListItem { .. } | Node::ListText { .. }) => i += 1,
787 Some(Node::Paragraph { text })
791 if text.is_empty()
792 && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
793 {
794 i += 1
795 }
796 _ => break,
797 }
798 }
799 render_list_run(&nodes[start..i], blocks, ctx);
800 }
801 other => {
802 render_one(other, blocks, ctx);
803 i += 1;
804 }
805 }
806 if blocks.len() > before {
807 let kept: Vec<String> = blocks.drain(before..).filter(|b| !b.is_empty()).collect();
817 blocks.extend(kept);
818 if ctx.pending_page_break {
819 if let Some(placeholder) = &ctx.page_break {
824 blocks.insert(before, placeholder.clone());
825 }
826 ctx.pending_page_break = false;
827 }
828 ctx.emitted_any = true;
829 }
830 }
831}
832
833fn render_list_run(items: &[Node], blocks: &mut Vec<String>, ctx: &Ctx) {
839 let mut lines: Vec<String> = Vec::new();
840 let mut any_top = false;
843
844 for item in items {
845 if let Node::ListText { level, text, glue } = item {
846 let text = ctx.text(text);
847 match lines.last_mut() {
848 Some(last) if *glue => last.push_str(&text),
849 _ => lines.push(format!("{}{text}", " ".repeat(*level as usize))),
850 }
851 continue;
852 }
853 let Node::ListItem {
854 ordered,
855 number,
856 first_in_list,
857 text,
858 level,
859 marker: orig_marker,
860 location: _,
861 dclx: _,
862 href: _,
863 layer,
864 } = item
865 else {
866 continue;
867 };
868 if !ctx.layers.contains(layer.or(ctx.current_layer)) {
872 continue;
873 }
874 let level = *level as usize;
875
876 if level == 0 {
885 if any_top && *first_in_list {
886 lines.push(String::new());
887 }
888 any_top = true;
889 }
890
891 let indent = " ".repeat(level);
892 let verbatim = orig_marker.as_deref().filter(|m| {
897 m.strip_suffix('.')
898 .is_some_and(|d| !d.is_empty() && d.chars().all(char::is_numeric))
899 });
900 let marker = match verbatim {
901 Some(m) if *ordered => m.to_string(),
902 _ if *ordered => format!("{number}."),
903 _ => "-".to_string(),
904 };
905 lines.push(format!("{indent}{marker} {}", list_item_text(text, ctx)));
906 }
907
908 if !lines.is_empty() {
911 blocks.push(lines.join("\n"));
912 }
913}
914
915fn list_item_text(text: &str, ctx: &Ctx) -> String {
923 let escaped = ctx.text(text);
924 if ctx.plain {
925 return escaped;
926 }
927 if let Some((own, tail)) = escaped.split_once('\n') {
928 if is_folded_child_tail(tail) {
929 return format!("{}\n{tail}", md_line_breaks(own));
930 }
931 }
932 md_line_breaks(&escaped)
933}
934
935fn is_folded_child_tail(tail: &str) -> bool {
942 const MARKER: &str = "<!-- image -->";
943 const FENCE: &str = "```";
944 let mut lines = tail.split('\n').peekable();
945 let mut any = false;
946 while let Some(line) = lines.next() {
947 let line = line.trim_start();
948 if line == MARKER {
949 any = true;
950 } else if line == FENCE {
951 loop {
953 match lines.next() {
954 Some(l) if l.trim_start() == FENCE => break,
955 Some(_) => {}
956 None => return false,
957 }
958 }
959 any = true;
960 } else if lines.next().map(str::trim_start) == Some(MARKER) {
961 any = true; } else {
963 return false;
964 }
965 }
966 any
967}
968
969fn render_one(node: &Node, blocks: &mut Vec<String>, ctx: &mut Ctx) {
974 match node {
975 Node::Group { .. }
977 | Node::Furniture { .. }
978 | Node::PageFurniture { .. }
979 | Node::FurnitureText { .. }
980 | Node::CommentSection { .. }
981 | Node::PictureChildren(_)
982 | Node::Commented { .. }
983 | Node::Located { .. }
984 | Node::Prov { .. }
985 | Node::Track { .. }
986 | Node::PageBreak
987 | Node::PageInfo { .. }
988 | Node::DoclangOnly(_) => {}
989 _ if !ctx.layer_visible() => return,
990 _ => {}
991 }
992 render_item(node, blocks, ctx)
993}
994
995fn render_item(node: &Node, blocks: &mut Vec<String>, ctx: &mut Ctx) {
996 match node {
997 Node::Heading { level, text } => {
998 if ctx.plain {
999 blocks.push(ctx.text(text));
1002 return;
1003 }
1004 let text = heading_line_breaks(&ctx.text(text));
1005 if ctx.in_table_cell {
1006 blocks.push(text);
1008 } else {
1009 let hashes = "#".repeat((*level).clamp(1, 6) as usize);
1010 blocks.push(format!("{hashes} {text}"));
1011 }
1012 }
1013 Node::Paragraph { text } if text.is_empty() => {}
1016 Node::Paragraph { text } => blocks.push(ctx.breaks(&ctx.text(text))),
1017 Node::LabeledText { .. } => render_item(&node.labeled_as_paragraph(), blocks, ctx),
1018 Node::Caption { text, .. } if text.is_empty() => {}
1021 Node::Caption { text, href } => {
1022 let body = ctx.breaks(&ctx.text(text));
1023 blocks.push(match href {
1024 Some(url) if !ctx.plain => format!("[{body}]({url})"),
1025 _ => body,
1026 });
1027 }
1028 Node::CheckboxItem { checked, text } => {
1029 let mark = if *checked { "- [x] " } else { "- [ ] " };
1030 blocks.push(ctx.breaks(&ctx.text(&format!("{mark}{text}"))));
1031 }
1032 Node::Code {
1033 language,
1034 text,
1035 pretty,
1036 ..
1037 } => {
1038 let lang = match language {
1040 Some(l) if ctx.strict => l.as_str(),
1041 _ => "",
1042 };
1043 let body = match pretty {
1046 Some(p) if ctx.strict => p.as_str(),
1047 _ => text.as_str(),
1048 };
1049 blocks.push(if ctx.plain {
1052 body.to_string()
1053 } else {
1054 format!("```{lang}\n{body}\n```")
1055 });
1056 }
1057 Node::Formula { latex, .. } => blocks.push(format!("$${latex}$$")),
1060 Node::Table(table) => {
1061 if let Some(cap) = &table.caption {
1064 if !cap.is_empty() {
1065 blocks.push(ctx.text(cap));
1066 }
1067 }
1068 let rendered = if ctx.plain {
1069 render_table(&ctx.plain_table(table), ctx.compact_tables)
1070 } else {
1071 render_table(table, ctx.compact_tables)
1072 };
1073 if !rendered.is_empty() {
1074 blocks.push(rendered);
1075 }
1076 }
1077 Node::Picture {
1086 caption,
1087 image,
1088 description,
1089 ..
1090 } => {
1091 if let Some(cap) = caption {
1092 if !cap.is_empty() {
1093 blocks.push(ctx.caption(cap));
1094 }
1095 }
1096 let alt = description
1097 .as_ref()
1098 .filter(|d| d.is_alt_text() && ctx.alt_text && !d.text.is_empty());
1099 let marker = picture_marker(image.as_ref(), ctx, alt.map(|d| d.text.as_str()));
1100 if let Some(desc) = description {
1101 let shown = !desc.is_alt_text() || (ctx.alt_text && !marker.starts_with("!["));
1102 if !desc.text.is_empty() && shown {
1103 blocks.push(ctx.breaks(&ctx.text(&desc.text)));
1104 }
1105 }
1106 blocks.push(marker);
1107 }
1108 Node::Chart {
1112 kind,
1113 table,
1114 caption,
1115 ..
1116 } => {
1117 if let Some(cap) = caption {
1118 if !cap.is_empty() {
1119 blocks.push(ctx.caption(cap));
1120 }
1121 }
1122 blocks.push(picture_marker(None, ctx, None));
1123 blocks.push(humanize_label(kind));
1124 let rendered = if ctx.plain {
1125 render_table(&ctx.plain_table(table), false)
1126 } else {
1127 render_table(table, false)
1128 };
1129 if !rendered.is_empty() {
1130 blocks.push(rendered);
1131 }
1132 }
1133 Node::DoclangOnly(_) => {}
1135 Node::Group {
1140 layer: Some(layer),
1141 children,
1142 ..
1143 } => {
1144 let outer = ctx.current_layer.replace(*layer);
1145 render(children, blocks, ctx);
1146 ctx.current_layer = outer;
1147 }
1148 Node::Group { children, .. } => render(children, blocks, ctx),
1149 Node::FieldRegion { items } => {
1150 for item in items {
1155 for part in [&item.marker, &item.key, &item.value].into_iter().flatten() {
1156 blocks.push(ctx.breaks(&ctx.text(part)));
1157 }
1158 }
1159 }
1160 Node::KeyValueGraph { .. } => blocks.push(MISSING_KEY_VALUE_ITEM.to_string()),
1163 Node::InlineGroup { md_text, .. } => blocks.push(ctx.breaks(&ctx.text(md_text))),
1166 Node::TextDump(text) => {
1168 if !text.is_empty() {
1169 blocks.push(text.clone());
1170 }
1171 }
1172 Node::Furniture { layer, inner } => {
1176 let outer = ctx.current_layer.replace(*layer);
1177 render_one(inner, blocks, ctx);
1178 ctx.current_layer = outer;
1179 }
1180 Node::PageFurniture { text, .. } | Node::FurnitureText { text, .. } => {
1184 if ctx.layers.furniture && !text.is_empty() {
1185 blocks.push(ctx.breaks(&ctx.text(text)));
1186 }
1187 }
1188 Node::PictureChildren(children) => {
1193 if ctx.traverse_pictures {
1194 render(children, blocks, ctx);
1195 }
1196 }
1197 Node::CommentSection { text, .. } => {
1202 if ctx.layers.notes && !text.is_empty() {
1203 blocks.push(ctx.breaks(&ctx.text(text)));
1204 }
1205 }
1206 Node::Commented { inner, .. } => render_one(inner, blocks, ctx),
1207 Node::Located { inner, .. } | Node::Prov { inner, .. } | Node::Track { inner, .. } => {
1209 render_one(inner, blocks, ctx)
1210 }
1211 Node::PageBreak => {}
1213 Node::PageInfo { .. } => {}
1215 Node::ListItem { .. } => render_list_run(std::slice::from_ref(node), blocks, ctx),
1220 Node::ListText { text, .. } if text.is_empty() => {}
1222 Node::ListText { text, .. } => blocks.push(ctx.breaks(&ctx.text(text))),
1223 }
1224}
1225
1226fn humanize_label(label: &str) -> String {
1231 let text = label.replace('_', " ");
1232 let mut chars = text.chars();
1233 match chars.next() {
1234 Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
1235 None => text,
1236 }
1237}
1238
1239fn image_alt(alt: Option<&str>) -> String {
1242 match alt {
1243 Some(text) => text
1244 .split_whitespace()
1245 .collect::<Vec<_>>()
1246 .join(" ")
1247 .replace('\\', "\\\\")
1248 .replace(']', "\\]"),
1249 None => "Image".to_string(),
1250 }
1251}
1252
1253fn picture_marker(image: Option<&crate::PictureImage>, ctx: &mut Ctx, alt: Option<&str>) -> String {
1254 match (ctx.images, image) {
1255 (ImageMode::Embedded, Some(img)) => {
1257 format!(
1258 "",
1259 image_alt(alt),
1260 crate::pixel_digest::docling_data_uri(img).1
1261 )
1262 }
1263 (ImageMode::Referenced, Some(img)) => {
1264 let path = format!(
1265 "{}/image_{:06}.{}",
1266 ctx.artifacts_dir,
1267 ctx.pic_index,
1268 ext_for(&img.mimetype)
1269 );
1270 ctx.pic_index += 1;
1271 ctx.artifacts.push((path.clone(), img.data.clone()));
1272 format!("", image_alt(alt), escape_uri_path(&path))
1273 }
1274 _ => ctx.image_placeholder.clone(),
1276 }
1277}
1278
1279pub(crate) fn escape_uri_path(value: &str) -> String {
1292 const KEEP: &str = "/%:@+,;=~$!&'*";
1293 let s = value.replace('\\', "/");
1294 if let Some(rest) = s.strip_prefix("//") {
1295 let rest = rest.trim_start_matches('/');
1297 let (host, tail) = rest.split_once('/').unwrap_or((rest, ""));
1298 return format!("file://{host}{}", percent_quote(&format!("/{tail}"), KEEP));
1299 }
1300 let bytes = s.as_bytes();
1301 if bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && bytes[2] == b'/' {
1302 return format!("file:///{}", percent_quote(&s, KEEP));
1304 }
1305 if let Some((scheme, rest)) = s.split_once(':') {
1309 let valid_scheme = scheme.len() > 1
1310 && scheme.as_bytes()[0].is_ascii_alphabetic()
1311 && scheme
1312 .bytes()
1313 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'));
1314 if valid_scheme {
1315 let (authority, rest) = match rest.strip_prefix("//") {
1316 Some(r) => {
1317 let end = r.find(['/', '?', '#']).unwrap_or(r.len());
1318 (Some(&r[..end]), &r[end..])
1319 }
1320 None => (None, rest),
1321 };
1322 let (before_frag, fragment) = rest.split_once('#').unwrap_or((rest, ""));
1323 let (path, query) = before_frag.split_once('?').unwrap_or((before_frag, ""));
1324 let mut out = format!("{scheme}:");
1325 if let Some(a) = authority {
1326 out.push_str("//");
1327 out.push_str(a);
1328 }
1329 out.push_str(&percent_quote(path, KEEP));
1330 if !query.is_empty() {
1331 out.push('?');
1332 out.push_str(&percent_quote(query, KEEP));
1333 }
1334 if !fragment.is_empty() {
1335 out.push('#');
1336 out.push_str(&percent_quote(fragment, KEEP));
1337 }
1338 return out;
1339 }
1340 }
1341 percent_quote(&s, KEEP)
1343}
1344
1345fn percent_quote(s: &str, safe: &str) -> String {
1348 let mut out = String::with_capacity(s.len());
1349 for &b in s.as_bytes() {
1350 let keep = b.is_ascii_alphanumeric()
1351 || matches!(b, b'_' | b'.' | b'-' | b'~')
1352 || (b.is_ascii() && safe.contains(b as char));
1353 if keep {
1354 out.push(b as char);
1355 } else {
1356 out.push_str(&format!("%{b:02X}"));
1357 }
1358 }
1359 out
1360}
1361
1362pub(crate) fn ext_for(mimetype: &str) -> &str {
1363 match mimetype {
1364 "image/jpeg" => "jpg",
1365 "image/gif" => "gif",
1366 "image/webp" => "webp",
1367 "image/bmp" => "bmp",
1368 "image/tiff" => "tif",
1369 _ => "png",
1370 }
1371}
1372
1373fn is_number_cell(t: &str) -> bool {
1392 t.parse::<f64>().is_ok() || is_thousands_number(t)
1393}
1394
1395fn is_thousands_number(t: &str) -> bool {
1401 let b = t.as_bytes();
1402 let mut i = 0;
1403 let start = i;
1404 if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
1405 i += 1;
1406 }
1407 let d0 = i;
1409 while i < b.len() && b[i].is_ascii_digit() && i - d0 < 3 {
1410 i += 1;
1411 }
1412 let has_int = i > d0;
1413 if has_int {
1414 while i + 3 < b.len() + 1
1416 && b.get(i) == Some(&b',')
1417 && b.get(i + 1).is_some_and(u8::is_ascii_digit)
1418 && b.get(i + 2).is_some_and(u8::is_ascii_digit)
1419 && b.get(i + 3).is_some_and(u8::is_ascii_digit)
1420 {
1421 i += 4;
1422 }
1423 } else {
1424 i = start;
1426 }
1427 if i < b.len() && b[i] == b'.' {
1429 i += 1;
1430 let f0 = i;
1431 while i < b.len() && b[i].is_ascii_digit() {
1432 i += 1;
1433 }
1434 if !has_int && i == f0 {
1435 return false; }
1437 } else if !has_int {
1438 return false; }
1440 i == b.len()
1441}
1442
1443fn flatten_header_rows(header_rows: &[Vec<String>], num_cols: usize) -> Vec<String> {
1452 (0..num_cols)
1453 .map(|c| {
1454 let mut parts: Vec<&str> = Vec::new();
1455 for row in header_rows {
1456 let text = row.get(c).map(String::as_str).unwrap_or("");
1457 if !text.is_empty() && parts.last() != Some(&text) {
1458 parts.push(text);
1459 }
1460 }
1461 parts.join(" - ")
1462 })
1463 .collect()
1464}
1465
1466pub(crate) fn render_table(table: &Table, compact: bool) -> String {
1467 if table.rows.is_empty() {
1468 return String::new();
1469 }
1470 let num_cols = table.rows.iter().map(Vec::len).max().unwrap_or(0);
1471 if num_cols == 0 {
1472 return String::new();
1473 }
1474
1475 let num_headers = table.header_row_count().min(table.rows.len());
1480 let escaped = |r: usize| -> Vec<String> {
1481 (0..num_cols)
1482 .map(|c| escape_cell(table.rows[r].get(c).map(String::as_str).unwrap_or("")))
1483 .collect()
1484 };
1485 let header_rows: Vec<Vec<String>> = (0..num_headers).map(escaped).collect();
1486 let header = flatten_header_rows(&header_rows, num_cols);
1487 let body: Vec<Vec<String>> = (num_headers..table.rows.len())
1488 .map(|r| {
1489 escaped(r)
1490 .into_iter()
1491 .map(|c| c.trim().to_string())
1492 .collect()
1493 })
1494 .collect();
1495
1496 if compact {
1497 let render_row = |row: &[String]| -> String { format!("| {} |", row.join(" | ")) };
1499 let mut lines = Vec::with_capacity(body.len() + 2);
1500 lines.push(render_row(&header));
1501 let sep: Vec<&str> = (0..num_cols).map(|_| "-").collect();
1502 lines.push(format!("| {} |", sep.join(" | ")));
1503 for row in &body {
1504 lines.push(render_row(row));
1505 }
1506 return lines.join("\n");
1507 }
1508
1509 let dw = |s: &str| s.chars().count();
1511
1512 let right: Vec<bool> = (0..num_cols)
1517 .map(|c| {
1518 let mut any = false;
1519 for row in &body {
1520 let t = row[c].trim();
1521 if t.is_empty() {
1522 continue;
1523 }
1524 if !is_number_cell(t) {
1525 return false;
1526 }
1527 any = true;
1528 }
1529 any
1530 })
1531 .collect();
1532
1533 let width: Vec<usize> = (0..num_cols)
1535 .map(|c| {
1536 let mut w = dw(&header[c]) + 2;
1537 for row in &body {
1538 w = w.max(dw(&row[c]));
1539 }
1540 w
1541 })
1542 .collect();
1543
1544 let fmt_cell = |s: &str, c: usize| -> String {
1545 let pad = " ".repeat(width[c].saturating_sub(dw(s)));
1546 let body = if right[c] {
1547 format!("{pad}{s}")
1548 } else {
1549 format!("{s}{pad}")
1550 };
1551 format!(" {body} ")
1552 };
1553 let render_row = |row: &[String]| -> String {
1554 let cells: Vec<String> = (0..num_cols).map(|c| fmt_cell(&row[c], c)).collect();
1555 format!("|{}|", cells.join("|"))
1556 };
1557
1558 let mut lines = Vec::with_capacity(body.len() + 2);
1559 lines.push(render_row(&header));
1560 let sep: Vec<String> = (0..num_cols).map(|c| "-".repeat(width[c] + 2)).collect();
1561 lines.push(format!("|{}|", sep.join("|")));
1562 for row in &body {
1563 lines.push(render_row(row));
1564 }
1565 lines.join("\n")
1566}
1567
1568fn escape_cell(s: &str) -> String {
1571 s.replace('\n', " ").replace('|', "|")
1572}
1573
1574#[cfg(test)]
1575mod tests {
1576 use super::*;
1577 use crate::{PictureImage, TableCell, TableStructure};
1578
1579 #[test]
1585 fn list_boundaries_come_from_the_backend_not_the_numbering() {
1586 let item = |ordered: bool, number: u64, first_in_list: bool, text: &str| Node::ListItem {
1587 ordered,
1588 number,
1589 first_in_list,
1590 text: text.into(),
1591 level: 0,
1592 marker: None,
1593 location: None,
1594 dclx: None,
1595 href: None,
1596 layer: None,
1597 };
1598 let md = |items: Vec<Node>| {
1599 let mut doc = DoclingDocument::new("t");
1600 for n in items {
1601 doc.push(n);
1602 }
1603 doc.export_to_markdown()
1604 };
1605 assert_eq!(
1607 md(vec![
1608 item(true, 1, true, "one"),
1609 item(true, 5, false, "five")
1610 ]),
1611 "1. one\n5. five\n"
1612 );
1613 assert_eq!(
1615 md(vec![
1616 item(false, 0, true, "bullet"),
1617 item(true, 1, false, "one"),
1618 item(false, 0, false, "bullet two"),
1619 ]),
1620 "- bullet\n1. one\n- bullet two\n"
1621 );
1622 assert_eq!(
1624 md(vec![
1625 item(true, 1, true, "a"),
1626 item(true, 2, false, "b"),
1627 item(true, 3, true, "new list, continuing count"),
1628 ]),
1629 "1. a\n2. b\n\n3. new list, continuing count\n"
1630 );
1631 }
1632
1633 #[test]
1634 fn renders_headings_paragraphs_and_lists() {
1635 let mut doc = DoclingDocument::new("demo");
1636 doc.add_heading(1, "Title");
1637 doc.add_paragraph("Hello world.");
1638 doc.push(Node::ListItem {
1639 ordered: false,
1640 number: 1,
1641 first_in_list: true,
1642 text: "first".into(),
1643 level: 0,
1644 marker: None,
1645 location: None,
1646 dclx: None,
1647 href: None,
1648 layer: None,
1649 });
1650 doc.push(Node::ListItem {
1651 ordered: false,
1652 number: 2,
1653 first_in_list: false,
1654 text: "second".into(),
1655 level: 0,
1656 marker: None,
1657 location: None,
1658 dclx: None,
1659 href: None,
1660 layer: None,
1661 });
1662 let md = doc.export_to_markdown();
1663 assert_eq!(md, "# Title\n\nHello world.\n\n- first\n- second\n");
1664 }
1665
1666 #[test]
1670 fn single_newlines_become_gfm_hard_line_breaks() {
1671 let mut doc = DoclingDocument::new("t");
1672 doc.push(Node::Heading {
1673 level: 1,
1674 text: "Hello\nWorld".into(),
1675 });
1676 doc.push(Node::Paragraph {
1677 text: "line one\nline two\n\npara two".into(),
1678 });
1679 doc.push(Node::ListItem {
1680 ordered: false,
1681 number: 1,
1682 first_in_list: true,
1683 text: "item\ncontinued".into(),
1684 level: 0,
1685 marker: None,
1686 location: None,
1687 dclx: None,
1688 href: None,
1689 layer: None,
1690 });
1691 doc.push(Node::TextDump("A1 B1 \n\n\nC1".into()));
1692 assert_eq!(
1693 doc.export_to_markdown(),
1694 "# Hello World\n\nline one \nline two\n\npara two\n\n- item \ncontinued\n\nA1 B1 \n\n\nC1\n"
1695 );
1696 }
1697
1698 #[test]
1701 fn table_cell_mode_and_field_regions() {
1702 let mut doc = DoclingDocument::new("t");
1703 doc.push(Node::Heading {
1704 level: 2,
1705 text: "A text".into(),
1706 });
1707 doc.push(Node::Paragraph {
1708 text: "body".into(),
1709 });
1710 assert_eq!(to_markdown_table_cell(&doc, false), "A text\n\nbody");
1711 assert_eq!(doc.export_to_markdown(), "## A text\n\nbody\n");
1712
1713 let mut doc = DoclingDocument::new("f");
1714 doc.push(Node::FieldRegion {
1715 items: vec![crate::FieldItem {
1716 marker: None,
1717 key: Some("Name:".into()),
1718 value: Some("John Doe".into()),
1719 value_kind: None,
1720 }],
1721 });
1722 assert_eq!(doc.export_to_markdown(), "Name:\n\nJohn Doe\n");
1723 }
1724
1725 #[test]
1726 fn strict_renders_recovered_links_legacy_does_not() {
1727 let mut doc = DoclingDocument::new("cv");
1728 doc.add_paragraph("Find me on LinkedIn or GitHub.");
1729 doc.links = vec![
1730 ("LinkedIn".into(), "https://www.linkedin.com/in/x/".into()),
1731 ("GitHub".into(), "https://github.com/x/".into()),
1732 ];
1733 assert_eq!(doc.export_to_markdown(), "Find me on LinkedIn or GitHub.\n");
1735 assert_eq!(
1737 doc.export_to_markdown_with(true),
1738 "Find me on [LinkedIn](https://www.linkedin.com/in/x/) or [GitHub](https://github.com/x/).\n"
1739 );
1740 }
1741
1742 #[test]
1743 fn strict_links_match_escaped_anchor_and_consume_in_order() {
1744 let mut doc = DoclingDocument::new("d");
1745 doc.add_paragraph("AI & ML here, and issues here, then issues there.");
1749 doc.links = vec![
1750 ("AI & ML".into(), "https://a/".into()),
1751 ("issues".into(), "https://first/".into()),
1752 ("issues".into(), "https://second/".into()),
1753 ];
1754 assert_eq!(
1755 doc.export_to_markdown_with(true),
1756 "[AI & ML](https://a/) here, and [issues](https://first/) here, then [issues](https://second/) there.\n"
1757 );
1758 }
1759
1760 #[test]
1764 fn referenced_image_destinations_are_escaped() {
1765 let cases = [
1766 (
1767 "doc_artifacts/image_000001_ab12.png",
1768 "doc_artifacts/image_000001_ab12.png",
1769 ),
1770 (
1771 "My Report_artifacts/img.png",
1772 "My%20Report_artifacts/img.png",
1773 ),
1774 ("artifacts/img (1).png", "artifacts/img%20%281%29.png"),
1775 ("100%_scale/a#b?c.png", "100%_scale/a%23b%3Fc.png"),
1776 ("/home/a b/img.png", "/home/a%20b/img.png"),
1777 (
1778 "My Report_artifacts\\img.png",
1779 "My%20Report_artifacts/img.png",
1780 ),
1781 (
1782 "C:/Users/me/My Docs/img.png",
1783 "file:///C:/Users/me/My%20Docs/img.png",
1784 ),
1785 ("C:\\Users\\me\\img.png", "file:///C:/Users/me/img.png"),
1786 (
1787 "//server/share/My Docs/img.png",
1788 "file://server/share/My%20Docs/img.png",
1789 ),
1790 ("\\\\server\\share\\img.png", "file://server/share/img.png"),
1791 ("file:///home/a b/img.png", "file:///home/a%20b/img.png"),
1792 (
1793 "s3://bucket/My Report_artifacts/img.png",
1794 "s3://bucket/My%20Report_artifacts/img.png",
1795 ),
1796 (
1797 "https://example.com:8080/a b.png?w=1&h=2#frag",
1798 "https://example.com:8080/a%20b.png?w=1&h=2#frag",
1799 ),
1800 (
1801 "https://example.com/img (1).png",
1802 "https://example.com/img%20%281%29.png",
1803 ),
1804 ("caf\u{e9}/im\u{e4}ge.png", "caf%C3%A9/im%C3%A4ge.png"),
1805 ];
1806 for (input, expected) in cases {
1807 assert_eq!(escape_uri_path(input), expected, "input {input:?}");
1808 assert_eq!(
1809 escape_uri_path(expected),
1810 expected,
1811 "idempotent {expected:?}"
1812 );
1813 }
1814 let mut doc = DoclingDocument::new("t");
1816 doc.push(Node::Picture {
1817 caption: None,
1818 caption_href: None,
1819 image: Some(PictureImage {
1820 dpi: PictureImage::DEFAULT_DPI,
1821 mimetype: "image/png".into(),
1822 width: 1,
1823 height: 1,
1824 data: b"x".to_vec(),
1825 }),
1826 classification: None,
1827 description: None,
1828 caption_parent: Default::default(),
1829 caption_location: None,
1830 });
1831 let (md, files) = doc
1832 .export_to_markdown_with_images(ImageMode::Referenced, "My Report (final)_artifacts");
1833 assert!(
1834 md.contains(""),
1835 "got:\n{md}"
1836 );
1837 assert_eq!(files[0].0, "My Report (final)_artifacts/image_000000.png");
1839 }
1840
1841 #[test]
1845 fn folded_list_item_pictures_keep_plain_newlines() {
1846 let doc = DoclingDocument::new("t");
1847 let ctx = Ctx::new(&doc, false, &MarkdownExportOptions::default());
1848 assert_eq!(
1849 list_item_text("Step\n<!-- image -->", &ctx),
1850 "Step\n<!-- image -->"
1851 );
1852 assert_eq!(
1853 list_item_text("Step\nAlt text\n<!-- image -->\n<!-- image -->", &ctx),
1854 "Step\nAlt text\n<!-- image -->\n<!-- image -->"
1855 );
1856 assert_eq!(
1857 list_item_text("line one\nline two", &ctx),
1858 "line one \nline two"
1859 );
1860 }
1861
1862 #[test]
1865 fn stacked_header_rows_flatten_into_one() {
1866 let mut t = Table {
1867 rows: vec![
1868 vec!["".into(), "% of Total".into(), "% of Total".into()],
1869 vec!["class".into(), "Train".into(), "Test".into()],
1870 vec!["Caption".into(), "2.04".into(), "1.77".into()],
1871 ],
1872 ..Default::default()
1873 };
1874 t.structure = Some(TableStructure {
1875 header_row: vec![true, true, false],
1876 col_continuation: vec![
1877 vec![false, false, true],
1878 vec![false, false, false],
1879 vec![false, false, false],
1880 ],
1881 ..Default::default()
1882 });
1883 assert_eq!(t.header_row_count(), 2);
1884 assert_eq!(
1885 render_table(&t, true),
1886 "| class | % of Total - Train | % of Total - Test |\n| - | - | - |\n| Caption | 2.04 | 1.77 |"
1887 );
1888 assert_eq!(
1890 render_table(&t, false),
1891 "| class | % of Total - Train | % of Total - Test |\n\
1892 |---------|----------------------|---------------------|\n\
1893 | Caption | 2.04 | 1.77 |"
1894 );
1895 }
1896
1897 #[test]
1900 fn vertically_spanning_header_does_not_extend_the_block() {
1901 let mut t = Table {
1902 rows: vec![
1903 vec!["Name".into(), "Value".into()],
1904 vec!["Name".into(), "1".into()],
1905 vec!["x".into(), "2".into()],
1906 ],
1907 ..Default::default()
1908 };
1909 t.structure = Some(TableStructure {
1910 col_header: vec![vec![true, true], vec![true, false], vec![false, false]],
1911 row_continuation: vec![vec![false, false], vec![true, false], vec![false, false]],
1912 ..Default::default()
1913 });
1914 assert_eq!(t.header_row_count(), 1);
1915 assert_eq!(
1916 render_table(&t, true),
1917 "| Name | Value |\n| - | - |\n| Name | 1 |\n| x | 2 |"
1918 );
1919 }
1920
1921 #[test]
1924 fn header_flags_not_on_row_zero_keep_all_rows_in_the_body() {
1925 let mut t = Table {
1926 rows: vec![
1927 vec!["1".into(), "2".into()],
1928 vec!["a".into(), "b".into()],
1929 vec!["333".into(), "4".into()],
1930 ],
1931 ..Default::default()
1932 };
1933 t.structure = Some(TableStructure {
1934 header_row: vec![false, true, false],
1935 ..Default::default()
1936 });
1937 assert_eq!(t.header_row_count(), 0);
1938 assert_eq!(
1939 render_table(&t, false),
1940 "| | |\n|-----|----|\n| 1 | 2 |\n| a | b |\n| 333 | 4 |"
1941 );
1942 }
1943
1944 #[test]
1949 fn pivot_row_headers_do_not_extend_the_header() {
1950 let mut t = Table {
1951 rows: vec![
1952 vec!["Year".into(), "Month".into()],
1953 vec!["2025".into(), "January".into()],
1954 vec!["2025".into(), "February".into()],
1955 ],
1956 ..Default::default()
1957 };
1958 t.structure = Some(TableStructure {
1959 col_header: vec![vec![true, true], vec![false, false], vec![false, false]],
1960 row_header: vec![vec![false, false], vec![true, false], vec![true, false]],
1961 row_continuation: vec![vec![false, false], vec![false, false], vec![true, false]],
1962 ..Default::default()
1963 });
1964 assert_eq!(t.header_row_count(), 1);
1965 assert_eq!(
1966 render_table(&t, true),
1967 "| Year | Month |\n| - | - |\n| 2025 | January |\n| 2025 | February |"
1968 );
1969 }
1970
1971 #[test]
1974 fn unflagged_cells_keep_row_zero_as_header() {
1975 let mut t = Table {
1976 rows: vec![vec!["h".into()], vec!["d".into()]],
1977 ..Default::default()
1978 };
1979 t.cells = Some(
1980 [(0usize, "h"), (1, "d")]
1981 .into_iter()
1982 .map(|(r, text)| TableCell {
1983 text: text.into(),
1984 bbox: None,
1985 start_row: r,
1986 start_col: 0,
1987 row_span: 1,
1988 col_span: 1,
1989 column_header: false,
1990 row_header: false,
1991 row_section: false,
1992 })
1993 .collect(),
1994 );
1995 assert_eq!(t.header_row_count(), 1);
1996 assert_eq!(render_table(&t, true), "| h |\n| - |\n| d |");
1997 }
1998
1999 fn flagged_table(rows: &[&[&str]], ched: impl Fn(usize, usize) -> bool) -> Table {
2001 let mut cells = Vec::new();
2002 for (r, row) in rows.iter().enumerate() {
2003 for (c, text) in row.iter().enumerate() {
2004 cells.push(TableCell {
2005 text: (*text).into(),
2006 bbox: None,
2007 start_row: r,
2008 start_col: c,
2009 row_span: 1,
2010 col_span: 1,
2011 column_header: ched(r, c),
2012 row_header: false,
2013 row_section: false,
2014 });
2015 }
2016 }
2017 Table {
2018 rows: rows
2019 .iter()
2020 .map(|row| row.iter().map(|t| (*t).to_string()).collect())
2021 .collect(),
2022 cells: Some(cells),
2023 ..Default::default()
2024 }
2025 }
2026
2027 #[test]
2031 fn rows_with_body_text_stop_the_header_block() {
2032 let t = flagged_table(
2034 &[
2035 &["Item", "Q1", "Q2"],
2036 &["Sales", "10", "20"],
2037 &["Costs", "5", "7"],
2038 ],
2039 |r, c| r == 0 || c == 0,
2040 );
2041 assert_eq!(t.header_row_count(), 1);
2042 assert_eq!(
2043 render_table(&t, false),
2044 "| Item | Q1 | Q2 |\n\
2045 |--------|------|------|\n\
2046 | Sales | 10 | 20 |\n\
2047 | Costs | 5 | 7 |"
2048 );
2049 let t = flagged_table(&[&["Sales", "10", "20"], &["Costs", "5", "7"]], |_, c| {
2052 c == 0
2053 });
2054 assert_eq!(t.header_row_count(), 0);
2055 assert_eq!(
2056 render_table(&t, false),
2057 "| | | |\n\
2058 |-------|----|----|\n\
2059 | Sales | 10 | 20 |\n\
2060 | Costs | 5 | 7 |"
2061 );
2062 let t = flagged_table(
2063 &[&["a", "1", "2"], &["b", "3", "4"], &["c", "5", "6"]],
2064 |r, c| c == 0 && r < 2,
2065 );
2066 assert_eq!(t.header_row_count(), 0);
2067 let t = flagged_table(&[&["a", "1", "2"], &["b", "3", "4"]], |r, c| {
2070 r == 0 && c == 0
2071 });
2072 assert_eq!(t.header_row_count(), 1);
2073 assert_eq!(
2074 render_table(&t, false),
2075 "| a | 1 | 2 |\n\
2076 |-----|-----|-----|\n\
2077 | b | 3 | 4 |"
2078 );
2079 let t = flagged_table(&[&["Item", "", ""], &["x", "1", "2"]], |_, c| c == 0);
2081 assert_eq!(t.header_row_count(), 1);
2082 assert_eq!(
2083 render_table(&t, false),
2084 "| Item | | |\n\
2085 |--------|----|----|\n\
2086 | x | 1 | 2 |"
2087 );
2088 }
2089
2090 #[test]
2091 fn renders_compact_table() {
2092 let mut doc = DoclingDocument::new("t");
2093 doc.compact_tables = true;
2096 doc.push(Node::Table(Table {
2097 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
2098 location: None,
2099 structure: None,
2100 cell_blocks: None,
2101 cells: None,
2102 caption: None,
2103 caption_parent: Default::default(),
2104 caption_location: None,
2105 }));
2106 let md = doc.export_to_markdown();
2107 assert_eq!(md, "| a | b |\n| - | - |\n| 1 | 2 |\n");
2108 }
2109
2110 #[test]
2111 fn renders_padded_github_table_by_default() {
2112 let mut doc = DoclingDocument::new("t");
2113 doc.push(Node::Table(Table {
2114 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
2115 location: None,
2116 structure: None,
2117 cell_blocks: None,
2118 cells: None,
2119 caption: None,
2120 caption_parent: Default::default(),
2121 caption_location: None,
2122 }));
2123 let md = doc.export_to_markdown();
2124 assert_eq!(md, "| a | b |\n|-----|-----|\n| 1 | 2 |\n");
2126 }
2127
2128 #[test]
2129 fn strict_unescapes_inline_underscores_legacy_keeps_them() {
2130 let mut doc = DoclingDocument::new("t");
2131 doc.add_heading(1, "a\\_b");
2132 doc.add_paragraph("x\\_y");
2133 doc.push(Node::ListItem {
2134 ordered: false,
2135 number: 1,
2136 first_in_list: true,
2137 text: "i\\_j".into(),
2138 level: 0,
2139 marker: None,
2140 location: None,
2141 dclx: None,
2142 href: None,
2143 layer: None,
2144 });
2145 assert_eq!(doc.export_to_markdown(), "# a\\_b\n\nx\\_y\n\n- i\\_j\n");
2147 assert_eq!(doc.export_to_markdown_with(true), "# a_b\n\nx_y\n\n- i_j\n");
2149 }
2150
2151 fn assert_stream_matches(
2154 doc: &DoclingDocument,
2155 strict: bool,
2156 images: ImageMode,
2157 splits: &[usize],
2158 ) {
2159 let (want, want_artifacts) = to_markdown_images(doc, strict, images, "artifacts");
2160 let mut streamer =
2161 MarkdownStreamer::with_artifacts(strict, images, doc.compact_tables, "artifacts")
2162 .with_page_break_placeholder(doc.page_break_placeholder.clone());
2163 let mut got = String::new();
2164 let mut got_artifacts = Vec::new();
2165 let mut start = 0;
2166 for &end in splits {
2167 let links = if start == 0 {
2170 doc.links.as_slice()
2171 } else {
2172 &[]
2173 };
2174 got.push_str(&streamer.push(&doc.nodes[start..end], links));
2175 got_artifacts.extend(streamer.take_artifacts());
2178 start = end;
2179 }
2180 got.push_str(&streamer.push(
2181 &doc.nodes[start..],
2182 if start == 0 {
2183 doc.links.as_slice()
2184 } else {
2185 &[]
2186 },
2187 ));
2188 got_artifacts.extend(streamer.take_artifacts());
2189 got.push_str(&streamer.finish());
2190 assert_eq!(
2191 got, want,
2192 "streamed output diverged (splits={splits:?}, strict={strict})"
2193 );
2194 assert_eq!(
2195 got_artifacts, want_artifacts,
2196 "streamed artifacts diverged (splits={splits:?}, strict={strict})"
2197 );
2198 }
2199
2200 #[test]
2201 fn streaming_is_byte_identical_to_buffered() {
2202 let mut doc = DoclingDocument::new("d");
2203 doc.add_heading(1, "Title");
2204 doc.add_paragraph("First paragraph.");
2205 doc.push(Node::ListItem {
2206 ordered: false,
2207 number: 1,
2208 first_in_list: true,
2209 text: "a".into(),
2210 level: 0,
2211 marker: None,
2212 location: None,
2213 dclx: None,
2214 href: None,
2215 layer: None,
2216 });
2217 doc.push(Node::ListItem {
2218 ordered: false,
2219 number: 2,
2220 first_in_list: false,
2221 text: "b".into(),
2222 level: 0,
2223 marker: None,
2224 location: None,
2225 dclx: None,
2226 href: None,
2227 layer: None,
2228 });
2229 doc.push(Node::Code {
2230 language: Some("rust".into()),
2231 text: "let x = 1;".into(),
2232 orig: None,
2233 pretty: None,
2234 });
2235 doc.push(Node::Table(Table {
2236 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
2237 location: None,
2238 structure: None,
2239 cell_blocks: None,
2240 cells: None,
2241 caption: None,
2242 caption_parent: Default::default(),
2243 caption_location: None,
2244 }));
2245 doc.push(Node::Picture {
2246 caption: Some("Fig 1".into()),
2247 caption_href: None,
2248 image: Some(PictureImage {
2249 dpi: PictureImage::DEFAULT_DPI,
2250 mimetype: "image/png".into(),
2251 width: 2,
2252 height: 2,
2253 data: b"png-one".to_vec(),
2254 }),
2255 classification: None,
2256 description: None,
2257 caption_parent: Default::default(),
2258 caption_location: None,
2259 });
2260 doc.add_paragraph("Last paragraph.");
2261 doc.push(Node::Picture {
2264 caption: None,
2265 caption_href: None,
2266 image: Some(PictureImage {
2267 dpi: PictureImage::DEFAULT_DPI,
2268 mimetype: "image/png".into(),
2269 width: 2,
2270 height: 2,
2271 data: b"png-two".to_vec(),
2272 }),
2273 classification: None,
2274 description: None,
2275 caption_parent: Default::default(),
2276 caption_location: None,
2277 });
2278
2279 for &strict in &[false, true] {
2282 for &images in &[
2283 ImageMode::Placeholder,
2284 ImageMode::Embedded,
2285 ImageMode::Referenced,
2286 ] {
2287 for splits in [&[][..], &[1][..], &[2][..], &[4][..], &[1, 4, 6, 7][..]] {
2288 assert_stream_matches(&doc, strict, images, splits);
2289 }
2290 }
2291 }
2292 }
2293
2294 #[test]
2295 fn streaming_applies_recovered_links_in_strict_mode() {
2296 let mut doc = DoclingDocument::new("d");
2297 doc.add_paragraph("See LinkedIn for details.");
2298 doc.add_paragraph("And GitHub too.");
2299 doc.links = vec![
2300 ("LinkedIn".into(), "https://lnkd/".into()),
2301 ("GitHub".into(), "https://gh/".into()),
2302 ];
2303 assert_stream_matches(&doc, true, ImageMode::Placeholder, &[1]);
2306 }
2307
2308 fn paged_doc() -> DoclingDocument {
2311 let mut doc = DoclingDocument::new("p");
2312 doc.push(Node::PageInfo {
2313 page_no: 1,
2314 width: 100.0,
2315 height: 100.0,
2316 });
2317 doc.add_heading(1, "Title");
2318 doc.add_paragraph("Page one.");
2319 doc.push(Node::PageBreak);
2321 doc.push(Node::PageInfo {
2322 page_no: 2,
2323 width: 100.0,
2324 height: 100.0,
2325 });
2326 doc.push(Node::PageFurniture {
2327 footer: true,
2328 location: [0, 500, 511, 511],
2329 text: "2".into(),
2330 });
2331 doc.push(Node::PageBreak);
2332 doc.push(Node::PageInfo {
2333 page_no: 3,
2334 width: 100.0,
2335 height: 100.0,
2336 });
2337 doc.add_paragraph("Page three.");
2338 doc.push(Node::PageBreak);
2340 doc
2341 }
2342
2343 #[test]
2344 fn page_break_placeholder_lands_between_pages_only() {
2345 let mut doc = paged_doc();
2346 assert_eq!(
2348 doc.export_to_markdown(),
2349 "# Title\n\nPage one.\n\nPage three.\n"
2350 );
2351 doc.page_break_placeholder = Some("<!-- page break -->".into());
2352 assert_eq!(
2356 doc.export_to_markdown(),
2357 "# Title\n\nPage one.\n\n<!-- page break -->\n\nPage three.\n"
2358 );
2359 doc.page_break_placeholder = Some(String::new());
2362 assert_eq!(
2363 doc.export_to_markdown(),
2364 "# Title\n\nPage one.\n\n\n\nPage three.\n"
2365 );
2366 }
2367
2368 #[test]
2369 fn page_break_placeholder_never_leads_a_single_page() {
2370 let mut doc = DoclingDocument::new("one");
2371 doc.page_break_placeholder = Some("---".into());
2372 doc.push(Node::PageBreak);
2373 doc.push(Node::PageInfo {
2374 page_no: 1,
2375 width: 10.0,
2376 height: 10.0,
2377 });
2378 doc.add_paragraph("Only page.");
2379 assert_eq!(doc.export_to_markdown(), "Only page.\n");
2380 doc.push(Node::PageBreak);
2382 doc.push(Node::PageBreak);
2383 doc.add_paragraph("Next.");
2384 assert_eq!(doc.export_to_markdown(), "Only page.\n\n---\n\nNext.\n");
2385 }
2386
2387 #[test]
2388 fn page_break_placeholder_streams_byte_identical() {
2389 let mut doc = paged_doc();
2390 doc.page_break_placeholder = Some("<!-- page break -->".into());
2391 for splits in [
2395 &[3usize][..],
2396 &[3, 6],
2397 &[3, 6, 8],
2398 &[1, 2, 3, 4, 5, 6, 7, 8, 9],
2399 &[8],
2400 ] {
2401 assert_stream_matches(&doc, false, ImageMode::Placeholder, splits);
2402 assert_stream_matches(&doc, true, ImageMode::Placeholder, splits);
2403 }
2404 }
2405
2406 #[test]
2407 fn strict_tightens_punctuation_spacing_legacy_keeps_it() {
2408 let mut doc = DoclingDocument::new("t");
2409 doc.add_paragraph("see [ 37 , 36 ] and ( x ) .");
2410 assert_eq!(doc.export_to_markdown(), "see [ 37 , 36 ] and ( x ) .\n");
2412 assert_eq!(doc.export_to_markdown_with(true), "see [37, 36] and (x).\n");
2414 }
2415
2416 fn options_doc() -> DoclingDocument {
2421 use crate::document::ContentLayer;
2422 let mut doc = DoclingDocument::new("opts");
2423 doc.push(Node::PageFurniture {
2424 footer: false,
2425 location: [0, 0, 0, 0],
2426 text: "FAX COVER \\_ R&D".into(),
2427 });
2428 doc.add_heading(1, "R&D \\_ report");
2429 doc.add_paragraph("Body a\\_b <tag>");
2430 doc.push(Node::Picture {
2431 caption: Some("Figure 1".into()),
2432 caption_href: None,
2433 image: None,
2434 classification: None,
2435 description: None,
2436 caption_parent: Default::default(),
2437 caption_location: None,
2438 });
2439 doc.push(Node::PictureChildren(vec![
2440 Node::Paragraph {
2441 text: "Field: Name".into(),
2442 },
2443 Node::Paragraph {
2444 text: "Field: Date".into(),
2445 },
2446 ]));
2447 doc.push(Node::CommentSection {
2448 name: "comment-1".into(),
2449 text: "[author: A]: note".into(),
2450 refs_note_text: false,
2451 grouped: true,
2452 });
2453 doc.push(Node::Group {
2454 label: "section".into(),
2455 name: Some("sheet: Hidden".into()),
2456 layer: Some(ContentLayer::Invisible),
2457 children: vec![Node::Paragraph {
2458 text: "hidden cell".into(),
2459 }],
2460 });
2461 doc.push(Node::Furniture {
2462 layer: ContentLayer::Furniture,
2463 inner: Box::new(Node::Paragraph {
2464 text: "Page 1 of 2".into(),
2465 }),
2466 });
2467 doc.push(Node::FurnitureText {
2468 label: "page_footer".into(),
2469 text: "footer line".into(),
2470 });
2471 doc
2472 }
2473
2474 #[test]
2478 fn default_options_are_the_default_export() {
2479 let doc = options_doc();
2480 let plain = doc.export_to_markdown();
2481 assert_eq!(
2482 plain,
2483 "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n"
2484 );
2485 let (with_default, artifacts) =
2486 doc.export_to_markdown_with_options(&MarkdownExportOptions::default());
2487 assert_eq!(with_default, plain);
2488 assert!(artifacts.is_empty());
2489 }
2490
2491 #[test]
2492 fn layers_render_furniture_notes_and_hidden_sheets() {
2493 use crate::document::ContentLayer;
2494 let doc = options_doc();
2495 let md = |layers: ContentLayers| {
2496 doc.export_to_markdown_with_options(&MarkdownExportOptions {
2497 layers,
2498 ..MarkdownExportOptions::default()
2499 })
2500 .0
2501 };
2502 assert_eq!(
2503 md(ContentLayers::BODY.with(ContentLayer::Furniture)),
2504 "FAX COVER \\_ R&D\n\n# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n\nPage 1 of 2\n\nfooter line\n",
2505 "a page header, a furniture-wrapped paragraph and a furniture text item render as paragraphs"
2506 );
2507 assert_eq!(
2508 md(ContentLayers::BODY.with(ContentLayer::Notes)),
2509 "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n\n[author: A]: note\n"
2510 );
2511 assert_eq!(
2512 md(ContentLayers::BODY.with(ContentLayer::Invisible)),
2513 "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n\nhidden cell\n",
2514 "a hidden sheet's items sit on the sheet's layer"
2515 );
2516 assert_eq!(
2517 md(ContentLayers::NONE.with(ContentLayer::Furniture)),
2518 "FAX COVER \\_ R&D\n\nPage 1 of 2\n\nfooter line\n",
2519 "without the body layer only the furniture prints"
2520 );
2521 assert_eq!(md(ContentLayers::NONE), "");
2522 assert_eq!(
2523 md(ContentLayers::ALL),
2524 "FAX COVER \\_ R&D\n\n# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n\n[author: A]: note\n\nhidden cell\n\nPage 1 of 2\n\nfooter line\n"
2525 );
2526 }
2527
2528 #[test]
2531 fn layers_apply_to_list_items() {
2532 use crate::document::ContentLayer;
2533 let mut doc = DoclingDocument::new("lists");
2534 doc.push(Node::ListItem {
2535 ordered: false,
2536 number: 1,
2537 first_in_list: true,
2538 text: "nav link".into(),
2539 level: 0,
2540 marker: None,
2541 location: None,
2542 dclx: None,
2543 href: None,
2544 layer: Some(ContentLayer::Furniture),
2545 });
2546 doc.add_paragraph("body");
2547 assert_eq!(doc.export_to_markdown(), "body\n");
2548 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2549 layers: ContentLayers::BODY.with(ContentLayer::Furniture),
2550 ..MarkdownExportOptions::default()
2551 });
2552 assert_eq!(md, "- nav link\n\nbody\n");
2553 }
2554
2555 #[test]
2556 fn traverse_pictures_prints_the_nested_text_after_the_picture() {
2557 let doc = options_doc();
2558 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2559 traverse_pictures: true,
2560 ..MarkdownExportOptions::default()
2561 });
2562 assert_eq!(
2563 md,
2564 "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n\nField: Name\n\nField: Date\n"
2565 );
2566 }
2567
2568 #[test]
2569 fn escaping_can_be_turned_off_per_kind() {
2570 let doc = options_doc();
2571 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2572 escape_html: false,
2573 ..MarkdownExportOptions::default()
2574 });
2575 assert_eq!(
2576 md,
2577 "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n"
2578 );
2579 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2580 escape_underscores: false,
2581 ..MarkdownExportOptions::default()
2582 });
2583 assert_eq!(
2584 md,
2585 "# R&D _ report\n\nBody a_b <tag>\n\nFigure 1\n\n<!-- image -->\n"
2586 );
2587 let mut doc = DoclingDocument::new("code");
2590 doc.push(Node::Code {
2591 language: None,
2592 text: "a & b \\_ c".into(),
2593 orig: None,
2594 pretty: None,
2595 });
2596 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2597 escape_html: false,
2598 escape_underscores: false,
2599 ..MarkdownExportOptions::default()
2600 });
2601 assert_eq!(md, "```\na & b \\_ c\n```\n");
2602 }
2603
2604 #[test]
2605 fn image_placeholder_is_configurable() {
2606 let doc = options_doc();
2607 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2608 image_placeholder: "[figure]".into(),
2609 ..MarkdownExportOptions::default()
2610 });
2611 assert!(md.contains("Figure 1\n\n[figure]\n"), "{md}");
2612 assert!(!md.contains("<!-- image -->"));
2613 }
2614
2615 #[test]
2621 fn empty_image_placeholder_prints_nothing() {
2622 fn picture(caption: Option<&str>) -> Node {
2623 Node::Picture {
2624 caption: caption.map(Into::into),
2625 caption_href: None,
2626 image: None,
2627 classification: None,
2628 description: None,
2629 caption_parent: Default::default(),
2630 caption_location: None,
2631 }
2632 }
2633 fn page(no: usize) -> Node {
2634 Node::PageInfo {
2635 page_no: no,
2636 width: 100.0,
2637 height: 100.0,
2638 }
2639 }
2640 fn para(text: &str) -> Node {
2641 Node::Paragraph { text: text.into() }
2642 }
2643 let options = MarkdownExportOptions {
2644 image_placeholder: String::new(),
2645 ..MarkdownExportOptions::default()
2646 };
2647 let cases: Vec<(Vec<Node>, Option<&str>, &str)> = vec![
2649 (
2650 vec![page(1), para("a"), picture(None), para("b")],
2651 None,
2652 "a\n\nb\n",
2653 ),
2654 (
2655 vec![page(1), para("a"), picture(Some("Figure 1")), para("b")],
2656 None,
2657 "a\n\nFigure 1\n\nb\n",
2658 ),
2659 (
2660 vec![
2661 page(1),
2662 para("a"),
2663 page(2),
2664 picture(None),
2665 page(3),
2666 para("b"),
2667 ],
2668 Some("<!-- pb -->"),
2669 "a\n\n<!-- pb -->\n\n<!-- pb -->\n\nb\n",
2670 ),
2671 (
2672 vec![
2673 page(1),
2674 para("a"),
2675 page(2),
2676 picture(None),
2677 page(3),
2678 para("b"),
2679 ],
2680 Some(""),
2681 "a\n\n\n\n\n\nb\n",
2682 ),
2683 (
2684 vec![page(1), picture(None), page(2), para("b")],
2685 Some("<!-- pb -->"),
2686 "<!-- pb -->\n\nb\n",
2687 ),
2688 (
2689 vec![page(1), picture(None), page(2), para("b")],
2690 Some(""),
2691 "\n\nb\n",
2692 ),
2693 (
2694 vec![page(1), para("a"), page(2), picture(None)],
2695 Some("<!-- pb -->"),
2696 "a\n\n<!-- pb -->\n",
2697 ),
2698 ];
2699 for (nodes, placeholder, expected) in cases {
2700 let mut doc = DoclingDocument::new("t");
2701 doc.page_break_placeholder = placeholder.map(Into::into);
2702 for node in nodes {
2703 doc.push(node);
2704 }
2705 let (md, _) = doc.export_to_markdown_with_options(&options);
2706 assert_eq!(md, expected, "page break {placeholder:?}");
2707 for size in 1..=doc.nodes.len() {
2710 let mut streamer = MarkdownStreamer::new(false, ImageMode::Placeholder, false)
2711 .with_export_options(&options)
2712 .with_page_break_placeholder(placeholder.map(Into::into));
2713 let mut out = String::new();
2714 for chunk in doc.nodes.chunks(size) {
2715 out.push_str(&streamer.push(chunk, &[]));
2716 }
2717 out.push_str(&streamer.finish());
2718 assert_eq!(
2719 out, expected,
2720 "chunks of {size}, page break {placeholder:?}"
2721 );
2722 }
2723 }
2724 let mut doc = DoclingDocument::new("t");
2726 doc.push(para("a"));
2727 doc.push(picture(None));
2728 doc.push(para("b"));
2729 assert_eq!(doc.export_to_markdown(), "a\n\n<!-- image -->\n\nb\n");
2730 }
2731
2732 #[test]
2735 fn streamer_matches_buffered_export_with_options() {
2736 let doc = options_doc();
2737 let options = MarkdownExportOptions {
2738 layers: ContentLayers::ALL,
2739 traverse_pictures: true,
2740 escape_html: false,
2741 escape_underscores: false,
2742 image_placeholder: "(img)".into(),
2743 ..MarkdownExportOptions::default()
2744 };
2745 let (buffered, _) = doc.export_to_markdown_with_options(&options);
2746 let mut streamer = MarkdownStreamer::new(false, ImageMode::Placeholder, false)
2747 .with_export_options(&options);
2748 let mut out = String::new();
2749 for chunk in doc.nodes.chunks(2) {
2750 out.push_str(&streamer.push(chunk, &[]));
2751 }
2752 out.push_str(&streamer.finish());
2753 assert_eq!(out, buffered);
2754 assert!(
2755 buffered.contains("(img)") && buffered.contains("R&D _ report"),
2756 "{buffered}"
2757 );
2758 }
2759
2760 #[test]
2763 fn plain_text_drops_the_markdown_decoration() {
2764 let item = |text: &str, ordered: bool, number: u64, level: u8| Node::ListItem {
2765 ordered,
2766 number,
2767 first_in_list: number == 1 && level == 0,
2768 text: text.into(),
2769 level,
2770 marker: None,
2771 location: None,
2772 dclx: None,
2773 href: None,
2774 layer: None,
2775 };
2776 let mut doc = DoclingDocument::new("plain");
2777 doc.add_heading(1, "Title with **bold**");
2778 doc.add_heading(2, "Section");
2779 doc.add_paragraph("Some **bold**, *italic*, ~~gone~~ and `code` with a [link](https://x.org).\nNext line.");
2780 doc.push(item("*one*", false, 1, 0));
2781 doc.push(item("[two](https://y.org)", false, 2, 0));
2782 doc.push(item("nested", true, 1, 1));
2783 doc.push(Node::CheckboxItem {
2784 checked: true,
2785 text: "done".into(),
2786 });
2787 doc.push(Node::Code {
2788 language: Some("rust".into()),
2789 text: "let x = **y**;".into(),
2790 orig: None,
2791 pretty: None,
2792 });
2793 doc.push(Node::Picture {
2794 caption: Some("Figure *1*".into()),
2795 caption_href: None,
2796 image: None,
2797 classification: None,
2798 description: None,
2799 caption_parent: Default::default(),
2800 caption_location: None,
2801 });
2802 doc.push(Node::Caption {
2803 text: "Linked caption".into(),
2804 href: Some("https://z.org".into()),
2805 });
2806 doc.push(Node::Table(Table {
2807 rows: vec![
2808 vec!["**n**".into(), "rich".into()],
2809 vec!["**2**".into(), "a \nb".into()],
2810 ],
2811 ..Default::default()
2812 }));
2813 doc.add_paragraph("R&D \\_ x");
2814 let text = doc.export_to_text();
2815 assert_eq!(
2816 text,
2817 "Title with bold\n\n\
2818 Section\n\n\
2819 Some bold, italic, gone and code with a link.\nNext line.\n\n\
2820 - one\n- two\n 1. nested\n\n\
2821 - [x] done\n\n\
2822 let x = **y**;\n\n\
2823 Figure 1\n\n\
2824 Linked caption\n\n\
2825 | n | rich |\n\
2826 |-----|--------|\n\
2827 | 2 | a b |\n\n\
2828 R&D _ x"
2829 );
2830
2831 let options = MarkdownExportOptions::plain_text();
2832 let (buffered, _) = doc.export_to_markdown_with_options(&options);
2833 assert_eq!(buffered, format!("{text}\n"));
2834 let mut streamer = MarkdownStreamer::new(false, ImageMode::Placeholder, false)
2835 .with_export_options(&options);
2836 let mut out = String::new();
2837 for chunk in doc.nodes.chunks(3) {
2838 out.push_str(&streamer.push(chunk, &[]));
2839 }
2840 out.push_str(&streamer.finish());
2841 assert_eq!(out, buffered);
2842 }
2843
2844 #[test]
2846 fn plain_inline_keeps_literal_markers() {
2847 for (input, want) in [
2848 ("**bold** and *it* and ***both***", "bold and it and both"),
2849 ("**[label](https://a.b/c_(d))** end", "label end"),
2850 (
2851 "grant *USE and *OBJMGT authority",
2852 "grant *USE and *OBJMGT authority",
2853 ),
2854 ("2 * 3 * 4", "2 * 3 * 4"),
2855 ("a ** b", "a ** b"),
2856 ("the `quoted’ and `x` term", "the `quoted’ and x term"),
2857 ("see [12] and [docs](u)", "see [12] and docs"),
2858 ("formula $[a](b)$ stays", "formula $[a](b)$ stays"),
2859 ("price $5 and **bold**", "price $5 and bold"),
2860 ("[outer [inner] text](u)", "outer [inner] text"),
2861 ("unclosed **bold", "unclosed **bold"),
2862 ] {
2863 assert_eq!(plain_inline(input), want, "{input}");
2864 }
2865 }
2866}