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 compact_tables: bool,
30 images: ImageMode,
31 artifacts_dir: String,
32 artifacts: Vec<(String, Vec<u8>)>,
34 pic_index: usize,
35 in_table_cell: bool,
39 page_break: Option<String>,
43 pending_page_break: bool,
49 emitted_any: bool,
52 layers: ContentLayers,
54 current_layer: Option<ContentLayer>,
59 traverse_pictures: bool,
61 escape_html: bool,
64 escape_underscores: bool,
66 image_placeholder: String,
68 plain: bool,
70}
71
72impl Ctx {
73 fn new(doc: &DoclingDocument, strict: bool, options: &MarkdownExportOptions) -> Self {
76 Ctx {
77 strict,
78 compact_tables: doc.compact_tables,
79 images: options.image_mode,
80 artifacts_dir: options.artifacts_dir.clone(),
81 artifacts: Vec::new(),
82 pic_index: 0,
83 in_table_cell: false,
84 page_break: doc.page_break_placeholder.clone(),
85 pending_page_break: false,
86 emitted_any: false,
87 layers: options.layers,
88 current_layer: None,
89 traverse_pictures: options.traverse_pictures,
90 escape_html: options.escape_html,
91 escape_underscores: options.escape_underscores,
92 image_placeholder: options.image_placeholder.clone(),
93 plain: options.plain_text,
94 }
95 }
96
97 fn layer_visible(&self) -> bool {
99 self.layers.contains(self.current_layer)
100 }
101
102 fn unescape(&self, text: &str) -> String {
109 let mut out = std::borrow::Cow::Borrowed(text);
110 if !self.escape_html
111 && (out.contains("&") || out.contains("<") || out.contains(">"))
112 {
113 out = std::borrow::Cow::Owned(
114 out.replace("<", "<")
115 .replace(">", ">")
116 .replace("&", "&"),
117 );
118 }
119 if !self.escape_underscores && out.contains("\\_") {
120 out = std::borrow::Cow::Owned(out.replace("\\_", "_"));
121 }
122 out.into_owned()
123 }
124
125 fn text(&self, text: &str) -> String {
128 let text = strict_text(text, self.strict);
129 if self.plain {
130 self.unescape(&plain_inline(&self.drop_image_markers(&text)))
131 } else {
132 self.unescape(&text)
133 }
134 }
135
136 fn caption(&self, text: &str) -> String {
140 if self.plain {
141 self.unescape(&plain_inline(text))
142 } else {
143 self.unescape(text)
144 }
145 }
146
147 fn breaks(&self, text: &str) -> String {
150 if self.plain {
151 text.to_string()
152 } else {
153 md_line_breaks(text)
154 }
155 }
156
157 fn plain_table(&self, table: &Table) -> Table {
164 let mut plain = table.clone();
165 for cell in plain.rows.iter_mut().flatten() {
166 if cell.contains(['*', '~', '`', '[', '\n', '<']) {
167 let text = self.drop_image_markers(&strip_hard_breaks(cell));
168 *cell = plain_inline(&text);
169 }
170 }
171 plain
172 }
173
174 fn drop_image_markers(&self, text: &str) -> String {
181 const MARKER: &str = "<!-- image -->";
182 if !text.contains(MARKER) && !text.contains("```") {
183 return text.to_string();
184 }
185 text.split("\n\n")
189 .filter_map(|block| {
190 let lines: Vec<String> = block
191 .split('\n')
192 .filter_map(|line| {
193 if line.trim() == MARKER || line.trim() == "```" {
196 return None;
197 }
198 Some(line.replace(MARKER, &self.image_placeholder))
199 })
200 .collect();
201 (!lines.is_empty()).then(|| lines.join("\n"))
202 })
203 .collect::<Vec<_>>()
204 .join("\n\n")
205 }
206}
207
208pub fn to_markdown(doc: &DoclingDocument, strict: bool) -> String {
214 to_markdown_images(doc, strict, ImageMode::Placeholder, "artifacts").0
215}
216
217pub fn to_markdown_images(
221 doc: &DoclingDocument,
222 strict: bool,
223 images: ImageMode,
224 artifacts_dir: &str,
225) -> (String, Vec<(String, Vec<u8>)>) {
226 to_markdown_with_options(
227 doc,
228 strict,
229 &MarkdownExportOptions {
230 image_mode: images,
231 artifacts_dir: artifacts_dir.to_string(),
232 ..MarkdownExportOptions::default()
233 },
234 )
235}
236
237pub fn to_markdown_with_options(
241 doc: &DoclingDocument,
242 strict: bool,
243 options: &MarkdownExportOptions,
244) -> (String, Vec<(String, Vec<u8>)>) {
245 let mut ctx = Ctx::new(doc, strict, options);
246 let mut blocks: Vec<String> = Vec::new();
247 render(&doc.nodes, &mut blocks, &mut ctx);
248 let mut body = blocks.join("\n\n");
249 if strict && !options.plain_text && !doc.links.is_empty() {
253 body = apply_links(&body, &doc.links);
254 }
255 let md = if body.is_empty() {
256 String::new()
257 } else {
258 format!("{body}\n")
259 };
260 (md, ctx.artifacts)
261}
262
263pub fn to_markdown_table_cell(doc: &DoclingDocument, strict: bool) -> String {
272 let mut ctx = Ctx::new(doc, strict, &MarkdownExportOptions::default());
273 ctx.in_table_cell = true;
274 ctx.artifacts_dir = String::new();
275 ctx.page_break = None;
279 let mut blocks: Vec<String> = Vec::new();
280 render(&doc.nodes, &mut blocks, &mut ctx);
281 blocks.join("\n\n")
282}
283
284fn apply_links(body: &str, links: &[(String, String)]) -> String {
292 let mut out = body.to_string();
293 let mut cursor = 0usize;
294 for (anchor, href) in links {
295 let anchor = anchor
296 .replace('&', "&")
297 .replace('<', "<")
298 .replace('>', ">");
299 if anchor.is_empty() {
300 continue;
301 }
302 if let Some(rel) = out[cursor..].find(&anchor) {
303 let at = cursor + rel;
304 let replacement = format!("[{anchor}]({href})");
306 out.replace_range(at..at + anchor.len(), &replacement);
307 cursor = at + replacement.len();
308 }
309 }
310 out
311}
312
313fn apply_links_chunk(chunk: &str, queue: &mut Vec<(String, String)>) -> String {
324 let mut out = chunk.to_string();
325 let mut cursor = 0usize;
326 let mut carried: Vec<(String, String)> = Vec::new();
327 for (anchor_raw, href) in std::mem::take(queue) {
328 let anchor = anchor_raw
329 .replace('&', "&")
330 .replace('<', "<")
331 .replace('>', ">");
332 if anchor.is_empty() {
333 continue;
334 }
335 if let Some(rel) = out[cursor..].find(&anchor) {
336 let at = cursor + rel;
337 let replacement = format!("[{anchor}]({href})");
338 out.replace_range(at..at + anchor.len(), &replacement);
339 cursor = at + replacement.len();
340 } else {
341 carried.push((anchor_raw, href));
343 }
344 }
345 *queue = carried;
346 out
347}
348
349pub struct MarkdownStreamer {
367 strict: bool,
368 images: ImageMode,
369 compact_tables: bool,
370 emitted_any: bool,
373 links: Vec<(String, String)>,
375 artifacts_dir: String,
379 artifacts: Vec<(String, Vec<u8>)>,
380 pic_index: usize,
381 page_break: Option<String>,
385 pending_page_break: bool,
386 items_emitted: bool,
392 layers: ContentLayers,
395 traverse_pictures: bool,
396 escape_html: bool,
397 escape_underscores: bool,
398 image_placeholder: String,
399 plain: bool,
400}
401
402impl MarkdownStreamer {
403 pub fn new(strict: bool, images: ImageMode, compact_tables: bool) -> Self {
406 debug_assert!(
407 images != ImageMode::Referenced,
408 "referenced image mode needs an artifacts dir; use with_artifacts"
409 );
410 Self::with_artifacts(strict, images, compact_tables, "artifacts")
411 }
412
413 pub fn with_artifacts(
420 strict: bool,
421 images: ImageMode,
422 compact_tables: bool,
423 artifacts_dir: &str,
424 ) -> Self {
425 Self {
426 strict,
427 images,
428 compact_tables,
429 emitted_any: false,
430 links: Vec::new(),
431 artifacts_dir: artifacts_dir.to_string(),
432 artifacts: Vec::new(),
433 pic_index: 0,
434 page_break: None,
435 pending_page_break: false,
436 items_emitted: false,
437 layers: ContentLayers::BODY,
438 traverse_pictures: false,
439 escape_html: true,
440 escape_underscores: true,
441 image_placeholder: "<!-- image -->".to_string(),
442 plain: false,
443 }
444 }
445
446 pub fn with_export_options(mut self, options: &MarkdownExportOptions) -> Self {
453 self.images = options.image_mode;
454 self.artifacts_dir = options.artifacts_dir.clone();
455 self.layers = options.layers;
456 self.traverse_pictures = options.traverse_pictures;
457 self.escape_html = options.escape_html;
458 self.escape_underscores = options.escape_underscores;
459 self.image_placeholder = options.image_placeholder.clone();
460 self.plain = options.plain_text;
461 self
462 }
463
464 pub fn with_page_break_placeholder(mut self, placeholder: Option<String>) -> Self {
469 self.page_break = placeholder;
470 self
471 }
472
473 pub fn take_artifacts(&mut self) -> Vec<(String, Vec<u8>)> {
478 std::mem::take(&mut self.artifacts)
479 }
480
481 pub fn push(&mut self, nodes: &[Node], links: &[(String, String)]) -> String {
486 self.links.extend(links.iter().cloned());
487 let mut ctx = Ctx {
488 strict: self.strict,
489 compact_tables: self.compact_tables,
490 images: self.images,
491 artifacts_dir: std::mem::take(&mut self.artifacts_dir),
492 artifacts: std::mem::take(&mut self.artifacts),
493 pic_index: self.pic_index,
494 in_table_cell: false,
495 page_break: std::mem::take(&mut self.page_break),
496 pending_page_break: self.pending_page_break,
497 emitted_any: self.items_emitted,
498 layers: self.layers,
499 current_layer: None,
500 traverse_pictures: self.traverse_pictures,
501 escape_html: self.escape_html,
502 escape_underscores: self.escape_underscores,
503 image_placeholder: std::mem::take(&mut self.image_placeholder),
504 plain: self.plain,
505 };
506 let mut blocks: Vec<String> = Vec::new();
507 render(nodes, &mut blocks, &mut ctx);
508 self.image_placeholder = std::mem::take(&mut ctx.image_placeholder);
509 self.artifacts_dir = std::mem::take(&mut ctx.artifacts_dir);
510 self.artifacts = std::mem::take(&mut ctx.artifacts);
511 self.pic_index = ctx.pic_index;
512 self.page_break = std::mem::take(&mut ctx.page_break);
513 self.pending_page_break = ctx.pending_page_break;
514 self.items_emitted = ctx.emitted_any;
515 if blocks.is_empty() {
516 return String::new();
517 }
518 let mut body = blocks.join("\n\n");
519 if self.strict && !self.plain && !self.links.is_empty() {
520 body = apply_links_chunk(&body, &mut self.links);
521 }
522 let chunk = if self.emitted_any {
523 format!("\n\n{body}")
524 } else {
525 body
526 };
527 self.emitted_any = true;
528 chunk
529 }
530
531 pub fn finish(self) -> String {
534 if self.emitted_any {
535 "\n".to_string()
536 } else {
537 String::new()
538 }
539 }
540}
541
542fn strict_text(text: &str, strict: bool) -> String {
550 if !strict {
551 return text.to_string();
552 }
553 text.replace("\\_", "_")
554 .replace(" ,", ",")
555 .replace(" .", ".")
556 .replace(" ;", ";")
557 .replace(" )", ")")
558 .replace("( ", "(")
559 .replace(" ]", "]")
560 .replace("[ ", "[")
561}
562
563pub(crate) fn plain_inline(text: &str) -> String {
576 if !text.contains(['*', '~', '`', '[']) {
577 return text.to_string();
578 }
579 let chars: Vec<char> = text.chars().collect();
580 let mut out = String::with_capacity(text.len());
581 plain_inline_into(&chars, &mut out);
582 out
583}
584
585fn plain_inline_into(chars: &[char], out: &mut String) {
586 let find = |open: usize, pat: &[char]| -> Option<usize> {
587 chars
588 .get(open..)?
589 .windows(pat.len())
590 .position(|w| w == pat)
591 .map(|p| open + p)
592 };
593 let span = |i: usize, pat: &[char]| -> Option<usize> {
596 if !chars[i..].starts_with(pat) {
597 return None;
598 }
599 let open = i + pat.len();
600 let end = find(open, pat)?;
601 (end > open && !chars[open].is_whitespace() && !chars[end - 1].is_whitespace())
602 .then_some(end)
603 };
604 let mut i = 0;
605 while i < chars.len() {
606 let mut matched = false;
607 for pat in [&['*', '*', '*'][..], &['*', '*'], &['~', '~'], &['*']] {
608 if let Some(end) = span(i, pat) {
609 plain_inline_into(&chars[i + pat.len()..end], out);
610 i = end + pat.len();
611 matched = true;
612 break;
613 }
614 }
615 if matched {
616 continue;
617 }
618 if chars[i] == '`' {
622 if let Some(end) = find(i + 1, &['`']).filter(|&e| {
623 e > i + 1 && !chars[i + 1].is_whitespace() && !chars[e - 1].is_whitespace()
624 }) {
625 out.extend(&chars[i + 1..end]);
626 i = end + 1;
627 continue;
628 }
629 }
630 if chars[i] == '$' {
633 if let Some(end) = find(i + 1, &['$']) {
634 out.extend(&chars[i..=end]);
635 i = end + 1;
636 continue;
637 }
638 }
639 if chars[i] == '[' {
642 if let Some(close) = closing_bracket(chars, i) {
643 if chars.get(close + 1) == Some(&'(') {
644 if let Some(endp) = crate::doclang::link_dest_end(chars, close + 2) {
645 plain_inline_into(&chars[i + 1..close], out);
646 i = endp + 1;
647 continue;
648 }
649 }
650 }
651 }
652 let c = chars[i];
655 out.push(c);
656 i += 1;
657 if matches!(c, '*' | '~') {
658 while i < chars.len() && chars[i] == c {
659 out.push(c);
660 i += 1;
661 }
662 }
663 }
664}
665
666fn closing_bracket(chars: &[char], open: usize) -> Option<usize> {
669 let mut depth = 0usize;
670 for (k, c) in chars.iter().enumerate().skip(open + 1) {
671 match c {
672 '[' => depth += 1,
673 ']' if depth == 0 => return Some(k),
674 ']' => depth -= 1,
675 _ => {}
676 }
677 }
678 None
679}
680
681fn md_line_breaks(text: &str) -> String {
687 if !text.contains('\n') {
688 return text.to_string();
689 }
690 text.split("\n\n")
691 .map(|para| para.replace('\n', " \n"))
692 .collect::<Vec<_>>()
693 .join("\n\n")
694}
695
696pub(crate) fn strip_hard_breaks(text: &str) -> String {
701 if text.contains(" \n") {
702 text.replace(" \n", "\n")
703 } else {
704 text.to_string()
705 }
706}
707
708fn heading_line_breaks(text: &str) -> String {
712 text.replace('\n', " ")
713}
714
715fn render(nodes: &[Node], blocks: &mut Vec<String>, ctx: &mut Ctx) {
716 let mut i = 0;
717 while i < nodes.len() {
718 let before = blocks.len();
719 match &nodes[i] {
720 Node::PageBreak | Node::PageInfo { .. } => {
730 if ctx.page_break.is_some() && ctx.emitted_any {
731 ctx.pending_page_break = true;
732 }
733 i += 1;
734 }
735 Node::ListItem { .. } => {
736 let start = i;
737 i += 1;
738 loop {
739 match nodes.get(i) {
740 Some(Node::ListItem { .. }) => i += 1,
741 Some(Node::Paragraph { text })
745 if text.is_empty()
746 && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
747 {
748 i += 1
749 }
750 _ => break,
751 }
752 }
753 render_list_run(&nodes[start..i], blocks, ctx);
754 }
755 other => {
756 render_one(other, blocks, ctx);
757 i += 1;
758 }
759 }
760 if blocks.len() > before {
761 let kept: Vec<String> = blocks.drain(before..).filter(|b| !b.is_empty()).collect();
771 blocks.extend(kept);
772 if ctx.pending_page_break {
773 if let Some(placeholder) = &ctx.page_break {
778 blocks.insert(before, placeholder.clone());
779 }
780 ctx.pending_page_break = false;
781 }
782 ctx.emitted_any = true;
783 }
784 }
785}
786
787fn render_list_run(items: &[Node], blocks: &mut Vec<String>, ctx: &Ctx) {
793 let mut lines: Vec<String> = Vec::new();
794 let mut any_top = false;
797
798 for item in items {
799 let Node::ListItem {
800 ordered,
801 number,
802 first_in_list,
803 text,
804 level,
805 marker: orig_marker,
806 location: _,
807 dclx: _,
808 href: _,
809 layer,
810 } = item
811 else {
812 continue;
813 };
814 if !ctx.layers.contains(layer.or(ctx.current_layer)) {
818 continue;
819 }
820 let level = *level as usize;
821
822 if level == 0 {
831 if any_top && *first_in_list {
832 lines.push(String::new());
833 }
834 any_top = true;
835 }
836
837 let indent = " ".repeat(level);
838 let verbatim = orig_marker.as_deref().filter(|m| {
843 m.strip_suffix('.')
844 .is_some_and(|d| !d.is_empty() && d.chars().all(char::is_numeric))
845 });
846 let marker = match verbatim {
847 Some(m) if *ordered => m.to_string(),
848 _ if *ordered => format!("{number}."),
849 _ => "-".to_string(),
850 };
851 lines.push(format!("{indent}{marker} {}", list_item_text(text, ctx)));
852 }
853
854 if !lines.is_empty() {
857 blocks.push(lines.join("\n"));
858 }
859}
860
861fn list_item_text(text: &str, ctx: &Ctx) -> String {
869 let escaped = ctx.text(text);
870 if ctx.plain {
871 return escaped;
872 }
873 if let Some((own, tail)) = escaped.split_once('\n') {
874 if is_folded_child_tail(tail) {
875 return format!("{}\n{tail}", md_line_breaks(own));
876 }
877 }
878 md_line_breaks(&escaped)
879}
880
881fn is_folded_child_tail(tail: &str) -> bool {
888 const MARKER: &str = "<!-- image -->";
889 const FENCE: &str = "```";
890 let mut lines = tail.split('\n').peekable();
891 let mut any = false;
892 while let Some(line) = lines.next() {
893 let line = line.trim_start();
894 if line == MARKER {
895 any = true;
896 } else if line == FENCE {
897 loop {
899 match lines.next() {
900 Some(l) if l.trim_start() == FENCE => break,
901 Some(_) => {}
902 None => return false,
903 }
904 }
905 any = true;
906 } else if lines.next().map(str::trim_start) == Some(MARKER) {
907 any = true; } else {
909 return false;
910 }
911 }
912 any
913}
914
915fn render_one(node: &Node, blocks: &mut Vec<String>, ctx: &mut Ctx) {
920 match node {
921 Node::Group { .. }
923 | Node::Furniture { .. }
924 | Node::PageFurniture { .. }
925 | Node::FurnitureText { .. }
926 | Node::CommentSection { .. }
927 | Node::PictureChildren(_)
928 | Node::Commented { .. }
929 | Node::Located { .. }
930 | Node::Prov { .. }
931 | Node::PageBreak
932 | Node::PageInfo { .. }
933 | Node::DoclangOnly(_) => {}
934 _ if !ctx.layer_visible() => return,
935 _ => {}
936 }
937 render_item(node, blocks, ctx)
938}
939
940fn render_item(node: &Node, blocks: &mut Vec<String>, ctx: &mut Ctx) {
941 match node {
942 Node::Heading { level, text } => {
943 if ctx.plain {
944 blocks.push(ctx.text(text));
947 return;
948 }
949 let text = heading_line_breaks(&ctx.text(text));
950 if ctx.in_table_cell {
951 blocks.push(text);
953 } else {
954 let hashes = "#".repeat((*level).clamp(1, 6) as usize);
955 blocks.push(format!("{hashes} {text}"));
956 }
957 }
958 Node::Paragraph { text } if text.is_empty() => {}
961 Node::Paragraph { text } => blocks.push(ctx.breaks(&ctx.text(text))),
962 Node::Caption { text, .. } if text.is_empty() => {}
965 Node::Caption { text, href } => {
966 let body = ctx.breaks(&ctx.text(text));
967 blocks.push(match href {
968 Some(url) if !ctx.plain => format!("[{body}]({url})"),
969 _ => body,
970 });
971 }
972 Node::CheckboxItem { checked, text } => {
973 let mark = if *checked { "- [x] " } else { "- [ ] " };
974 blocks.push(ctx.breaks(&ctx.text(&format!("{mark}{text}"))));
975 }
976 Node::Code {
977 language,
978 text,
979 pretty,
980 ..
981 } => {
982 let lang = match language {
984 Some(l) if ctx.strict => l.as_str(),
985 _ => "",
986 };
987 let body = match pretty {
990 Some(p) if ctx.strict => p.as_str(),
991 _ => text.as_str(),
992 };
993 blocks.push(if ctx.plain {
996 body.to_string()
997 } else {
998 format!("```{lang}\n{body}\n```")
999 });
1000 }
1001 Node::Formula { latex, .. } => blocks.push(format!("$${latex}$$")),
1004 Node::Table(table) => {
1005 if let Some(cap) = &table.caption {
1008 if !cap.is_empty() {
1009 blocks.push(ctx.breaks(&ctx.text(cap)));
1010 }
1011 }
1012 let rendered = if ctx.plain {
1013 render_table(&ctx.plain_table(table), ctx.compact_tables)
1014 } else {
1015 render_table(table, ctx.compact_tables)
1016 };
1017 if !rendered.is_empty() {
1018 blocks.push(rendered);
1019 }
1020 }
1021 Node::Picture { caption, image, .. } => {
1023 if let Some(cap) = caption {
1024 if !cap.is_empty() {
1025 blocks.push(ctx.breaks(&ctx.caption(cap)));
1026 }
1027 }
1028 blocks.push(picture_marker(image.as_ref(), ctx));
1029 }
1030 Node::Chart {
1034 kind,
1035 table,
1036 caption,
1037 ..
1038 } => {
1039 if let Some(cap) = caption {
1040 if !cap.is_empty() {
1041 blocks.push(ctx.breaks(&ctx.caption(cap)));
1042 }
1043 }
1044 blocks.push(picture_marker(None, ctx));
1045 blocks.push(humanize_label(kind));
1046 let rendered = if ctx.plain {
1047 render_table(&ctx.plain_table(table), false)
1048 } else {
1049 render_table(table, false)
1050 };
1051 if !rendered.is_empty() {
1052 blocks.push(rendered);
1053 }
1054 }
1055 Node::DoclangOnly(_) => {}
1057 Node::Group {
1062 layer: Some(layer),
1063 children,
1064 ..
1065 } => {
1066 let outer = ctx.current_layer.replace(*layer);
1067 render(children, blocks, ctx);
1068 ctx.current_layer = outer;
1069 }
1070 Node::Group { children, .. } => render(children, blocks, ctx),
1071 Node::FieldRegion { items } => {
1072 for item in items {
1077 for part in [&item.marker, &item.key, &item.value].into_iter().flatten() {
1078 blocks.push(ctx.breaks(&ctx.text(part)));
1079 }
1080 }
1081 }
1082 Node::KeyValueGraph { .. } => blocks.push(MISSING_KEY_VALUE_ITEM.to_string()),
1085 Node::InlineGroup { md_text, .. } => blocks.push(ctx.breaks(&ctx.text(md_text))),
1088 Node::TextDump(text) => {
1090 if !text.is_empty() {
1091 blocks.push(text.clone());
1092 }
1093 }
1094 Node::Furniture { layer, inner } => {
1098 let outer = ctx.current_layer.replace(*layer);
1099 render_one(inner, blocks, ctx);
1100 ctx.current_layer = outer;
1101 }
1102 Node::PageFurniture { text, .. } | Node::FurnitureText { text, .. } => {
1106 if ctx.layers.furniture && !text.is_empty() {
1107 blocks.push(ctx.breaks(&ctx.text(text)));
1108 }
1109 }
1110 Node::PictureChildren(children) => {
1115 if ctx.traverse_pictures {
1116 render(children, blocks, ctx);
1117 }
1118 }
1119 Node::CommentSection { text, .. } => {
1124 if ctx.layers.notes && !text.is_empty() {
1125 blocks.push(ctx.breaks(&ctx.text(text)));
1126 }
1127 }
1128 Node::Commented { inner, .. } => render_one(inner, blocks, ctx),
1129 Node::Located { inner, .. } | Node::Prov { inner, .. } => render_one(inner, blocks, ctx),
1131 Node::PageBreak => {}
1133 Node::PageInfo { .. } => {}
1135 Node::ListItem { .. } => render_list_run(std::slice::from_ref(node), blocks, ctx),
1140 }
1141}
1142
1143fn humanize_label(label: &str) -> String {
1148 let text = label.replace('_', " ");
1149 let mut chars = text.chars();
1150 match chars.next() {
1151 Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
1152 None => text,
1153 }
1154}
1155
1156fn picture_marker(image: Option<&crate::PictureImage>, ctx: &mut Ctx) -> String {
1157 match (ctx.images, image) {
1158 (ImageMode::Embedded, Some(img)) => {
1160 format!("", crate::pixel_digest::docling_data_uri(img).1)
1161 }
1162 (ImageMode::Referenced, Some(img)) => {
1163 let path = format!(
1164 "{}/image_{:06}.{}",
1165 ctx.artifacts_dir,
1166 ctx.pic_index,
1167 ext_for(&img.mimetype)
1168 );
1169 ctx.pic_index += 1;
1170 ctx.artifacts.push((path.clone(), img.data.clone()));
1171 format!("", escape_uri_path(&path))
1172 }
1173 _ => ctx.image_placeholder.clone(),
1175 }
1176}
1177
1178pub(crate) fn escape_uri_path(value: &str) -> String {
1191 const KEEP: &str = "/%:@+,;=~$!&'*";
1192 let s = value.replace('\\', "/");
1193 if let Some(rest) = s.strip_prefix("//") {
1194 let rest = rest.trim_start_matches('/');
1196 let (host, tail) = rest.split_once('/').unwrap_or((rest, ""));
1197 return format!("file://{host}{}", percent_quote(&format!("/{tail}"), KEEP));
1198 }
1199 let bytes = s.as_bytes();
1200 if bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && bytes[2] == b'/' {
1201 return format!("file:///{}", percent_quote(&s, KEEP));
1203 }
1204 if let Some((scheme, rest)) = s.split_once(':') {
1208 let valid_scheme = scheme.len() > 1
1209 && scheme.as_bytes()[0].is_ascii_alphabetic()
1210 && scheme
1211 .bytes()
1212 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'));
1213 if valid_scheme {
1214 let (authority, rest) = match rest.strip_prefix("//") {
1215 Some(r) => {
1216 let end = r.find(['/', '?', '#']).unwrap_or(r.len());
1217 (Some(&r[..end]), &r[end..])
1218 }
1219 None => (None, rest),
1220 };
1221 let (before_frag, fragment) = rest.split_once('#').unwrap_or((rest, ""));
1222 let (path, query) = before_frag.split_once('?').unwrap_or((before_frag, ""));
1223 let mut out = format!("{scheme}:");
1224 if let Some(a) = authority {
1225 out.push_str("//");
1226 out.push_str(a);
1227 }
1228 out.push_str(&percent_quote(path, KEEP));
1229 if !query.is_empty() {
1230 out.push('?');
1231 out.push_str(&percent_quote(query, KEEP));
1232 }
1233 if !fragment.is_empty() {
1234 out.push('#');
1235 out.push_str(&percent_quote(fragment, KEEP));
1236 }
1237 return out;
1238 }
1239 }
1240 percent_quote(&s, KEEP)
1242}
1243
1244fn percent_quote(s: &str, safe: &str) -> String {
1247 let mut out = String::with_capacity(s.len());
1248 for &b in s.as_bytes() {
1249 let keep = b.is_ascii_alphanumeric()
1250 || matches!(b, b'_' | b'.' | b'-' | b'~')
1251 || (b.is_ascii() && safe.contains(b as char));
1252 if keep {
1253 out.push(b as char);
1254 } else {
1255 out.push_str(&format!("%{b:02X}"));
1256 }
1257 }
1258 out
1259}
1260
1261pub(crate) fn ext_for(mimetype: &str) -> &str {
1262 match mimetype {
1263 "image/jpeg" => "jpg",
1264 "image/gif" => "gif",
1265 "image/webp" => "webp",
1266 "image/bmp" => "bmp",
1267 "image/tiff" => "tif",
1268 _ => "png",
1269 }
1270}
1271
1272fn is_number_cell(t: &str) -> bool {
1291 t.parse::<f64>().is_ok() || is_thousands_number(t)
1292}
1293
1294fn is_thousands_number(t: &str) -> bool {
1300 let b = t.as_bytes();
1301 let mut i = 0;
1302 let start = i;
1303 if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
1304 i += 1;
1305 }
1306 let d0 = i;
1308 while i < b.len() && b[i].is_ascii_digit() && i - d0 < 3 {
1309 i += 1;
1310 }
1311 let has_int = i > d0;
1312 if has_int {
1313 while i + 3 < b.len() + 1
1315 && b.get(i) == Some(&b',')
1316 && b.get(i + 1).is_some_and(u8::is_ascii_digit)
1317 && b.get(i + 2).is_some_and(u8::is_ascii_digit)
1318 && b.get(i + 3).is_some_and(u8::is_ascii_digit)
1319 {
1320 i += 4;
1321 }
1322 } else {
1323 i = start;
1325 }
1326 if i < b.len() && b[i] == b'.' {
1328 i += 1;
1329 let f0 = i;
1330 while i < b.len() && b[i].is_ascii_digit() {
1331 i += 1;
1332 }
1333 if !has_int && i == f0 {
1334 return false; }
1336 } else if !has_int {
1337 return false; }
1339 i == b.len()
1340}
1341
1342fn flatten_header_rows(header_rows: &[Vec<String>], num_cols: usize) -> Vec<String> {
1351 (0..num_cols)
1352 .map(|c| {
1353 let mut parts: Vec<&str> = Vec::new();
1354 for row in header_rows {
1355 let text = row.get(c).map(String::as_str).unwrap_or("");
1356 if !text.is_empty() && parts.last() != Some(&text) {
1357 parts.push(text);
1358 }
1359 }
1360 parts.join(" - ")
1361 })
1362 .collect()
1363}
1364
1365pub(crate) fn render_table(table: &Table, compact: bool) -> String {
1366 if table.rows.is_empty() {
1367 return String::new();
1368 }
1369 let num_cols = table.rows.iter().map(Vec::len).max().unwrap_or(0);
1370 if num_cols == 0 {
1371 return String::new();
1372 }
1373
1374 let num_headers = table.header_row_count().min(table.rows.len());
1379 let escaped = |r: usize| -> Vec<String> {
1380 (0..num_cols)
1381 .map(|c| escape_cell(table.rows[r].get(c).map(String::as_str).unwrap_or("")))
1382 .collect()
1383 };
1384 let header_rows: Vec<Vec<String>> = (0..num_headers).map(escaped).collect();
1385 let header = flatten_header_rows(&header_rows, num_cols);
1386 let body: Vec<Vec<String>> = (num_headers..table.rows.len())
1387 .map(|r| {
1388 escaped(r)
1389 .into_iter()
1390 .map(|c| c.trim().to_string())
1391 .collect()
1392 })
1393 .collect();
1394
1395 if compact {
1396 let render_row = |row: &[String]| -> String { format!("| {} |", row.join(" | ")) };
1398 let mut lines = Vec::with_capacity(body.len() + 2);
1399 lines.push(render_row(&header));
1400 let sep: Vec<&str> = (0..num_cols).map(|_| "-").collect();
1401 lines.push(format!("| {} |", sep.join(" | ")));
1402 for row in &body {
1403 lines.push(render_row(row));
1404 }
1405 return lines.join("\n");
1406 }
1407
1408 let dw = |s: &str| s.chars().count();
1410
1411 let right: Vec<bool> = (0..num_cols)
1416 .map(|c| {
1417 let mut any = false;
1418 for row in &body {
1419 let t = row[c].trim();
1420 if t.is_empty() {
1421 continue;
1422 }
1423 if !is_number_cell(t) {
1424 return false;
1425 }
1426 any = true;
1427 }
1428 any
1429 })
1430 .collect();
1431
1432 let width: Vec<usize> = (0..num_cols)
1434 .map(|c| {
1435 let mut w = dw(&header[c]) + 2;
1436 for row in &body {
1437 w = w.max(dw(&row[c]));
1438 }
1439 w
1440 })
1441 .collect();
1442
1443 let fmt_cell = |s: &str, c: usize| -> String {
1444 let pad = " ".repeat(width[c].saturating_sub(dw(s)));
1445 let body = if right[c] {
1446 format!("{pad}{s}")
1447 } else {
1448 format!("{s}{pad}")
1449 };
1450 format!(" {body} ")
1451 };
1452 let render_row = |row: &[String]| -> String {
1453 let cells: Vec<String> = (0..num_cols).map(|c| fmt_cell(&row[c], c)).collect();
1454 format!("|{}|", cells.join("|"))
1455 };
1456
1457 let mut lines = Vec::with_capacity(body.len() + 2);
1458 lines.push(render_row(&header));
1459 let sep: Vec<String> = (0..num_cols).map(|c| "-".repeat(width[c] + 2)).collect();
1460 lines.push(format!("|{}|", sep.join("|")));
1461 for row in &body {
1462 lines.push(render_row(row));
1463 }
1464 lines.join("\n")
1465}
1466
1467fn escape_cell(s: &str) -> String {
1470 s.replace('\n', " ").replace('|', "|")
1471}
1472
1473#[cfg(test)]
1474mod tests {
1475 use super::*;
1476 use crate::{PictureImage, TableCell, TableStructure};
1477
1478 #[test]
1484 fn list_boundaries_come_from_the_backend_not_the_numbering() {
1485 let item = |ordered: bool, number: u64, first_in_list: bool, text: &str| Node::ListItem {
1486 ordered,
1487 number,
1488 first_in_list,
1489 text: text.into(),
1490 level: 0,
1491 marker: None,
1492 location: None,
1493 dclx: None,
1494 href: None,
1495 layer: None,
1496 };
1497 let md = |items: Vec<Node>| {
1498 let mut doc = DoclingDocument::new("t");
1499 for n in items {
1500 doc.push(n);
1501 }
1502 doc.export_to_markdown()
1503 };
1504 assert_eq!(
1506 md(vec![
1507 item(true, 1, true, "one"),
1508 item(true, 5, false, "five")
1509 ]),
1510 "1. one\n5. five\n"
1511 );
1512 assert_eq!(
1514 md(vec![
1515 item(false, 0, true, "bullet"),
1516 item(true, 1, false, "one"),
1517 item(false, 0, false, "bullet two"),
1518 ]),
1519 "- bullet\n1. one\n- bullet two\n"
1520 );
1521 assert_eq!(
1523 md(vec![
1524 item(true, 1, true, "a"),
1525 item(true, 2, false, "b"),
1526 item(true, 3, true, "new list, continuing count"),
1527 ]),
1528 "1. a\n2. b\n\n3. new list, continuing count\n"
1529 );
1530 }
1531
1532 #[test]
1533 fn renders_headings_paragraphs_and_lists() {
1534 let mut doc = DoclingDocument::new("demo");
1535 doc.add_heading(1, "Title");
1536 doc.add_paragraph("Hello world.");
1537 doc.push(Node::ListItem {
1538 ordered: false,
1539 number: 1,
1540 first_in_list: true,
1541 text: "first".into(),
1542 level: 0,
1543 marker: None,
1544 location: None,
1545 dclx: None,
1546 href: None,
1547 layer: None,
1548 });
1549 doc.push(Node::ListItem {
1550 ordered: false,
1551 number: 2,
1552 first_in_list: false,
1553 text: "second".into(),
1554 level: 0,
1555 marker: None,
1556 location: None,
1557 dclx: None,
1558 href: None,
1559 layer: None,
1560 });
1561 let md = doc.export_to_markdown();
1562 assert_eq!(md, "# Title\n\nHello world.\n\n- first\n- second\n");
1563 }
1564
1565 #[test]
1569 fn single_newlines_become_gfm_hard_line_breaks() {
1570 let mut doc = DoclingDocument::new("t");
1571 doc.push(Node::Heading {
1572 level: 1,
1573 text: "Hello\nWorld".into(),
1574 });
1575 doc.push(Node::Paragraph {
1576 text: "line one\nline two\n\npara two".into(),
1577 });
1578 doc.push(Node::ListItem {
1579 ordered: false,
1580 number: 1,
1581 first_in_list: true,
1582 text: "item\ncontinued".into(),
1583 level: 0,
1584 marker: None,
1585 location: None,
1586 dclx: None,
1587 href: None,
1588 layer: None,
1589 });
1590 doc.push(Node::TextDump("A1 B1 \n\n\nC1".into()));
1591 assert_eq!(
1592 doc.export_to_markdown(),
1593 "# Hello World\n\nline one \nline two\n\npara two\n\n- item \ncontinued\n\nA1 B1 \n\n\nC1\n"
1594 );
1595 }
1596
1597 #[test]
1600 fn table_cell_mode_and_field_regions() {
1601 let mut doc = DoclingDocument::new("t");
1602 doc.push(Node::Heading {
1603 level: 2,
1604 text: "A text".into(),
1605 });
1606 doc.push(Node::Paragraph {
1607 text: "body".into(),
1608 });
1609 assert_eq!(to_markdown_table_cell(&doc, false), "A text\n\nbody");
1610 assert_eq!(doc.export_to_markdown(), "## A text\n\nbody\n");
1611
1612 let mut doc = DoclingDocument::new("f");
1613 doc.push(Node::FieldRegion {
1614 items: vec![crate::FieldItem {
1615 marker: None,
1616 key: Some("Name:".into()),
1617 value: Some("John Doe".into()),
1618 value_kind: None,
1619 }],
1620 });
1621 assert_eq!(doc.export_to_markdown(), "Name:\n\nJohn Doe\n");
1622 }
1623
1624 #[test]
1625 fn strict_renders_recovered_links_legacy_does_not() {
1626 let mut doc = DoclingDocument::new("cv");
1627 doc.add_paragraph("Find me on LinkedIn or GitHub.");
1628 doc.links = vec![
1629 ("LinkedIn".into(), "https://www.linkedin.com/in/x/".into()),
1630 ("GitHub".into(), "https://github.com/x/".into()),
1631 ];
1632 assert_eq!(doc.export_to_markdown(), "Find me on LinkedIn or GitHub.\n");
1634 assert_eq!(
1636 doc.export_to_markdown_with(true),
1637 "Find me on [LinkedIn](https://www.linkedin.com/in/x/) or [GitHub](https://github.com/x/).\n"
1638 );
1639 }
1640
1641 #[test]
1642 fn strict_links_match_escaped_anchor_and_consume_in_order() {
1643 let mut doc = DoclingDocument::new("d");
1644 doc.add_paragraph("AI & ML here, and issues here, then issues there.");
1648 doc.links = vec![
1649 ("AI & ML".into(), "https://a/".into()),
1650 ("issues".into(), "https://first/".into()),
1651 ("issues".into(), "https://second/".into()),
1652 ];
1653 assert_eq!(
1654 doc.export_to_markdown_with(true),
1655 "[AI & ML](https://a/) here, and [issues](https://first/) here, then [issues](https://second/) there.\n"
1656 );
1657 }
1658
1659 #[test]
1663 fn referenced_image_destinations_are_escaped() {
1664 let cases = [
1665 (
1666 "doc_artifacts/image_000001_ab12.png",
1667 "doc_artifacts/image_000001_ab12.png",
1668 ),
1669 (
1670 "My Report_artifacts/img.png",
1671 "My%20Report_artifacts/img.png",
1672 ),
1673 ("artifacts/img (1).png", "artifacts/img%20%281%29.png"),
1674 ("100%_scale/a#b?c.png", "100%_scale/a%23b%3Fc.png"),
1675 ("/home/a b/img.png", "/home/a%20b/img.png"),
1676 (
1677 "My Report_artifacts\\img.png",
1678 "My%20Report_artifacts/img.png",
1679 ),
1680 (
1681 "C:/Users/me/My Docs/img.png",
1682 "file:///C:/Users/me/My%20Docs/img.png",
1683 ),
1684 ("C:\\Users\\me\\img.png", "file:///C:/Users/me/img.png"),
1685 (
1686 "//server/share/My Docs/img.png",
1687 "file://server/share/My%20Docs/img.png",
1688 ),
1689 ("\\\\server\\share\\img.png", "file://server/share/img.png"),
1690 ("file:///home/a b/img.png", "file:///home/a%20b/img.png"),
1691 (
1692 "s3://bucket/My Report_artifacts/img.png",
1693 "s3://bucket/My%20Report_artifacts/img.png",
1694 ),
1695 (
1696 "https://example.com:8080/a b.png?w=1&h=2#frag",
1697 "https://example.com:8080/a%20b.png?w=1&h=2#frag",
1698 ),
1699 (
1700 "https://example.com/img (1).png",
1701 "https://example.com/img%20%281%29.png",
1702 ),
1703 ("caf\u{e9}/im\u{e4}ge.png", "caf%C3%A9/im%C3%A4ge.png"),
1704 ];
1705 for (input, expected) in cases {
1706 assert_eq!(escape_uri_path(input), expected, "input {input:?}");
1707 assert_eq!(
1708 escape_uri_path(expected),
1709 expected,
1710 "idempotent {expected:?}"
1711 );
1712 }
1713 let mut doc = DoclingDocument::new("t");
1715 doc.push(Node::Picture {
1716 caption: None,
1717 caption_href: None,
1718 image: Some(PictureImage {
1719 dpi: PictureImage::DEFAULT_DPI,
1720 mimetype: "image/png".into(),
1721 width: 1,
1722 height: 1,
1723 data: b"x".to_vec(),
1724 }),
1725 classification: None,
1726 caption_parent: Default::default(),
1727 caption_location: None,
1728 });
1729 let (md, files) = doc
1730 .export_to_markdown_with_images(ImageMode::Referenced, "My Report (final)_artifacts");
1731 assert!(
1732 md.contains(""),
1733 "got:\n{md}"
1734 );
1735 assert_eq!(files[0].0, "My Report (final)_artifacts/image_000000.png");
1737 }
1738
1739 #[test]
1743 fn folded_list_item_pictures_keep_plain_newlines() {
1744 let doc = DoclingDocument::new("t");
1745 let ctx = Ctx::new(&doc, false, &MarkdownExportOptions::default());
1746 assert_eq!(
1747 list_item_text("Step\n<!-- image -->", &ctx),
1748 "Step\n<!-- image -->"
1749 );
1750 assert_eq!(
1751 list_item_text("Step\nAlt text\n<!-- image -->\n<!-- image -->", &ctx),
1752 "Step\nAlt text\n<!-- image -->\n<!-- image -->"
1753 );
1754 assert_eq!(
1755 list_item_text("line one\nline two", &ctx),
1756 "line one \nline two"
1757 );
1758 }
1759
1760 #[test]
1763 fn stacked_header_rows_flatten_into_one() {
1764 let mut t = Table {
1765 rows: vec![
1766 vec!["".into(), "% of Total".into(), "% of Total".into()],
1767 vec!["class".into(), "Train".into(), "Test".into()],
1768 vec!["Caption".into(), "2.04".into(), "1.77".into()],
1769 ],
1770 ..Default::default()
1771 };
1772 t.structure = Some(TableStructure {
1773 header_row: vec![true, true, false],
1774 col_continuation: vec![
1775 vec![false, false, true],
1776 vec![false, false, false],
1777 vec![false, false, false],
1778 ],
1779 ..Default::default()
1780 });
1781 assert_eq!(t.header_row_count(), 2);
1782 assert_eq!(
1783 render_table(&t, true),
1784 "| class | % of Total - Train | % of Total - Test |\n| - | - | - |\n| Caption | 2.04 | 1.77 |"
1785 );
1786 assert_eq!(
1788 render_table(&t, false),
1789 "| class | % of Total - Train | % of Total - Test |\n\
1790 |---------|----------------------|---------------------|\n\
1791 | Caption | 2.04 | 1.77 |"
1792 );
1793 }
1794
1795 #[test]
1798 fn vertically_spanning_header_does_not_extend_the_block() {
1799 let mut t = Table {
1800 rows: vec![
1801 vec!["Name".into(), "Value".into()],
1802 vec!["Name".into(), "1".into()],
1803 vec!["x".into(), "2".into()],
1804 ],
1805 ..Default::default()
1806 };
1807 t.structure = Some(TableStructure {
1808 col_header: vec![vec![true, true], vec![true, false], vec![false, false]],
1809 row_continuation: vec![vec![false, false], vec![true, false], vec![false, false]],
1810 ..Default::default()
1811 });
1812 assert_eq!(t.header_row_count(), 1);
1813 assert_eq!(
1814 render_table(&t, true),
1815 "| Name | Value |\n| - | - |\n| Name | 1 |\n| x | 2 |"
1816 );
1817 }
1818
1819 #[test]
1822 fn header_flags_not_on_row_zero_keep_all_rows_in_the_body() {
1823 let mut t = Table {
1824 rows: vec![
1825 vec!["1".into(), "2".into()],
1826 vec!["a".into(), "b".into()],
1827 vec!["333".into(), "4".into()],
1828 ],
1829 ..Default::default()
1830 };
1831 t.structure = Some(TableStructure {
1832 header_row: vec![false, true, false],
1833 ..Default::default()
1834 });
1835 assert_eq!(t.header_row_count(), 0);
1836 assert_eq!(
1837 render_table(&t, false),
1838 "| | |\n|-----|----|\n| 1 | 2 |\n| a | b |\n| 333 | 4 |"
1839 );
1840 }
1841
1842 #[test]
1847 fn pivot_row_headers_do_not_extend_the_header() {
1848 let mut t = Table {
1849 rows: vec![
1850 vec!["Year".into(), "Month".into()],
1851 vec!["2025".into(), "January".into()],
1852 vec!["2025".into(), "February".into()],
1853 ],
1854 ..Default::default()
1855 };
1856 t.structure = Some(TableStructure {
1857 col_header: vec![vec![true, true], vec![false, false], vec![false, false]],
1858 row_header: vec![vec![false, false], vec![true, false], vec![true, false]],
1859 row_continuation: vec![vec![false, false], vec![false, false], vec![true, false]],
1860 ..Default::default()
1861 });
1862 assert_eq!(t.header_row_count(), 1);
1863 assert_eq!(
1864 render_table(&t, true),
1865 "| Year | Month |\n| - | - |\n| 2025 | January |\n| 2025 | February |"
1866 );
1867 }
1868
1869 #[test]
1872 fn unflagged_cells_keep_row_zero_as_header() {
1873 let mut t = Table {
1874 rows: vec![vec!["h".into()], vec!["d".into()]],
1875 ..Default::default()
1876 };
1877 t.cells = Some(
1878 [(0usize, "h"), (1, "d")]
1879 .into_iter()
1880 .map(|(r, text)| TableCell {
1881 text: text.into(),
1882 bbox: None,
1883 start_row: r,
1884 start_col: 0,
1885 row_span: 1,
1886 col_span: 1,
1887 column_header: false,
1888 row_header: false,
1889 row_section: false,
1890 })
1891 .collect(),
1892 );
1893 assert_eq!(t.header_row_count(), 1);
1894 assert_eq!(render_table(&t, true), "| h |\n| - |\n| d |");
1895 }
1896
1897 fn flagged_table(rows: &[&[&str]], ched: impl Fn(usize, usize) -> bool) -> Table {
1899 let mut cells = Vec::new();
1900 for (r, row) in rows.iter().enumerate() {
1901 for (c, text) in row.iter().enumerate() {
1902 cells.push(TableCell {
1903 text: (*text).into(),
1904 bbox: None,
1905 start_row: r,
1906 start_col: c,
1907 row_span: 1,
1908 col_span: 1,
1909 column_header: ched(r, c),
1910 row_header: false,
1911 row_section: false,
1912 });
1913 }
1914 }
1915 Table {
1916 rows: rows
1917 .iter()
1918 .map(|row| row.iter().map(|t| (*t).to_string()).collect())
1919 .collect(),
1920 cells: Some(cells),
1921 ..Default::default()
1922 }
1923 }
1924
1925 #[test]
1929 fn rows_with_body_text_stop_the_header_block() {
1930 let t = flagged_table(
1932 &[
1933 &["Item", "Q1", "Q2"],
1934 &["Sales", "10", "20"],
1935 &["Costs", "5", "7"],
1936 ],
1937 |r, c| r == 0 || c == 0,
1938 );
1939 assert_eq!(t.header_row_count(), 1);
1940 assert_eq!(
1941 render_table(&t, false),
1942 "| Item | Q1 | Q2 |\n\
1943 |--------|------|------|\n\
1944 | Sales | 10 | 20 |\n\
1945 | Costs | 5 | 7 |"
1946 );
1947 let t = flagged_table(&[&["Sales", "10", "20"], &["Costs", "5", "7"]], |_, c| {
1950 c == 0
1951 });
1952 assert_eq!(t.header_row_count(), 0);
1953 assert_eq!(
1954 render_table(&t, false),
1955 "| | | |\n\
1956 |-------|----|----|\n\
1957 | Sales | 10 | 20 |\n\
1958 | Costs | 5 | 7 |"
1959 );
1960 let t = flagged_table(
1961 &[&["a", "1", "2"], &["b", "3", "4"], &["c", "5", "6"]],
1962 |r, c| c == 0 && r < 2,
1963 );
1964 assert_eq!(t.header_row_count(), 0);
1965 let t = flagged_table(&[&["a", "1", "2"], &["b", "3", "4"]], |r, c| {
1968 r == 0 && c == 0
1969 });
1970 assert_eq!(t.header_row_count(), 1);
1971 assert_eq!(
1972 render_table(&t, false),
1973 "| a | 1 | 2 |\n\
1974 |-----|-----|-----|\n\
1975 | b | 3 | 4 |"
1976 );
1977 let t = flagged_table(&[&["Item", "", ""], &["x", "1", "2"]], |_, c| c == 0);
1979 assert_eq!(t.header_row_count(), 1);
1980 assert_eq!(
1981 render_table(&t, false),
1982 "| Item | | |\n\
1983 |--------|----|----|\n\
1984 | x | 1 | 2 |"
1985 );
1986 }
1987
1988 #[test]
1989 fn renders_compact_table() {
1990 let mut doc = DoclingDocument::new("t");
1991 doc.compact_tables = true;
1994 doc.push(Node::Table(Table {
1995 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
1996 location: None,
1997 structure: None,
1998 cell_blocks: None,
1999 cells: None,
2000 caption: None,
2001 caption_parent: Default::default(),
2002 caption_location: None,
2003 }));
2004 let md = doc.export_to_markdown();
2005 assert_eq!(md, "| a | b |\n| - | - |\n| 1 | 2 |\n");
2006 }
2007
2008 #[test]
2009 fn renders_padded_github_table_by_default() {
2010 let mut doc = DoclingDocument::new("t");
2011 doc.push(Node::Table(Table {
2012 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
2013 location: None,
2014 structure: None,
2015 cell_blocks: None,
2016 cells: None,
2017 caption: None,
2018 caption_parent: Default::default(),
2019 caption_location: None,
2020 }));
2021 let md = doc.export_to_markdown();
2022 assert_eq!(md, "| a | b |\n|-----|-----|\n| 1 | 2 |\n");
2024 }
2025
2026 #[test]
2027 fn strict_unescapes_inline_underscores_legacy_keeps_them() {
2028 let mut doc = DoclingDocument::new("t");
2029 doc.add_heading(1, "a\\_b");
2030 doc.add_paragraph("x\\_y");
2031 doc.push(Node::ListItem {
2032 ordered: false,
2033 number: 1,
2034 first_in_list: true,
2035 text: "i\\_j".into(),
2036 level: 0,
2037 marker: None,
2038 location: None,
2039 dclx: None,
2040 href: None,
2041 layer: None,
2042 });
2043 assert_eq!(doc.export_to_markdown(), "# a\\_b\n\nx\\_y\n\n- i\\_j\n");
2045 assert_eq!(doc.export_to_markdown_with(true), "# a_b\n\nx_y\n\n- i_j\n");
2047 }
2048
2049 fn assert_stream_matches(
2052 doc: &DoclingDocument,
2053 strict: bool,
2054 images: ImageMode,
2055 splits: &[usize],
2056 ) {
2057 let (want, want_artifacts) = to_markdown_images(doc, strict, images, "artifacts");
2058 let mut streamer =
2059 MarkdownStreamer::with_artifacts(strict, images, doc.compact_tables, "artifacts")
2060 .with_page_break_placeholder(doc.page_break_placeholder.clone());
2061 let mut got = String::new();
2062 let mut got_artifacts = Vec::new();
2063 let mut start = 0;
2064 for &end in splits {
2065 let links = if start == 0 {
2068 doc.links.as_slice()
2069 } else {
2070 &[]
2071 };
2072 got.push_str(&streamer.push(&doc.nodes[start..end], links));
2073 got_artifacts.extend(streamer.take_artifacts());
2076 start = end;
2077 }
2078 got.push_str(&streamer.push(
2079 &doc.nodes[start..],
2080 if start == 0 {
2081 doc.links.as_slice()
2082 } else {
2083 &[]
2084 },
2085 ));
2086 got_artifacts.extend(streamer.take_artifacts());
2087 got.push_str(&streamer.finish());
2088 assert_eq!(
2089 got, want,
2090 "streamed output diverged (splits={splits:?}, strict={strict})"
2091 );
2092 assert_eq!(
2093 got_artifacts, want_artifacts,
2094 "streamed artifacts diverged (splits={splits:?}, strict={strict})"
2095 );
2096 }
2097
2098 #[test]
2099 fn streaming_is_byte_identical_to_buffered() {
2100 let mut doc = DoclingDocument::new("d");
2101 doc.add_heading(1, "Title");
2102 doc.add_paragraph("First paragraph.");
2103 doc.push(Node::ListItem {
2104 ordered: false,
2105 number: 1,
2106 first_in_list: true,
2107 text: "a".into(),
2108 level: 0,
2109 marker: None,
2110 location: None,
2111 dclx: None,
2112 href: None,
2113 layer: None,
2114 });
2115 doc.push(Node::ListItem {
2116 ordered: false,
2117 number: 2,
2118 first_in_list: false,
2119 text: "b".into(),
2120 level: 0,
2121 marker: None,
2122 location: None,
2123 dclx: None,
2124 href: None,
2125 layer: None,
2126 });
2127 doc.push(Node::Code {
2128 language: Some("rust".into()),
2129 text: "let x = 1;".into(),
2130 orig: None,
2131 pretty: None,
2132 });
2133 doc.push(Node::Table(Table {
2134 rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]],
2135 location: None,
2136 structure: None,
2137 cell_blocks: None,
2138 cells: None,
2139 caption: None,
2140 caption_parent: Default::default(),
2141 caption_location: None,
2142 }));
2143 doc.push(Node::Picture {
2144 caption: Some("Fig 1".into()),
2145 caption_href: None,
2146 image: Some(PictureImage {
2147 dpi: PictureImage::DEFAULT_DPI,
2148 mimetype: "image/png".into(),
2149 width: 2,
2150 height: 2,
2151 data: b"png-one".to_vec(),
2152 }),
2153 classification: None,
2154 caption_parent: Default::default(),
2155 caption_location: None,
2156 });
2157 doc.add_paragraph("Last paragraph.");
2158 doc.push(Node::Picture {
2161 caption: None,
2162 caption_href: None,
2163 image: Some(PictureImage {
2164 dpi: PictureImage::DEFAULT_DPI,
2165 mimetype: "image/png".into(),
2166 width: 2,
2167 height: 2,
2168 data: b"png-two".to_vec(),
2169 }),
2170 classification: None,
2171 caption_parent: Default::default(),
2172 caption_location: None,
2173 });
2174
2175 for &strict in &[false, true] {
2178 for &images in &[
2179 ImageMode::Placeholder,
2180 ImageMode::Embedded,
2181 ImageMode::Referenced,
2182 ] {
2183 for splits in [&[][..], &[1][..], &[2][..], &[4][..], &[1, 4, 6, 7][..]] {
2184 assert_stream_matches(&doc, strict, images, splits);
2185 }
2186 }
2187 }
2188 }
2189
2190 #[test]
2191 fn streaming_applies_recovered_links_in_strict_mode() {
2192 let mut doc = DoclingDocument::new("d");
2193 doc.add_paragraph("See LinkedIn for details.");
2194 doc.add_paragraph("And GitHub too.");
2195 doc.links = vec![
2196 ("LinkedIn".into(), "https://lnkd/".into()),
2197 ("GitHub".into(), "https://gh/".into()),
2198 ];
2199 assert_stream_matches(&doc, true, ImageMode::Placeholder, &[1]);
2202 }
2203
2204 fn paged_doc() -> DoclingDocument {
2207 let mut doc = DoclingDocument::new("p");
2208 doc.push(Node::PageInfo {
2209 page_no: 1,
2210 width: 100.0,
2211 height: 100.0,
2212 });
2213 doc.add_heading(1, "Title");
2214 doc.add_paragraph("Page one.");
2215 doc.push(Node::PageBreak);
2217 doc.push(Node::PageInfo {
2218 page_no: 2,
2219 width: 100.0,
2220 height: 100.0,
2221 });
2222 doc.push(Node::PageFurniture {
2223 footer: true,
2224 location: [0, 500, 511, 511],
2225 text: "2".into(),
2226 });
2227 doc.push(Node::PageBreak);
2228 doc.push(Node::PageInfo {
2229 page_no: 3,
2230 width: 100.0,
2231 height: 100.0,
2232 });
2233 doc.add_paragraph("Page three.");
2234 doc.push(Node::PageBreak);
2236 doc
2237 }
2238
2239 #[test]
2240 fn page_break_placeholder_lands_between_pages_only() {
2241 let mut doc = paged_doc();
2242 assert_eq!(
2244 doc.export_to_markdown(),
2245 "# Title\n\nPage one.\n\nPage three.\n"
2246 );
2247 doc.page_break_placeholder = Some("<!-- page break -->".into());
2248 assert_eq!(
2252 doc.export_to_markdown(),
2253 "# Title\n\nPage one.\n\n<!-- page break -->\n\nPage three.\n"
2254 );
2255 doc.page_break_placeholder = Some(String::new());
2258 assert_eq!(
2259 doc.export_to_markdown(),
2260 "# Title\n\nPage one.\n\n\n\nPage three.\n"
2261 );
2262 }
2263
2264 #[test]
2265 fn page_break_placeholder_never_leads_a_single_page() {
2266 let mut doc = DoclingDocument::new("one");
2267 doc.page_break_placeholder = Some("---".into());
2268 doc.push(Node::PageBreak);
2269 doc.push(Node::PageInfo {
2270 page_no: 1,
2271 width: 10.0,
2272 height: 10.0,
2273 });
2274 doc.add_paragraph("Only page.");
2275 assert_eq!(doc.export_to_markdown(), "Only page.\n");
2276 doc.push(Node::PageBreak);
2278 doc.push(Node::PageBreak);
2279 doc.add_paragraph("Next.");
2280 assert_eq!(doc.export_to_markdown(), "Only page.\n\n---\n\nNext.\n");
2281 }
2282
2283 #[test]
2284 fn page_break_placeholder_streams_byte_identical() {
2285 let mut doc = paged_doc();
2286 doc.page_break_placeholder = Some("<!-- page break -->".into());
2287 for splits in [
2291 &[3usize][..],
2292 &[3, 6],
2293 &[3, 6, 8],
2294 &[1, 2, 3, 4, 5, 6, 7, 8, 9],
2295 &[8],
2296 ] {
2297 assert_stream_matches(&doc, false, ImageMode::Placeholder, splits);
2298 assert_stream_matches(&doc, true, ImageMode::Placeholder, splits);
2299 }
2300 }
2301
2302 #[test]
2303 fn strict_tightens_punctuation_spacing_legacy_keeps_it() {
2304 let mut doc = DoclingDocument::new("t");
2305 doc.add_paragraph("see [ 37 , 36 ] and ( x ) .");
2306 assert_eq!(doc.export_to_markdown(), "see [ 37 , 36 ] and ( x ) .\n");
2308 assert_eq!(doc.export_to_markdown_with(true), "see [37, 36] and (x).\n");
2310 }
2311
2312 fn options_doc() -> DoclingDocument {
2317 use crate::document::ContentLayer;
2318 let mut doc = DoclingDocument::new("opts");
2319 doc.push(Node::PageFurniture {
2320 footer: false,
2321 location: [0, 0, 0, 0],
2322 text: "FAX COVER \\_ R&D".into(),
2323 });
2324 doc.add_heading(1, "R&D \\_ report");
2325 doc.add_paragraph("Body a\\_b <tag>");
2326 doc.push(Node::Picture {
2327 caption: Some("Figure 1".into()),
2328 caption_href: None,
2329 image: None,
2330 classification: None,
2331 caption_parent: Default::default(),
2332 caption_location: None,
2333 });
2334 doc.push(Node::PictureChildren(vec![
2335 Node::Paragraph {
2336 text: "Field: Name".into(),
2337 },
2338 Node::Paragraph {
2339 text: "Field: Date".into(),
2340 },
2341 ]));
2342 doc.push(Node::CommentSection {
2343 name: "comment-1".into(),
2344 text: "[author: A]: note".into(),
2345 refs_note_text: false,
2346 grouped: true,
2347 });
2348 doc.push(Node::Group {
2349 label: "section".into(),
2350 name: Some("sheet: Hidden".into()),
2351 layer: Some(ContentLayer::Invisible),
2352 children: vec![Node::Paragraph {
2353 text: "hidden cell".into(),
2354 }],
2355 });
2356 doc.push(Node::Furniture {
2357 layer: ContentLayer::Furniture,
2358 inner: Box::new(Node::Paragraph {
2359 text: "Page 1 of 2".into(),
2360 }),
2361 });
2362 doc.push(Node::FurnitureText {
2363 label: "page_footer".into(),
2364 text: "footer line".into(),
2365 });
2366 doc
2367 }
2368
2369 #[test]
2373 fn default_options_are_the_default_export() {
2374 let doc = options_doc();
2375 let plain = doc.export_to_markdown();
2376 assert_eq!(
2377 plain,
2378 "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n"
2379 );
2380 let (with_default, artifacts) =
2381 doc.export_to_markdown_with_options(&MarkdownExportOptions::default());
2382 assert_eq!(with_default, plain);
2383 assert!(artifacts.is_empty());
2384 }
2385
2386 #[test]
2387 fn layers_render_furniture_notes_and_hidden_sheets() {
2388 use crate::document::ContentLayer;
2389 let doc = options_doc();
2390 let md = |layers: ContentLayers| {
2391 doc.export_to_markdown_with_options(&MarkdownExportOptions {
2392 layers,
2393 ..MarkdownExportOptions::default()
2394 })
2395 .0
2396 };
2397 assert_eq!(
2398 md(ContentLayers::BODY.with(ContentLayer::Furniture)),
2399 "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",
2400 "a page header, a furniture-wrapped paragraph and a furniture text item render as paragraphs"
2401 );
2402 assert_eq!(
2403 md(ContentLayers::BODY.with(ContentLayer::Notes)),
2404 "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n\n[author: A]: note\n"
2405 );
2406 assert_eq!(
2407 md(ContentLayers::BODY.with(ContentLayer::Invisible)),
2408 "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n\nhidden cell\n",
2409 "a hidden sheet's items sit on the sheet's layer"
2410 );
2411 assert_eq!(
2412 md(ContentLayers::NONE.with(ContentLayer::Furniture)),
2413 "FAX COVER \\_ R&D\n\nPage 1 of 2\n\nfooter line\n",
2414 "without the body layer only the furniture prints"
2415 );
2416 assert_eq!(md(ContentLayers::NONE), "");
2417 assert_eq!(
2418 md(ContentLayers::ALL),
2419 "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"
2420 );
2421 }
2422
2423 #[test]
2426 fn layers_apply_to_list_items() {
2427 use crate::document::ContentLayer;
2428 let mut doc = DoclingDocument::new("lists");
2429 doc.push(Node::ListItem {
2430 ordered: false,
2431 number: 1,
2432 first_in_list: true,
2433 text: "nav link".into(),
2434 level: 0,
2435 marker: None,
2436 location: None,
2437 dclx: None,
2438 href: None,
2439 layer: Some(ContentLayer::Furniture),
2440 });
2441 doc.add_paragraph("body");
2442 assert_eq!(doc.export_to_markdown(), "body\n");
2443 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2444 layers: ContentLayers::BODY.with(ContentLayer::Furniture),
2445 ..MarkdownExportOptions::default()
2446 });
2447 assert_eq!(md, "- nav link\n\nbody\n");
2448 }
2449
2450 #[test]
2451 fn traverse_pictures_prints_the_nested_text_after_the_picture() {
2452 let doc = options_doc();
2453 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2454 traverse_pictures: true,
2455 ..MarkdownExportOptions::default()
2456 });
2457 assert_eq!(
2458 md,
2459 "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n\nField: Name\n\nField: Date\n"
2460 );
2461 }
2462
2463 #[test]
2464 fn escaping_can_be_turned_off_per_kind() {
2465 let doc = options_doc();
2466 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2467 escape_html: false,
2468 ..MarkdownExportOptions::default()
2469 });
2470 assert_eq!(
2471 md,
2472 "# R&D \\_ report\n\nBody a\\_b <tag>\n\nFigure 1\n\n<!-- image -->\n"
2473 );
2474 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2475 escape_underscores: false,
2476 ..MarkdownExportOptions::default()
2477 });
2478 assert_eq!(
2479 md,
2480 "# R&D _ report\n\nBody a_b <tag>\n\nFigure 1\n\n<!-- image -->\n"
2481 );
2482 let mut doc = DoclingDocument::new("code");
2485 doc.push(Node::Code {
2486 language: None,
2487 text: "a & b \\_ c".into(),
2488 orig: None,
2489 pretty: None,
2490 });
2491 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2492 escape_html: false,
2493 escape_underscores: false,
2494 ..MarkdownExportOptions::default()
2495 });
2496 assert_eq!(md, "```\na & b \\_ c\n```\n");
2497 }
2498
2499 #[test]
2500 fn image_placeholder_is_configurable() {
2501 let doc = options_doc();
2502 let (md, _) = doc.export_to_markdown_with_options(&MarkdownExportOptions {
2503 image_placeholder: "[figure]".into(),
2504 ..MarkdownExportOptions::default()
2505 });
2506 assert!(md.contains("Figure 1\n\n[figure]\n"), "{md}");
2507 assert!(!md.contains("<!-- image -->"));
2508 }
2509
2510 #[test]
2516 fn empty_image_placeholder_prints_nothing() {
2517 fn picture(caption: Option<&str>) -> Node {
2518 Node::Picture {
2519 caption: caption.map(Into::into),
2520 caption_href: None,
2521 image: None,
2522 classification: None,
2523 caption_parent: Default::default(),
2524 caption_location: None,
2525 }
2526 }
2527 fn page(no: usize) -> Node {
2528 Node::PageInfo {
2529 page_no: no,
2530 width: 100.0,
2531 height: 100.0,
2532 }
2533 }
2534 fn para(text: &str) -> Node {
2535 Node::Paragraph { text: text.into() }
2536 }
2537 let options = MarkdownExportOptions {
2538 image_placeholder: String::new(),
2539 ..MarkdownExportOptions::default()
2540 };
2541 let cases: Vec<(Vec<Node>, Option<&str>, &str)> = vec![
2543 (
2544 vec![page(1), para("a"), picture(None), para("b")],
2545 None,
2546 "a\n\nb\n",
2547 ),
2548 (
2549 vec![page(1), para("a"), picture(Some("Figure 1")), para("b")],
2550 None,
2551 "a\n\nFigure 1\n\nb\n",
2552 ),
2553 (
2554 vec![
2555 page(1),
2556 para("a"),
2557 page(2),
2558 picture(None),
2559 page(3),
2560 para("b"),
2561 ],
2562 Some("<!-- pb -->"),
2563 "a\n\n<!-- pb -->\n\n<!-- pb -->\n\nb\n",
2564 ),
2565 (
2566 vec![
2567 page(1),
2568 para("a"),
2569 page(2),
2570 picture(None),
2571 page(3),
2572 para("b"),
2573 ],
2574 Some(""),
2575 "a\n\n\n\n\n\nb\n",
2576 ),
2577 (
2578 vec![page(1), picture(None), page(2), para("b")],
2579 Some("<!-- pb -->"),
2580 "<!-- pb -->\n\nb\n",
2581 ),
2582 (
2583 vec![page(1), picture(None), page(2), para("b")],
2584 Some(""),
2585 "\n\nb\n",
2586 ),
2587 (
2588 vec![page(1), para("a"), page(2), picture(None)],
2589 Some("<!-- pb -->"),
2590 "a\n\n<!-- pb -->\n",
2591 ),
2592 ];
2593 for (nodes, placeholder, expected) in cases {
2594 let mut doc = DoclingDocument::new("t");
2595 doc.page_break_placeholder = placeholder.map(Into::into);
2596 for node in nodes {
2597 doc.push(node);
2598 }
2599 let (md, _) = doc.export_to_markdown_with_options(&options);
2600 assert_eq!(md, expected, "page break {placeholder:?}");
2601 for size in 1..=doc.nodes.len() {
2604 let mut streamer = MarkdownStreamer::new(false, ImageMode::Placeholder, false)
2605 .with_export_options(&options)
2606 .with_page_break_placeholder(placeholder.map(Into::into));
2607 let mut out = String::new();
2608 for chunk in doc.nodes.chunks(size) {
2609 out.push_str(&streamer.push(chunk, &[]));
2610 }
2611 out.push_str(&streamer.finish());
2612 assert_eq!(
2613 out, expected,
2614 "chunks of {size}, page break {placeholder:?}"
2615 );
2616 }
2617 }
2618 let mut doc = DoclingDocument::new("t");
2620 doc.push(para("a"));
2621 doc.push(picture(None));
2622 doc.push(para("b"));
2623 assert_eq!(doc.export_to_markdown(), "a\n\n<!-- image -->\n\nb\n");
2624 }
2625
2626 #[test]
2629 fn streamer_matches_buffered_export_with_options() {
2630 use crate::document::ContentLayer;
2631 let doc = options_doc();
2632 let options = MarkdownExportOptions {
2633 layers: ContentLayers::ALL,
2634 traverse_pictures: true,
2635 escape_html: false,
2636 escape_underscores: false,
2637 image_placeholder: "(img)".into(),
2638 ..MarkdownExportOptions::default()
2639 };
2640 let (buffered, _) = doc.export_to_markdown_with_options(&options);
2641 let mut streamer = MarkdownStreamer::new(false, ImageMode::Placeholder, false)
2642 .with_export_options(&options);
2643 let mut out = String::new();
2644 for chunk in doc.nodes.chunks(2) {
2645 out.push_str(&streamer.push(chunk, &[]));
2646 }
2647 out.push_str(&streamer.finish());
2648 assert_eq!(out, buffered);
2649 assert!(
2650 buffered.contains("(img)") && buffered.contains("R&D _ report"),
2651 "{buffered}"
2652 );
2653 let _ = ContentLayer::Notes;
2654 }
2655
2656 #[test]
2659 fn plain_text_drops_the_markdown_decoration() {
2660 let item = |text: &str, ordered: bool, number: u64, level: u8| Node::ListItem {
2661 ordered,
2662 number,
2663 first_in_list: number == 1 && level == 0,
2664 text: text.into(),
2665 level,
2666 marker: None,
2667 location: None,
2668 dclx: None,
2669 href: None,
2670 layer: None,
2671 };
2672 let mut doc = DoclingDocument::new("plain");
2673 doc.add_heading(1, "Title with **bold**");
2674 doc.add_heading(2, "Section");
2675 doc.add_paragraph("Some **bold**, *italic*, ~~gone~~ and `code` with a [link](https://x.org).\nNext line.");
2676 doc.push(item("*one*", false, 1, 0));
2677 doc.push(item("[two](https://y.org)", false, 2, 0));
2678 doc.push(item("nested", true, 1, 1));
2679 doc.push(Node::CheckboxItem {
2680 checked: true,
2681 text: "done".into(),
2682 });
2683 doc.push(Node::Code {
2684 language: Some("rust".into()),
2685 text: "let x = **y**;".into(),
2686 orig: None,
2687 pretty: None,
2688 });
2689 doc.push(Node::Picture {
2690 caption: Some("Figure *1*".into()),
2691 caption_href: None,
2692 image: None,
2693 classification: None,
2694 caption_parent: Default::default(),
2695 caption_location: None,
2696 });
2697 doc.push(Node::Caption {
2698 text: "Linked caption".into(),
2699 href: Some("https://z.org".into()),
2700 });
2701 doc.push(Node::Table(Table {
2702 rows: vec![
2703 vec!["**n**".into(), "rich".into()],
2704 vec!["**2**".into(), "a \nb".into()],
2705 ],
2706 ..Default::default()
2707 }));
2708 doc.add_paragraph("R&D \\_ x");
2709 let text = doc.export_to_text();
2710 assert_eq!(
2711 text,
2712 "Title with bold\n\n\
2713 Section\n\n\
2714 Some bold, italic, gone and code with a link.\nNext line.\n\n\
2715 - one\n- two\n 1. nested\n\n\
2716 - [x] done\n\n\
2717 let x = **y**;\n\n\
2718 Figure 1\n\n\
2719 Linked caption\n\n\
2720 | n | rich |\n\
2721 |-----|--------|\n\
2722 | 2 | a b |\n\n\
2723 R&D _ x"
2724 );
2725
2726 let options = MarkdownExportOptions::plain_text();
2727 let (buffered, _) = doc.export_to_markdown_with_options(&options);
2728 assert_eq!(buffered, format!("{text}\n"));
2729 let mut streamer = MarkdownStreamer::new(false, ImageMode::Placeholder, false)
2730 .with_export_options(&options);
2731 let mut out = String::new();
2732 for chunk in doc.nodes.chunks(3) {
2733 out.push_str(&streamer.push(chunk, &[]));
2734 }
2735 out.push_str(&streamer.finish());
2736 assert_eq!(out, buffered);
2737 }
2738
2739 #[test]
2741 fn plain_inline_keeps_literal_markers() {
2742 for (input, want) in [
2743 ("**bold** and *it* and ***both***", "bold and it and both"),
2744 ("**[label](https://a.b/c_(d))** end", "label end"),
2745 (
2746 "grant *USE and *OBJMGT authority",
2747 "grant *USE and *OBJMGT authority",
2748 ),
2749 ("2 * 3 * 4", "2 * 3 * 4"),
2750 ("a ** b", "a ** b"),
2751 ("the `quoted’ and `x` term", "the `quoted’ and x term"),
2752 ("see [12] and [docs](u)", "see [12] and docs"),
2753 ("formula $[a](b)$ stays", "formula $[a](b)$ stays"),
2754 ("price $5 and **bold**", "price $5 and bold"),
2755 ("[outer [inner] text](u)", "outer [inner] text"),
2756 ("unclosed **bold", "unclosed **bold"),
2757 ] {
2758 assert_eq!(plain_inline(input), want, "{input}");
2759 }
2760 }
2761}