Skip to main content

mrk/markdown/
mod.rs

1mod blocks;
2mod context;
3mod footnote;
4mod heading;
5mod inline;
6mod layout;
7mod list;
8mod quote;
9mod raw;
10mod rule;
11mod table;
12
13use comrak::nodes::{AstNode, NodeValue};
14use comrak::{Arena, Options, parse_document};
15
16use self::blocks::Group;
17pub use self::blocks::{Section, SectionKind};
18use self::context::Context;
19use self::layout::Spacing;
20use crate::document::{Block, Document, Settings, Span, Style};
21use crate::{code, mermaid, text};
22
23/// Renders GitHub-flavoured Markdown into a document at `settings.width`; images and links are never fetched.
24pub fn render(source: &str, settings: &Settings) -> Document {
25    let blocks = layout::stack(groups(source, settings).into_iter().map(Group::stacked), Spacing::Loose);
26    Document { blocks }
27}
28
29/// The document's top-level sections, each with the source lines it came from, for a consumer that diffs or pairs them.
30/// A list gives one section per top-level item, nested items staying inside theirs; the footnote definitions are one
31/// last section. No blank line separates or surrounds them: `render` puts one between sections and between loose items.
32pub fn render_sections(source: &str, settings: &Settings) -> Vec<Section> {
33    let sections = groups(source, settings).into_iter().flat_map(Group::sections);
34    sections.filter(|section| !layout::is_empty(&section.blocks)).collect()
35}
36
37fn groups(source: &str, settings: &Settings) -> Vec<Group> {
38    let arena = Arena::new();
39    let root = parse_document(&arena, source, &options());
40    let diagrams = mermaid::Allowance::new(raw::diagrams(root), settings.cell.is_some());
41    let highlights = code::Allowance::new(raw::highlighted(root));
42    blocks::groups(root, source, &Context::new(settings, &diagrams, &highlights))
43}
44
45fn options() -> Options<'static> {
46    let mut options = Options::default();
47    options.extension.table = true;
48    options.extension.strikethrough = true;
49    options.extension.tasklist = true;
50    options.extension.autolink = true;
51    options.extension.footnotes = true;
52    options.extension.alerts = true;
53    options.extension.front_matter_delimiter = Some(rule::FRONT_MATTER_DELIMITER.to_owned());
54    options
55}
56
57/// The blocks inside a container, rendered in `context` and spaced as the container says.
58fn children<'a>(node: &'a AstNode<'a>, context: &Context, spacing: Spacing) -> Vec<Block> {
59    layout::stack(node.children().map(|child| block(child, context)), spacing)
60}
61
62/// A container's blocks at its own width, with no room left to indent them: `marker` opens its first paragraph, or
63/// stands on a line of its own above anything else.
64/// `restyle` changes the blocks, never the marker.
65fn unindented<'a>(node: &'a AstNode<'a>, marker: &[Span], context: &Context, spacing: Spacing, restyle: fn(Style) -> Style) -> Vec<Block> {
66    let opening = node.first_child().filter(|child| matches!(child.data().value, NodeValue::Paragraph));
67    let rest = node.children().skip(usize::from(opening.is_some())).map(|child| block(child, context));
68    let rest = layout::restyle(layout::stack(rest, spacing), restyle);
69    match opening {
70        Some(paragraph) => layout::stack([marked_paragraph(paragraph, marker, context, restyle), rest], spacing),
71        None => layout::stack([wrapped(marker, context), rest], Spacing::Tight),
72    }
73}
74
75/// A paragraph behind `marker`, restyled as `restyle` says while the marker keeps its own style.
76fn marked_paragraph<'a>(paragraph: &'a AstNode<'a>, marker: &[Span], context: &Context, restyle: fn(Style) -> Style) -> Vec<Block> {
77    let text = inline::spans(paragraph, context.style, context).into_iter().map(|span| Span { style: restyle(span.style), ..span });
78    let spans: Vec<Span> = marker.iter().cloned().chain(text).collect();
79    wrapped(&spans, context)
80}
81
82/// `spans` wrapped at the context's width, as a paragraph is.
83fn wrapped(spans: &[Span], context: &Context) -> Vec<Block> {
84    layout::lines(text::wrap(spans, context.width(), &[]))
85}
86
87fn block<'a>(node: &'a AstNode<'a>, context: &Context) -> Vec<Block> {
88    match &node.data().value {
89        NodeValue::Paragraph => wrapped(&inline::spans(node, context.style, context), context),
90        NodeValue::Heading(heading) => heading::render(node, heading.level, context),
91        NodeValue::List(list) => list::render(node, list, context),
92        NodeValue::BlockQuote => quote::render(node, context),
93        NodeValue::Alert(alert) => quote::alert(node, alert, context),
94        NodeValue::CodeBlock(code) => raw::code(node, code, context),
95        NodeValue::HtmlBlock(html) => layout::lines(raw::html(&html.literal, context)),
96        NodeValue::ThematicBreak => layout::lines(vec![rule::thematic(context)]),
97        NodeValue::Table(table) => layout::lines(table::render(node, table, context)),
98        NodeValue::FrontMatter(source) => layout::lines(rule::front_matter(source, context)),
99        _ => children(node, context, Spacing::Loose),
100    }
101}
102
103#[cfg(test)]
104fn plain_at(source: &str, width: usize) -> String {
105    crate::document::plain(&render(source, &Settings { width, ..crate::document::test_settings() }))
106}
107
108/// `plain_at` 40 columns wide on a terminal that draws pictures.
109#[cfg(test)]
110fn plain_with_pictures(source: &str) -> String {
111    let cell = Some(crate::document::CellSize { width_px: 10, height_px: 22 });
112    crate::document::plain(&render(source, &Settings { width: 40, cell, ..crate::document::test_settings() }))
113}
114
115/// The spans of every line at 80 columns, pictures left out.
116#[cfg(test)]
117fn styled(source: &str) -> Vec<Vec<Span>> {
118    let document = render(source, &crate::document::test_settings());
119    document.blocks.iter().flat_map(Block::lines).map(|line| line.spans.clone()).collect()
120}
121
122/// `snapshot::ansi` of the source at `width` columns.
123#[cfg(all(test, feature = "cli"))]
124fn ansi_at(source: &str, width: usize) -> String {
125    crate::snapshot::ansi(&render(source, &Settings { width, ..crate::document::test_settings() }))
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131    use crate::document::{Line, MIN_WIDTH, Style};
132    use crate::theme::MRK_DARK;
133
134    /// The showcase without its fenced blocks, which belong to `code` and `mermaid`.
135    fn showcase_without_fences() -> String {
136        let source = include_str!("../../tests/fixtures/showcase.md");
137        source.split("```").step_by(2).collect()
138    }
139
140    const EVERYTHING: &str = "# A heading long enough to wrap at twenty columns\n\n## Second level with a verylongunbreakableword\n\nText with `a long inline code span` and a [link](https://example.com/a/very/long/path) and ![an image](i.png).\n\n- item\n  - nested item with more words\n    1. ordered deeper\n       > quoted inside a list, long enough to wrap\n\n> [!CAUTION]\n> An alert with a long body that wraps.\n\n| a | b | c |\n|---|:-:|--:|\n| one cell with many words | two | three |\n\n<div class=\"x\">html block that is long enough to wrap around</div>\n\n---\n\nNote[^n].\n\n[^n]: A footnote that is long enough to wrap.\n";
141
142    fn lines(source: &str, width: usize) -> Vec<Line> {
143        let settings = Settings { width, ..crate::document::test_settings() };
144        render(source, &settings).blocks.iter().flat_map(Block::lines).cloned().collect()
145    }
146
147    #[test]
148    fn showcase_at_80_columns() {
149        insta::assert_snapshot!(plain_at(&showcase_without_fences(), 80));
150    }
151
152    #[test]
153    fn showcase_at_40_columns() {
154        insta::assert_snapshot!(plain_at(&showcase_without_fences(), 40));
155    }
156
157    #[test]
158    fn no_line_exceeds_the_width() {
159        let showcase = include_str!("../../tests/fixtures/showcase.md");
160        let zero_width_words = format!("{} \u{200b} b \u{ad} c \u{301} d\n", "a".repeat(20));
161        for width in MIN_WIDTH..=60 {
162            for source in [EVERYTHING, showcase, &zero_width_words] {
163                let too_wide: Vec<String> = lines(source, width).iter().filter(|line| line.width() > width).map(Line::plain).collect();
164
165                assert!(too_wide.is_empty(), "at {width} columns: {too_wide:#?}");
166            }
167        }
168    }
169
170    #[test]
171    fn blocks_are_one_blank_line_apart_with_none_around() {
172        let lines = lines(EVERYTHING, 40);
173        let is_blank = |line: &Line| line.plain().trim().is_empty();
174
175        assert!(!is_blank(&lines[0]));
176        assert!(!is_blank(&lines[lines.len() - 1]));
177        assert!(lines.windows(2).all(|pair| !(is_blank(&pair[0]) && is_blank(&pair[1]))));
178    }
179
180    #[test]
181    fn a_width_under_the_minimum_lays_out_at_the_minimum() {
182        assert_eq!(plain_at(EVERYTHING, 3), plain_at(EVERYTHING, MIN_WIDTH));
183    }
184
185    #[test]
186    fn empty_source_is_an_empty_document() {
187        assert_eq!(render("", &crate::document::test_settings()), Document::default());
188    }
189
190    #[test]
191    fn hostile_nesting_renders_without_overflowing_the_stack() {
192        let sources =
193            ["> ".repeat(100_000), "- ".repeat(20_000), format!("{}a{}", "*".repeat(50_000), "*".repeat(50_000)), "[".repeat(50_000)];
194        for source in sources {
195            assert!(lines(&source, 40).iter().all(|line| line.width() <= 40));
196        }
197    }
198
199    #[test]
200    fn html_is_shown_as_muted_literal_text() {
201        let (muted, text) = (Style::fg(MRK_DARK.palette.muted), Style::fg(MRK_DARK.palette.text));
202
203        assert_eq!(plain_at("<details>\n<summary>Hi</summary>\n</details>", 80), "<details>\n<summary>Hi</summary>\n</details>\n");
204        assert_eq!(styled("<details>\n</details>"), [[Span::new("<details>", muted)], [Span::new("</details>", muted)]]);
205        assert_eq!(
206            styled("a <kbd>b</kbd> c"),
207            [[Span::new("a ", text), Span::new("<kbd>", muted), Span::new("b", text), Span::new("</kbd>", muted), Span::new(" c", text)]]
208        );
209    }
210
211    #[test]
212    fn soft_breaks_join_and_hard_breaks_split() {
213        assert_eq!(plain_at("one\ntwo  \nthree\\\nfour", 80), "one two\nthree\nfour\n");
214    }
215
216    #[test]
217    fn front_matter_is_muted_lines_then_a_rule() {
218        insta::assert_snapshot!(plain_at("---\ntitle: Hello\ntags: [a, b]\n---\n\nBody", 30));
219        assert_eq!(
220            styled("---\ntitle: Hello\n---\n"),
221            [
222                [Span::new("title: Hello", Style::fg(MRK_DARK.palette.muted))],
223                [Span::new("─".repeat(80), Style::fg(MRK_DARK.palette.subtle)).framed()]
224            ]
225        );
226    }
227
228    #[test]
229    fn front_matter_keeps_every_line_between_its_fences() {
230        let source = "---\nnote: |\n  ---\n  +++\n---\n\n\nBody";
231
232        assert_eq!(plain_at(source, 30), format!("note: |\n  ---\n  +++\n{}\n\nBody\n", "─".repeat(30)));
233    }
234
235    #[test]
236    fn a_front_matter_indent_takes_at_most_half_the_width() {
237        let source = format!("---\n{}deep: value\n---\n", " ".repeat(100));
238
239        assert_eq!(plain_at(&source, 20).lines().next(), Some("          deep:"));
240    }
241}