Skip to main content

deepdoc_core/
render.rs

1//! Serializers: `Document` → Markdown | JSON | text.
2//!
3//! Pure functions — no I/O, no globals — so they are unit-testable on small
4//! in-memory documents. Every block type is covered here; extractors only have
5//! to produce a sane [`Document`].
6
7use crate::model::{Block, Document, Inline, Metadata, Row, Span};
8
9/// Output format for the renderers.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11pub enum OutputFormat {
12    #[default]
13    Markdown,
14    Json,
15    Text,
16}
17
18/// Options that influence rendering.
19#[derive(Debug, Clone, Default)]
20pub struct RenderOpts {
21    /// Emit document metadata as YAML front-matter (`--metadata`).
22    pub metadata: bool,
23}
24
25/// Render a document in the requested format.
26pub fn render(doc: &Document, format: OutputFormat, opts: &RenderOpts) -> String {
27    match format {
28        OutputFormat::Markdown => to_markdown(doc, opts),
29        OutputFormat::Json => to_json(doc).to_string(),
30        OutputFormat::Text => to_text(doc),
31    }
32}
33
34/// `Document` → Markdown.
35pub fn to_markdown(doc: &Document, opts: &RenderOpts) -> String {
36    let body = blocks_to_markdown(&doc.blocks);
37    let front = if opts.metadata {
38        front_matter(&doc.meta)
39    } else {
40        String::new()
41    };
42
43    if body.trim().is_empty() {
44        return front;
45    }
46    format!("{front}{}\n", body.trim_end())
47}
48
49/// `Document` → JSON.
50///
51/// The schema is the model's serde derive and is a public contract from here
52/// on: `{"meta": {…}, "blocks": [{"type": …}]}`, with inline spans adjacently
53/// tagged as `{"type": …, "value": …}`. See the snapshot test below.
54pub fn to_json(doc: &Document) -> serde_json::Value {
55    serde_json::to_value(doc).expect("Document is always serializable")
56}
57
58/// `Document` → plain text: structure without markup.
59pub fn to_text(doc: &Document) -> String {
60    let body = blocks_to_text(&doc.blocks);
61    if body.trim().is_empty() {
62        return String::new();
63    }
64    format!("{}\n", body.trim_end())
65}
66
67// ---------------------------------------------------------------- markdown --
68
69/// Render a run of blocks, each separated by a blank line.
70fn blocks_to_markdown(blocks: &[Block]) -> String {
71    markdown_with_ranges(blocks).0
72}
73
74/// Render blocks and record where each one landed in the output.
75///
76/// [`crate::chunk`] cuts on block boundaries and reports byte ranges into the
77/// Markdown a plain `deepdoc file --format md` run would print, so it needs the
78/// offsets this renderer already knows. One implementation keeps the two from
79/// drifting apart. A block that renders to nothing gets `None`.
80///
81/// The trailing blank line the caller trims away sits past the last range, so
82/// every range stays valid in the trimmed string too.
83pub(crate) fn markdown_with_ranges(blocks: &[Block]) -> (String, Vec<Option<(usize, usize)>>) {
84    let mut out = String::new();
85    let mut ranges = Vec::with_capacity(blocks.len());
86
87    for block in blocks {
88        let rendered = block_to_markdown(block);
89        if rendered.trim().is_empty() {
90            ranges.push(None);
91            continue;
92        }
93        let start = out.len();
94        out.push_str(rendered.trim_end());
95        ranges.push(Some((start, out.len())));
96        out.push_str("\n\n");
97    }
98
99    (out, ranges)
100}
101
102fn block_to_markdown(block: &Block) -> String {
103    match block {
104        Block::Heading { level, text } => {
105            let hashes = "#".repeat((*level).clamp(1, 6) as usize);
106            format!("{hashes} {}", one_line(&inline_to_markdown(text)))
107        }
108        Block::Paragraph { text } => escape_leading_marker(&inline_to_markdown(text)),
109        Block::List { ordered, items } => list_to_markdown(*ordered, items),
110        Block::Table { header, rows } => table_to_markdown(header.as_ref(), rows),
111        Block::Code { lang, text } => code_to_markdown(lang.as_deref(), text),
112        // The model carries no pixels — only the alt text is worth keeping.
113        Block::Image { alt } => match alt {
114            Some(alt) if !alt.trim().is_empty() => {
115                format!("![{}]()", escape_markdown(alt.trim()))
116            }
117            _ => String::new(),
118        },
119        // Page markers survive as comments: invisible when rendered, greppable in the source.
120        Block::PageBreak { page } => format!("<!-- page {page} -->"),
121    }
122}
123
124fn list_to_markdown(ordered: bool, items: &[Vec<Block>]) -> String {
125    let mut out = String::new();
126
127    for (index, item) in items.iter().enumerate() {
128        let marker = if ordered {
129            format!("{}. ", index + 1)
130        } else {
131            "- ".to_string()
132        };
133        let body = item_to_markdown(item);
134        let body = body.trim_end();
135
136        if body.is_empty() {
137            out.push_str(marker.trim_end());
138            out.push('\n');
139            continue;
140        }
141
142        let indent = " ".repeat(marker.chars().count());
143        for (line_index, line) in body.lines().enumerate() {
144            if line_index == 0 {
145                out.push_str(&marker);
146            } else if !line.is_empty() {
147                out.push_str(&indent);
148            }
149            out.push_str(line);
150            out.push('\n');
151        }
152    }
153
154    out
155}
156
157/// Render the blocks of one list item.
158///
159/// Same as [`blocks_to_markdown`], except that a nested list follows its
160/// item's text directly: the blank line a normal block separation would add
161/// turns a tight list into a loose one.
162fn item_to_markdown(blocks: &[Block]) -> String {
163    let mut out = String::new();
164
165    for (index, block) in blocks.iter().enumerate() {
166        let rendered = block_to_markdown(block);
167        if rendered.trim().is_empty() {
168            continue;
169        }
170        out.push_str(rendered.trim_end());
171
172        let tight = matches!(block, Block::Paragraph { .. })
173            && matches!(blocks.get(index + 1), Some(Block::List { .. }));
174        out.push_str(if tight { "\n" } else { "\n\n" });
175    }
176
177    out
178}
179
180fn table_to_markdown(header: Option<&Row>, rows: &[Row]) -> String {
181    let width = header
182        .iter()
183        .copied()
184        .chain(rows.iter())
185        .map(|row| row.cells.len())
186        .max()
187        .unwrap_or(0);
188    if width == 0 {
189        return String::new();
190    }
191
192    let cells = |row: Option<&Row>| -> Vec<String> {
193        let mut cells: Vec<String> = row
194            .map(|row| row.cells.iter().map(cell_to_markdown).collect())
195            .unwrap_or_default();
196        cells.resize(width, String::new());
197        cells
198    };
199
200    // A Markdown table always needs a header row; synthesise an empty one when
201    // the source had none (a headerless spreadsheet range, say).
202    let header_cells = cells(header);
203    let body_cells: Vec<Vec<String>> = rows.iter().map(|row| cells(Some(row))).collect();
204
205    // Pad the columns so the source table stays readable, as in the CLI spec.
206    let mut widths = vec![3usize; width];
207    for row in std::iter::once(&header_cells).chain(body_cells.iter()) {
208        for (column, cell) in row.iter().enumerate() {
209            widths[column] = widths[column].max(cell.chars().count());
210        }
211    }
212
213    let render_row = |cells: &[String]| -> String {
214        let padded: Vec<String> = cells
215            .iter()
216            .enumerate()
217            .map(|(column, cell)| {
218                let padding = widths[column].saturating_sub(cell.chars().count());
219                format!("{cell}{}", " ".repeat(padding))
220            })
221            .collect();
222        format!("| {} |", padded.join(" | "))
223    };
224
225    let separator: Vec<String> = widths.iter().map(|width| "-".repeat(*width)).collect();
226
227    let mut out = render_row(&header_cells);
228    out.push('\n');
229    out.push_str(&render_row(&separator));
230    for row in &body_cells {
231        out.push('\n');
232        out.push_str(&render_row(row));
233    }
234    out
235}
236
237fn code_to_markdown(lang: Option<&str>, text: &str) -> String {
238    // The fence must be longer than the longest backtick run inside the code.
239    let longest_run = text
240        .split(|c| c != '`')
241        .map(|run| run.len())
242        .max()
243        .unwrap_or(0);
244    let fence = "`".repeat(longest_run.max(2) + 1);
245    format!(
246        "{fence}{}\n{}\n{fence}",
247        lang.unwrap_or(""),
248        text.trim_end()
249    )
250}
251
252/// A table cell: inline markup, but never anything that breaks the row.
253fn cell_to_markdown(cell: &Inline) -> String {
254    one_line(&inline_to_markdown(cell)).replace('|', "\\|")
255}
256
257fn inline_to_markdown(inline: &Inline) -> String {
258    spans_to_markdown(&inline.spans)
259}
260
261fn spans_to_markdown(spans: &[Span]) -> String {
262    let mut out = String::new();
263    for span in spans {
264        match span {
265            Span::Text(text) => out.push_str(&escape_markdown(text)),
266            Span::Bold(spans) => {
267                let inner = spans_to_markdown(spans);
268                if !inner.trim().is_empty() {
269                    out.push_str(&format!("**{}**", inner.trim()));
270                }
271            }
272            Span::Italic(spans) => {
273                let inner = spans_to_markdown(spans);
274                if !inner.trim().is_empty() {
275                    out.push_str(&format!("*{}*", inner.trim()));
276                }
277            }
278            Span::Code(text) => {
279                let longest_run = text
280                    .split(|c| c != '`')
281                    .map(|run| run.len())
282                    .max()
283                    .unwrap_or(0);
284                let fence = "`".repeat(longest_run + 1);
285                let padding = if text.starts_with('`') || text.ends_with('`') {
286                    " "
287                } else {
288                    ""
289                };
290                out.push_str(&format!("{fence}{padding}{text}{padding}{fence}"));
291            }
292            Span::Link { href, text } => {
293                let label = spans_to_markdown(text);
294                let label = if label.trim().is_empty() {
295                    escape_markdown(href)
296                } else {
297                    label
298                };
299                out.push_str(&format!("[{}]({})", label.trim(), escape_href(href)));
300            }
301            // Two trailing spaces are Markdown's hard line break.
302            Span::LineBreak => out.push_str("  \n"),
303        }
304    }
305    out
306}
307
308/// Escape the characters that would otherwise turn text into markup.
309///
310/// Deliberately narrow: over-escaping (`snake\_case`, `1\. one`) makes the
311/// output worse to read than the odd stray asterisk. `_` is escaped only where
312/// CommonMark would actually treat it as emphasis — at a word boundary.
313fn escape_markdown(text: &str) -> String {
314    let chars: Vec<char> = text.chars().collect();
315    let mut out = String::with_capacity(text.len());
316
317    for (index, ch) in chars.iter().enumerate() {
318        match ch {
319            '\\' | '`' | '*' | '[' | ']' | '<' => {
320                out.push('\\');
321                out.push(*ch);
322            }
323            '_' => {
324                let before_is_word = index
325                    .checked_sub(1)
326                    .and_then(|i| chars.get(i))
327                    .is_some_and(|c| c.is_alphanumeric());
328                let after_is_word = chars.get(index + 1).is_some_and(|c| c.is_alphanumeric());
329                if before_is_word && after_is_word {
330                    out.push('_');
331                } else {
332                    out.push_str("\\_");
333                }
334            }
335            _ => out.push(*ch),
336        }
337    }
338
339    out
340}
341
342/// Escape a paragraph that would otherwise read as a heading, quote or list item.
343fn escape_leading_marker(text: &str) -> String {
344    let trimmed = text.trim_start();
345    let starts_ordered_item = || {
346        let digits: String = trimmed.chars().take_while(char::is_ascii_digit).collect();
347        !digits.is_empty()
348            && matches!(
349                trimmed.chars().nth(digits.len()),
350                Some('.') | Some(')') if trimmed.chars().nth(digits.len() + 1) == Some(' ')
351            )
352    };
353
354    let needs_escape = trimmed.starts_with('#')
355        || trimmed.starts_with('>')
356        || trimmed.starts_with('|')
357        || trimmed.starts_with("- ")
358        || trimmed.starts_with("+ ")
359        || starts_ordered_item();
360
361    if needs_escape {
362        let offset = text.len() - trimmed.len();
363        format!("{}\\{}", &text[..offset], trimmed)
364    } else {
365        text.to_string()
366    }
367}
368
369/// A link target that survives Markdown's `[text](href)` syntax.
370fn escape_href(href: &str) -> String {
371    if href.contains([' ', '(', ')']) {
372        format!("<{}>", href.replace('>', "%3E"))
373    } else {
374        href.to_string()
375    }
376}
377
378/// Collapse a string onto a single line — for headings and table cells.
379pub(crate) fn one_line(text: &str) -> String {
380    text.split_whitespace().collect::<Vec<_>>().join(" ")
381}
382
383// -------------------------------------------------------------------- text --
384
385fn blocks_to_text(blocks: &[Block]) -> String {
386    let mut out = String::new();
387    for block in blocks {
388        let rendered = block_to_text(block);
389        if rendered.trim().is_empty() {
390            continue;
391        }
392        out.push_str(rendered.trim_end());
393        out.push_str("\n\n");
394    }
395    out
396}
397
398fn block_to_text(block: &Block) -> String {
399    match block {
400        Block::Heading { text, .. } => one_line(&text.plain_text()),
401        Block::Paragraph { text } => text.plain_text(),
402        Block::List { ordered, items } => list_to_text(*ordered, items),
403        Block::Table { header, rows } => header
404            .iter()
405            .chain(rows.iter())
406            .map(Row::plain_text)
407            .collect::<Vec<_>>()
408            .join("\n"),
409        Block::Code { text, .. } => text.trim_end().to_string(),
410        Block::Image { alt } => alt.clone().unwrap_or_default(),
411        Block::PageBreak { .. } => String::new(),
412    }
413}
414
415fn list_to_text(ordered: bool, items: &[Vec<Block>]) -> String {
416    let mut out = String::new();
417
418    for (index, item) in items.iter().enumerate() {
419        let marker = if ordered {
420            format!("{}. ", index + 1)
421        } else {
422            "- ".to_string()
423        };
424        let body = blocks_to_text(item);
425        let body = body.trim_end();
426        if body.is_empty() {
427            continue;
428        }
429
430        let indent = " ".repeat(marker.chars().count());
431        for (line_index, line) in body.lines().enumerate() {
432            if line_index == 0 {
433                out.push_str(&marker);
434            } else if !line.is_empty() {
435                out.push_str(&indent);
436            }
437            out.push_str(line);
438            out.push('\n');
439        }
440    }
441
442    out
443}
444
445// ---------------------------------------------------------- front-matter --
446
447/// Metadata as a YAML front-matter block, empty when there is nothing to say.
448fn front_matter(meta: &Metadata) -> String {
449    let mut fields: Vec<(&str, String)> = Vec::new();
450    if let Some(title) = &meta.title {
451        fields.push(("title", yaml_string(title)));
452    }
453    if let Some(author) = &meta.author {
454        fields.push(("author", yaml_string(author)));
455    }
456    if let Some(created) = &meta.created {
457        fields.push(("created", yaml_string(created)));
458    }
459    if let Some(language) = &meta.language {
460        fields.push(("language", yaml_string(language)));
461    }
462    if let Some(publisher) = &meta.publisher {
463        fields.push(("publisher", yaml_string(publisher)));
464    }
465    if let Some(pages) = meta.page_count {
466        fields.push(("pages", pages.to_string()));
467    }
468    if let Some(format) = meta.source_format {
469        fields.push(("format", yaml_string(format.as_str())));
470    }
471
472    if fields.is_empty() {
473        return String::new();
474    }
475
476    let body: String = fields
477        .iter()
478        .map(|(key, value)| format!("{key}: {value}\n"))
479        .collect();
480    format!("---\n{body}---\n\n")
481}
482
483/// Quote a string for YAML — double quotes, backslash and quote escaped.
484fn yaml_string(value: &str) -> String {
485    format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
486}
487
488#[cfg(test)]
489mod tests {
490    use super::*;
491    use crate::detect::Format;
492
493    fn doc(blocks: Vec<Block>) -> Document {
494        Document {
495            meta: Metadata::default(),
496            blocks,
497        }
498    }
499
500    fn md(blocks: Vec<Block>) -> String {
501        to_markdown(&doc(blocks), &RenderOpts::default())
502    }
503
504    #[test]
505    fn renders_headings() {
506        assert_eq!(
507            md(vec![
508                Block::Heading {
509                    level: 1,
510                    text: Inline::text("Title")
511                },
512                Block::Heading {
513                    level: 6,
514                    text: Inline::text("Deep")
515                },
516                // Levels outside 1..=6 are clamped, not dropped.
517                Block::Heading {
518                    level: 9,
519                    text: Inline::text("Deeper")
520                },
521            ]),
522            "# Title\n\n###### Deep\n\n###### Deeper\n"
523        );
524    }
525
526    #[test]
527    fn renders_paragraphs_and_escapes_markup() {
528        assert_eq!(
529            md(vec![Block::paragraph("a * b [c] _d_ `e` <f>")]),
530            "a \\* b \\[c\\] \\_d\\_ \\`e\\` \\<f>\n"
531        );
532    }
533
534    #[test]
535    fn leaves_intra_word_underscores_alone() {
536        assert_eq!(
537            md(vec![Block::paragraph("snake_case_name")]),
538            "snake_case_name\n"
539        );
540    }
541
542    #[test]
543    fn escapes_paragraphs_that_would_read_as_block_markup() {
544        assert_eq!(
545            md(vec![Block::paragraph("# not a heading")]),
546            "\\# not a heading\n"
547        );
548        assert_eq!(
549            md(vec![Block::paragraph("- not a list")]),
550            "\\- not a list\n"
551        );
552        assert_eq!(
553            md(vec![Block::paragraph("1. not a list")]),
554            "\\1. not a list\n"
555        );
556        assert_eq!(
557            md(vec![Block::paragraph("> not a quote")]),
558            "\\> not a quote\n"
559        );
560        // A bare number is not a list item.
561        assert_eq!(
562            md(vec![Block::paragraph("2026 was fine")]),
563            "2026 was fine\n"
564        );
565    }
566
567    #[test]
568    fn renders_inline_markup() {
569        let inline = Inline::new(vec![
570            Span::Bold(vec![Span::Text("bold".into())]),
571            Span::Text(" ".into()),
572            Span::Italic(vec![Span::Text("italic".into())]),
573            Span::Text(" ".into()),
574            Span::Code("let x = 1;".into()),
575            Span::LineBreak,
576            Span::Link {
577                href: "https://example.com".into(),
578                text: vec![Span::Text("site".into())],
579            },
580        ]);
581        assert_eq!(
582            md(vec![Block::Paragraph { text: inline }]),
583            "**bold** *italic* `let x = 1;`  \n[site](https://example.com)\n"
584        );
585    }
586
587    #[test]
588    fn inline_code_picks_a_longer_fence_when_needed() {
589        let inline = Inline::new(vec![Span::Code("a ` b".into())]);
590        assert_eq!(md(vec![Block::Paragraph { text: inline }]), "``a ` b``\n");
591    }
592
593    #[test]
594    fn link_targets_with_spaces_are_bracketed() {
595        let inline = Inline::new(vec![Span::Link {
596            href: "./my file.pdf".into(),
597            text: vec![Span::Text("file".into())],
598        }]);
599        assert_eq!(
600            md(vec![Block::Paragraph { text: inline }]),
601            "[file](<./my file.pdf>)\n"
602        );
603    }
604
605    #[test]
606    fn renders_unordered_and_ordered_lists() {
607        assert_eq!(
608            md(vec![Block::List {
609                ordered: false,
610                items: vec![vec![Block::paragraph("one")], vec![Block::paragraph("two")]],
611            }]),
612            "- one\n- two\n"
613        );
614        assert_eq!(
615            md(vec![Block::List {
616                ordered: true,
617                items: vec![vec![Block::paragraph("one")], vec![Block::paragraph("two")]],
618            }]),
619            "1. one\n2. two\n"
620        );
621    }
622
623    #[test]
624    fn renders_nested_lists_and_multi_block_items() {
625        let rendered = md(vec![Block::List {
626            ordered: false,
627            items: vec![vec![
628                Block::paragraph("outer"),
629                Block::List {
630                    ordered: true,
631                    items: vec![vec![Block::paragraph("inner")]],
632                },
633            ]],
634        }]);
635        // A nested list stays tight: no blank line after its item's text.
636        assert_eq!(rendered, "- outer\n  1. inner\n");
637    }
638
639    #[test]
640    fn renders_tables_with_padded_columns() {
641        let rendered = md(vec![Block::Table {
642            header: Some(Row::from_texts(["Segment", "Q1"])),
643            rows: vec![
644                Row::from_texts(["Cloud", "4.1"]),
645                Row::from_texts(["Devices", "1.2"]),
646            ],
647        }]);
648        assert_eq!(
649            rendered,
650            "| Segment | Q1  |\n\
651             | ------- | --- |\n\
652             | Cloud   | 4.1 |\n\
653             | Devices | 1.2 |\n"
654        );
655    }
656
657    #[test]
658    fn tables_escape_pipes_and_ragged_rows() {
659        let rendered = md(vec![Block::Table {
660            header: None,
661            rows: vec![
662                Row::from_texts(["a|b", "c"]),
663                // A short row is padded, not dropped.
664                Row::from_texts(["d"]),
665            ],
666        }]);
667        assert_eq!(
668            rendered,
669            "|      |     |\n\
670             | ---- | --- |\n\
671             | a\\|b | c   |\n\
672             | d    |     |\n"
673        );
674    }
675
676    #[test]
677    fn renders_fenced_code() {
678        assert_eq!(
679            md(vec![Block::Code {
680                lang: Some("rust".into()),
681                text: "fn main() {}\n".into(),
682            }]),
683            "```rust\nfn main() {}\n```\n"
684        );
685    }
686
687    #[test]
688    fn code_fence_grows_past_inner_backticks() {
689        assert_eq!(
690            md(vec![Block::Code {
691                lang: None,
692                text: "```\nnested\n```".into(),
693            }]),
694            "````\n```\nnested\n```\n````\n"
695        );
696    }
697
698    #[test]
699    fn renders_images_and_page_breaks() {
700        assert_eq!(
701            md(vec![
702                Block::Image {
703                    alt: Some("a [diagram]".into())
704                },
705                Block::PageBreak { page: 2 },
706                Block::Image { alt: None },
707            ]),
708            "![a \\[diagram\\]]()\n\n<!-- page 2 -->\n"
709        );
710    }
711
712    /// Every block type, one document: blocks separated by exactly one blank
713    /// line, one newline at the end, and no trailing spaces except Markdown's
714    /// hard break.
715    #[test]
716    fn markdown_spacing_is_uniform() {
717        let rendered = md(vec![
718            Block::Heading {
719                level: 1,
720                text: Inline::text("Title"),
721            },
722            Block::paragraph("body"),
723            Block::List {
724                ordered: false,
725                items: vec![vec![Block::paragraph("one")], vec![Block::paragraph("two")]],
726            },
727            Block::Table {
728                header: Some(Row::from_texts(["a", "b"])),
729                rows: vec![Row::from_texts(["1", "2"])],
730            },
731            Block::Code {
732                lang: None,
733                text: "code".into(),
734            },
735            // Renders to nothing, and must not leave a gap behind it.
736            Block::Image { alt: None },
737            Block::PageBreak { page: 2 },
738            Block::paragraph("after the break"),
739        ]);
740
741        assert!(
742            !rendered.contains("\n\n\n"),
743            "blank lines pile up:\n{rendered}"
744        );
745        assert!(rendered.ends_with("break\n"));
746        for line in rendered.lines() {
747            assert!(
748                line == line.trim_end() || line.ends_with("  "),
749                "trailing space on {line:?}"
750            );
751        }
752    }
753
754    /// The offsets `chunk` builds on must point at the same Markdown a plain
755    /// render prints.
756    #[test]
757    fn block_ranges_slice_the_rendered_markdown() {
758        let blocks = vec![
759            Block::Heading {
760                level: 2,
761                text: Inline::text("Section"),
762            },
763            Block::Image { alt: None },
764            Block::paragraph("body"),
765        ];
766        let (body, ranges) = markdown_with_ranges(&blocks);
767        let rendered = to_markdown(&doc(blocks), &RenderOpts::default());
768
769        assert_eq!(ranges.len(), 3);
770        assert!(ranges[1].is_none(), "an empty block occupies no range");
771        for (start, end) in ranges.iter().flatten() {
772            assert_eq!(body[*start..*end], rendered[*start..*end]);
773        }
774        let (start, end) = ranges[2].unwrap();
775        assert_eq!(&rendered[start..end], "body");
776    }
777
778    #[test]
779    fn empty_document_renders_to_nothing() {
780        assert_eq!(md(vec![]), "");
781        assert_eq!(to_text(&doc(vec![])), "");
782    }
783
784    #[test]
785    fn text_output_keeps_structure_without_markup() {
786        let rendered = to_text(&doc(vec![
787            Block::Heading {
788                level: 2,
789                text: Inline::text("Summary"),
790            },
791            Block::Paragraph {
792                text: Inline::new(vec![
793                    Span::Bold(vec![Span::Text("bold".into())]),
794                    Span::Text(" and ".into()),
795                    Span::Link {
796                        href: "https://example.com".into(),
797                        text: vec![Span::Text("a link".into())],
798                    },
799                ]),
800            },
801            Block::List {
802                ordered: true,
803                items: vec![vec![Block::paragraph("one")], vec![Block::paragraph("two")]],
804            },
805            Block::Table {
806                header: Some(Row::from_texts(["a", "b"])),
807                rows: vec![Row::from_texts(["1", "2"])],
808            },
809        ]));
810        assert_eq!(
811            rendered,
812            "Summary\n\nbold and a link\n\n1. one\n2. two\n\na\tb\n1\t2\n"
813        );
814    }
815
816    #[test]
817    fn metadata_becomes_front_matter() {
818        let doc = Document {
819            meta: Metadata {
820                title: Some(r#"A "quoted" title"#.into()),
821                page_count: Some(8),
822                source_format: Some(Format::Pdf),
823                ..Metadata::default()
824            },
825            blocks: vec![Block::paragraph("body")],
826        };
827        let rendered = to_markdown(&doc, &RenderOpts { metadata: true });
828        assert_eq!(
829            rendered,
830            "---\ntitle: \"A \\\"quoted\\\" title\"\npages: 8\nformat: \"pdf\"\n---\n\nbody\n"
831        );
832    }
833
834    #[test]
835    fn front_matter_is_skipped_when_there_is_no_metadata() {
836        let doc = doc(vec![Block::paragraph("body")]);
837        assert_eq!(to_markdown(&doc, &RenderOpts { metadata: true }), "body\n");
838    }
839
840    /// The JSON schema is a public contract — this snapshot is what breaks when
841    /// a field is renamed.
842    #[test]
843    fn json_schema_snapshot() {
844        let doc = Document {
845            meta: Metadata {
846                title: Some("Report".into()),
847                source_format: Some(Format::Csv),
848                ..Metadata::default()
849            },
850            blocks: vec![
851                Block::Heading {
852                    level: 1,
853                    text: Inline::text("Title"),
854                },
855                Block::Paragraph {
856                    text: Inline::new(vec![Span::Bold(vec![Span::Text("hi".into())])]),
857                },
858                Block::Table {
859                    header: Some(Row::from_texts(["a"])),
860                    rows: vec![Row::from_texts(["1"])],
861                },
862            ],
863        };
864
865        let expected = serde_json::json!({
866            "meta": { "title": "Report", "source_format": "csv" },
867            "blocks": [
868                { "type": "heading", "level": 1, "text": [{ "type": "text", "value": "Title" }] },
869                {
870                    "type": "paragraph",
871                    "text": [{
872                        "type": "bold",
873                        "value": [{ "type": "text", "value": "hi" }],
874                    }],
875                },
876                {
877                    "type": "table",
878                    "header": { "cells": [[{ "type": "text", "value": "a" }]] },
879                    "rows": [{ "cells": [[{ "type": "text", "value": "1" }]] }],
880                },
881            ],
882        });
883        assert_eq!(to_json(&doc), expected);
884    }
885}