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 *cell = crate::fallback::strip_owned(std::mem::take(cell));
172 if cell.contains(['*', '~', '`', '[', '\n', '<']) {
173 let text = self.drop_image_markers(&strip_hard_breaks(cell));
174 *cell = plain_inline(&text);
175 }
176 }
177 plain
178 }
179
180 fn drop_image_markers(&self, text: &str) -> String {
187 const MARKER: &str = "<!-- image -->";
188 if !text.contains(MARKER) && !text.contains("```") {
189 return text.to_string();
190 }
191 text.split("\n\n")
195 .filter_map(|block| {
196 let lines: Vec<String> = block
197 .split('\n')
198 .filter_map(|line| {
199 if line.trim() == MARKER || is_fence_line(line.trim()) {
202 return None;
203 }
204 Some(line.replace(MARKER, &self.image_placeholder))
205 })
206 .collect();
207 (!lines.is_empty()).then(|| lines.join("\n"))
208 })
209 .collect::<Vec<_>>()
210 .join("\n\n")
211 }
212}
213
214pub fn to_markdown(doc: &DoclingDocument, strict: bool) -> String {
220 to_markdown_images(doc, strict, ImageMode::Placeholder, "artifacts").0
221}
222
223pub fn to_markdown_images(
227 doc: &DoclingDocument,
228 strict: bool,
229 images: ImageMode,
230 artifacts_dir: &str,
231) -> (String, Vec<(String, Vec<u8>)>) {
232 to_markdown_with_options(
233 doc,
234 strict,
235 &MarkdownExportOptions {
236 image_mode: images,
237 artifacts_dir: artifacts_dir.to_string(),
238 ..MarkdownExportOptions::default()
239 },
240 )
241}
242
243pub fn to_markdown_with_options(
247 doc: &DoclingDocument,
248 strict: bool,
249 options: &MarkdownExportOptions,
250) -> (String, Vec<(String, Vec<u8>)>) {
251 let mut ctx = Ctx::new(doc, strict, options);
252 let mut blocks: Vec<String> = Vec::new();
253 render(&doc.nodes, &mut blocks, &mut ctx);
254 let mut body = blocks.join("\n\n");
255 if strict && !options.plain_text && !doc.links.is_empty() {
259 body = apply_links(&body, &doc.links);
260 }
261 let front = if doc.metadata_output.front_matter() && !options.plain_text {
264 doc.metadata.to_front_matter()
265 } else {
266 String::new()
267 };
268 let md = match (front.is_empty(), body.is_empty()) {
269 (true, true) => String::new(),
270 (true, false) => format!("{body}\n"),
271 (false, true) => front,
272 (false, false) => format!("{front}\n{body}\n"),
273 };
274 (fallback_tags(md, options.plain_text), ctx.artifacts)
275}
276
277fn fallback_tags(md: String, plain: bool) -> String {
281 let mode = if plain {
282 crate::FormattingFallback::None
283 } else {
284 crate::FormattingFallback::Html
285 };
286 match crate::fallback::render(&md, mode) {
287 std::borrow::Cow::Borrowed(_) => md,
288 std::borrow::Cow::Owned(s) => s,
289 }
290}
291
292pub fn to_markdown_table_cell(doc: &DoclingDocument, strict: bool) -> String {
301 let mut ctx = Ctx::new(doc, strict, &MarkdownExportOptions::default());
302 ctx.in_table_cell = true;
303 ctx.artifacts_dir = String::new();
304 ctx.page_break = None;
308 let mut blocks: Vec<String> = Vec::new();
309 render(&doc.nodes, &mut blocks, &mut ctx);
310 blocks.join("\n\n")
311}
312
313fn apply_links(body: &str, links: &[(String, String)]) -> String {
321 let mut out = body.to_string();
322 let mut cursor = 0usize;
323 for (anchor, href) in links {
324 let anchor = anchor
325 .replace('&', "&")
326 .replace('<', "<")
327 .replace('>', ">");
328 if anchor.is_empty() {
329 continue;
330 }
331 if let Some(rel) = out[cursor..].find(&anchor) {
332 let at = cursor + rel;
333 let replacement = crate::hyperlink::markdown_link(&anchor, href);
336 out.replace_range(at..at + anchor.len(), &replacement);
337 cursor = at + replacement.len();
338 }
339 }
340 out
341}
342
343fn apply_links_chunk(chunk: &str, queue: &mut Vec<(String, String)>) -> String {
354 let mut out = chunk.to_string();
355 let mut cursor = 0usize;
356 let mut carried: Vec<(String, String)> = Vec::new();
357 for (anchor_raw, href) in std::mem::take(queue) {
358 let anchor = anchor_raw
359 .replace('&', "&")
360 .replace('<', "<")
361 .replace('>', ">");
362 if anchor.is_empty() {
363 continue;
364 }
365 if let Some(rel) = out[cursor..].find(&anchor) {
366 let at = cursor + rel;
367 let replacement = crate::hyperlink::markdown_link(&anchor, &href);
368 out.replace_range(at..at + anchor.len(), &replacement);
369 cursor = at + replacement.len();
370 } else {
371 carried.push((anchor_raw, href));
373 }
374 }
375 *queue = carried;
376 out
377}
378
379pub struct MarkdownStreamer {
397 strict: bool,
398 images: ImageMode,
399 compact_tables: bool,
400 picture_alt_text: bool,
402 front_matter: Option<String>,
406 emitted_any: bool,
409 links: Vec<(String, String)>,
411 artifacts_dir: String,
415 artifacts: Vec<(String, Vec<u8>)>,
416 pic_index: usize,
417 page_break: Option<String>,
421 pending_page_break: bool,
422 items_emitted: bool,
428 held: Option<Node>,
433 layers: ContentLayers,
436 traverse_pictures: bool,
437 escape_html: bool,
438 escape_underscores: bool,
439 image_placeholder: String,
440 plain: bool,
441}
442
443impl MarkdownStreamer {
444 pub fn new(strict: bool, images: ImageMode, compact_tables: bool) -> Self {
447 debug_assert!(
448 images != ImageMode::Referenced,
449 "referenced image mode needs an artifacts dir; use with_artifacts"
450 );
451 Self::with_artifacts(strict, images, compact_tables, "artifacts")
452 }
453
454 pub fn with_artifacts(
461 strict: bool,
462 images: ImageMode,
463 compact_tables: bool,
464 artifacts_dir: &str,
465 ) -> Self {
466 Self {
467 strict,
468 images,
469 compact_tables,
470 picture_alt_text: false,
471 front_matter: None,
472 emitted_any: false,
473 links: Vec::new(),
474 artifacts_dir: artifacts_dir.to_string(),
475 artifacts: Vec::new(),
476 pic_index: 0,
477 page_break: None,
478 pending_page_break: false,
479 items_emitted: false,
480 held: None,
481 layers: ContentLayers::BODY,
482 traverse_pictures: false,
483 escape_html: true,
484 escape_underscores: true,
485 image_placeholder: "<!-- image -->".to_string(),
486 plain: false,
487 }
488 }
489
490 pub fn with_export_options(mut self, options: &MarkdownExportOptions) -> Self {
497 self.images = options.image_mode;
498 self.artifacts_dir = options.artifacts_dir.clone();
499 self.layers = options.layers;
500 self.traverse_pictures = options.traverse_pictures;
501 self.escape_html = options.escape_html;
502 self.escape_underscores = options.escape_underscores;
503 self.image_placeholder = options.image_placeholder.clone();
504 self.plain = options.plain_text;
505 self
506 }
507
508 pub fn with_page_break_placeholder(mut self, placeholder: Option<String>) -> Self {
513 self.page_break = placeholder;
514 self
515 }
516
517 pub fn with_picture_alt_text(mut self, on: bool) -> Self {
521 self.picture_alt_text = on;
522 self
523 }
524
525 pub fn with_metadata(mut self, metadata: &crate::metadata::DocumentMetadata) -> Self {
530 self.front_matter = (!self.plain)
531 .then(|| metadata.to_front_matter())
532 .filter(|f| !f.is_empty());
533 self
534 }
535
536 pub fn take_artifacts(&mut self) -> Vec<(String, Vec<u8>)> {
541 std::mem::take(&mut self.artifacts)
542 }
543
544 pub fn push(&mut self, nodes: &[Node], links: &[(String, String)]) -> String {
549 self.push_holding(nodes, links, true)
550 }
551
552 fn push_holding(&mut self, nodes: &[Node], links: &[(String, String)], hold: bool) -> String {
555 self.links.extend(links.iter().cloned());
556 let images = self.images;
560 let ends_on_picture = |nodes: &[Node]| {
561 matches!(images, ImageMode::Placeholder)
562 && matches!(nodes.last(), Some(Node::Picture { .. }))
563 };
564 let mut owned: Vec<Node> = Vec::new();
565 let mut nodes = nodes;
566 if self.held.is_some() || (hold && ends_on_picture(nodes)) {
567 owned.extend(self.held.take());
568 owned.extend(nodes.iter().cloned());
569 if hold && ends_on_picture(&owned) {
570 self.held = owned.pop();
571 }
572 nodes = &owned;
573 }
574 let mut ctx = Ctx {
575 strict: self.strict,
576 alt_text: self.strict || self.picture_alt_text,
577 compact_tables: self.compact_tables,
578 images: self.images,
579 artifacts_dir: std::mem::take(&mut self.artifacts_dir),
580 artifacts: std::mem::take(&mut self.artifacts),
581 pic_index: self.pic_index,
582 in_table_cell: false,
583 page_break: std::mem::take(&mut self.page_break),
584 pending_page_break: self.pending_page_break,
585 emitted_any: self.items_emitted,
586 layers: self.layers,
587 current_layer: None,
588 traverse_pictures: self.traverse_pictures,
589 escape_html: self.escape_html,
590 escape_underscores: self.escape_underscores,
591 image_placeholder: std::mem::take(&mut self.image_placeholder),
592 plain: self.plain,
593 };
594 let mut blocks: Vec<String> = Vec::new();
595 render(nodes, &mut blocks, &mut ctx);
596 self.image_placeholder = std::mem::take(&mut ctx.image_placeholder);
597 self.artifacts_dir = std::mem::take(&mut ctx.artifacts_dir);
598 self.artifacts = std::mem::take(&mut ctx.artifacts);
599 self.pic_index = ctx.pic_index;
600 self.page_break = std::mem::take(&mut ctx.page_break);
601 self.pending_page_break = ctx.pending_page_break;
602 self.items_emitted = ctx.emitted_any;
603 if blocks.is_empty() {
604 return String::new();
605 }
606 let mut body = blocks.join("\n\n");
607 if self.strict && !self.plain && !self.links.is_empty() {
608 body = apply_links_chunk(&body, &mut self.links);
609 }
610 let chunk = if let Some(front) = self.front_matter.take() {
611 format!("{front}\n{body}")
612 } else if self.emitted_any {
613 format!("\n\n{body}")
614 } else {
615 body
616 };
617 self.emitted_any = true;
618 fallback_tags(chunk, self.plain)
619 }
620
621 pub fn finish(mut self) -> String {
624 let mut out = String::new();
625 if self.held.is_some() {
626 out.push_str(&self.push_holding(&[], &[], false));
627 }
628 if let Some(front) = self.front_matter {
629 out.push_str(&front);
630 } else if self.emitted_any {
631 out.push('\n');
632 }
633 out
634 }
635}
636
637fn strict_text(text: &str, strict: bool) -> String {
645 if !strict {
646 return text.to_string();
647 }
648 if let Some(rest) = text.strip_prefix("[ ] ") {
651 return format!("[ ] {}", strict_text(rest, strict));
652 }
653 text.replace("\\_", "_")
654 .replace(" ,", ",")
655 .replace(" .", ".")
656 .replace(" ;", ";")
657 .replace(" )", ")")
658 .replace("( ", "(")
659 .replace(" ]", "]")
660 .replace("[ ", "[")
661}
662
663pub fn longest_backtick_run(text: &str) -> usize {
666 let (mut best, mut run) = (0, 0);
667 for c in text.chars() {
668 if c == '`' {
669 run += 1;
670 best = best.max(run);
671 } else {
672 run = 0;
673 }
674 }
675 best
676}
677
678pub fn code_span(text: &str) -> String {
684 let ticks = "`".repeat(longest_backtick_run(text) + 1);
685 let pad = if text.starts_with('`') || text.ends_with('`') || needs_space_pad(text) {
686 " "
687 } else {
688 ""
689 };
690 format!("{ticks}{pad}{text}{pad}{ticks}")
691}
692
693fn needs_space_pad(text: &str) -> bool {
699 let normalized = text.replace("\r\n", "\n").replace(['\r', '\n'], " ");
700 normalized.starts_with(' ')
701 && normalized.ends_with(' ')
702 && !normalized.trim_matches(' ').is_empty()
703}
704
705pub fn code_fence(language: &str, body: &str) -> String {
710 let fence = "`".repeat(longest_backtick_run(body).max(2) + 1);
711 format!("{fence}{language}\n{body}\n{fence}")
712}
713
714pub(crate) fn code_span_bounds(chars: &[char], i: usize) -> Option<(usize, usize, usize)> {
723 let n = chars[i..].iter().take_while(|&&c| c == '`').count();
724 if n == 0 {
725 return None;
726 }
727 let mut k = i + n;
728 while k < chars.len() {
729 if chars[k] != '`' {
730 k += 1;
731 continue;
732 }
733 let run = chars[k..].iter().take_while(|&&c| c == '`').count();
734 if run == n {
735 let (mut s, mut e) = (i + n, k);
736 let space = |c: char| matches!(c, ' ' | '\n' | '\r');
737 if e - s >= 2
738 && space(chars[s])
739 && space(chars[e - 1])
740 && chars[s..e].iter().any(|&c| !space(c))
741 {
742 s += 1;
743 e -= 1;
744 }
745 return Some((s, e, k + run));
746 }
747 k += run;
748 }
749 None
750}
751
752fn is_fence_line(line: &str) -> bool {
754 line.len() >= 3 && line.bytes().all(|b| b == b'`')
755}
756
757pub(crate) fn plain_inline(text: &str) -> String {
770 if !text.contains(['*', '~', '`', '[']) {
771 return text.to_string();
772 }
773 let chars: Vec<char> = text.chars().collect();
774 let mut out = String::with_capacity(text.len());
775 plain_inline_into(&chars, &mut out);
776 out
777}
778
779fn plain_inline_into(chars: &[char], out: &mut String) {
780 let find = |open: usize, pat: &[char]| -> Option<usize> {
783 chars
784 .get(open..)?
785 .windows(pat.len())
786 .enumerate()
787 .position(|(k, w)| w == pat && (open + k == 0 || chars[open + k - 1] != '\\'))
788 .map(|p| open + p)
789 };
790 let span = |i: usize, pat: &[char]| -> Option<usize> {
793 if !chars[i..].starts_with(pat) {
794 return None;
795 }
796 let open = i + pat.len();
797 let end = find(open, pat)?;
798 (end > open && !chars[open].is_whitespace() && !chars[end - 1].is_whitespace())
799 .then_some(end)
800 };
801 let mut i = 0;
802 while i < chars.len() {
803 if chars[i] == '\\' && chars.get(i + 1) == Some(&'*') {
805 out.push('*');
806 i += 2;
807 continue;
808 }
809 let mut matched = false;
810 for pat in [&['*', '*', '*'][..], &['*', '*'], &['~', '~'], &['*']] {
811 if let Some(end) = span(i, pat) {
812 plain_inline_into(&chars[i + pat.len()..end], out);
813 i = end + pat.len();
814 matched = true;
815 break;
816 }
817 }
818 if matched {
819 continue;
820 }
821 if chars[i] == '`' {
825 if let Some((s, e, after)) = code_span_bounds(chars, i).filter(|&(s, e, _)| {
826 e > s && !chars[s].is_whitespace() && !chars[e - 1].is_whitespace()
827 }) {
828 out.extend(&chars[s..e]);
829 i = after;
830 continue;
831 }
832 }
833 if chars[i] == '$' {
836 if let Some(end) = find(i + 1, &['$']) {
837 out.extend(&chars[i..=end]);
838 i = end + 1;
839 continue;
840 }
841 }
842 if chars[i] == '[' {
845 if let Some(close) = closing_bracket(chars, i) {
846 if chars.get(close + 1) == Some(&'(') {
847 if let Some(endp) = crate::doclang::link_dest_end(chars, close + 2) {
848 plain_inline_into(&chars[i + 1..close], out);
849 i = endp + 1;
850 continue;
851 }
852 }
853 }
854 }
855 let c = chars[i];
858 out.push(c);
859 i += 1;
860 if matches!(c, '*' | '~') {
861 while i < chars.len() && chars[i] == c {
862 out.push(c);
863 i += 1;
864 }
865 }
866 }
867}
868
869fn closing_bracket(chars: &[char], open: usize) -> Option<usize> {
872 let mut depth = 0usize;
873 for (k, c) in chars.iter().enumerate().skip(open + 1) {
874 match c {
875 '[' => depth += 1,
876 ']' if depth == 0 => return Some(k),
877 ']' => depth -= 1,
878 _ => {}
879 }
880 }
881 None
882}
883
884fn md_line_breaks(text: &str) -> String {
892 if !text.contains('\n') {
893 return text.to_string();
894 }
895 text.split("\n\n")
896 .map(|para| para.replace('\n', " \n"))
897 .collect::<Vec<_>>()
898 .join("\n\n")
899}
900
901pub(crate) fn strip_hard_breaks(text: &str) -> String {
906 if text.contains(" \n") {
907 text.replace(" \n", "\n")
908 } else {
909 text.to_string()
910 }
911}
912
913fn heading_line_breaks(text: &str) -> String {
917 text.replace('\n', " ")
918}
919
920fn render(nodes: &[Node], blocks: &mut Vec<String>, ctx: &mut Ctx) {
921 let mut i = 0;
922 while i < nodes.len() {
923 let before = blocks.len();
924 match &nodes[i] {
925 Node::PageBreak | Node::PageInfo { .. } => {
935 if ctx.page_break.is_some() && ctx.emitted_any {
936 ctx.pending_page_break = true;
937 }
938 i += 1;
939 }
940 Node::ListItem { .. } => {
941 let start = i;
942 i += 1;
943 loop {
944 match nodes.get(i) {
945 Some(Node::ListItem { .. } | Node::ListText { .. }) => i += 1,
946 Some(Node::Paragraph { text })
950 if text.is_empty()
951 && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
952 {
953 i += 1
954 }
955 _ => break,
956 }
957 }
958 render_list_run(&nodes[start..i], blocks, ctx);
959 }
960 other => {
961 let before_item = blocks.len();
962 render_one(other, blocks, ctx);
963 if matches!(other, Node::Picture { .. })
969 && matches!(ctx.images, ImageMode::Placeholder)
970 && blocks.len() > before_item
971 && matches!(
972 nodes.get(i + 1),
973 Some(Node::Code { language: Some(l), .. }) if l == "mermaid"
974 )
975 {
976 blocks.pop();
977 }
978 i += 1;
979 }
980 }
981 if blocks.len() > before {
982 let kept: Vec<String> = blocks.drain(before..).filter(|b| !b.is_empty()).collect();
992 blocks.extend(kept);
993 if ctx.pending_page_break {
994 if let Some(placeholder) = &ctx.page_break {
999 blocks.insert(before, placeholder.clone());
1000 }
1001 ctx.pending_page_break = false;
1002 }
1003 ctx.emitted_any = true;
1004 }
1005 }
1006}
1007
1008fn render_list_run(items: &[Node], blocks: &mut Vec<String>, ctx: &Ctx) {
1014 let mut lines: Vec<String> = Vec::new();
1015 let mut any_top = false;
1018
1019 for item in items {
1020 if let Node::ListText { level, text, glue } = item {
1021 let text = ctx.text(text);
1022 match lines.last_mut() {
1023 Some(last) if *glue => last.push_str(&text),
1024 _ => lines.push(format!("{}{text}", " ".repeat(*level as usize))),
1025 }
1026 continue;
1027 }
1028 let Node::ListItem {
1029 ordered,
1030 number,
1031 first_in_list,
1032 text,
1033 level,
1034 marker: orig_marker,
1035 location: _,
1036 dclx: _,
1037 split: _,
1038 href: _,
1039 layer,
1040 } = item
1041 else {
1042 continue;
1043 };
1044 if !ctx.layers.contains(layer.or(ctx.current_layer)) {
1048 continue;
1049 }
1050 let level = *level as usize;
1051
1052 if level == 0 {
1061 if any_top && *first_in_list {
1062 lines.push(String::new());
1063 }
1064 any_top = true;
1065 }
1066
1067 let indent = " ".repeat(level);
1068 lines.push(format!(
1069 "{indent}{} {}",
1070 list_item_marker(orig_marker.as_deref().unwrap_or(""), *ordered, *number),
1071 list_item_text(text, ctx)
1072 ));
1073 }
1074
1075 if !lines.is_empty() {
1078 blocks.push(lines.join("\n"));
1079 }
1080}
1081
1082fn list_item_marker(marker: &str, ordered: bool, number: u64) -> String {
1091 let already_valid = matches!(marker, "-" | "*" | "+")
1092 || marker
1093 .strip_suffix('.')
1094 .is_some_and(|d| !d.is_empty() && d.chars().all(char::is_numeric));
1095 if already_valid {
1096 return marker.to_string();
1097 }
1098 let outer = if ordered && marker.is_empty() {
1099 format!("{number}.")
1100 } else {
1101 "-".to_string()
1102 };
1103 if marker.chars().any(char::is_alphanumeric) {
1104 format!("{outer} {marker}")
1105 } else {
1106 outer
1107 }
1108}
1109
1110fn list_item_text(text: &str, ctx: &Ctx) -> String {
1118 let escaped = ctx.text(text);
1119 if ctx.plain {
1120 return escaped;
1121 }
1122 if let Some((own, tail)) = escaped.split_once('\n') {
1123 if is_folded_child_tail(tail) {
1124 return format!("{}\n{tail}", md_line_breaks(own));
1125 }
1126 }
1127 md_line_breaks(&escaped)
1128}
1129
1130fn is_folded_child_tail(tail: &str) -> bool {
1137 const MARKER: &str = "<!-- image -->";
1138 let mut lines = tail.split('\n').peekable();
1139 let mut any = false;
1140 while let Some(line) = lines.next() {
1141 let line = line.trim_start();
1142 if line == MARKER {
1143 any = true;
1144 } else if is_fence_line(line) {
1145 loop {
1148 match lines.next() {
1149 Some(l) if l.trim_start() == line => break,
1150 Some(_) => {}
1151 None => return false,
1152 }
1153 }
1154 any = true;
1155 } else if lines.next().map(str::trim_start) == Some(MARKER) {
1156 any = true; } else {
1158 return false;
1159 }
1160 }
1161 any
1162}
1163
1164fn render_one(node: &Node, blocks: &mut Vec<String>, ctx: &mut Ctx) {
1169 match node {
1170 Node::Group { .. }
1172 | Node::Furniture { .. }
1173 | Node::PageFurniture { .. }
1174 | Node::FurnitureText { .. }
1175 | Node::CommentSection { .. }
1176 | Node::PictureChildren(_)
1177 | Node::Commented { .. }
1178 | Node::ScriptText { .. }
1179 | Node::Located { .. }
1180 | Node::Prov { .. }
1181 | Node::Track { .. }
1182 | Node::PageBreak
1183 | Node::PageInfo { .. }
1184 | Node::ProvContinuation { .. }
1185 | Node::DoclangOnly(_) => {}
1186 _ if !ctx.layer_visible() => return,
1187 _ => {}
1188 }
1189 render_item(node, blocks, ctx)
1190}
1191
1192fn render_item(node: &Node, blocks: &mut Vec<String>, ctx: &mut Ctx) {
1193 match node {
1194 Node::Heading { level, text } => {
1195 if ctx.plain {
1196 blocks.push(ctx.text(text));
1199 return;
1200 }
1201 let text = heading_line_breaks(&ctx.text(text));
1202 if ctx.in_table_cell {
1203 blocks.push(text);
1205 } else {
1206 let hashes = "#".repeat((*level).clamp(1, 6) as usize);
1207 blocks.push(format!("{hashes} {text}"));
1208 }
1209 }
1210 Node::Paragraph { text } if text.is_empty() => {}
1213 Node::Paragraph { text } => blocks.push(ctx.breaks(&ctx.text(text))),
1214 Node::LabeledText { .. } => render_item(&node.labeled_as_paragraph(), blocks, ctx),
1215 Node::Caption { text, .. } if text.is_empty() => {}
1218 Node::Caption { text, href } => {
1219 let body = ctx.breaks(&ctx.text(text));
1220 blocks.push(match href {
1221 Some(url) if !ctx.plain => crate::hyperlink::markdown_link(&body, url),
1222 _ => body,
1223 });
1224 }
1225 Node::CheckboxItem { checked, text } => {
1226 let mark = if *checked { "- [x]" } else { "- [ ]" };
1229 let sep = if text.starts_with(' ') { "" } else { " " };
1230 blocks.push(ctx.breaks(&ctx.text(&format!("{mark}{sep}{text}"))));
1231 }
1232 Node::Code {
1233 language,
1234 text,
1235 pretty,
1236 ..
1237 } => {
1238 let lang = match language {
1243 Some(l) if ctx.strict || l == "mermaid" => l.as_str(),
1244 _ => "",
1245 };
1246 let body = match pretty {
1249 Some(p) if ctx.strict => p.as_str(),
1250 _ => text.as_str(),
1251 };
1252 blocks.push(if ctx.plain {
1255 body.to_string()
1256 } else {
1257 code_fence(lang, body)
1258 });
1259 }
1260 Node::Formula { latex, orig, .. } => {
1266 if !latex.is_empty() {
1267 blocks.push(format!("$${latex}$$"));
1268 } else if !orig.is_empty() {
1269 blocks.push(FORMULA_NOT_DECODED.to_string());
1270 }
1271 }
1272 Node::Table(table) => {
1273 if let Some(cap) = &table.caption {
1276 if !cap.is_empty() {
1277 blocks.push(ctx.text(cap));
1278 }
1279 }
1280 let rendered = if ctx.plain {
1281 render_table(&ctx.plain_table(table), ctx.compact_tables)
1282 } else {
1283 render_table(table, ctx.compact_tables)
1284 };
1285 if !rendered.is_empty() {
1286 blocks.push(rendered);
1287 }
1288 for note in table.footnotes.iter().filter(|n| !n.is_empty()) {
1291 blocks.push(ctx.text(note));
1292 }
1293 }
1294 Node::Picture {
1303 caption,
1304 image,
1305 description,
1306 ..
1307 } => {
1308 if let Some(cap) = caption {
1309 if !cap.is_empty() {
1310 blocks.push(ctx.caption(cap));
1311 }
1312 }
1313 let alt = description
1314 .as_ref()
1315 .filter(|d| d.is_alt_text() && ctx.alt_text && !d.text.is_empty());
1316 let marker = picture_marker(image.as_ref(), ctx, alt.map(|d| d.text.as_str()));
1317 let native = description
1321 .as_ref()
1322 .filter(|d| d.is_docling_meta() && !d.text.is_empty());
1323 if let Some(desc) = description.as_ref().filter(|d| !d.is_docling_meta()) {
1324 let shown = !desc.is_alt_text() || (ctx.alt_text && !marker.starts_with("!["));
1325 if !desc.text.is_empty() && shown {
1326 blocks.push(ctx.breaks(&ctx.text(&desc.text)));
1327 }
1328 }
1329 blocks.push(marker);
1330 if let Some(desc) = native {
1331 blocks.push(ctx.breaks(&ctx.text(&desc.text)));
1332 }
1333 }
1334 Node::Chart {
1338 kind,
1339 table,
1340 caption,
1341 ..
1342 } => {
1343 if let Some(cap) = caption {
1344 if !cap.is_empty() {
1345 blocks.push(ctx.caption(cap));
1346 }
1347 }
1348 blocks.push(picture_marker(None, ctx, None));
1349 blocks.push(humanize_label(kind));
1350 let rendered = if ctx.plain {
1351 render_table(&ctx.plain_table(table), false)
1352 } else {
1353 render_table(table, false)
1354 };
1355 if !rendered.is_empty() {
1356 blocks.push(rendered);
1357 }
1358 }
1359 Node::DoclangOnly(_) => {}
1361 Node::Group {
1366 layer: Some(layer),
1367 children,
1368 ..
1369 } => {
1370 let outer = ctx.current_layer.replace(*layer);
1371 render(children, blocks, ctx);
1372 ctx.current_layer = outer;
1373 }
1374 Node::Group { children, .. } => render(children, blocks, ctx),
1375 Node::FieldRegion { items } => {
1376 for item in items {
1381 for part in [&item.marker, &item.key, &item.value].into_iter().flatten() {
1382 blocks.push(ctx.breaks(&ctx.text(part)));
1383 }
1384 }
1385 }
1386 Node::KeyValueGraph { .. } => blocks.push(MISSING_KEY_VALUE_ITEM.to_string()),
1389 Node::InlineGroup { md_text, .. } => blocks.push(ctx.breaks(&ctx.text(md_text))),
1392 Node::TextDump(text) => {
1394 if !text.is_empty() {
1395 blocks.push(text.clone());
1396 }
1397 }
1398 Node::Furniture { layer, inner } => {
1402 let outer = ctx.current_layer.replace(*layer);
1403 render_one(inner, blocks, ctx);
1404 ctx.current_layer = outer;
1405 }
1406 Node::PageFurniture { text, .. } | Node::FurnitureText { text, .. } => {
1410 if ctx.layers.furniture && !text.is_empty() {
1411 blocks.push(ctx.breaks(&ctx.text(text)));
1412 }
1413 }
1414 Node::PictureChildren(children) => {
1419 if ctx.traverse_pictures {
1420 render(children, blocks, ctx);
1421 }
1422 }
1423 Node::CommentSection { text, .. } => {
1428 if ctx.layers.notes && !text.is_empty() {
1429 blocks.push(ctx.breaks(&ctx.text(text)));
1430 }
1431 }
1432 Node::Commented { inner, .. } => render_one(inner, blocks, ctx),
1433 Node::ScriptText { inner, .. } => render_one(inner, blocks, ctx),
1436 Node::Located { inner, .. } | Node::Prov { inner, .. } | Node::Track { inner, .. } => {
1438 render_one(inner, blocks, ctx)
1439 }
1440 Node::PageBreak => {}
1442 Node::PageInfo { .. } | Node::ProvContinuation { .. } => {}
1444 Node::Anchor { .. } => {}
1446 Node::ListItem { .. } => render_list_run(std::slice::from_ref(node), blocks, ctx),
1451 Node::ListText { text, .. } if text.is_empty() => {}
1453 Node::ListText { text, .. } => blocks.push(ctx.breaks(&ctx.text(text))),
1454 }
1455}
1456
1457fn humanize_label(label: &str) -> String {
1462 let text = label.replace('_', " ");
1463 let mut chars = text.chars();
1464 match chars.next() {
1465 Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
1466 None => text,
1467 }
1468}
1469
1470fn image_alt(alt: Option<&str>) -> String {
1473 match alt {
1474 Some(text) => text
1475 .split_whitespace()
1476 .collect::<Vec<_>>()
1477 .join(" ")
1478 .replace('\\', "\\\\")
1479 .replace(']', "\\]"),
1480 None => "Image".to_string(),
1481 }
1482}
1483
1484fn picture_marker(image: Option<&crate::PictureImage>, ctx: &mut Ctx, alt: Option<&str>) -> String {
1485 match (ctx.images, image) {
1486 (ImageMode::Embedded, Some(img)) => {
1488 format!(
1489 "",
1490 image_alt(alt),
1491 crate::pixel_digest::docling_data_uri(img).1
1492 )
1493 }
1494 (ImageMode::Referenced, Some(img)) => {
1495 let path = format!(
1496 "{}/image_{:06}.{}",
1497 ctx.artifacts_dir,
1498 ctx.pic_index,
1499 ext_for(&img.mimetype)
1500 );
1501 ctx.pic_index += 1;
1502 ctx.artifacts.push((path.clone(), img.data.clone()));
1503 format!("", image_alt(alt), escape_uri_path(&path))
1504 }
1505 _ => ctx.image_placeholder.clone(),
1507 }
1508}
1509
1510pub(crate) fn escape_uri_path(value: &str) -> String {
1523 const KEEP: &str = "/%:@+,;=~$!&'*";
1524 let s = value.replace('\\', "/");
1525 if let Some(rest) = s.strip_prefix("//") {
1526 let rest = rest.trim_start_matches('/');
1528 let (host, tail) = rest.split_once('/').unwrap_or((rest, ""));
1529 return format!("file://{host}{}", percent_quote(&format!("/{tail}"), KEEP));
1530 }
1531 let bytes = s.as_bytes();
1532 if bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && bytes[2] == b'/' {
1533 return format!("file:///{}", percent_quote(&s, KEEP));
1535 }
1536 if let Some((scheme, rest)) = s.split_once(':') {
1540 let valid_scheme = scheme.len() > 1
1541 && scheme.as_bytes()[0].is_ascii_alphabetic()
1542 && scheme
1543 .bytes()
1544 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'));
1545 if valid_scheme {
1546 let (authority, rest) = match rest.strip_prefix("//") {
1547 Some(r) => {
1548 let end = r.find(['/', '?', '#']).unwrap_or(r.len());
1549 (Some(&r[..end]), &r[end..])
1550 }
1551 None => (None, rest),
1552 };
1553 let (before_frag, fragment) = rest.split_once('#').unwrap_or((rest, ""));
1554 let (path, query) = before_frag.split_once('?').unwrap_or((before_frag, ""));
1555 let mut out = format!("{scheme}:");
1556 if let Some(a) = authority {
1557 out.push_str("//");
1558 out.push_str(a);
1559 }
1560 out.push_str(&percent_quote(path, KEEP));
1561 if !query.is_empty() {
1562 out.push('?');
1563 out.push_str(&percent_quote(query, KEEP));
1564 }
1565 if !fragment.is_empty() {
1566 out.push('#');
1567 out.push_str(&percent_quote(fragment, KEEP));
1568 }
1569 return out;
1570 }
1571 }
1572 percent_quote(&s, KEEP)
1574}
1575
1576fn percent_quote(s: &str, safe: &str) -> String {
1579 let mut out = String::with_capacity(s.len());
1580 for &b in s.as_bytes() {
1581 let keep = b.is_ascii_alphanumeric()
1582 || matches!(b, b'_' | b'.' | b'-' | b'~')
1583 || (b.is_ascii() && safe.contains(b as char));
1584 if keep {
1585 out.push(b as char);
1586 } else {
1587 out.push_str(&format!("%{b:02X}"));
1588 }
1589 }
1590 out
1591}
1592
1593pub(crate) fn ext_for(mimetype: &str) -> &str {
1594 match mimetype {
1595 "image/jpeg" => "jpg",
1596 "image/gif" => "gif",
1597 "image/webp" => "webp",
1598 "image/bmp" => "bmp",
1599 "image/tiff" => "tif",
1600 "image/svg+xml" => "svg",
1601 _ => "png",
1602 }
1603}
1604
1605fn is_number_cell(t: &str) -> bool {
1624 t.parse::<f64>().is_ok() || is_thousands_number(t)
1625}
1626
1627fn is_thousands_number(t: &str) -> bool {
1633 let b = t.as_bytes();
1634 let mut i = 0;
1635 let start = i;
1636 if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
1637 i += 1;
1638 }
1639 let d0 = i;
1641 while i < b.len() && b[i].is_ascii_digit() && i - d0 < 3 {
1642 i += 1;
1643 }
1644 let has_int = i > d0;
1645 if has_int {
1646 while i + 3 < b.len() + 1
1648 && b.get(i) == Some(&b',')
1649 && b.get(i + 1).is_some_and(u8::is_ascii_digit)
1650 && b.get(i + 2).is_some_and(u8::is_ascii_digit)
1651 && b.get(i + 3).is_some_and(u8::is_ascii_digit)
1652 {
1653 i += 4;
1654 }
1655 } else {
1656 i = start;
1658 }
1659 if i < b.len() && b[i] == b'.' {
1661 i += 1;
1662 let f0 = i;
1663 while i < b.len() && b[i].is_ascii_digit() {
1664 i += 1;
1665 }
1666 if !has_int && i == f0 {
1667 return false; }
1669 } else if !has_int {
1670 return false; }
1672 i == b.len()
1673}
1674
1675fn flatten_header_rows(header_rows: &[Vec<String>], num_cols: usize) -> Vec<String> {
1684 (0..num_cols)
1685 .map(|c| {
1686 let mut parts: Vec<&str> = Vec::new();
1687 for row in header_rows {
1688 let text = row.get(c).map(String::as_str).unwrap_or("");
1689 if !text.is_empty() && parts.last() != Some(&text) {
1690 parts.push(text);
1691 }
1692 }
1693 parts.join(" - ")
1694 })
1695 .collect()
1696}
1697
1698pub(crate) const FORMULA_NOT_DECODED: &str = "<!-- formula-not-decoded -->";
1701
1702pub(crate) fn render_table(table: &Table, compact: bool) -> String {
1703 if table.rows.is_empty() {
1704 return String::new();
1705 }
1706 let num_cols = table.rows.iter().map(Vec::len).max().unwrap_or(0);
1707 if num_cols == 0 {
1708 return String::new();
1709 }
1710
1711 let num_headers = table.header_row_count().min(table.rows.len());
1716 let escaped = |r: usize| -> Vec<String> {
1719 (0..num_cols)
1720 .map(|c| {
1721 let cell = table.rows[r].get(c).map(String::as_str).unwrap_or("");
1722 escape_cell(&crate::fallback::render(
1723 cell,
1724 crate::FormattingFallback::Html,
1725 ))
1726 })
1727 .collect()
1728 };
1729 let header_rows: Vec<Vec<String>> = (0..num_headers).map(escaped).collect();
1730 let header = flatten_header_rows(&header_rows, num_cols);
1731 let body: Vec<Vec<String>> = (num_headers..table.rows.len())
1732 .map(|r| {
1733 escaped(r)
1734 .into_iter()
1735 .map(|c| c.trim().to_string())
1736 .collect()
1737 })
1738 .collect();
1739
1740 if compact {
1741 let render_row = |row: &[String]| -> String { format!("| {} |", row.join(" | ")) };
1743 let mut lines = Vec::with_capacity(body.len() + 2);
1744 lines.push(render_row(&header));
1745 let sep: Vec<&str> = (0..num_cols).map(|_| "-").collect();
1746 lines.push(format!("| {} |", sep.join(" | ")));
1747 for row in &body {
1748 lines.push(render_row(row));
1749 }
1750 return lines.join("\n");
1751 }
1752
1753 let dw = |s: &str| s.chars().count();
1755
1756 let right: Vec<bool> = (0..num_cols)
1761 .map(|c| {
1762 let mut any = false;
1763 for row in &body {
1764 let t = row[c].trim();
1765 if t.is_empty() {
1766 continue;
1767 }
1768 if !is_number_cell(t) {
1769 return false;
1770 }
1771 any = true;
1772 }
1773 any
1774 })
1775 .collect();
1776
1777 let width: Vec<usize> = (0..num_cols)
1779 .map(|c| {
1780 let mut w = dw(&header[c]) + 2;
1781 for row in &body {
1782 w = w.max(dw(&row[c]));
1783 }
1784 w
1785 })
1786 .collect();
1787
1788 let fmt_cell = |s: &str, c: usize| -> String {
1789 let pad = " ".repeat(width[c].saturating_sub(dw(s)));
1790 let body = if right[c] {
1791 format!("{pad}{s}")
1792 } else {
1793 format!("{s}{pad}")
1794 };
1795 format!(" {body} ")
1796 };
1797 let render_row = |row: &[String]| -> String {
1798 let cells: Vec<String> = (0..num_cols).map(|c| fmt_cell(&row[c], c)).collect();
1799 format!("|{}|", cells.join("|"))
1800 };
1801
1802 let mut lines = Vec::with_capacity(body.len() + 2);
1803 lines.push(render_row(&header));
1804 let sep: Vec<String> = (0..num_cols).map(|c| "-".repeat(width[c] + 2)).collect();
1805 lines.push(format!("|{}|", sep.join("|")));
1806 for row in &body {
1807 lines.push(render_row(row));
1808 }
1809 lines.join("\n")
1810}
1811
1812fn escape_cell(s: &str) -> String {
1815 s.replace('\n', " ").replace('|', "|")
1816}
1817
1818#[cfg(test)]
1819mod tests {
1820 use super::*;
1821 use crate::{PictureImage, TableCell, TableStructure};
1822
1823 #[test]
1828 fn an_undecoded_formula_prints_the_placeholder() {
1829 let formula = |latex: &str, orig: &str| Node::Formula {
1830 latex: latex.into(),
1831 orig: orig.into(),
1832 location: None,
1833 };
1834 let mut doc = DoclingDocument::new("t");
1835 doc.nodes = vec![
1836 formula("E = mc^2", "E = mc 2"),
1837 formula("", "E = mc 2"),
1838 formula("", ""),
1839 Node::Paragraph {
1840 text: "After.".into(),
1841 },
1842 ];
1843 assert_eq!(
1844 doc.export_to_markdown().trim(),
1845 "$$E = mc^2$$\n\n<!-- formula-not-decoded -->\n\nAfter."
1846 );
1847 let chunks: Vec<String> = crate::chunker::HierarchicalChunker
1848 .chunk(&doc)
1849 .into_iter()
1850 .map(|c| c.text)
1851 .collect();
1852 assert_eq!(
1853 chunks,
1854 ["$$E = mc^2$$", "<!-- formula-not-decoded -->", "After."]
1855 );
1856 }
1857
1858 #[test]
1864 fn list_boundaries_come_from_the_backend_not_the_numbering() {
1865 let item = |ordered: bool, number: u64, first_in_list: bool, text: &str| Node::ListItem {
1866 ordered,
1867 number,
1868 first_in_list,
1869 text: text.into(),
1870 level: 0,
1871 marker: None,
1872 location: None,
1873 split: None,
1874 dclx: None,
1875 href: None,
1876 layer: None,
1877 };
1878 let md = |items: Vec<Node>| {
1879 let mut doc = DoclingDocument::new("t");
1880 for n in items {
1881 doc.push(n);
1882 }
1883 doc.export_to_markdown()
1884 };
1885 assert_eq!(
1887 md(vec![
1888 item(true, 1, true, "one"),
1889 item(true, 5, false, "five")
1890 ]),
1891 "1. one\n5. five\n"
1892 );
1893 assert_eq!(
1895 md(vec![
1896 item(false, 0, true, "bullet"),
1897 item(true, 1, false, "one"),
1898 item(false, 0, false, "bullet two"),
1899 ]),
1900 "- bullet\n1. one\n- bullet two\n"
1901 );
1902 assert_eq!(
1904 md(vec![
1905 item(true, 1, true, "a"),
1906 item(true, 2, false, "b"),
1907 item(true, 3, true, "new list, continuing count"),
1908 ]),
1909 "1. a\n2. b\n\n3. new list, continuing count\n"
1910 );
1911 }
1912
1913 #[test]
1914 fn renders_headings_paragraphs_and_lists() {
1915 let mut doc = DoclingDocument::new("demo");
1916 doc.add_heading(1, "Title");
1917 doc.add_paragraph("Hello world.");
1918 doc.push(Node::ListItem {
1919 ordered: false,
1920 number: 1,
1921 first_in_list: true,
1922 text: "first".into(),
1923 level: 0,
1924 marker: None,
1925 location: None,
1926 split: None,
1927 dclx: None,
1928 href: None,
1929 layer: None,
1930 });
1931 doc.push(Node::ListItem {
1932 ordered: false,
1933 number: 2,
1934 first_in_list: false,
1935 text: "second".into(),
1936 level: 0,
1937 marker: None,
1938 location: None,
1939 split: None,
1940 dclx: None,
1941 href: None,
1942 layer: None,
1943 });
1944 let md = doc.export_to_markdown();
1945 assert_eq!(md, "# Title\n\nHello world.\n\n- first\n- second\n");
1946 }
1947
1948 #[test]
1952 fn single_newlines_become_gfm_hard_line_breaks() {
1953 let mut doc = DoclingDocument::new("t");
1954 doc.push(Node::Heading {
1955 level: 1,
1956 text: "Hello\nWorld".into(),
1957 });
1958 doc.push(Node::Paragraph {
1959 text: "line one\nline two\n\npara two".into(),
1960 });
1961 doc.push(Node::ListItem {
1962 ordered: false,
1963 number: 1,
1964 first_in_list: true,
1965 text: "item\ncontinued".into(),
1966 level: 0,
1967 marker: None,
1968 location: None,
1969 split: None,
1970 dclx: None,
1971 href: None,
1972 layer: None,
1973 });
1974 doc.push(Node::TextDump("A1 B1 \n\n\nC1".into()));
1975 assert_eq!(
1976 doc.export_to_markdown(),
1977 "# Hello World\n\nline one \nline two\n\npara two\n\n- item \ncontinued\n\nA1 B1 \n\n\nC1\n"
1978 );
1979 }
1980
1981 #[test]
1984 fn table_cell_mode_and_field_regions() {
1985 let mut doc = DoclingDocument::new("t");
1986 doc.push(Node::Heading {
1987 level: 2,
1988 text: "A text".into(),
1989 });
1990 doc.push(Node::Paragraph {
1991 text: "body".into(),
1992 });
1993 assert_eq!(to_markdown_table_cell(&doc, false), "A text\n\nbody");
1994 assert_eq!(doc.export_to_markdown(), "## A text\n\nbody\n");
1995
1996 let mut doc = DoclingDocument::new("f");
1997 doc.push(Node::FieldRegion {
1998 items: vec![crate::FieldItem {
1999 marker: None,
2000 key: Some("Name:".into()),
2001 value: Some("John Doe".into()),
2002 value_kind: None,
2003 }],
2004 });
2005 assert_eq!(doc.export_to_markdown(), "Name:\n\nJohn Doe\n");
2006 }
2007
2008 #[test]
2009 fn strict_renders_recovered_links_legacy_does_not() {
2010 let mut doc = DoclingDocument::new("cv");
2011 doc.add_paragraph("Find me on LinkedIn or GitHub.");
2012 doc.links = vec![
2013 ("LinkedIn".into(), "https://www.linkedin.com/in/x/".into()),
2014 ("GitHub".into(), "https://github.com/x/".into()),
2015 ];
2016 assert_eq!(doc.export_to_markdown(), "Find me on LinkedIn or GitHub.\n");
2018 assert_eq!(
2020 doc.export_to_markdown_with(true),
2021 "Find me on [LinkedIn](https://www.linkedin.com/in/x/) or [GitHub](https://github.com/x/).\n"
2022 );
2023 }
2024
2025 #[test]
2026 fn strict_links_match_escaped_anchor_and_consume_in_order() {
2027 let mut doc = DoclingDocument::new("d");
2028 doc.add_paragraph("AI & ML here, and issues here, then issues there.");
2032 doc.links = vec![
2033 ("AI & ML".into(), "https://a/".into()),
2034 ("issues".into(), "https://first/".into()),
2035 ("issues".into(), "https://second/".into()),
2036 ];
2037 assert_eq!(
2038 doc.export_to_markdown_with(true),
2039 "[AI & ML](https://a/) here, and [issues](https://first/) here, then [issues](https://second/) there.\n"
2040 );
2041 }
2042
2043 #[test]
2047 fn referenced_image_destinations_are_escaped() {
2048 let cases = [
2049 (
2050 "doc_artifacts/image_000001_ab12.png",
2051 "doc_artifacts/image_000001_ab12.png",
2052 ),
2053 (
2054 "My Report_artifacts/img.png",
2055 "My%20Report_artifacts/img.png",
2056 ),
2057 ("artifacts/img (1).png", "artifacts/img%20%281%29.png"),
2058 ("100%_scale/a#b?c.png", "100%_scale/a%23b%3Fc.png"),
2059 ("/home/a b/img.png", "/home/a%20b/img.png"),
2060 (
2061 "My Report_artifacts\\img.png",
2062 "My%20Report_artifacts/img.png",
2063 ),
2064 (
2065 "C:/Users/me/My Docs/img.png",
2066 "file:///C:/Users/me/My%20Docs/img.png",
2067 ),
2068 ("C:\\Users\\me\\img.png", "file:///C:/Users/me/img.png"),
2069 (
2070 "//server/share/My Docs/img.png",
2071 "file://server/share/My%20Docs/img.png",
2072 ),
2073 ("\\\\server\\share\\img.png", "file://server/share/img.png"),
2074 ("file:///home/a b/img.png", "file:///home/a%20b/img.png"),
2075 (
2076 "s3://bucket/My Report_artifacts/img.png",
2077 "s3://bucket/My%20Report_artifacts/img.png",
2078 ),
2079 (
2080 "https://example.com:8080/a b.png?w=1&h=2#frag",
2081 "https://example.com:8080/a%20b.png?w=1&h=2#frag",
2082 ),
2083 (
2084 "https://example.com/img (1).png",
2085 "https://example.com/img%20%281%29.png",
2086 ),
2087 ("caf\u{e9}/im\u{e4}ge.png", "caf%C3%A9/im%C3%A4ge.png"),
2088 ];
2089 for (input, expected) in cases {
2090 assert_eq!(escape_uri_path(input), expected, "input {input:?}");
2091 assert_eq!(
2092 escape_uri_path(expected),
2093 expected,
2094 "idempotent {expected:?}"
2095 );
2096 }
2097 let mut doc = DoclingDocument::new("t");
2099 doc.push(Node::Picture {
2100 caption: None,
2101 caption_href: None,
2102 image: Some(PictureImage {
2103 dpi: PictureImage::DEFAULT_DPI,
2104 mimetype: "image/png".into(),
2105 width: 1,
2106 height: 1,
2107 data: b"x".to_vec(),
2108 display_size: None,
2109 }),
2110 classification: None,
2111 description: None,
2112 caption_parent: Default::default(),
2113 caption_location: None,
2114 });
2115 let (md, files) = doc
2116 .export_to_markdown_with_images(ImageMode::Referenced, "My Report (final)_artifacts");
2117 assert!(
2118 md.contains(""),
2119 "got:\n{md}"
2120 );
2121 assert_eq!(files[0].0, "My Report (final)_artifacts/image_000000.png");
2123 }
2124
2125 #[test]
2129 fn folded_list_item_pictures_keep_plain_newlines() {
2130 let doc = DoclingDocument::new("t");
2131 let ctx = Ctx::new(&doc, false, &MarkdownExportOptions::default());
2132 assert_eq!(
2133 list_item_text("Step\n<!-- image -->", &ctx),
2134 "Step\n<!-- image -->"
2135 );
2136 assert_eq!(
2137 list_item_text("Step\nAlt text\n<!-- image -->\n<!-- image -->", &ctx),
2138 "Step\nAlt text\n<!-- image -->\n<!-- image -->"
2139 );
2140 assert_eq!(
2141 list_item_text("line one\nline two", &ctx),
2142 "line one \nline two"
2143 );
2144 }
2145
2146 #[test]
2149 fn stacked_header_rows_flatten_into_one() {
2150 let mut t = Table {
2151 rows: vec![
2152 vec!["".into(), "% of Total".into(), "% of Total".into()],
2153 vec!["class".into(), "Train".into(), "Test".into()],
2154 vec!["Caption".into(), "2.04".into(), "1.77".into()],
2155 ],
2156 ..Default::default()
2157 };
2158 t.structure = Some(TableStructure {
2159 header_row: vec![true, true, false],
2160 col_continuation: vec![
2161 vec![false, false, true],
2162 vec![false, false, false],
2163 vec![false, false, false],
2164 ],
2165 ..Default::default()
2166 });
2167 assert_eq!(t.header_row_count(), 2);
2168 assert_eq!(
2169 render_table(&t, true),
2170 "| class | % of Total - Train | % of Total - Test |\n| - | - | - |\n| Caption | 2.04 | 1.77 |"
2171 );
2172 assert_eq!(
2174 render_table(&t, false),
2175 "| class | % of Total - Train | % of Total - Test |\n\
2176 |---------|----------------------|---------------------|\n\
2177 | Caption | 2.04 | 1.77 |"
2178 );
2179 }
2180
2181 #[test]
2184 fn vertically_spanning_header_does_not_extend_the_block() {
2185 let mut t = Table {
2186 rows: vec![
2187 vec!["Name".into(), "Value".into()],
2188 vec!["Name".into(), "1".into()],
2189 vec!["x".into(), "2".into()],
2190 ],
2191 ..Default::default()
2192 };
2193 t.structure = Some(TableStructure {
2194 col_header: vec![vec![true, true], vec![true, false], vec![false, false]],
2195 row_continuation: vec![vec![false, false], vec![true, false], vec![false, false]],
2196 ..Default::default()
2197 });
2198 assert_eq!(t.header_row_count(), 1);
2199 assert_eq!(
2200 render_table(&t, true),
2201 "| Name | Value |\n| - | - |\n| Name | 1 |\n| x | 2 |"
2202 );
2203 }
2204
2205 #[test]
2208 fn header_flags_not_on_row_zero_keep_all_rows_in_the_body() {
2209 let mut t = Table {
2210 rows: vec![
2211 vec!["1".into(), "2".into()],
2212 vec!["a".into(), "b".into()],
2213 vec!["333".into(), "4".into()],
2214 ],
2215 ..Default::default()
2216 };
2217 t.structure = Some(TableStructure {
2218 header_row: vec![false, true, false],
2219 ..Default::default()
2220 });
2221 assert_eq!(t.header_row_count(), 0);
2222 assert_eq!(
2223 render_table(&t, false),
2224 "| | |\n|-----|----|\n| 1 | 2 |\n| a | b |\n| 333 | 4 |"
2225 );
2226 }
2227
2228 #[test]
2233 fn pivot_row_headers_do_not_extend_the_header() {
2234 let mut t = Table {
2235 rows: vec![
2236 vec!["Year".into(), "Month".into()],
2237 vec!["2025".into(), "January".into()],
2238 vec!["2025".into(), "February".into()],
2239 ],
2240 ..Default::default()
2241 };
2242 t.structure = Some(TableStructure {
2243 col_header: vec![vec![true, true], vec![false, false], vec![false, false]],
2244 row_header: vec![vec![false, false], vec![true, false], vec![true, false]],
2245 row_continuation: vec![vec![false, false], vec![false, false], vec![true, false]],
2246 ..Default::default()
2247 });
2248 assert_eq!(t.header_row_count(), 1);
2249 assert_eq!(
2250 render_table(&t, true),
2251 "| Year | Month |\n| - | - |\n| 2025 | January |\n| 2025 | February |"
2252 );
2253 }
2254
2255 #[test]
2258 fn unflagged_cells_keep_row_zero_as_header() {
2259 let mut t = Table {
2260 rows: vec![vec!["h".into()], vec!["d".into()]],
2261 ..Default::default()
2262 };
2263 t.cells = Some(
2264 [(0usize, "h"), (1, "d")]
2265 .into_iter()
2266 .map(|(r, text)| TableCell {
2267 text: text.into(),
2268 bbox: None,
2269 start_row: r,
2270 start_col: 0,
2271 row_span: 1,
2272 col_span: 1,
2273 column_header: false,
2274 row_header: false,
2275 row_section: false,
2276 })
2277 .collect(),
2278 );
2279 assert_eq!(t.header_row_count(), 1);
2280 assert_eq!(render_table(&t, true), "| h |\n| - |\n| d |");
2281 }
2282
2283 fn flagged_table(rows: &[&[&str]], ched: impl Fn(usize, usize) -> bool) -> Table {
2285 let mut cells = Vec::new();
2286 for (r, row) in rows.iter().enumerate() {
2287 for (c, text) in row.iter().enumerate() {
2288 cells.push(TableCell {
2289 text: (*text).into(),
2290 bbox: None,
2291 start_row: r,
2292 start_col: c,
2293 row_span: 1,
2294 col_span: 1,
2295 column_header: ched(r, c),
2296 row_header: false,
2297 row_section: false,
2298 });
2299 }
2300 }
2301 Table {
2302 rows: rows
2303 .iter()
2304 .map(|row| row.iter().map(|t| (*t).to_string()).collect())
2305 .collect(),
2306 cells: Some(cells),
2307 ..Default::default()
2308 }
2309 }
2310
2311 #[test]
2315 fn rows_with_body_text_stop_the_header_block() {
2316 let t = flagged_table(
2318 &[
2319 &["Item", "Q1", "Q2"],
2320 &["Sales", "10", "20"],
2321 &["Costs", "5", "7"],
2322 ],
2323 |r, c| r == 0 || c == 0,
2324 );
2325 assert_eq!(t.header_row_count(), 1);
2326 assert_eq!(
2327 render_table(&t, false),
2328 "| Item | Q1 | Q2 |\n\
2329 |--------|------|------|\n\
2330 | Sales | 10 | 20 |\n\
2331 | Costs | 5 | 7 |"
2332 );
2333 let t = flagged_table(&[&["Sales", "10", "20"], &["Costs", "5", "7"]], |_, c| {
2336 c == 0
2337 });
2338 assert_eq!(t.header_row_count(), 0);
2339 assert_eq!(
2340 render_table(&t, false),
2341 "| | | |\n\
2342 |-------|----|----|\n\
2343 | Sales | 10 | 20 |\n\
2344 | Costs | 5 | 7 |"
2345 );
2346 let t = flagged_table(
2347 &[&["a", "1", "2"], &["b", "3", "4"], &["c", "5", "6"]],
2348 |r, c| c == 0 && r < 2,
2349 );
2350 assert_eq!(t.header_row_count(), 0);
2351 let t = flagged_table(&[&["a", "1", "2"], &["b", "3", "4"]], |r, c| {
2354 r == 0 && c == 0
2355 });
2356 assert_eq!(t.header_row_count(), 1);
2357 assert_eq!(
2358 render_table(&t, false),
2359 "| a | 1 | 2 |\n\
2360 |-----|-----|-----|\n\
2361 | b | 3 | 4 |"
2362 );
2363 let t = flagged_table(&[&["Item", "", ""], &["x", "1", "2"]], |_, c| c == 0);
2365 assert_eq!(t.header_row_count(), 1);
2366 assert_eq!(
2367 render_table(&t, false),
2368 "| Item | | |\n\
2369 |--------|----|----|\n\
2370 | x | 1 | 2 |"
2371 );
2372 }
2373
2374 #[test]
2375 fn renders_compact_table() {
2376 let mut doc = DoclingDocument::new("t");
2377 doc.compact_tables = true;
2380 doc.push(Node::Table(Table {
2381 footnotes: Vec::new(),
2382 footnotes_as_runs: false,
2383 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
2384 location: None,
2385 structure: None,
2386 cell_blocks: None,
2387 cells: None,
2388 caption: None,
2389 caption_parent: Default::default(),
2390 caption_location: None,
2391 document_index: false,
2392 }));
2393 let md = doc.export_to_markdown();
2394 assert_eq!(md, "| a | b |\n| - | - |\n| 1 | 2 |\n");
2395 }
2396
2397 #[test]
2398 fn renders_padded_github_table_by_default() {
2399 let mut doc = DoclingDocument::new("t");
2400 doc.push(Node::Table(Table {
2401 footnotes: Vec::new(),
2402 footnotes_as_runs: false,
2403 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
2404 location: None,
2405 structure: None,
2406 cell_blocks: None,
2407 cells: None,
2408 caption: None,
2409 caption_parent: Default::default(),
2410 caption_location: None,
2411 document_index: false,
2412 }));
2413 let md = doc.export_to_markdown();
2414 assert_eq!(md, "| a | b |\n|-----|-----|\n| 1 | 2 |\n");
2416 }
2417
2418 #[test]
2419 fn strict_unescapes_inline_underscores_legacy_keeps_them() {
2420 let mut doc = DoclingDocument::new("t");
2421 doc.add_heading(1, "a\\_b");
2422 doc.add_paragraph("x\\_y");
2423 doc.push(Node::ListItem {
2424 ordered: false,
2425 number: 1,
2426 first_in_list: true,
2427 text: "i\\_j".into(),
2428 level: 0,
2429 marker: None,
2430 location: None,
2431 split: None,
2432 dclx: None,
2433 href: None,
2434 layer: None,
2435 });
2436 assert_eq!(doc.export_to_markdown(), "# a\\_b\n\nx\\_y\n\n- i\\_j\n");
2438 assert_eq!(doc.export_to_markdown_with(true), "# a_b\n\nx_y\n\n- i_j\n");
2440 }
2441
2442 fn assert_stream_matches(
2445 doc: &DoclingDocument,
2446 strict: bool,
2447 images: ImageMode,
2448 splits: &[usize],
2449 ) {
2450 let (want, want_artifacts) = to_markdown_images(doc, strict, images, "artifacts");
2451 let mut streamer =
2452 MarkdownStreamer::with_artifacts(strict, images, doc.compact_tables, "artifacts")
2453 .with_page_break_placeholder(doc.page_break_placeholder.clone());
2454 let mut got = String::new();
2455 let mut got_artifacts = Vec::new();
2456 let mut start = 0;
2457 for &end in splits {
2458 let links = if start == 0 {
2461 doc.links.as_slice()
2462 } else {
2463 &[]
2464 };
2465 got.push_str(&streamer.push(&doc.nodes[start..end], links));
2466 got_artifacts.extend(streamer.take_artifacts());
2469 start = end;
2470 }
2471 got.push_str(&streamer.push(
2472 &doc.nodes[start..],
2473 if start == 0 {
2474 doc.links.as_slice()
2475 } else {
2476 &[]
2477 },
2478 ));
2479 got_artifacts.extend(streamer.take_artifacts());
2480 got.push_str(&streamer.finish());
2481 assert_eq!(
2482 got, want,
2483 "streamed output diverged (splits={splits:?}, strict={strict})"
2484 );
2485 assert_eq!(
2486 got_artifacts, want_artifacts,
2487 "streamed artifacts diverged (splits={splits:?}, strict={strict})"
2488 );
2489 }
2490
2491 #[test]
2492 fn streaming_is_byte_identical_to_buffered() {
2493 let mut doc = DoclingDocument::new("d");
2494 doc.add_heading(1, "Title");
2495 doc.add_paragraph("First paragraph.");
2496 doc.push(Node::ListItem {
2497 ordered: false,
2498 number: 1,
2499 first_in_list: true,
2500 text: "a".into(),
2501 level: 0,
2502 marker: None,
2503 location: None,
2504 split: None,
2505 dclx: None,
2506 href: None,
2507 layer: None,
2508 });
2509 doc.push(Node::ListItem {
2510 ordered: false,
2511 number: 2,
2512 first_in_list: false,
2513 text: "b".into(),
2514 level: 0,
2515 marker: None,
2516 location: None,
2517 split: None,
2518 dclx: None,
2519 href: None,
2520 layer: None,
2521 });
2522 doc.push(Node::Code {
2523 language: Some("rust".into()),
2524 text: "let x = 1;".into(),
2525 orig: None,
2526 pretty: None,
2527 });
2528 doc.push(Node::Table(Table {
2529 footnotes: Vec::new(),
2530 footnotes_as_runs: false,
2531 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
2532 location: None,
2533 structure: None,
2534 cell_blocks: None,
2535 cells: None,
2536 caption: None,
2537 caption_parent: Default::default(),
2538 caption_location: None,
2539 document_index: false,
2540 }));
2541 doc.push(Node::Picture {
2542 caption: Some("Fig 1".into()),
2543 caption_href: None,
2544 image: Some(PictureImage {
2545 dpi: PictureImage::DEFAULT_DPI,
2546 mimetype: "image/png".into(),
2547 width: 2,
2548 height: 2,
2549 data: b"png-one".to_vec(),
2550 display_size: None,
2551 }),
2552 classification: None,
2553 description: None,
2554 caption_parent: Default::default(),
2555 caption_location: None,
2556 });
2557 doc.add_paragraph("Last paragraph.");
2558 doc.push(Node::Picture {
2561 caption: None,
2562 caption_href: None,
2563 image: Some(PictureImage {
2564 dpi: PictureImage::DEFAULT_DPI,
2565 mimetype: "image/png".into(),
2566 width: 2,
2567 height: 2,
2568 data: b"png-two".to_vec(),
2569 display_size: None,
2570 }),
2571 classification: None,
2572 description: None,
2573 caption_parent: Default::default(),
2574 caption_location: None,
2575 });
2576
2577 for &strict in &[false, true] {
2580 for &images in &[
2581 ImageMode::Placeholder,
2582 ImageMode::Embedded,
2583 ImageMode::Referenced,
2584 ] {
2585 for splits in [&[][..], &[1][..], &[2][..], &[4][..], &[1, 4, 6, 7][..]] {
2586 assert_stream_matches(&doc, strict, images, splits);
2587 }
2588 }
2589 }
2590 }
2591
2592 #[test]
2593 fn streaming_applies_recovered_links_in_strict_mode() {
2594 let mut doc = DoclingDocument::new("d");
2595 doc.add_paragraph("See LinkedIn for details.");
2596 doc.add_paragraph("And GitHub too.");
2597 doc.links = vec![
2598 ("LinkedIn".into(), "https://lnkd/".into()),
2599 ("GitHub".into(), "https://gh/".into()),
2600 ];
2601 assert_stream_matches(&doc, true, ImageMode::Placeholder, &[1]);
2604 }
2605
2606 fn paged_doc() -> DoclingDocument {
2609 let mut doc = DoclingDocument::new("p");
2610 doc.push(Node::PageInfo {
2611 page_no: 1,
2612 width: 100.0,
2613 height: 100.0,
2614 });
2615 doc.add_heading(1, "Title");
2616 doc.add_paragraph("Page one.");
2617 doc.push(Node::PageBreak);
2619 doc.push(Node::PageInfo {
2620 page_no: 2,
2621 width: 100.0,
2622 height: 100.0,
2623 });
2624 doc.push(Node::PageFurniture {
2625 footer: true,
2626 location: [0, 500, 511, 511],
2627 text: "2".into(),
2628 });
2629 doc.push(Node::PageBreak);
2630 doc.push(Node::PageInfo {
2631 page_no: 3,
2632 width: 100.0,
2633 height: 100.0,
2634 });
2635 doc.add_paragraph("Page three.");
2636 doc.push(Node::PageBreak);
2638 doc
2639 }
2640
2641 #[test]
2642 fn page_break_placeholder_lands_between_pages_only() {
2643 let mut doc = paged_doc();
2644 assert_eq!(
2646 doc.export_to_markdown(),
2647 "# Title\n\nPage one.\n\nPage three.\n"
2648 );
2649 doc.page_break_placeholder = Some("<!-- page break -->".into());
2650 assert_eq!(
2654 doc.export_to_markdown(),
2655 "# Title\n\nPage one.\n\n<!-- page break -->\n\nPage three.\n"
2656 );
2657 doc.page_break_placeholder = Some(String::new());
2660 assert_eq!(
2661 doc.export_to_markdown(),
2662 "# Title\n\nPage one.\n\n\n\nPage three.\n"
2663 );
2664 }
2665
2666 #[test]
2667 fn page_break_placeholder_never_leads_a_single_page() {
2668 let mut doc = DoclingDocument::new("one");
2669 doc.page_break_placeholder = Some("---".into());
2670 doc.push(Node::PageBreak);
2671 doc.push(Node::PageInfo {
2672 page_no: 1,
2673 width: 10.0,
2674 height: 10.0,
2675 });
2676 doc.add_paragraph("Only page.");
2677 assert_eq!(doc.export_to_markdown(), "Only page.\n");
2678 doc.push(Node::PageBreak);
2680 doc.push(Node::PageBreak);
2681 doc.add_paragraph("Next.");
2682 assert_eq!(doc.export_to_markdown(), "Only page.\n\n---\n\nNext.\n");
2683 }
2684
2685 #[test]
2686 fn page_break_placeholder_streams_byte_identical() {
2687 let mut doc = paged_doc();
2688 doc.page_break_placeholder = Some("<!-- page break -->".into());
2689 for splits in [
2693 &[3usize][..],
2694 &[3, 6],
2695 &[3, 6, 8],
2696 &[1, 2, 3, 4, 5, 6, 7, 8, 9],
2697 &[8],
2698 ] {
2699 assert_stream_matches(&doc, false, ImageMode::Placeholder, splits);
2700 assert_stream_matches(&doc, true, ImageMode::Placeholder, splits);
2701 }
2702 }
2703
2704 #[test]
2705 fn strict_tightens_punctuation_spacing_legacy_keeps_it() {
2706 let mut doc = DoclingDocument::new("t");
2707 doc.add_paragraph("see [ 37 , 36 ] and ( x ) .");
2708 assert_eq!(doc.export_to_markdown(), "see [ 37 , 36 ] and ( x ) .\n");
2710 assert_eq!(doc.export_to_markdown_with(true), "see [37, 36] and (x).\n");
2712 }
2713
2714 fn options_doc() -> DoclingDocument {
2719 use crate::document::ContentLayer;
2720 let mut doc = DoclingDocument::new("opts");
2721 doc.push(Node::PageFurniture {
2722 footer: false,
2723 location: [0, 0, 0, 0],
2724 text: "FAX COVER \\_ R&D".into(),
2725 });
2726 doc.add_heading(1, "R&D \\_ report");
2727 doc.add_paragraph("Body a\\_b <tag>");
2728 doc.push(Node::Picture {
2729 caption: Some("Figure 1".into()),
2730 caption_href: None,
2731 image: None,
2732 classification: None,
2733 description: None,
2734 caption_parent: Default::default(),
2735 caption_location: None,
2736 });
2737 doc.push(Node::PictureChildren(vec![
2738 Node::Paragraph {
2739 text: "Field: Name".into(),
2740 },
2741 Node::Paragraph {
2742 text: "Field: Date".into(),
2743 },
2744 ]));
2745 doc.push(Node::CommentSection {
2746 name: "comment-1".into(),
2747 text: "[author: A]: note".into(),
2748 refs_note_text: false,
2749 grouped: true,
2750 });
2751 doc.push(Node::Group {
2752 label: "section".into(),
2753 name: Some("sheet: Hidden".into()),
2754 layer: Some(ContentLayer::Invisible),
2755 children: vec![Node::Paragraph {
2756 text: "hidden cell".into(),
2757 }],
2758 });
2759 doc.push(Node::Furniture {
2760 layer: ContentLayer::Furniture,
2761 inner: Box::new(Node::Paragraph {
2762 text: "Page 1 of 2".into(),
2763 }),
2764 });
2765 doc.push(Node::FurnitureText {
2766 label: "page_footer".into(),
2767 text: "footer line".into(),
2768 });
2769 doc
2770 }
2771
2772 #[test]
2776 fn default_options_are_the_default_export() {
2777 let doc = options_doc();
2778 let plain = doc.export_to_markdown();
2779 assert_eq!(
2780 plain,
2781 "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n"
2782 );
2783 let (with_default, artifacts) =
2784 doc.export_to_markdown_with_options(&MarkdownExportOptions::default());
2785 assert_eq!(with_default, plain);
2786 assert!(artifacts.is_empty());
2787 }
2788
2789 #[test]
2790 fn layers_render_furniture_notes_and_hidden_sheets() {
2791 use crate::document::ContentLayer;
2792 let doc = options_doc();
2793 let md = |layers: ContentLayers| {
2794 doc.export_to_markdown_with_options(&MarkdownExportOptions {
2795 layers,
2796 ..MarkdownExportOptions::default()
2797 })
2798 .0
2799 };
2800 assert_eq!(
2801 md(ContentLayers::BODY.with(ContentLayer::Furniture)),
2802 "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",
2803 "a page header, a furniture-wrapped paragraph and a furniture text item render as paragraphs"
2804 );
2805 assert_eq!(
2806 md(ContentLayers::BODY.with(ContentLayer::Notes)),
2807 "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n\n[author: A]: note\n"
2808 );
2809 assert_eq!(
2810 md(ContentLayers::BODY.with(ContentLayer::Invisible)),
2811 "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n\nhidden cell\n",
2812 "a hidden sheet's items sit on the sheet's layer"
2813 );
2814 assert_eq!(
2815 md(ContentLayers::NONE.with(ContentLayer::Furniture)),
2816 "FAX COVER \\_ R&D\n\nPage 1 of 2\n\nfooter line\n",
2817 "without the body layer only the furniture prints"
2818 );
2819 assert_eq!(md(ContentLayers::NONE), "");
2820 assert_eq!(
2821 md(ContentLayers::ALL),
2822 "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"
2823 );
2824 }
2825
2826 #[test]
2829 fn layers_apply_to_list_items() {
2830 use crate::document::ContentLayer;
2831 let mut doc = DoclingDocument::new("lists");
2832 doc.push(Node::ListItem {
2833 ordered: false,
2834 number: 1,
2835 first_in_list: true,
2836 text: "nav link".into(),
2837 level: 0,
2838 marker: None,
2839 location: None,
2840 split: None,
2841 dclx: None,
2842 href: None,
2843 layer: Some(ContentLayer::Furniture),
2844 });
2845 doc.add_paragraph("body");
2846 assert_eq!(doc.export_to_markdown(), "body\n");
2847 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2848 layers: ContentLayers::BODY.with(ContentLayer::Furniture),
2849 ..MarkdownExportOptions::default()
2850 });
2851 assert_eq!(md, "- nav link\n\nbody\n");
2852 }
2853
2854 #[test]
2855 fn traverse_pictures_prints_the_nested_text_after_the_picture() {
2856 let doc = options_doc();
2857 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2858 traverse_pictures: true,
2859 ..MarkdownExportOptions::default()
2860 });
2861 assert_eq!(
2862 md,
2863 "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n\nField: Name\n\nField: Date\n"
2864 );
2865 }
2866
2867 #[test]
2868 fn escaping_can_be_turned_off_per_kind() {
2869 let doc = options_doc();
2870 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2871 escape_html: false,
2872 ..MarkdownExportOptions::default()
2873 });
2874 assert_eq!(
2875 md,
2876 "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n"
2877 );
2878 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2879 escape_underscores: false,
2880 ..MarkdownExportOptions::default()
2881 });
2882 assert_eq!(
2883 md,
2884 "# R&D _ report\n\nBody a_b <tag>\n\nFigure 1\n\n<!-- image -->\n"
2885 );
2886 let mut doc = DoclingDocument::new("code");
2889 doc.push(Node::Code {
2890 language: None,
2891 text: "a & b \\_ c".into(),
2892 orig: None,
2893 pretty: None,
2894 });
2895 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2896 escape_html: false,
2897 escape_underscores: false,
2898 ..MarkdownExportOptions::default()
2899 });
2900 assert_eq!(md, "```\na & b \\_ c\n```\n");
2901 }
2902
2903 #[test]
2907 fn fences_and_spans_out_length_inner_backticks() {
2908 let code = |text: &str| Node::Code {
2909 language: Some("md".into()),
2910 text: text.into(),
2911 orig: None,
2912 pretty: None,
2913 };
2914 let fence_of = |text: &str| {
2915 let mut doc = DoclingDocument::new("d");
2916 doc.push(code(text));
2917 (doc.export_to_markdown(), doc.export_to_markdown_with(true))
2918 };
2919 assert_eq!(fence_of("x").0, "```\nx\n```\n");
2920 assert_eq!(fence_of("a ` b").0, "```\na ` b\n```\n");
2921 assert_eq!(fence_of("a ``` b").0, "````\na ``` b\n````\n");
2922 assert_eq!(
2923 fence_of("a ``` b ```` c"),
2924 (
2925 "`````\na ``` b ```` c\n`````\n".to_string(),
2926 "`````md\na ``` b ```` c\n`````\n".to_string()
2927 )
2928 );
2929 assert_eq!(code_span("x"), "`x`");
2930 assert_eq!(code_span("a`b"), "``a`b``");
2931 assert_eq!(code_span("a ``` b"), "````a ``` b````");
2932 assert_eq!(code_span("`x"), "`` `x ``");
2933 assert_eq!(code_span("x`"), "`` x` ``");
2934 let cases = [
2937 (" x ", "` x `"),
2938 (" x ", "` x `"),
2939 (" ", "` `"),
2940 (" ", "` `"),
2941 (" x", "` x`"),
2942 ("x ", "`x `"),
2943 (" \t ", "` \t `"),
2944 (" \u{a0} ", "` \u{a0} `"),
2945 ("\tx\t", "`\tx\t`"),
2946 ("\u{a0}x\u{a0}", "`\u{a0}x\u{a0}`"),
2947 (" `x` ", "`` `x` ``"),
2948 ("\nx ", "` \nx `"),
2949 (" x\n", "` x\n `"),
2950 ("\nx\n", "` \nx\n `"),
2951 ("\r\nx\r\n", "` \r\nx\r\n `"),
2952 ("\rx\r", "` \rx\r `"),
2953 (" x\ny ", "` x\ny `"),
2954 (" \n ", "` \n `"),
2955 (" \r\n ", "` \r\n `"),
2956 ];
2957 for (code, want) in cases {
2958 assert_eq!(code_span(code), want, "{code:?}");
2959 let chars: Vec<char> = want.chars().collect();
2961 let (s, e, after) = code_span_bounds(&chars, 0).unwrap();
2962 assert_eq!(after, chars.len());
2963 if !code.contains(['\n', '\r']) {
2964 assert_eq!(chars[s..e].iter().collect::<String>(), code, "{want:?}");
2965 }
2966 }
2967 for (span, text) in [
2968 ("`x`", "x"),
2969 ("``a`b``", "a`b"),
2970 ("`` `x ``", "`x"),
2971 ("````a ``` b````", "a ``` b"),
2972 ] {
2973 assert_eq!(
2974 plain_inline(&format!("see {span} here")),
2975 format!("see {text} here")
2976 );
2977 }
2978 let mut doc = DoclingDocument::new("d");
2981 doc.push(code("a ``` b"));
2982 assert_eq!(doc.export_to_text(), "a ``` b");
2983 let mut doc = DoclingDocument::new("d");
2985 doc.add_paragraph("Before.");
2986 doc.push(code("a ``` b ```` c"));
2987 doc.add_paragraph("After.");
2988 assert_stream_matches(&doc, false, ImageMode::Placeholder, &[1, 2]);
2989 assert_stream_matches(&doc, true, ImageMode::Placeholder, &[1, 2]);
2990 }
2991
2992 #[test]
2997 fn mermaid_code_item_replaces_its_picture_placeholder() {
2998 let picture = || Node::Picture {
2999 caption: None,
3000 caption_href: None,
3001 image: None,
3002 classification: None,
3003 description: None,
3004 caption_parent: Default::default(),
3005 caption_location: None,
3006 };
3007 let mut doc = DoclingDocument::new("d");
3008 doc.add_paragraph("Before.");
3009 doc.push(picture());
3010 doc.push(Node::Code {
3011 language: Some("mermaid".into()),
3012 text: "flowchart TD\n A --> B".into(),
3013 orig: None,
3014 pretty: None,
3015 });
3016 doc.add_paragraph("After.");
3017 doc.push(picture());
3018 let md = doc.export_to_markdown();
3019 assert_eq!(
3020 md,
3021 "Before.\n\n```mermaid\nflowchart TD\n A --> B\n```\n\nAfter.\n\n<!-- image -->\n"
3022 );
3023 assert_eq!(doc.export_to_markdown_with(true), md);
3024 for splits in [&[1][..], &[2], &[1, 2], &[2, 3], &[1, 2, 3, 4]] {
3025 assert_stream_matches(&doc, false, ImageMode::Placeholder, splits);
3026 assert_stream_matches(&doc, true, ImageMode::Placeholder, splits);
3027 }
3028 let mut doc = DoclingDocument::new("d");
3030 doc.add_paragraph("Only.");
3031 doc.push(picture());
3032 assert_eq!(doc.export_to_markdown(), "Only.\n\n<!-- image -->\n");
3033 assert_stream_matches(&doc, false, ImageMode::Placeholder, &[1]);
3034 assert_stream_matches(&doc, false, ImageMode::Placeholder, &[2]);
3035 }
3036
3037 #[test]
3038 fn image_placeholder_is_configurable() {
3039 let doc = options_doc();
3040 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
3041 image_placeholder: "[figure]".into(),
3042 ..MarkdownExportOptions::default()
3043 });
3044 assert!(md.contains("Figure 1\n\n[figure]\n"), "{md}");
3045 assert!(!md.contains("<!-- image -->"));
3046 }
3047
3048 #[test]
3054 fn empty_image_placeholder_prints_nothing() {
3055 fn picture(caption: Option<&str>) -> Node {
3056 Node::Picture {
3057 caption: caption.map(Into::into),
3058 caption_href: None,
3059 image: None,
3060 classification: None,
3061 description: None,
3062 caption_parent: Default::default(),
3063 caption_location: None,
3064 }
3065 }
3066 fn page(no: usize) -> Node {
3067 Node::PageInfo {
3068 page_no: no,
3069 width: 100.0,
3070 height: 100.0,
3071 }
3072 }
3073 fn para(text: &str) -> Node {
3074 Node::Paragraph { text: text.into() }
3075 }
3076 let options = MarkdownExportOptions {
3077 image_placeholder: String::new(),
3078 ..MarkdownExportOptions::default()
3079 };
3080 let cases: Vec<(Vec<Node>, Option<&str>, &str)> = vec![
3082 (
3083 vec![page(1), para("a"), picture(None), para("b")],
3084 None,
3085 "a\n\nb\n",
3086 ),
3087 (
3088 vec![page(1), para("a"), picture(Some("Figure 1")), para("b")],
3089 None,
3090 "a\n\nFigure 1\n\nb\n",
3091 ),
3092 (
3093 vec![
3094 page(1),
3095 para("a"),
3096 page(2),
3097 picture(None),
3098 page(3),
3099 para("b"),
3100 ],
3101 Some("<!-- pb -->"),
3102 "a\n\n<!-- pb -->\n\n<!-- pb -->\n\nb\n",
3103 ),
3104 (
3105 vec![
3106 page(1),
3107 para("a"),
3108 page(2),
3109 picture(None),
3110 page(3),
3111 para("b"),
3112 ],
3113 Some(""),
3114 "a\n\n\n\n\n\nb\n",
3115 ),
3116 (
3117 vec![page(1), picture(None), page(2), para("b")],
3118 Some("<!-- pb -->"),
3119 "<!-- pb -->\n\nb\n",
3120 ),
3121 (
3122 vec![page(1), picture(None), page(2), para("b")],
3123 Some(""),
3124 "\n\nb\n",
3125 ),
3126 (
3127 vec![page(1), para("a"), page(2), picture(None)],
3128 Some("<!-- pb -->"),
3129 "a\n\n<!-- pb -->\n",
3130 ),
3131 ];
3132 for (nodes, placeholder, expected) in cases {
3133 let mut doc = DoclingDocument::new("t");
3134 doc.page_break_placeholder = placeholder.map(Into::into);
3135 for node in nodes {
3136 doc.push(node);
3137 }
3138 let (md, _) = doc.export_to_markdown_with_options(&options);
3139 assert_eq!(md, expected, "page break {placeholder:?}");
3140 for size in 1..=doc.nodes.len() {
3143 let mut streamer = MarkdownStreamer::new(false, ImageMode::Placeholder, false)
3144 .with_export_options(&options)
3145 .with_page_break_placeholder(placeholder.map(Into::into));
3146 let mut out = String::new();
3147 for chunk in doc.nodes.chunks(size) {
3148 out.push_str(&streamer.push(chunk, &[]));
3149 }
3150 out.push_str(&streamer.finish());
3151 assert_eq!(
3152 out, expected,
3153 "chunks of {size}, page break {placeholder:?}"
3154 );
3155 }
3156 }
3157 let mut doc = DoclingDocument::new("t");
3159 doc.push(para("a"));
3160 doc.push(picture(None));
3161 doc.push(para("b"));
3162 assert_eq!(doc.export_to_markdown(), "a\n\n<!-- image -->\n\nb\n");
3163 }
3164
3165 #[test]
3168 fn streamer_matches_buffered_export_with_options() {
3169 let doc = options_doc();
3170 let options = MarkdownExportOptions {
3171 layers: ContentLayers::ALL,
3172 traverse_pictures: true,
3173 escape_html: false,
3174 escape_underscores: false,
3175 image_placeholder: "(img)".into(),
3176 ..MarkdownExportOptions::default()
3177 };
3178 let (buffered, _) = doc.export_to_markdown_with_options(&options);
3179 let mut streamer = MarkdownStreamer::new(false, ImageMode::Placeholder, false)
3180 .with_export_options(&options);
3181 let mut out = String::new();
3182 for chunk in doc.nodes.chunks(2) {
3183 out.push_str(&streamer.push(chunk, &[]));
3184 }
3185 out.push_str(&streamer.finish());
3186 assert_eq!(out, buffered);
3187 assert!(
3188 buffered.contains("(img)") && buffered.contains("R&D _ report"),
3189 "{buffered}"
3190 );
3191 }
3192
3193 #[test]
3196 fn plain_text_reads_escaped_stars() {
3197 assert_eq!(plain_inline("A\\*\\*\\* GmbH"), "A*** GmbH");
3198 assert_eq!(
3199 plain_inline("**FN \\*0\\*271\\*h** and *h\\*.at*"),
3200 "FN *0*271*h and h*.at"
3201 );
3202 }
3203
3204 #[test]
3207 fn plain_text_drops_the_markdown_decoration() {
3208 let item = |text: &str, ordered: bool, number: u64, level: u8| Node::ListItem {
3209 ordered,
3210 number,
3211 first_in_list: number == 1 && level == 0,
3212 text: text.into(),
3213 level,
3214 marker: None,
3215 location: None,
3216 split: None,
3217 dclx: None,
3218 href: None,
3219 layer: None,
3220 };
3221 let mut doc = DoclingDocument::new("plain");
3222 doc.add_heading(1, "Title with **bold**");
3223 doc.add_heading(2, "Section");
3224 doc.add_paragraph("Some **bold**, *italic*, ~~gone~~ and `code` with a [link](https://x.org).\nNext line.");
3225 doc.push(item("*one*", false, 1, 0));
3226 doc.push(item("[two](https://y.org)", false, 2, 0));
3227 doc.push(item("nested", true, 1, 1));
3228 doc.push(Node::CheckboxItem {
3229 checked: true,
3230 text: "done".into(),
3231 });
3232 doc.push(Node::Code {
3233 language: Some("rust".into()),
3234 text: "let x = **y**;".into(),
3235 orig: None,
3236 pretty: None,
3237 });
3238 doc.push(Node::Picture {
3239 caption: Some("Figure *1*".into()),
3240 caption_href: None,
3241 image: None,
3242 classification: None,
3243 description: None,
3244 caption_parent: Default::default(),
3245 caption_location: None,
3246 });
3247 doc.push(Node::Caption {
3248 text: "Linked caption".into(),
3249 href: Some("https://z.org".into()),
3250 });
3251 doc.push(Node::Table(Table {
3252 rows: vec![
3253 vec!["**n**".into(), "rich".into()],
3254 vec!["**2**".into(), "a \nb".into()],
3255 ],
3256 ..Default::default()
3257 }));
3258 doc.add_paragraph("R&D \\_ x");
3259 let text = doc.export_to_text();
3260 assert_eq!(
3261 text,
3262 "Title with bold\n\n\
3263 Section\n\n\
3264 Some bold, italic, gone and code with a link.\nNext line.\n\n\
3265 - one\n- two\n 1. nested\n\n\
3266 - [x] done\n\n\
3267 let x = **y**;\n\n\
3268 Figure 1\n\n\
3269 Linked caption\n\n\
3270 | n | rich |\n\
3271 |-----|--------|\n\
3272 | 2 | a b |\n\n\
3273 R&D _ x"
3274 );
3275
3276 let options = MarkdownExportOptions::plain_text();
3277 let (buffered, _) = doc.export_to_markdown_with_options(&options);
3278 assert_eq!(buffered, format!("{text}\n"));
3279 let mut streamer = MarkdownStreamer::new(false, ImageMode::Placeholder, false)
3280 .with_export_options(&options);
3281 let mut out = String::new();
3282 for chunk in doc.nodes.chunks(3) {
3283 out.push_str(&streamer.push(chunk, &[]));
3284 }
3285 out.push_str(&streamer.finish());
3286 assert_eq!(out, buffered);
3287 }
3288
3289 #[test]
3291 fn plain_inline_keeps_literal_markers() {
3292 for (input, want) in [
3293 ("**bold** and *it* and ***both***", "bold and it and both"),
3294 ("**[label](https://a.b/c_(d))** end", "label end"),
3295 (
3296 "grant *USE and *OBJMGT authority",
3297 "grant *USE and *OBJMGT authority",
3298 ),
3299 ("2 * 3 * 4", "2 * 3 * 4"),
3300 ("a ** b", "a ** b"),
3301 ("the `quoted’ and `x` term", "the `quoted’ and x term"),
3302 ("see [12] and [docs](u)", "see [12] and docs"),
3303 ("formula $[a](b)$ stays", "formula $[a](b)$ stays"),
3304 ("price $5 and **bold**", "price $5 and bold"),
3305 ("[outer [inner] text](u)", "outer [inner] text"),
3306 ("unclosed **bold", "unclosed **bold"),
3307 ] {
3308 assert_eq!(plain_inline(input), want, "{input}");
3309 }
3310 }
3311}