Skip to main content

mrk/code/
mod.rs

1mod budget;
2mod highlight;
3mod language;
4mod panel;
5
6pub(crate) use self::budget::{Allowance, Highlighting, highlighting};
7use crate::document::{Line, MIN_WIDTH, Settings};
8
9/// A fenced code block as a panel: every line exactly `settings.width` cells, at least `MIN_WIDTH`, highlighted
10/// when the language is known, within the bounds of `budget.rs`. `language` is a language name (`rust`, `ts`), not a
11/// whole fence info string.
12pub fn render(code: &str, language: Option<&str>, settings: &Settings) -> Vec<Line> {
13    let alone = Allowance::new([(0, highlighting(code, language))]);
14    render_in_document(code, language, 0, &alone, settings)
15}
16
17/// `render` for a block of a document, highlighted only when the document's `allowance` admits its `key`.
18pub(crate) fn render_in_document(code: &str, language: Option<&str>, key: usize, allowance: &Allowance, settings: &Settings) -> Vec<Line> {
19    panel(code, language, allowance.highlighted(key), settings)
20}
21
22/// The panel of `code`, its first `highlighted` bytes highlighted and the rest plain.
23fn panel(code: &str, language: Option<&str>, highlighted: usize, settings: &Settings) -> Vec<Line> {
24    let (head, tail) = code.split_at(highlighted);
25    let theme = &settings.theme;
26    let rows = highlight::highlight(head, language.filter(|_| !head.is_empty()), theme).chain(highlight::highlight(tail, None, theme));
27    panel::panel(rows, language, settings.width.max(MIN_WIDTH), &theme.palette)
28}
29
30#[cfg(test)]
31mod tests {
32    use super::*;
33    use crate::document::test_settings;
34
35    const RUST: &str = "fn main() {\n    let greeting = \"hello\";\n    println!(\"{greeting}\");\n}\n";
36
37    fn at_width(width: usize) -> Settings {
38        Settings { width, ..test_settings() }
39    }
40
41    fn framed(lines: &[Line]) -> String {
42        lines.iter().map(|line| format!("│{}│\n", line.plain())).collect()
43    }
44
45    #[test]
46    fn highlighting_stops_at_the_first_line_too_long_to_highlight() {
47        let code = format!("let a = 1;\nlet b = \"{}\";\nlet c = 2;\n", "x".repeat(16 * 1024));
48        let (rust, text) = (render(&code, Some("rust"), &at_width(40)), render(&code, Some("text"), &at_width(40)));
49
50        assert_ne!(rust[1], text[1]);
51        assert_eq!(rust[2..], text[2..]);
52    }
53
54    #[test]
55    fn a_block_its_document_does_not_admit_is_plain() {
56        let settings = test_settings();
57        let (rust, text) = (render(RUST, Some("rust"), &settings), render(RUST, Some("text"), &settings));
58        let in_document = |allowance: &Allowance| render_in_document(RUST, Some("rust"), 1, allowance, &settings);
59
60        assert_eq!(in_document(&Allowance::new([(1, highlighting(RUST, Some("rust")))])), rust);
61        assert_eq!(in_document(&Allowance::new([(2, highlighting(RUST, Some("rust")))]))[1..], text[1..]);
62    }
63
64    #[test]
65    fn rust_panel() {
66        insta::assert_snapshot!(framed(&render(RUST, Some("rust"), &at_width(40))));
67    }
68
69    #[test]
70    fn plain_panel_without_label() {
71        insta::assert_snapshot!(framed(&render("just text\n\n\tindented\n", None, &at_width(24))));
72    }
73
74    #[test]
75    fn long_lines_wrap_with_a_marker() {
76        let code = "let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];\n";
77
78        insta::assert_snapshot!(framed(&render(code, Some("rs"), &at_width(30))));
79    }
80
81    #[test]
82    fn a_width_under_the_minimum_renders_at_the_minimum() {
83        assert!(render("let tab =\t1;\n", None, &at_width(4)).iter().all(|line| line.width() == MIN_WIDTH));
84    }
85
86    #[test]
87    fn a_label_too_wide_is_shortened() {
88        insta::assert_snapshot!(framed(&render("x\n", Some("averyveryverylonglanguagename"), &at_width(16))));
89    }
90
91    #[test]
92    fn escape_bytes_in_code_do_not_shorten_the_background() {
93        let lines = render("printf '\x1b[31mred\x1b[0m'\n", None, &at_width(24));
94        let visible = |line: &Line| line.plain().chars().filter(|character| !character.is_control()).count();
95
96        assert!(lines.iter().all(|line| visible(line) == 24), "{}", framed(&lines));
97    }
98
99    #[test]
100    fn every_line_is_exactly_the_width() {
101        let code = "fn wide() {\n\tlet 漢字 = \"日本語のテキストはとても長いのでここで折り返されるはずです\";\n}\n";
102        for width in [MIN_WIDTH, 9, 12, 20, 40, 80, 100] {
103            for language in [Some("rust"), None, Some("klingon")] {
104                let lines = render(code, language, &at_width(width));
105                assert!(lines.iter().all(|line| line.width() == width), "width {width}, {language:?}:\n{}", framed(&lines));
106            }
107        }
108    }
109
110    #[test]
111    fn every_span_sits_on_the_surface() {
112        let settings = test_settings();
113        let lines = render(RUST, Some("rust"), &settings);
114
115        assert!(lines.iter().flat_map(|line| &line.spans).all(|span| span.style.bg == Some(settings.theme.palette.surface)));
116    }
117
118    #[test]
119    fn label_is_muted_and_continuation_is_subtle() {
120        let settings = at_width(20);
121        let palette = settings.theme.palette;
122        let lines = render("0123456789012345678901234\n", Some("text"), &settings);
123
124        let label = lines[0].spans.iter().find(|span| span.text == "text").map(|span| span.style.fg);
125        let marker = lines[2].spans.iter().find(|span| span.text == "↪ ").map(|span| span.style.fg);
126        assert_eq!(label, Some(Some(palette.muted)));
127        assert_eq!(marker, Some(Some(palette.subtle)));
128    }
129
130    #[cfg(feature = "cli")]
131    #[test]
132    fn rust_panel_in_colour() {
133        let lines = render("fn main() {\n    let a = \"b\";\n}\n", Some("rust"), &at_width(24));
134
135        insta::assert_snapshot!(crate::snapshot::ansi(&crate::document::Document { blocks: vec![crate::document::Block::Lines(lines)] }));
136    }
137}