mrk-cli 0.12.0

Render Markdown beautifully in the terminal: syntax highlighting, tables, themes, and Mermaid diagrams as images.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
mod budget;
mod cache;
mod catch;
mod frame;
mod kind;
mod label;
mod source;
mod svg;
mod text;
mod worker;

use std::fmt;
use std::sync::Arc;

pub(crate) use self::budget::Allowance;
use self::budget::{Diagram, Load};
use self::cache::Recent;
use self::catch::caught;
pub use self::catch::is_catching;
use crate::document::{Block, CellSize, Line, Picture, Settings};
use crate::raster::{RasterError, Svg};

static DRAWINGS: Recent<Drawing> = Recent::new();
/// The text a diagram was last drawn as, with the width it was drawn for.
static TEXTS: Recent<(usize, DrawnText)> = Recent::new();

type Drawing = Result<Arc<Svg>, DiagramError>;
type DrawnText = Result<Arc<Vec<Line>>, DiagramError>;

/// Why a diagram is not drawn; the source fallback shows it in its note.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum DiagramError {
    Oversized,
    OverBudget(Load),
    OverDocumentBudget,
    /// Given up on at the deadline while laying out.
    TimedOut,
    /// The deadline had passed before it started.
    OutOfTime,
    Invalid(String),
    UnknownKind,
    Crashed,
    Empty,
    TooWide(usize),
    TooLarge,
    UnreadableSvg(String),
    PngEncoding(String),
}

impl fmt::Display for DiagramError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Oversized => write!(formatter, "diagram over {} KiB", budget::MAX_SOURCE_BYTES / 1024),
            Self::OverBudget(load) => write!(formatter, "over {} {}, too many to lay out", load.limit(), load.unit()),
            Self::OverDocumentBudget => {
                write!(formatter, "over the {} s of layout a document's diagrams share", budget::MAX_DOCUMENT_COST_MS / 1000)
            }
            Self::TimedOut => write!(formatter, "too slow to lay out"),
            Self::OutOfTime => write!(formatter, "out of time for the document's diagrams"),
            Self::Invalid(message) => write!(formatter, "{message}"),
            Self::UnknownKind => write!(formatter, "not a kind of diagram mrk draws"),
            Self::Crashed => write!(formatter, "the diagram renderer crashed"),
            Self::Empty => write!(formatter, "nothing to draw"),
            Self::TooWide(width) => write!(formatter, "the diagram is wider than {width} columns"),
            Self::TooLarge => write!(formatter, "diagram too large to draw"),
            Self::UnreadableSvg(message) => write!(formatter, "unreadable SVG ({message})"),
            Self::PngEncoding(message) => write!(formatter, "PNG encoding failed ({message})"),
        }
    }
}

impl DiagramError {
    /// An engine's reason for refusing a diagram, which may quote the source: the note shows its first line as span
    /// text.
    fn invalid(reason: &impl fmt::Display) -> Self {
        Self::Invalid(reason.to_string().lines().next().unwrap_or("invalid diagram").to_owned())
    }
}

impl From<RasterError> for DiagramError {
    fn from(error: RasterError) -> Self {
        match error {
            RasterError::UnreadableSvg(message) => Self::UnreadableSvg(message),
            RasterError::NoCanvas => Self::Empty,
            RasterError::PngEncoding(message) => Self::PngEncoding(message),
        }
    }
}

/// A ```mermaid block on its own: a picture when `settings.cell` is set and the diagram renders, text otherwise.
pub fn render(source: &str, settings: &Settings) -> Block {
    Diagram::new(source).and_then(|diagram| drawn(source, &diagram, settings)).unwrap_or_else(|error| as_source(source, &error, settings))
}

/// A ```mermaid block of a document, shown as source when the document's budget does not let it through.
pub(crate) fn render_in_document(source: &str, settings: &Settings, allowance: &Allowance) -> Block {
    allowance.admit(source).and_then(|diagram| drawn(source, diagram, settings)).unwrap_or_else(|error| as_source(source, &error, settings))
}

fn drawn(source: &str, diagram: &Diagram, settings: &Settings) -> Result<Block, DiagramError> {
    match settings.cell.map(|cell| picture(source, diagram, cell, settings)) {
        Some(Ok(picture)) => Ok(Block::Picture(picture)),
        // Given up on at the deadline, the picture left its text no time; kept, it starts neither engine again.
        Some(Err(DiagramError::TimedOut)) => Err(DiagramError::TimedOut),
        _ => as_text(source, diagram, settings),
    }
}

/// Laid out and turned into a tree once per source and palette, a timeout included: only the fit and the raster
/// depend on the width.
fn picture(source: &str, diagram: &Diagram, cell: CellSize, settings: &Settings) -> Result<Picture, DiagramError> {
    let drawing = DRAWINGS.find(source, &settings.theme.palette).unwrap_or_else(|| drawing_kept(source, diagram, settings))?;
    let (width, height) = drawing.size();
    let frame = frame::fit(width, height, svg::FONT_SIZE_PX, cell, settings.width).ok_or(DiagramError::TooLarge)?;
    let png = caught(|| drawing.draw(frame.scale, frame.width_px, frame.height_px))??;
    let alt = kind::describe(source).to_owned();
    Ok(Picture { png, cols: frame.cols, rows: frame.rows, alt, indent: Line::blank(), concealed_text: None })
}

fn drawing_kept(source: &str, diagram: &Diagram, settings: &Settings) -> Drawing {
    let drawing = drawing(diagram, settings);
    if is_worth_keeping(&drawing) {
        DRAWINGS.keep(source, &settings.theme.palette, drawing.clone());
    }
    drawing
}

/// Only the layout runs against the deadline, so the fonts the tree loads on first use are never left to a thread
/// given up on.
fn drawing(diagram: &Diagram, settings: &Settings) -> Drawing {
    let (graph, palette) = (diagram.picture_graph()?, settings.theme.palette);
    let svg = worker::run(settings.diagram_deadline, move || Ok(svg::render(&graph, &palette)))?;
    Ok(Arc::new(caught(|| Svg::parse(&svg))??))
}

/// vt-mermaid lays out for the width, so it runs again after a resize, unless it once ran out of time.
fn as_text(source: &str, diagram: &Diagram, settings: &Settings) -> Result<Block, DiagramError> {
    let text = match TEXTS.find(source, &settings.theme.palette) {
        Some((width, text)) if width == settings.width || text == Err(DiagramError::TimedOut) => text,
        _ => text_kept(source, diagram, settings),
    };
    text.map(|lines| Block::Lines(lines.to_vec()))
}

fn text_kept(source: &str, diagram: &Diagram, settings: &Settings) -> DrawnText {
    let text = drawn_text(diagram, settings);
    if is_worth_keeping(&text) {
        TEXTS.keep(source, &settings.theme.palette, (settings.width, text.clone()));
    }
    text
}

fn drawn_text(diagram: &Diagram, settings: &Settings) -> DrawnText {
    diagram.admit_text()?;
    let (source, width, palette) = (diagram.text_source(), settings.width, settings.theme.palette);
    worker::run(settings.diagram_deadline, move || text::render(&source, width, &palette)).map(Arc::new)
}

/// A diagram the deadline came before is not kept, so the next render, with a deadline of its own, lays it out.
fn is_worth_keeping<T>(drawn: &Result<T, DiagramError>) -> bool {
    !matches!(drawn, Err(DiagramError::OutOfTime))
}

fn as_source(source: &str, error: &DiagramError, settings: &Settings) -> Block {
    Block::Lines(source::render(source, &error.to_string(), settings.width, &settings.theme.palette))
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]

    use std::time::Instant;

    use super::*;
    use crate::document::Line;
    use crate::document::test_settings;

    const FLOWCHART: &str = "graph TD\n  A[Start] --> B{Ready?}\n  B -->|yes| C[Render]\n  B -->|no| D[Wait]\n  D --> B\n";
    const SEQUENCE: &str = "sequenceDiagram\n  Alice->>Bob: Hello\n  Bob-->>Alice: Hi\n";
    const CELL: CellSize = CellSize { width_px: 16, height_px: 36 };

    fn with_cell() -> Settings {
        Settings { cell: Some(CELL), ..test_settings() }
    }

    fn lines(block: Block) -> Vec<Line> {
        match block {
            Block::Lines(lines) => lines,
            other => panic!("expected lines, got {other:?}"),
        }
    }

    fn picture_of(source: &str) -> Picture {
        match render(source, &with_cell()) {
            Block::Picture(picture) => picture,
            other => panic!("expected a picture, got {other:?}"),
        }
    }

    fn assert_fills_its_cells(picture: &Picture) {
        let drawn = crate::raster::inspect(&picture.png).unwrap();
        assert_eq!(drawn.width, u32::from(picture.cols) * u32::from(CELL.width_px));
        assert_eq!(drawn.height, u32::from(picture.rows) * u32::from(CELL.height_px));

        assert!(usize::from(picture.cols) <= with_cell().width);
        assert!(drawn.has_ink);
    }

    const HTML_LABELS: &str =
        "flowchart TD\n A[\"<b>A. Storage</b>\"] --> B[\"<i>B</i> form<br/>two lines\"]\n A --> C[\"`**bold** md string`\"]\n";
    const PLAIN_LABELS: &str = "flowchart TD\n A[\"A. Storage\"] --> B[\"B form<br>two lines\"]\n A --> C[\"bold md string\"]\n";

    #[test]
    fn html_and_markdown_labels_draw_as_their_words_in_text() {
        let plain = lines(render(HTML_LABELS, &test_settings())).iter().map(Line::plain).collect::<Vec<_>>().join("\n");

        insta::assert_snapshot!(plain);
    }

    #[cfg(feature = "cli")]
    #[test]
    fn html_and_markdown_emphasis_draws_bold_and_italic_in_text() {
        let lines = lines(render(HTML_LABELS, &test_settings()));

        insta::assert_snapshot!(crate::snapshot::ansi(&crate::document::Document { blocks: vec![Block::Lines(lines)] }));
    }

    #[test]
    fn a_sequence_shows_emphasis_tags_as_written_in_text_as_mermaid_does() {
        let lines = lines(render("sequenceDiagram\n  A->>B: <b>hi</b><span>!</span>", &test_settings()));

        assert!(lines.iter().any(|line| line.plain().contains("<b>hi</b>!")), "{lines:?}");
    }

    #[test]
    fn html_and_markdown_labels_draw_as_their_words_in_a_picture() {
        assert_eq!(picture_of(HTML_LABELS).png, picture_of(PLAIN_LABELS).png);
    }

    #[test]
    fn a_clicked_node_draws_the_same_picture() {
        assert_eq!(picture_of("flowchart LR\n a --> b\n click a \"https://x\"").png, picture_of("flowchart LR\n a --> b").png);
    }

    #[test]
    fn flowchart_becomes_a_picture() {
        let picture = picture_of(FLOWCHART);

        assert_eq!(picture.alt, "flowchart");
        assert!(picture.rows >= 5, "rows {}", picture.rows);
        assert_fills_its_cells(&picture);
    }

    #[test]
    fn sequence_diagram_becomes_a_picture() {
        let picture = picture_of(SEQUENCE);

        assert_eq!(picture.alt, "sequence diagram");
        assert!(picture.cols >= 10, "cols {}", picture.cols);
        assert_fills_its_cells(&picture);
    }

    #[test]
    fn without_a_cell_size_the_diagram_is_text() {
        let lines = lines(render(FLOWCHART, &test_settings()));

        assert!(lines.iter().any(|line| line.plain().contains("Render")));
        assert!(lines.iter().all(|line| line.width() <= 80));
    }

    #[test]
    fn oversized_source_is_shown_as_source() {
        let source = format!("graph TD\n{}", "  A --> B\n".repeat(7000));

        let lines = lines(render(&source, &with_cell()));

        assert_eq!(lines[0].plain(), "mermaid: diagram over 64 KiB");
        assert_eq!(lines[1].plain(), "graph TD");
    }

    #[test]
    fn a_subgraph_inside_itself_draws_with_both_engines() {
        let source = "graph TD\n subgraph a\n subgraph a\n x --> y\n end\n end";

        assert!(matches!(render(source, &test_settings()), Block::Lines(text) if !text[0].plain().starts_with("mermaid:")));
        assert!(matches!(render(source, &with_cell()), Block::Picture(_)));
    }

    #[test]
    fn a_kind_vt_mermaid_does_not_draw_shows_as_source_with_its_note() {
        let lines = lines(render("pie\n  \"a\" : 1", &test_settings()));

        assert_eq!(lines[0].plain(), "mermaid: pie diagrams are not drawn as text yet");
        assert_eq!(lines[1].plain(), "pie");
    }

    #[test]
    fn a_kind_mrk_does_not_know_is_shown_as_source_not_drawn_as_a_flowchart() {
        let source = "roadmap-beta\n  step one\n  step two";

        let lines = lines(render(source, &with_cell()));

        assert_eq!(lines[1].plain(), "roadmap-beta");
    }

    /// Edges between pseudo-random nodes, the shape that took the engines longest to lay out.
    fn tangled(nodes: usize, edges: usize) -> String {
        let edge = |index: usize| format!("  n{} --> n{}\n", index * 7919 % nodes, index * 104_729 % nodes);
        format!("graph TD\n{}", (0..edges).map(edge).collect::<String>())
    }

    #[test]
    fn diagrams_too_costly_to_lay_out_are_refused_before_either_engine() {
        let costly = [
            (tangled(100, 500), "mermaid: over 150 edges, too many to lay out"),
            (tangled(1000, 3500), "mermaid: over 150 edges, too many to lay out"),
            (format!("classDiagram\n{}", "  A --> B\n".repeat(151)), "mermaid: over 150 edges, too many to lay out"),
        ];

        for (source, note) in &costly {
            assert!(source.len() <= budget::MAX_SOURCE_BYTES, "{note}: {} bytes", source.len());
            for settings in [test_settings(), with_cell()] {
                assert_eq!(lines(render(source, &settings))[0].plain(), *note);
            }
        }
    }

    /// x, y, their edge and every subgraph are links: 147 subgraphs is the most a picture's count admits.
    #[test]
    fn the_deepest_subgraphs_the_budget_admits_run_on_a_default_thread_stack() {
        let opening: String = (0..147).map(|level| format!(" subgraph s{level}\n")).collect();
        let source = format!("graph TD\n{opening} x --> y\n{}", " end\n".repeat(147));
        assert!(budget::Diagram::new(&source).unwrap().picture_graph().is_ok());

        let drawn = std::thread::Builder::new()
            .stack_size(2 * 1024 * 1024)
            .spawn(move || [Settings { width: 1000, ..test_settings() }, with_cell()].map(|settings| render(&source, &settings)))
            .unwrap()
            .join()
            .unwrap();

        assert!(matches!(&drawn, [Block::Lines(_), Block::Picture(_)]), "{drawn:?}");
    }

    #[test]
    fn a_long_sequence_over_the_picture_budget_still_draws_as_text() {
        let source = format!("sequenceDiagram\n{}", "  a ->> b: hi\n".repeat(1000));

        let lines = lines(render(&source, &with_cell()));

        assert!(lines.iter().any(|line| line.plain().contains("hi")));
        assert!(!lines[0].plain().starts_with("mermaid:"));
    }

    #[test]
    fn a_diagram_the_deadline_came_before_shows_as_source_then_draws_on_the_next_render() {
        let source = tangled(20, 41);

        let out_of_time = lines(render(&source, &Settings { diagram_deadline: Some(Instant::now()), ..with_cell() }));
        let next = render(&source, &with_cell());

        assert_eq!(out_of_time[0].plain(), "mermaid: out of time for the document's diagrams");
        assert!(matches!(next, Block::Picture(_)), "{next:?}");
    }

    #[test]
    fn a_picture_given_up_on_at_the_deadline_is_too_slow_and_a_resize_starts_no_engine() {
        let source = tangled(20, 43);
        DRAWINGS.keep(&source, &with_cell().theme.palette, Err(DiagramError::TimedOut));

        let given_up = lines(render(&source, &Settings { diagram_deadline: Some(Instant::now()), ..with_cell() }));
        let resized = lines(render(&source, &Settings { width: 60, ..with_cell() }));

        assert_eq!(given_up[0].plain(), "mermaid: too slow to lay out");
        assert_eq!(resized[0].plain(), "mermaid: too slow to lay out");
    }

    #[test]
    fn only_what_the_deadline_came_before_is_laid_out_again() {
        assert!(!is_worth_keeping::<()>(&Err(DiagramError::OutOfTime)));
        assert!(is_worth_keeping::<()>(&Err(DiagramError::TimedOut)));
        assert!(is_worth_keeping(&Ok(())));
    }

    #[test]
    fn a_diagram_past_the_document_budget_shows_as_source_with_its_note() {
        let lines = lines(render_in_document(FLOWCHART, &with_cell(), &Allowance::new([], true)));

        assert_eq!(lines[0].plain(), "mermaid: over the 12 s of layout a document's diagrams share");
        assert_eq!(lines[1].plain(), "graph TD");
    }

    #[test]
    fn a_document_lays_out_each_diagram_that_fits_what_is_left_of_its_budget() {
        let chain = |diagram: usize| (0..39).map(|node| format!("  d{diagram}n{node} --> d{diagram}n{}\n", node + 1)).collect::<String>();
        let diagram = |index: usize| format!("graph TD\n{}", chain(index));
        let fitting = budget::MAX_DOCUMENT_COST_MS / Diagram::new(&diagram(0)).unwrap().cost(false);
        let document: String = (0..=fitting).map(|index| format!("```mermaid\n{}```\n\n", diagram(index))).collect();
        let document = format!("{document}```mermaid\ngraph TD\n  small --> one\n```\n");

        let plain = crate::document::plain(&crate::markdown::render(&document, &test_settings()));

        assert_eq!(plain.matches("mermaid: over the 12 s of layout").count(), 1);
        assert!(plain.contains(&format!("d{fitting}n38 --> d{fitting}n39")), "{plain}");
        assert!(!plain.contains("small --> one"), "{plain}");
    }

    #[test]
    fn syntax_mermaid_rs_renderer_refuses_still_draws_as_text() {
        let sources = [
            "classDiagram\n  class Shape {\n    <<interface>>\n    +area() float\n  }\n  Shape <|-- Circle",
            "sequenceDiagram\n  box Purple Front\n    participant A\n  end\n  A->>B: hi\n  B-->>A: ok",
        ];

        for source in sources {
            let lines = lines(render(source, &test_settings()));

            assert!(!lines[0].plain().starts_with("mermaid:"), "{source:?}: {}", lines[0].plain());
        }
    }

    #[test]
    fn text_too_wide_for_the_width_falls_back_to_source() {
        let settings = Settings { width: 12, ..test_settings() };

        let lines = lines(render(FLOWCHART, &settings));

        assert!(lines.iter().all(|line| line.width() <= 12));
    }

    #[test]
    fn garbage_never_panics() {
        let garbage = [
            "",
            " ",
            "graph",
            "graph TD\n  A[",
            "sequenceDiagram\n  ->>",
            "pie\n  \"x\": -1",
            "%%{init: ",
            "\u{0}\u{1b}[31m",
            "graph TD; A-->A-->A-->A",
        ];
        let truncated = (0..FLOWCHART.len()).filter(|end| FLOWCHART.is_char_boundary(*end)).map(|end| &FLOWCHART[..end]);

        for source in garbage.into_iter().chain(truncated) {
            for settings in [test_settings(), with_cell()] {
                let block = render(source, &settings);
                if let Block::Lines(lines) = block {
                    assert!(lines.iter().all(|line| line.width() <= settings.width), "{source:?}");
                }
            }
        }
    }
}