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