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 {
731 if !text.contains('\n') {
732 return text.to_string();
733 }
734 text.split("\n\n")
735 .map(|para| para.replace('\n', " \n"))
736 .collect::<Vec<_>>()
737 .join("\n\n")
738}
739
740pub(crate) fn strip_hard_breaks(text: &str) -> String {
745 if text.contains(" \n") {
746 text.replace(" \n", "\n")
747 } else {
748 text.to_string()
749 }
750}
751
752fn heading_line_breaks(text: &str) -> String {
756 text.replace('\n', " ")
757}
758
759fn render(nodes: &[Node], blocks: &mut Vec<String>, ctx: &mut Ctx) {
760 let mut i = 0;
761 while i < nodes.len() {
762 let before = blocks.len();
763 match &nodes[i] {
764 Node::PageBreak | Node::PageInfo { .. } => {
774 if ctx.page_break.is_some() && ctx.emitted_any {
775 ctx.pending_page_break = true;
776 }
777 i += 1;
778 }
779 Node::ListItem { .. } => {
780 let start = i;
781 i += 1;
782 loop {
783 match nodes.get(i) {
784 Some(Node::ListItem { .. }) => i += 1,
785 Some(Node::Paragraph { text })
789 if text.is_empty()
790 && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
791 {
792 i += 1
793 }
794 _ => break,
795 }
796 }
797 render_list_run(&nodes[start..i], blocks, ctx);
798 }
799 other => {
800 render_one(other, blocks, ctx);
801 i += 1;
802 }
803 }
804 if blocks.len() > before {
805 let kept: Vec<String> = blocks.drain(before..).filter(|b| !b.is_empty()).collect();
815 blocks.extend(kept);
816 if ctx.pending_page_break {
817 if let Some(placeholder) = &ctx.page_break {
822 blocks.insert(before, placeholder.clone());
823 }
824 ctx.pending_page_break = false;
825 }
826 ctx.emitted_any = true;
827 }
828 }
829}
830
831fn render_list_run(items: &[Node], blocks: &mut Vec<String>, ctx: &Ctx) {
837 let mut lines: Vec<String> = Vec::new();
838 let mut any_top = false;
841
842 for item in items {
843 let Node::ListItem {
844 ordered,
845 number,
846 first_in_list,
847 text,
848 level,
849 marker: orig_marker,
850 location: _,
851 dclx: _,
852 href: _,
853 layer,
854 } = item
855 else {
856 continue;
857 };
858 if !ctx.layers.contains(layer.or(ctx.current_layer)) {
862 continue;
863 }
864 let level = *level as usize;
865
866 if level == 0 {
875 if any_top && *first_in_list {
876 lines.push(String::new());
877 }
878 any_top = true;
879 }
880
881 let indent = " ".repeat(level);
882 let verbatim = orig_marker.as_deref().filter(|m| {
887 m.strip_suffix('.')
888 .is_some_and(|d| !d.is_empty() && d.chars().all(char::is_numeric))
889 });
890 let marker = match verbatim {
891 Some(m) if *ordered => m.to_string(),
892 _ if *ordered => format!("{number}."),
893 _ => "-".to_string(),
894 };
895 lines.push(format!("{indent}{marker} {}", list_item_text(text, ctx)));
896 }
897
898 if !lines.is_empty() {
901 blocks.push(lines.join("\n"));
902 }
903}
904
905fn list_item_text(text: &str, ctx: &Ctx) -> String {
913 let escaped = ctx.text(text);
914 if ctx.plain {
915 return escaped;
916 }
917 if let Some((own, tail)) = escaped.split_once('\n') {
918 if is_folded_child_tail(tail) {
919 return format!("{}\n{tail}", md_line_breaks(own));
920 }
921 }
922 md_line_breaks(&escaped)
923}
924
925fn is_folded_child_tail(tail: &str) -> bool {
932 const MARKER: &str = "<!-- image -->";
933 const FENCE: &str = "```";
934 let mut lines = tail.split('\n').peekable();
935 let mut any = false;
936 while let Some(line) = lines.next() {
937 let line = line.trim_start();
938 if line == MARKER {
939 any = true;
940 } else if line == FENCE {
941 loop {
943 match lines.next() {
944 Some(l) if l.trim_start() == FENCE => break,
945 Some(_) => {}
946 None => return false,
947 }
948 }
949 any = true;
950 } else if lines.next().map(str::trim_start) == Some(MARKER) {
951 any = true; } else {
953 return false;
954 }
955 }
956 any
957}
958
959fn render_one(node: &Node, blocks: &mut Vec<String>, ctx: &mut Ctx) {
964 match node {
965 Node::Group { .. }
967 | Node::Furniture { .. }
968 | Node::PageFurniture { .. }
969 | Node::FurnitureText { .. }
970 | Node::CommentSection { .. }
971 | Node::PictureChildren(_)
972 | Node::Commented { .. }
973 | Node::Located { .. }
974 | Node::Prov { .. }
975 | Node::Track { .. }
976 | Node::PageBreak
977 | Node::PageInfo { .. }
978 | Node::DoclangOnly(_) => {}
979 _ if !ctx.layer_visible() => return,
980 _ => {}
981 }
982 render_item(node, blocks, ctx)
983}
984
985fn render_item(node: &Node, blocks: &mut Vec<String>, ctx: &mut Ctx) {
986 match node {
987 Node::Heading { level, text } => {
988 if ctx.plain {
989 blocks.push(ctx.text(text));
992 return;
993 }
994 let text = heading_line_breaks(&ctx.text(text));
995 if ctx.in_table_cell {
996 blocks.push(text);
998 } else {
999 let hashes = "#".repeat((*level).clamp(1, 6) as usize);
1000 blocks.push(format!("{hashes} {text}"));
1001 }
1002 }
1003 Node::Paragraph { text } if text.is_empty() => {}
1006 Node::Paragraph { text } => blocks.push(ctx.breaks(&ctx.text(text))),
1007 Node::LabeledText { .. } => render_item(&node.labeled_as_paragraph(), blocks, ctx),
1008 Node::Caption { text, .. } if text.is_empty() => {}
1011 Node::Caption { text, href } => {
1012 let body = ctx.breaks(&ctx.text(text));
1013 blocks.push(match href {
1014 Some(url) if !ctx.plain => format!("[{body}]({url})"),
1015 _ => body,
1016 });
1017 }
1018 Node::CheckboxItem { checked, text } => {
1019 let mark = if *checked { "- [x] " } else { "- [ ] " };
1020 blocks.push(ctx.breaks(&ctx.text(&format!("{mark}{text}"))));
1021 }
1022 Node::Code {
1023 language,
1024 text,
1025 pretty,
1026 ..
1027 } => {
1028 let lang = match language {
1030 Some(l) if ctx.strict => l.as_str(),
1031 _ => "",
1032 };
1033 let body = match pretty {
1036 Some(p) if ctx.strict => p.as_str(),
1037 _ => text.as_str(),
1038 };
1039 blocks.push(if ctx.plain {
1042 body.to_string()
1043 } else {
1044 format!("```{lang}\n{body}\n```")
1045 });
1046 }
1047 Node::Formula { latex, .. } => blocks.push(format!("$${latex}$$")),
1050 Node::Table(table) => {
1051 if let Some(cap) = &table.caption {
1054 if !cap.is_empty() {
1055 blocks.push(ctx.breaks(&ctx.text(cap)));
1056 }
1057 }
1058 let rendered = if ctx.plain {
1059 render_table(&ctx.plain_table(table), ctx.compact_tables)
1060 } else {
1061 render_table(table, ctx.compact_tables)
1062 };
1063 if !rendered.is_empty() {
1064 blocks.push(rendered);
1065 }
1066 }
1067 Node::Picture {
1076 caption,
1077 image,
1078 description,
1079 ..
1080 } => {
1081 if let Some(cap) = caption {
1082 if !cap.is_empty() {
1083 blocks.push(ctx.breaks(&ctx.caption(cap)));
1084 }
1085 }
1086 let alt = description
1087 .as_ref()
1088 .filter(|d| d.is_alt_text() && ctx.alt_text && !d.text.is_empty());
1089 let marker = picture_marker(image.as_ref(), ctx, alt.map(|d| d.text.as_str()));
1090 if let Some(desc) = description {
1091 let shown = !desc.is_alt_text() || (ctx.alt_text && !marker.starts_with("!["));
1092 if !desc.text.is_empty() && shown {
1093 blocks.push(ctx.breaks(&ctx.text(&desc.text)));
1094 }
1095 }
1096 blocks.push(marker);
1097 }
1098 Node::Chart {
1102 kind,
1103 table,
1104 caption,
1105 ..
1106 } => {
1107 if let Some(cap) = caption {
1108 if !cap.is_empty() {
1109 blocks.push(ctx.breaks(&ctx.caption(cap)));
1110 }
1111 }
1112 blocks.push(picture_marker(None, ctx, None));
1113 blocks.push(humanize_label(kind));
1114 let rendered = if ctx.plain {
1115 render_table(&ctx.plain_table(table), false)
1116 } else {
1117 render_table(table, false)
1118 };
1119 if !rendered.is_empty() {
1120 blocks.push(rendered);
1121 }
1122 }
1123 Node::DoclangOnly(_) => {}
1125 Node::Group {
1130 layer: Some(layer),
1131 children,
1132 ..
1133 } => {
1134 let outer = ctx.current_layer.replace(*layer);
1135 render(children, blocks, ctx);
1136 ctx.current_layer = outer;
1137 }
1138 Node::Group { children, .. } => render(children, blocks, ctx),
1139 Node::FieldRegion { items } => {
1140 for item in items {
1145 for part in [&item.marker, &item.key, &item.value].into_iter().flatten() {
1146 blocks.push(ctx.breaks(&ctx.text(part)));
1147 }
1148 }
1149 }
1150 Node::KeyValueGraph { .. } => blocks.push(MISSING_KEY_VALUE_ITEM.to_string()),
1153 Node::InlineGroup { md_text, .. } => blocks.push(ctx.breaks(&ctx.text(md_text))),
1156 Node::TextDump(text) => {
1158 if !text.is_empty() {
1159 blocks.push(text.clone());
1160 }
1161 }
1162 Node::Furniture { layer, inner } => {
1166 let outer = ctx.current_layer.replace(*layer);
1167 render_one(inner, blocks, ctx);
1168 ctx.current_layer = outer;
1169 }
1170 Node::PageFurniture { text, .. } | Node::FurnitureText { text, .. } => {
1174 if ctx.layers.furniture && !text.is_empty() {
1175 blocks.push(ctx.breaks(&ctx.text(text)));
1176 }
1177 }
1178 Node::PictureChildren(children) => {
1183 if ctx.traverse_pictures {
1184 render(children, blocks, ctx);
1185 }
1186 }
1187 Node::CommentSection { text, .. } => {
1192 if ctx.layers.notes && !text.is_empty() {
1193 blocks.push(ctx.breaks(&ctx.text(text)));
1194 }
1195 }
1196 Node::Commented { inner, .. } => render_one(inner, blocks, ctx),
1197 Node::Located { inner, .. } | Node::Prov { inner, .. } | Node::Track { inner, .. } => {
1199 render_one(inner, blocks, ctx)
1200 }
1201 Node::PageBreak => {}
1203 Node::PageInfo { .. } => {}
1205 Node::ListItem { .. } => render_list_run(std::slice::from_ref(node), blocks, ctx),
1210 }
1211}
1212
1213fn humanize_label(label: &str) -> String {
1218 let text = label.replace('_', " ");
1219 let mut chars = text.chars();
1220 match chars.next() {
1221 Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
1222 None => text,
1223 }
1224}
1225
1226fn image_alt(alt: Option<&str>) -> String {
1229 match alt {
1230 Some(text) => text
1231 .split_whitespace()
1232 .collect::<Vec<_>>()
1233 .join(" ")
1234 .replace('\\', "\\\\")
1235 .replace(']', "\\]"),
1236 None => "Image".to_string(),
1237 }
1238}
1239
1240fn picture_marker(image: Option<&crate::PictureImage>, ctx: &mut Ctx, alt: Option<&str>) -> String {
1241 match (ctx.images, image) {
1242 (ImageMode::Embedded, Some(img)) => {
1244 format!(
1245 "",
1246 image_alt(alt),
1247 crate::pixel_digest::docling_data_uri(img).1
1248 )
1249 }
1250 (ImageMode::Referenced, Some(img)) => {
1251 let path = format!(
1252 "{}/image_{:06}.{}",
1253 ctx.artifacts_dir,
1254 ctx.pic_index,
1255 ext_for(&img.mimetype)
1256 );
1257 ctx.pic_index += 1;
1258 ctx.artifacts.push((path.clone(), img.data.clone()));
1259 format!("", image_alt(alt), escape_uri_path(&path))
1260 }
1261 _ => ctx.image_placeholder.clone(),
1263 }
1264}
1265
1266pub(crate) fn escape_uri_path(value: &str) -> String {
1279 const KEEP: &str = "/%:@+,;=~$!&'*";
1280 let s = value.replace('\\', "/");
1281 if let Some(rest) = s.strip_prefix("//") {
1282 let rest = rest.trim_start_matches('/');
1284 let (host, tail) = rest.split_once('/').unwrap_or((rest, ""));
1285 return format!("file://{host}{}", percent_quote(&format!("/{tail}"), KEEP));
1286 }
1287 let bytes = s.as_bytes();
1288 if bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && bytes[2] == b'/' {
1289 return format!("file:///{}", percent_quote(&s, KEEP));
1291 }
1292 if let Some((scheme, rest)) = s.split_once(':') {
1296 let valid_scheme = scheme.len() > 1
1297 && scheme.as_bytes()[0].is_ascii_alphabetic()
1298 && scheme
1299 .bytes()
1300 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'));
1301 if valid_scheme {
1302 let (authority, rest) = match rest.strip_prefix("//") {
1303 Some(r) => {
1304 let end = r.find(['/', '?', '#']).unwrap_or(r.len());
1305 (Some(&r[..end]), &r[end..])
1306 }
1307 None => (None, rest),
1308 };
1309 let (before_frag, fragment) = rest.split_once('#').unwrap_or((rest, ""));
1310 let (path, query) = before_frag.split_once('?').unwrap_or((before_frag, ""));
1311 let mut out = format!("{scheme}:");
1312 if let Some(a) = authority {
1313 out.push_str("//");
1314 out.push_str(a);
1315 }
1316 out.push_str(&percent_quote(path, KEEP));
1317 if !query.is_empty() {
1318 out.push('?');
1319 out.push_str(&percent_quote(query, KEEP));
1320 }
1321 if !fragment.is_empty() {
1322 out.push('#');
1323 out.push_str(&percent_quote(fragment, KEEP));
1324 }
1325 return out;
1326 }
1327 }
1328 percent_quote(&s, KEEP)
1330}
1331
1332fn percent_quote(s: &str, safe: &str) -> String {
1335 let mut out = String::with_capacity(s.len());
1336 for &b in s.as_bytes() {
1337 let keep = b.is_ascii_alphanumeric()
1338 || matches!(b, b'_' | b'.' | b'-' | b'~')
1339 || (b.is_ascii() && safe.contains(b as char));
1340 if keep {
1341 out.push(b as char);
1342 } else {
1343 out.push_str(&format!("%{b:02X}"));
1344 }
1345 }
1346 out
1347}
1348
1349pub(crate) fn ext_for(mimetype: &str) -> &str {
1350 match mimetype {
1351 "image/jpeg" => "jpg",
1352 "image/gif" => "gif",
1353 "image/webp" => "webp",
1354 "image/bmp" => "bmp",
1355 "image/tiff" => "tif",
1356 _ => "png",
1357 }
1358}
1359
1360fn is_number_cell(t: &str) -> bool {
1379 t.parse::<f64>().is_ok() || is_thousands_number(t)
1380}
1381
1382fn is_thousands_number(t: &str) -> bool {
1388 let b = t.as_bytes();
1389 let mut i = 0;
1390 let start = i;
1391 if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
1392 i += 1;
1393 }
1394 let d0 = i;
1396 while i < b.len() && b[i].is_ascii_digit() && i - d0 < 3 {
1397 i += 1;
1398 }
1399 let has_int = i > d0;
1400 if has_int {
1401 while i + 3 < b.len() + 1
1403 && b.get(i) == Some(&b',')
1404 && b.get(i + 1).is_some_and(u8::is_ascii_digit)
1405 && b.get(i + 2).is_some_and(u8::is_ascii_digit)
1406 && b.get(i + 3).is_some_and(u8::is_ascii_digit)
1407 {
1408 i += 4;
1409 }
1410 } else {
1411 i = start;
1413 }
1414 if i < b.len() && b[i] == b'.' {
1416 i += 1;
1417 let f0 = i;
1418 while i < b.len() && b[i].is_ascii_digit() {
1419 i += 1;
1420 }
1421 if !has_int && i == f0 {
1422 return false; }
1424 } else if !has_int {
1425 return false; }
1427 i == b.len()
1428}
1429
1430fn flatten_header_rows(header_rows: &[Vec<String>], num_cols: usize) -> Vec<String> {
1439 (0..num_cols)
1440 .map(|c| {
1441 let mut parts: Vec<&str> = Vec::new();
1442 for row in header_rows {
1443 let text = row.get(c).map(String::as_str).unwrap_or("");
1444 if !text.is_empty() && parts.last() != Some(&text) {
1445 parts.push(text);
1446 }
1447 }
1448 parts.join(" - ")
1449 })
1450 .collect()
1451}
1452
1453pub(crate) fn render_table(table: &Table, compact: bool) -> String {
1454 if table.rows.is_empty() {
1455 return String::new();
1456 }
1457 let num_cols = table.rows.iter().map(Vec::len).max().unwrap_or(0);
1458 if num_cols == 0 {
1459 return String::new();
1460 }
1461
1462 let num_headers = table.header_row_count().min(table.rows.len());
1467 let escaped = |r: usize| -> Vec<String> {
1468 (0..num_cols)
1469 .map(|c| escape_cell(table.rows[r].get(c).map(String::as_str).unwrap_or("")))
1470 .collect()
1471 };
1472 let header_rows: Vec<Vec<String>> = (0..num_headers).map(escaped).collect();
1473 let header = flatten_header_rows(&header_rows, num_cols);
1474 let body: Vec<Vec<String>> = (num_headers..table.rows.len())
1475 .map(|r| {
1476 escaped(r)
1477 .into_iter()
1478 .map(|c| c.trim().to_string())
1479 .collect()
1480 })
1481 .collect();
1482
1483 if compact {
1484 let render_row = |row: &[String]| -> String { format!("| {} |", row.join(" | ")) };
1486 let mut lines = Vec::with_capacity(body.len() + 2);
1487 lines.push(render_row(&header));
1488 let sep: Vec<&str> = (0..num_cols).map(|_| "-").collect();
1489 lines.push(format!("| {} |", sep.join(" | ")));
1490 for row in &body {
1491 lines.push(render_row(row));
1492 }
1493 return lines.join("\n");
1494 }
1495
1496 let dw = |s: &str| s.chars().count();
1498
1499 let right: Vec<bool> = (0..num_cols)
1504 .map(|c| {
1505 let mut any = false;
1506 for row in &body {
1507 let t = row[c].trim();
1508 if t.is_empty() {
1509 continue;
1510 }
1511 if !is_number_cell(t) {
1512 return false;
1513 }
1514 any = true;
1515 }
1516 any
1517 })
1518 .collect();
1519
1520 let width: Vec<usize> = (0..num_cols)
1522 .map(|c| {
1523 let mut w = dw(&header[c]) + 2;
1524 for row in &body {
1525 w = w.max(dw(&row[c]));
1526 }
1527 w
1528 })
1529 .collect();
1530
1531 let fmt_cell = |s: &str, c: usize| -> String {
1532 let pad = " ".repeat(width[c].saturating_sub(dw(s)));
1533 let body = if right[c] {
1534 format!("{pad}{s}")
1535 } else {
1536 format!("{s}{pad}")
1537 };
1538 format!(" {body} ")
1539 };
1540 let render_row = |row: &[String]| -> String {
1541 let cells: Vec<String> = (0..num_cols).map(|c| fmt_cell(&row[c], c)).collect();
1542 format!("|{}|", cells.join("|"))
1543 };
1544
1545 let mut lines = Vec::with_capacity(body.len() + 2);
1546 lines.push(render_row(&header));
1547 let sep: Vec<String> = (0..num_cols).map(|c| "-".repeat(width[c] + 2)).collect();
1548 lines.push(format!("|{}|", sep.join("|")));
1549 for row in &body {
1550 lines.push(render_row(row));
1551 }
1552 lines.join("\n")
1553}
1554
1555fn escape_cell(s: &str) -> String {
1558 s.replace('\n', " ").replace('|', "|")
1559}
1560
1561#[cfg(test)]
1562mod tests {
1563 use super::*;
1564 use crate::{PictureImage, TableCell, TableStructure};
1565
1566 #[test]
1572 fn list_boundaries_come_from_the_backend_not_the_numbering() {
1573 let item = |ordered: bool, number: u64, first_in_list: bool, text: &str| Node::ListItem {
1574 ordered,
1575 number,
1576 first_in_list,
1577 text: text.into(),
1578 level: 0,
1579 marker: None,
1580 location: None,
1581 dclx: None,
1582 href: None,
1583 layer: None,
1584 };
1585 let md = |items: Vec<Node>| {
1586 let mut doc = DoclingDocument::new("t");
1587 for n in items {
1588 doc.push(n);
1589 }
1590 doc.export_to_markdown()
1591 };
1592 assert_eq!(
1594 md(vec![
1595 item(true, 1, true, "one"),
1596 item(true, 5, false, "five")
1597 ]),
1598 "1. one\n5. five\n"
1599 );
1600 assert_eq!(
1602 md(vec![
1603 item(false, 0, true, "bullet"),
1604 item(true, 1, false, "one"),
1605 item(false, 0, false, "bullet two"),
1606 ]),
1607 "- bullet\n1. one\n- bullet two\n"
1608 );
1609 assert_eq!(
1611 md(vec![
1612 item(true, 1, true, "a"),
1613 item(true, 2, false, "b"),
1614 item(true, 3, true, "new list, continuing count"),
1615 ]),
1616 "1. a\n2. b\n\n3. new list, continuing count\n"
1617 );
1618 }
1619
1620 #[test]
1621 fn renders_headings_paragraphs_and_lists() {
1622 let mut doc = DoclingDocument::new("demo");
1623 doc.add_heading(1, "Title");
1624 doc.add_paragraph("Hello world.");
1625 doc.push(Node::ListItem {
1626 ordered: false,
1627 number: 1,
1628 first_in_list: true,
1629 text: "first".into(),
1630 level: 0,
1631 marker: None,
1632 location: None,
1633 dclx: None,
1634 href: None,
1635 layer: None,
1636 });
1637 doc.push(Node::ListItem {
1638 ordered: false,
1639 number: 2,
1640 first_in_list: false,
1641 text: "second".into(),
1642 level: 0,
1643 marker: None,
1644 location: None,
1645 dclx: None,
1646 href: None,
1647 layer: None,
1648 });
1649 let md = doc.export_to_markdown();
1650 assert_eq!(md, "# Title\n\nHello world.\n\n- first\n- second\n");
1651 }
1652
1653 #[test]
1657 fn single_newlines_become_gfm_hard_line_breaks() {
1658 let mut doc = DoclingDocument::new("t");
1659 doc.push(Node::Heading {
1660 level: 1,
1661 text: "Hello\nWorld".into(),
1662 });
1663 doc.push(Node::Paragraph {
1664 text: "line one\nline two\n\npara two".into(),
1665 });
1666 doc.push(Node::ListItem {
1667 ordered: false,
1668 number: 1,
1669 first_in_list: true,
1670 text: "item\ncontinued".into(),
1671 level: 0,
1672 marker: None,
1673 location: None,
1674 dclx: None,
1675 href: None,
1676 layer: None,
1677 });
1678 doc.push(Node::TextDump("A1 B1 \n\n\nC1".into()));
1679 assert_eq!(
1680 doc.export_to_markdown(),
1681 "# Hello World\n\nline one \nline two\n\npara two\n\n- item \ncontinued\n\nA1 B1 \n\n\nC1\n"
1682 );
1683 }
1684
1685 #[test]
1688 fn table_cell_mode_and_field_regions() {
1689 let mut doc = DoclingDocument::new("t");
1690 doc.push(Node::Heading {
1691 level: 2,
1692 text: "A text".into(),
1693 });
1694 doc.push(Node::Paragraph {
1695 text: "body".into(),
1696 });
1697 assert_eq!(to_markdown_table_cell(&doc, false), "A text\n\nbody");
1698 assert_eq!(doc.export_to_markdown(), "## A text\n\nbody\n");
1699
1700 let mut doc = DoclingDocument::new("f");
1701 doc.push(Node::FieldRegion {
1702 items: vec![crate::FieldItem {
1703 marker: None,
1704 key: Some("Name:".into()),
1705 value: Some("John Doe".into()),
1706 value_kind: None,
1707 }],
1708 });
1709 assert_eq!(doc.export_to_markdown(), "Name:\n\nJohn Doe\n");
1710 }
1711
1712 #[test]
1713 fn strict_renders_recovered_links_legacy_does_not() {
1714 let mut doc = DoclingDocument::new("cv");
1715 doc.add_paragraph("Find me on LinkedIn or GitHub.");
1716 doc.links = vec![
1717 ("LinkedIn".into(), "https://www.linkedin.com/in/x/".into()),
1718 ("GitHub".into(), "https://github.com/x/".into()),
1719 ];
1720 assert_eq!(doc.export_to_markdown(), "Find me on LinkedIn or GitHub.\n");
1722 assert_eq!(
1724 doc.export_to_markdown_with(true),
1725 "Find me on [LinkedIn](https://www.linkedin.com/in/x/) or [GitHub](https://github.com/x/).\n"
1726 );
1727 }
1728
1729 #[test]
1730 fn strict_links_match_escaped_anchor_and_consume_in_order() {
1731 let mut doc = DoclingDocument::new("d");
1732 doc.add_paragraph("AI & ML here, and issues here, then issues there.");
1736 doc.links = vec![
1737 ("AI & ML".into(), "https://a/".into()),
1738 ("issues".into(), "https://first/".into()),
1739 ("issues".into(), "https://second/".into()),
1740 ];
1741 assert_eq!(
1742 doc.export_to_markdown_with(true),
1743 "[AI & ML](https://a/) here, and [issues](https://first/) here, then [issues](https://second/) there.\n"
1744 );
1745 }
1746
1747 #[test]
1751 fn referenced_image_destinations_are_escaped() {
1752 let cases = [
1753 (
1754 "doc_artifacts/image_000001_ab12.png",
1755 "doc_artifacts/image_000001_ab12.png",
1756 ),
1757 (
1758 "My Report_artifacts/img.png",
1759 "My%20Report_artifacts/img.png",
1760 ),
1761 ("artifacts/img (1).png", "artifacts/img%20%281%29.png"),
1762 ("100%_scale/a#b?c.png", "100%_scale/a%23b%3Fc.png"),
1763 ("/home/a b/img.png", "/home/a%20b/img.png"),
1764 (
1765 "My Report_artifacts\\img.png",
1766 "My%20Report_artifacts/img.png",
1767 ),
1768 (
1769 "C:/Users/me/My Docs/img.png",
1770 "file:///C:/Users/me/My%20Docs/img.png",
1771 ),
1772 ("C:\\Users\\me\\img.png", "file:///C:/Users/me/img.png"),
1773 (
1774 "//server/share/My Docs/img.png",
1775 "file://server/share/My%20Docs/img.png",
1776 ),
1777 ("\\\\server\\share\\img.png", "file://server/share/img.png"),
1778 ("file:///home/a b/img.png", "file:///home/a%20b/img.png"),
1779 (
1780 "s3://bucket/My Report_artifacts/img.png",
1781 "s3://bucket/My%20Report_artifacts/img.png",
1782 ),
1783 (
1784 "https://example.com:8080/a b.png?w=1&h=2#frag",
1785 "https://example.com:8080/a%20b.png?w=1&h=2#frag",
1786 ),
1787 (
1788 "https://example.com/img (1).png",
1789 "https://example.com/img%20%281%29.png",
1790 ),
1791 ("caf\u{e9}/im\u{e4}ge.png", "caf%C3%A9/im%C3%A4ge.png"),
1792 ];
1793 for (input, expected) in cases {
1794 assert_eq!(escape_uri_path(input), expected, "input {input:?}");
1795 assert_eq!(
1796 escape_uri_path(expected),
1797 expected,
1798 "idempotent {expected:?}"
1799 );
1800 }
1801 let mut doc = DoclingDocument::new("t");
1803 doc.push(Node::Picture {
1804 caption: None,
1805 caption_href: None,
1806 image: Some(PictureImage {
1807 dpi: PictureImage::DEFAULT_DPI,
1808 mimetype: "image/png".into(),
1809 width: 1,
1810 height: 1,
1811 data: b"x".to_vec(),
1812 }),
1813 classification: None,
1814 description: None,
1815 caption_parent: Default::default(),
1816 caption_location: None,
1817 });
1818 let (md, files) = doc
1819 .export_to_markdown_with_images(ImageMode::Referenced, "My Report (final)_artifacts");
1820 assert!(
1821 md.contains(""),
1822 "got:\n{md}"
1823 );
1824 assert_eq!(files[0].0, "My Report (final)_artifacts/image_000000.png");
1826 }
1827
1828 #[test]
1832 fn folded_list_item_pictures_keep_plain_newlines() {
1833 let doc = DoclingDocument::new("t");
1834 let ctx = Ctx::new(&doc, false, &MarkdownExportOptions::default());
1835 assert_eq!(
1836 list_item_text("Step\n<!-- image -->", &ctx),
1837 "Step\n<!-- image -->"
1838 );
1839 assert_eq!(
1840 list_item_text("Step\nAlt text\n<!-- image -->\n<!-- image -->", &ctx),
1841 "Step\nAlt text\n<!-- image -->\n<!-- image -->"
1842 );
1843 assert_eq!(
1844 list_item_text("line one\nline two", &ctx),
1845 "line one \nline two"
1846 );
1847 }
1848
1849 #[test]
1852 fn stacked_header_rows_flatten_into_one() {
1853 let mut t = Table {
1854 rows: vec![
1855 vec!["".into(), "% of Total".into(), "% of Total".into()],
1856 vec!["class".into(), "Train".into(), "Test".into()],
1857 vec!["Caption".into(), "2.04".into(), "1.77".into()],
1858 ],
1859 ..Default::default()
1860 };
1861 t.structure = Some(TableStructure {
1862 header_row: vec![true, true, false],
1863 col_continuation: vec![
1864 vec![false, false, true],
1865 vec![false, false, false],
1866 vec![false, false, false],
1867 ],
1868 ..Default::default()
1869 });
1870 assert_eq!(t.header_row_count(), 2);
1871 assert_eq!(
1872 render_table(&t, true),
1873 "| class | % of Total - Train | % of Total - Test |\n| - | - | - |\n| Caption | 2.04 | 1.77 |"
1874 );
1875 assert_eq!(
1877 render_table(&t, false),
1878 "| class | % of Total - Train | % of Total - Test |\n\
1879 |---------|----------------------|---------------------|\n\
1880 | Caption | 2.04 | 1.77 |"
1881 );
1882 }
1883
1884 #[test]
1887 fn vertically_spanning_header_does_not_extend_the_block() {
1888 let mut t = Table {
1889 rows: vec![
1890 vec!["Name".into(), "Value".into()],
1891 vec!["Name".into(), "1".into()],
1892 vec!["x".into(), "2".into()],
1893 ],
1894 ..Default::default()
1895 };
1896 t.structure = Some(TableStructure {
1897 col_header: vec![vec![true, true], vec![true, false], vec![false, false]],
1898 row_continuation: vec![vec![false, false], vec![true, false], vec![false, false]],
1899 ..Default::default()
1900 });
1901 assert_eq!(t.header_row_count(), 1);
1902 assert_eq!(
1903 render_table(&t, true),
1904 "| Name | Value |\n| - | - |\n| Name | 1 |\n| x | 2 |"
1905 );
1906 }
1907
1908 #[test]
1911 fn header_flags_not_on_row_zero_keep_all_rows_in_the_body() {
1912 let mut t = Table {
1913 rows: vec![
1914 vec!["1".into(), "2".into()],
1915 vec!["a".into(), "b".into()],
1916 vec!["333".into(), "4".into()],
1917 ],
1918 ..Default::default()
1919 };
1920 t.structure = Some(TableStructure {
1921 header_row: vec![false, true, false],
1922 ..Default::default()
1923 });
1924 assert_eq!(t.header_row_count(), 0);
1925 assert_eq!(
1926 render_table(&t, false),
1927 "| | |\n|-----|----|\n| 1 | 2 |\n| a | b |\n| 333 | 4 |"
1928 );
1929 }
1930
1931 #[test]
1936 fn pivot_row_headers_do_not_extend_the_header() {
1937 let mut t = Table {
1938 rows: vec![
1939 vec!["Year".into(), "Month".into()],
1940 vec!["2025".into(), "January".into()],
1941 vec!["2025".into(), "February".into()],
1942 ],
1943 ..Default::default()
1944 };
1945 t.structure = Some(TableStructure {
1946 col_header: vec![vec![true, true], vec![false, false], vec![false, false]],
1947 row_header: vec![vec![false, false], vec![true, false], vec![true, false]],
1948 row_continuation: vec![vec![false, false], vec![false, false], vec![true, false]],
1949 ..Default::default()
1950 });
1951 assert_eq!(t.header_row_count(), 1);
1952 assert_eq!(
1953 render_table(&t, true),
1954 "| Year | Month |\n| - | - |\n| 2025 | January |\n| 2025 | February |"
1955 );
1956 }
1957
1958 #[test]
1961 fn unflagged_cells_keep_row_zero_as_header() {
1962 let mut t = Table {
1963 rows: vec![vec!["h".into()], vec!["d".into()]],
1964 ..Default::default()
1965 };
1966 t.cells = Some(
1967 [(0usize, "h"), (1, "d")]
1968 .into_iter()
1969 .map(|(r, text)| TableCell {
1970 text: text.into(),
1971 bbox: None,
1972 start_row: r,
1973 start_col: 0,
1974 row_span: 1,
1975 col_span: 1,
1976 column_header: false,
1977 row_header: false,
1978 row_section: false,
1979 })
1980 .collect(),
1981 );
1982 assert_eq!(t.header_row_count(), 1);
1983 assert_eq!(render_table(&t, true), "| h |\n| - |\n| d |");
1984 }
1985
1986 fn flagged_table(rows: &[&[&str]], ched: impl Fn(usize, usize) -> bool) -> Table {
1988 let mut cells = Vec::new();
1989 for (r, row) in rows.iter().enumerate() {
1990 for (c, text) in row.iter().enumerate() {
1991 cells.push(TableCell {
1992 text: (*text).into(),
1993 bbox: None,
1994 start_row: r,
1995 start_col: c,
1996 row_span: 1,
1997 col_span: 1,
1998 column_header: ched(r, c),
1999 row_header: false,
2000 row_section: false,
2001 });
2002 }
2003 }
2004 Table {
2005 rows: rows
2006 .iter()
2007 .map(|row| row.iter().map(|t| (*t).to_string()).collect())
2008 .collect(),
2009 cells: Some(cells),
2010 ..Default::default()
2011 }
2012 }
2013
2014 #[test]
2018 fn rows_with_body_text_stop_the_header_block() {
2019 let t = flagged_table(
2021 &[
2022 &["Item", "Q1", "Q2"],
2023 &["Sales", "10", "20"],
2024 &["Costs", "5", "7"],
2025 ],
2026 |r, c| r == 0 || c == 0,
2027 );
2028 assert_eq!(t.header_row_count(), 1);
2029 assert_eq!(
2030 render_table(&t, false),
2031 "| Item | Q1 | Q2 |\n\
2032 |--------|------|------|\n\
2033 | Sales | 10 | 20 |\n\
2034 | Costs | 5 | 7 |"
2035 );
2036 let t = flagged_table(&[&["Sales", "10", "20"], &["Costs", "5", "7"]], |_, c| {
2039 c == 0
2040 });
2041 assert_eq!(t.header_row_count(), 0);
2042 assert_eq!(
2043 render_table(&t, false),
2044 "| | | |\n\
2045 |-------|----|----|\n\
2046 | Sales | 10 | 20 |\n\
2047 | Costs | 5 | 7 |"
2048 );
2049 let t = flagged_table(
2050 &[&["a", "1", "2"], &["b", "3", "4"], &["c", "5", "6"]],
2051 |r, c| c == 0 && r < 2,
2052 );
2053 assert_eq!(t.header_row_count(), 0);
2054 let t = flagged_table(&[&["a", "1", "2"], &["b", "3", "4"]], |r, c| {
2057 r == 0 && c == 0
2058 });
2059 assert_eq!(t.header_row_count(), 1);
2060 assert_eq!(
2061 render_table(&t, false),
2062 "| a | 1 | 2 |\n\
2063 |-----|-----|-----|\n\
2064 | b | 3 | 4 |"
2065 );
2066 let t = flagged_table(&[&["Item", "", ""], &["x", "1", "2"]], |_, c| c == 0);
2068 assert_eq!(t.header_row_count(), 1);
2069 assert_eq!(
2070 render_table(&t, false),
2071 "| Item | | |\n\
2072 |--------|----|----|\n\
2073 | x | 1 | 2 |"
2074 );
2075 }
2076
2077 #[test]
2078 fn renders_compact_table() {
2079 let mut doc = DoclingDocument::new("t");
2080 doc.compact_tables = true;
2083 doc.push(Node::Table(Table {
2084 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
2085 location: None,
2086 structure: None,
2087 cell_blocks: None,
2088 cells: None,
2089 caption: None,
2090 caption_parent: Default::default(),
2091 caption_location: None,
2092 }));
2093 let md = doc.export_to_markdown();
2094 assert_eq!(md, "| a | b |\n| - | - |\n| 1 | 2 |\n");
2095 }
2096
2097 #[test]
2098 fn renders_padded_github_table_by_default() {
2099 let mut doc = DoclingDocument::new("t");
2100 doc.push(Node::Table(Table {
2101 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
2102 location: None,
2103 structure: None,
2104 cell_blocks: None,
2105 cells: None,
2106 caption: None,
2107 caption_parent: Default::default(),
2108 caption_location: None,
2109 }));
2110 let md = doc.export_to_markdown();
2111 assert_eq!(md, "| a | b |\n|-----|-----|\n| 1 | 2 |\n");
2113 }
2114
2115 #[test]
2116 fn strict_unescapes_inline_underscores_legacy_keeps_them() {
2117 let mut doc = DoclingDocument::new("t");
2118 doc.add_heading(1, "a\\_b");
2119 doc.add_paragraph("x\\_y");
2120 doc.push(Node::ListItem {
2121 ordered: false,
2122 number: 1,
2123 first_in_list: true,
2124 text: "i\\_j".into(),
2125 level: 0,
2126 marker: None,
2127 location: None,
2128 dclx: None,
2129 href: None,
2130 layer: None,
2131 });
2132 assert_eq!(doc.export_to_markdown(), "# a\\_b\n\nx\\_y\n\n- i\\_j\n");
2134 assert_eq!(doc.export_to_markdown_with(true), "# a_b\n\nx_y\n\n- i_j\n");
2136 }
2137
2138 fn assert_stream_matches(
2141 doc: &DoclingDocument,
2142 strict: bool,
2143 images: ImageMode,
2144 splits: &[usize],
2145 ) {
2146 let (want, want_artifacts) = to_markdown_images(doc, strict, images, "artifacts");
2147 let mut streamer =
2148 MarkdownStreamer::with_artifacts(strict, images, doc.compact_tables, "artifacts")
2149 .with_page_break_placeholder(doc.page_break_placeholder.clone());
2150 let mut got = String::new();
2151 let mut got_artifacts = Vec::new();
2152 let mut start = 0;
2153 for &end in splits {
2154 let links = if start == 0 {
2157 doc.links.as_slice()
2158 } else {
2159 &[]
2160 };
2161 got.push_str(&streamer.push(&doc.nodes[start..end], links));
2162 got_artifacts.extend(streamer.take_artifacts());
2165 start = end;
2166 }
2167 got.push_str(&streamer.push(
2168 &doc.nodes[start..],
2169 if start == 0 {
2170 doc.links.as_slice()
2171 } else {
2172 &[]
2173 },
2174 ));
2175 got_artifacts.extend(streamer.take_artifacts());
2176 got.push_str(&streamer.finish());
2177 assert_eq!(
2178 got, want,
2179 "streamed output diverged (splits={splits:?}, strict={strict})"
2180 );
2181 assert_eq!(
2182 got_artifacts, want_artifacts,
2183 "streamed artifacts diverged (splits={splits:?}, strict={strict})"
2184 );
2185 }
2186
2187 #[test]
2188 fn streaming_is_byte_identical_to_buffered() {
2189 let mut doc = DoclingDocument::new("d");
2190 doc.add_heading(1, "Title");
2191 doc.add_paragraph("First paragraph.");
2192 doc.push(Node::ListItem {
2193 ordered: false,
2194 number: 1,
2195 first_in_list: true,
2196 text: "a".into(),
2197 level: 0,
2198 marker: None,
2199 location: None,
2200 dclx: None,
2201 href: None,
2202 layer: None,
2203 });
2204 doc.push(Node::ListItem {
2205 ordered: false,
2206 number: 2,
2207 first_in_list: false,
2208 text: "b".into(),
2209 level: 0,
2210 marker: None,
2211 location: None,
2212 dclx: None,
2213 href: None,
2214 layer: None,
2215 });
2216 doc.push(Node::Code {
2217 language: Some("rust".into()),
2218 text: "let x = 1;".into(),
2219 orig: None,
2220 pretty: None,
2221 });
2222 doc.push(Node::Table(Table {
2223 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
2224 location: None,
2225 structure: None,
2226 cell_blocks: None,
2227 cells: None,
2228 caption: None,
2229 caption_parent: Default::default(),
2230 caption_location: None,
2231 }));
2232 doc.push(Node::Picture {
2233 caption: Some("Fig 1".into()),
2234 caption_href: None,
2235 image: Some(PictureImage {
2236 dpi: PictureImage::DEFAULT_DPI,
2237 mimetype: "image/png".into(),
2238 width: 2,
2239 height: 2,
2240 data: b"png-one".to_vec(),
2241 }),
2242 classification: None,
2243 description: None,
2244 caption_parent: Default::default(),
2245 caption_location: None,
2246 });
2247 doc.add_paragraph("Last paragraph.");
2248 doc.push(Node::Picture {
2251 caption: None,
2252 caption_href: None,
2253 image: Some(PictureImage {
2254 dpi: PictureImage::DEFAULT_DPI,
2255 mimetype: "image/png".into(),
2256 width: 2,
2257 height: 2,
2258 data: b"png-two".to_vec(),
2259 }),
2260 classification: None,
2261 description: None,
2262 caption_parent: Default::default(),
2263 caption_location: None,
2264 });
2265
2266 for &strict in &[false, true] {
2269 for &images in &[
2270 ImageMode::Placeholder,
2271 ImageMode::Embedded,
2272 ImageMode::Referenced,
2273 ] {
2274 for splits in [&[][..], &[1][..], &[2][..], &[4][..], &[1, 4, 6, 7][..]] {
2275 assert_stream_matches(&doc, strict, images, splits);
2276 }
2277 }
2278 }
2279 }
2280
2281 #[test]
2282 fn streaming_applies_recovered_links_in_strict_mode() {
2283 let mut doc = DoclingDocument::new("d");
2284 doc.add_paragraph("See LinkedIn for details.");
2285 doc.add_paragraph("And GitHub too.");
2286 doc.links = vec![
2287 ("LinkedIn".into(), "https://lnkd/".into()),
2288 ("GitHub".into(), "https://gh/".into()),
2289 ];
2290 assert_stream_matches(&doc, true, ImageMode::Placeholder, &[1]);
2293 }
2294
2295 fn paged_doc() -> DoclingDocument {
2298 let mut doc = DoclingDocument::new("p");
2299 doc.push(Node::PageInfo {
2300 page_no: 1,
2301 width: 100.0,
2302 height: 100.0,
2303 });
2304 doc.add_heading(1, "Title");
2305 doc.add_paragraph("Page one.");
2306 doc.push(Node::PageBreak);
2308 doc.push(Node::PageInfo {
2309 page_no: 2,
2310 width: 100.0,
2311 height: 100.0,
2312 });
2313 doc.push(Node::PageFurniture {
2314 footer: true,
2315 location: [0, 500, 511, 511],
2316 text: "2".into(),
2317 });
2318 doc.push(Node::PageBreak);
2319 doc.push(Node::PageInfo {
2320 page_no: 3,
2321 width: 100.0,
2322 height: 100.0,
2323 });
2324 doc.add_paragraph("Page three.");
2325 doc.push(Node::PageBreak);
2327 doc
2328 }
2329
2330 #[test]
2331 fn page_break_placeholder_lands_between_pages_only() {
2332 let mut doc = paged_doc();
2333 assert_eq!(
2335 doc.export_to_markdown(),
2336 "# Title\n\nPage one.\n\nPage three.\n"
2337 );
2338 doc.page_break_placeholder = Some("<!-- page break -->".into());
2339 assert_eq!(
2343 doc.export_to_markdown(),
2344 "# Title\n\nPage one.\n\n<!-- page break -->\n\nPage three.\n"
2345 );
2346 doc.page_break_placeholder = Some(String::new());
2349 assert_eq!(
2350 doc.export_to_markdown(),
2351 "# Title\n\nPage one.\n\n\n\nPage three.\n"
2352 );
2353 }
2354
2355 #[test]
2356 fn page_break_placeholder_never_leads_a_single_page() {
2357 let mut doc = DoclingDocument::new("one");
2358 doc.page_break_placeholder = Some("---".into());
2359 doc.push(Node::PageBreak);
2360 doc.push(Node::PageInfo {
2361 page_no: 1,
2362 width: 10.0,
2363 height: 10.0,
2364 });
2365 doc.add_paragraph("Only page.");
2366 assert_eq!(doc.export_to_markdown(), "Only page.\n");
2367 doc.push(Node::PageBreak);
2369 doc.push(Node::PageBreak);
2370 doc.add_paragraph("Next.");
2371 assert_eq!(doc.export_to_markdown(), "Only page.\n\n---\n\nNext.\n");
2372 }
2373
2374 #[test]
2375 fn page_break_placeholder_streams_byte_identical() {
2376 let mut doc = paged_doc();
2377 doc.page_break_placeholder = Some("<!-- page break -->".into());
2378 for splits in [
2382 &[3usize][..],
2383 &[3, 6],
2384 &[3, 6, 8],
2385 &[1, 2, 3, 4, 5, 6, 7, 8, 9],
2386 &[8],
2387 ] {
2388 assert_stream_matches(&doc, false, ImageMode::Placeholder, splits);
2389 assert_stream_matches(&doc, true, ImageMode::Placeholder, splits);
2390 }
2391 }
2392
2393 #[test]
2394 fn strict_tightens_punctuation_spacing_legacy_keeps_it() {
2395 let mut doc = DoclingDocument::new("t");
2396 doc.add_paragraph("see [ 37 , 36 ] and ( x ) .");
2397 assert_eq!(doc.export_to_markdown(), "see [ 37 , 36 ] and ( x ) .\n");
2399 assert_eq!(doc.export_to_markdown_with(true), "see [37, 36] and (x).\n");
2401 }
2402
2403 fn options_doc() -> DoclingDocument {
2408 use crate::document::ContentLayer;
2409 let mut doc = DoclingDocument::new("opts");
2410 doc.push(Node::PageFurniture {
2411 footer: false,
2412 location: [0, 0, 0, 0],
2413 text: "FAX COVER \\_ R&D".into(),
2414 });
2415 doc.add_heading(1, "R&D \\_ report");
2416 doc.add_paragraph("Body a\\_b <tag>");
2417 doc.push(Node::Picture {
2418 caption: Some("Figure 1".into()),
2419 caption_href: None,
2420 image: None,
2421 classification: None,
2422 description: None,
2423 caption_parent: Default::default(),
2424 caption_location: None,
2425 });
2426 doc.push(Node::PictureChildren(vec![
2427 Node::Paragraph {
2428 text: "Field: Name".into(),
2429 },
2430 Node::Paragraph {
2431 text: "Field: Date".into(),
2432 },
2433 ]));
2434 doc.push(Node::CommentSection {
2435 name: "comment-1".into(),
2436 text: "[author: A]: note".into(),
2437 refs_note_text: false,
2438 grouped: true,
2439 });
2440 doc.push(Node::Group {
2441 label: "section".into(),
2442 name: Some("sheet: Hidden".into()),
2443 layer: Some(ContentLayer::Invisible),
2444 children: vec![Node::Paragraph {
2445 text: "hidden cell".into(),
2446 }],
2447 });
2448 doc.push(Node::Furniture {
2449 layer: ContentLayer::Furniture,
2450 inner: Box::new(Node::Paragraph {
2451 text: "Page 1 of 2".into(),
2452 }),
2453 });
2454 doc.push(Node::FurnitureText {
2455 label: "page_footer".into(),
2456 text: "footer line".into(),
2457 });
2458 doc
2459 }
2460
2461 #[test]
2465 fn default_options_are_the_default_export() {
2466 let doc = options_doc();
2467 let plain = doc.export_to_markdown();
2468 assert_eq!(
2469 plain,
2470 "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n"
2471 );
2472 let (with_default, artifacts) =
2473 doc.export_to_markdown_with_options(&MarkdownExportOptions::default());
2474 assert_eq!(with_default, plain);
2475 assert!(artifacts.is_empty());
2476 }
2477
2478 #[test]
2479 fn layers_render_furniture_notes_and_hidden_sheets() {
2480 use crate::document::ContentLayer;
2481 let doc = options_doc();
2482 let md = |layers: ContentLayers| {
2483 doc.export_to_markdown_with_options(&MarkdownExportOptions {
2484 layers,
2485 ..MarkdownExportOptions::default()
2486 })
2487 .0
2488 };
2489 assert_eq!(
2490 md(ContentLayers::BODY.with(ContentLayer::Furniture)),
2491 "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",
2492 "a page header, a furniture-wrapped paragraph and a furniture text item render as paragraphs"
2493 );
2494 assert_eq!(
2495 md(ContentLayers::BODY.with(ContentLayer::Notes)),
2496 "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n\n[author: A]: note\n"
2497 );
2498 assert_eq!(
2499 md(ContentLayers::BODY.with(ContentLayer::Invisible)),
2500 "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n\nhidden cell\n",
2501 "a hidden sheet's items sit on the sheet's layer"
2502 );
2503 assert_eq!(
2504 md(ContentLayers::NONE.with(ContentLayer::Furniture)),
2505 "FAX COVER \\_ R&D\n\nPage 1 of 2\n\nfooter line\n",
2506 "without the body layer only the furniture prints"
2507 );
2508 assert_eq!(md(ContentLayers::NONE), "");
2509 assert_eq!(
2510 md(ContentLayers::ALL),
2511 "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"
2512 );
2513 }
2514
2515 #[test]
2518 fn layers_apply_to_list_items() {
2519 use crate::document::ContentLayer;
2520 let mut doc = DoclingDocument::new("lists");
2521 doc.push(Node::ListItem {
2522 ordered: false,
2523 number: 1,
2524 first_in_list: true,
2525 text: "nav link".into(),
2526 level: 0,
2527 marker: None,
2528 location: None,
2529 dclx: None,
2530 href: None,
2531 layer: Some(ContentLayer::Furniture),
2532 });
2533 doc.add_paragraph("body");
2534 assert_eq!(doc.export_to_markdown(), "body\n");
2535 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2536 layers: ContentLayers::BODY.with(ContentLayer::Furniture),
2537 ..MarkdownExportOptions::default()
2538 });
2539 assert_eq!(md, "- nav link\n\nbody\n");
2540 }
2541
2542 #[test]
2543 fn traverse_pictures_prints_the_nested_text_after_the_picture() {
2544 let doc = options_doc();
2545 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2546 traverse_pictures: true,
2547 ..MarkdownExportOptions::default()
2548 });
2549 assert_eq!(
2550 md,
2551 "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n\nField: Name\n\nField: Date\n"
2552 );
2553 }
2554
2555 #[test]
2556 fn escaping_can_be_turned_off_per_kind() {
2557 let doc = options_doc();
2558 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2559 escape_html: false,
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"
2565 );
2566 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2567 escape_underscores: false,
2568 ..MarkdownExportOptions::default()
2569 });
2570 assert_eq!(
2571 md,
2572 "# R&D _ report\n\nBody a_b <tag>\n\nFigure 1\n\n<!-- image -->\n"
2573 );
2574 let mut doc = DoclingDocument::new("code");
2577 doc.push(Node::Code {
2578 language: None,
2579 text: "a & b \\_ c".into(),
2580 orig: None,
2581 pretty: None,
2582 });
2583 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2584 escape_html: false,
2585 escape_underscores: false,
2586 ..MarkdownExportOptions::default()
2587 });
2588 assert_eq!(md, "```\na & b \\_ c\n```\n");
2589 }
2590
2591 #[test]
2592 fn image_placeholder_is_configurable() {
2593 let doc = options_doc();
2594 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2595 image_placeholder: "[figure]".into(),
2596 ..MarkdownExportOptions::default()
2597 });
2598 assert!(md.contains("Figure 1\n\n[figure]\n"), "{md}");
2599 assert!(!md.contains("<!-- image -->"));
2600 }
2601
2602 #[test]
2608 fn empty_image_placeholder_prints_nothing() {
2609 fn picture(caption: Option<&str>) -> Node {
2610 Node::Picture {
2611 caption: caption.map(Into::into),
2612 caption_href: None,
2613 image: None,
2614 classification: None,
2615 description: None,
2616 caption_parent: Default::default(),
2617 caption_location: None,
2618 }
2619 }
2620 fn page(no: usize) -> Node {
2621 Node::PageInfo {
2622 page_no: no,
2623 width: 100.0,
2624 height: 100.0,
2625 }
2626 }
2627 fn para(text: &str) -> Node {
2628 Node::Paragraph { text: text.into() }
2629 }
2630 let options = MarkdownExportOptions {
2631 image_placeholder: String::new(),
2632 ..MarkdownExportOptions::default()
2633 };
2634 let cases: Vec<(Vec<Node>, Option<&str>, &str)> = vec![
2636 (
2637 vec![page(1), para("a"), picture(None), para("b")],
2638 None,
2639 "a\n\nb\n",
2640 ),
2641 (
2642 vec![page(1), para("a"), picture(Some("Figure 1")), para("b")],
2643 None,
2644 "a\n\nFigure 1\n\nb\n",
2645 ),
2646 (
2647 vec![
2648 page(1),
2649 para("a"),
2650 page(2),
2651 picture(None),
2652 page(3),
2653 para("b"),
2654 ],
2655 Some("<!-- pb -->"),
2656 "a\n\n<!-- pb -->\n\n<!-- pb -->\n\nb\n",
2657 ),
2658 (
2659 vec![
2660 page(1),
2661 para("a"),
2662 page(2),
2663 picture(None),
2664 page(3),
2665 para("b"),
2666 ],
2667 Some(""),
2668 "a\n\n\n\n\n\nb\n",
2669 ),
2670 (
2671 vec![page(1), picture(None), page(2), para("b")],
2672 Some("<!-- pb -->"),
2673 "<!-- pb -->\n\nb\n",
2674 ),
2675 (
2676 vec![page(1), picture(None), page(2), para("b")],
2677 Some(""),
2678 "\n\nb\n",
2679 ),
2680 (
2681 vec![page(1), para("a"), page(2), picture(None)],
2682 Some("<!-- pb -->"),
2683 "a\n\n<!-- pb -->\n",
2684 ),
2685 ];
2686 for (nodes, placeholder, expected) in cases {
2687 let mut doc = DoclingDocument::new("t");
2688 doc.page_break_placeholder = placeholder.map(Into::into);
2689 for node in nodes {
2690 doc.push(node);
2691 }
2692 let (md, _) = doc.export_to_markdown_with_options(&options);
2693 assert_eq!(md, expected, "page break {placeholder:?}");
2694 for size in 1..=doc.nodes.len() {
2697 let mut streamer = MarkdownStreamer::new(false, ImageMode::Placeholder, false)
2698 .with_export_options(&options)
2699 .with_page_break_placeholder(placeholder.map(Into::into));
2700 let mut out = String::new();
2701 for chunk in doc.nodes.chunks(size) {
2702 out.push_str(&streamer.push(chunk, &[]));
2703 }
2704 out.push_str(&streamer.finish());
2705 assert_eq!(
2706 out, expected,
2707 "chunks of {size}, page break {placeholder:?}"
2708 );
2709 }
2710 }
2711 let mut doc = DoclingDocument::new("t");
2713 doc.push(para("a"));
2714 doc.push(picture(None));
2715 doc.push(para("b"));
2716 assert_eq!(doc.export_to_markdown(), "a\n\n<!-- image -->\n\nb\n");
2717 }
2718
2719 #[test]
2722 fn streamer_matches_buffered_export_with_options() {
2723 let doc = options_doc();
2724 let options = MarkdownExportOptions {
2725 layers: ContentLayers::ALL,
2726 traverse_pictures: true,
2727 escape_html: false,
2728 escape_underscores: false,
2729 image_placeholder: "(img)".into(),
2730 ..MarkdownExportOptions::default()
2731 };
2732 let (buffered, _) = doc.export_to_markdown_with_options(&options);
2733 let mut streamer = MarkdownStreamer::new(false, ImageMode::Placeholder, false)
2734 .with_export_options(&options);
2735 let mut out = String::new();
2736 for chunk in doc.nodes.chunks(2) {
2737 out.push_str(&streamer.push(chunk, &[]));
2738 }
2739 out.push_str(&streamer.finish());
2740 assert_eq!(out, buffered);
2741 assert!(
2742 buffered.contains("(img)") && buffered.contains("R&D _ report"),
2743 "{buffered}"
2744 );
2745 }
2746
2747 #[test]
2750 fn plain_text_drops_the_markdown_decoration() {
2751 let item = |text: &str, ordered: bool, number: u64, level: u8| Node::ListItem {
2752 ordered,
2753 number,
2754 first_in_list: number == 1 && level == 0,
2755 text: text.into(),
2756 level,
2757 marker: None,
2758 location: None,
2759 dclx: None,
2760 href: None,
2761 layer: None,
2762 };
2763 let mut doc = DoclingDocument::new("plain");
2764 doc.add_heading(1, "Title with **bold**");
2765 doc.add_heading(2, "Section");
2766 doc.add_paragraph("Some **bold**, *italic*, ~~gone~~ and `code` with a [link](https://x.org).\nNext line.");
2767 doc.push(item("*one*", false, 1, 0));
2768 doc.push(item("[two](https://y.org)", false, 2, 0));
2769 doc.push(item("nested", true, 1, 1));
2770 doc.push(Node::CheckboxItem {
2771 checked: true,
2772 text: "done".into(),
2773 });
2774 doc.push(Node::Code {
2775 language: Some("rust".into()),
2776 text: "let x = **y**;".into(),
2777 orig: None,
2778 pretty: None,
2779 });
2780 doc.push(Node::Picture {
2781 caption: Some("Figure *1*".into()),
2782 caption_href: None,
2783 image: None,
2784 classification: None,
2785 description: None,
2786 caption_parent: Default::default(),
2787 caption_location: None,
2788 });
2789 doc.push(Node::Caption {
2790 text: "Linked caption".into(),
2791 href: Some("https://z.org".into()),
2792 });
2793 doc.push(Node::Table(Table {
2794 rows: vec![
2795 vec!["**n**".into(), "rich".into()],
2796 vec!["**2**".into(), "a \nb".into()],
2797 ],
2798 ..Default::default()
2799 }));
2800 doc.add_paragraph("R&D \\_ x");
2801 let text = doc.export_to_text();
2802 assert_eq!(
2803 text,
2804 "Title with bold\n\n\
2805 Section\n\n\
2806 Some bold, italic, gone and code with a link.\nNext line.\n\n\
2807 - one\n- two\n 1. nested\n\n\
2808 - [x] done\n\n\
2809 let x = **y**;\n\n\
2810 Figure 1\n\n\
2811 Linked caption\n\n\
2812 | n | rich |\n\
2813 |-----|--------|\n\
2814 | 2 | a b |\n\n\
2815 R&D _ x"
2816 );
2817
2818 let options = MarkdownExportOptions::plain_text();
2819 let (buffered, _) = doc.export_to_markdown_with_options(&options);
2820 assert_eq!(buffered, format!("{text}\n"));
2821 let mut streamer = MarkdownStreamer::new(false, ImageMode::Placeholder, false)
2822 .with_export_options(&options);
2823 let mut out = String::new();
2824 for chunk in doc.nodes.chunks(3) {
2825 out.push_str(&streamer.push(chunk, &[]));
2826 }
2827 out.push_str(&streamer.finish());
2828 assert_eq!(out, buffered);
2829 }
2830
2831 #[test]
2833 fn plain_inline_keeps_literal_markers() {
2834 for (input, want) in [
2835 ("**bold** and *it* and ***both***", "bold and it and both"),
2836 ("**[label](https://a.b/c_(d))** end", "label end"),
2837 (
2838 "grant *USE and *OBJMGT authority",
2839 "grant *USE and *OBJMGT authority",
2840 ),
2841 ("2 * 3 * 4", "2 * 3 * 4"),
2842 ("a ** b", "a ** b"),
2843 ("the `quoted’ and `x` term", "the `quoted’ and x term"),
2844 ("see [12] and [docs](u)", "see [12] and docs"),
2845 ("formula $[a](b)$ stays", "formula $[a](b)$ stays"),
2846 ("price $5 and **bold**", "price $5 and bold"),
2847 ("[outer [inner] text](u)", "outer [inner] text"),
2848 ("unclosed **bold", "unclosed **bold"),
2849 ] {
2850 assert_eq!(plain_inline(input), want, "{input}");
2851 }
2852 }
2853}