mbterm 0.1.4

ANSI terminal renderer for MBDown documents
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
456
457
458
459
460
461
462
//! MBTerm: safe CommonMark and restricted BBCode rendering for ANSI terminals.

mod ansi;
mod bbcode;
mod frame;
mod layout;
mod markdown;
mod syntax;
mod table;

use std::collections::BTreeMap;

pub use ansi::{strip_osc8_sequences, strip_terminal_sequences};
pub use bbcode::{
    escape, strip_bbcode, BasicColor, BlinkStyle, Color, ParseColorError, TextStyle, UnderlineStyle,
};

mod catppuccin {
    use crate::Color;

    pub const PINK: Color = Color::Rgb(245, 194, 231);
    pub const MAUVE: Color = Color::Rgb(203, 166, 247);
    pub const RED: Color = Color::Rgb(243, 139, 168);
    pub const PEACH: Color = Color::Rgb(250, 179, 135);
    pub const YELLOW: Color = Color::Rgb(249, 226, 175);
    pub const GREEN: Color = Color::Rgb(166, 227, 161);
    pub const TEAL: Color = Color::Rgb(148, 226, 213);
    pub const SKY: Color = Color::Rgb(137, 220, 235);
    pub const SAPPHIRE: Color = Color::Rgb(116, 199, 236);
    pub const BLUE: Color = Color::Rgb(137, 180, 250);
    pub const LAVENDER: Color = Color::Rgb(180, 190, 254);
    pub const TEXT: Color = Color::Rgb(205, 214, 244);
    pub const SUBTEXT_0: Color = Color::Rgb(166, 173, 200);
    pub const OVERLAY_1: Color = Color::Rgb(127, 132, 156);
    pub const OVERLAY_0: Color = Color::Rgb(108, 112, 134);

    pub const SYNTAX: [Color; 13] = [
        PINK, MAUVE, RED, PEACH, YELLOW, GREEN, TEAL, SKY, SAPPHIRE, BLUE, LAVENDER, TEXT,
        SUBTEXT_0,
    ];
}

/// Outer-corner glyphs used by framed blocks and tables.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CornerStyle {
    #[default]
    Square,
    Rounded,
}

impl CornerStyle {
    pub(crate) const fn top_left(self) -> char {
        match self {
            Self::Square => '┌',
            Self::Rounded => '╭',
        }
    }

    pub(crate) const fn top_right(self) -> char {
        match self {
            Self::Square => '┐',
            Self::Rounded => '╮',
        }
    }

    pub(crate) const fn bottom_left(self) -> char {
        match self {
            Self::Square => '└',
            Self::Rounded => '╰',
        }
    }

    pub(crate) const fn bottom_right(self) -> char {
        match self {
            Self::Square => '┘',
            Self::Rounded => '╯',
        }
    }
}

/// Named BBCode styles such as `[warning]...[/warning]`.
#[derive(Clone, Debug)]
pub struct Theme {
    styles: BTreeMap<String, TextStyle>,
    corner_style: CornerStyle,
}

impl Default for Theme {
    fn default() -> Self {
        let styles = BTreeMap::from([
            (
                "markdown-heading".to_string(),
                TextStyle::new().foreground(catppuccin::LAVENDER),
            ),
            (
                "markdown-quote".to_string(),
                TextStyle::new().foreground(catppuccin::MAUVE),
            ),
            (
                "markdown-list".to_string(),
                TextStyle::new().foreground(catppuccin::TEAL).bold(),
            ),
            (
                "markdown-rule".to_string(),
                TextStyle::new().foreground(catppuccin::OVERLAY_0),
            ),
            (
                "markdown-code".to_string(),
                TextStyle::new().foreground(catppuccin::OVERLAY_1),
            ),
            (
                "markdown-inline-code".to_string(),
                TextStyle::new().foreground(catppuccin::PEACH),
            ),
            (
                "markdown-box".to_string(),
                TextStyle::new().foreground(catppuccin::BLUE),
            ),
            (
                "markdown-hashtag".to_string(),
                TextStyle::new().foreground(catppuccin::PINK).bold(),
            ),
            (
                "markdown-wikilink".to_string(),
                TextStyle::new().foreground(catppuccin::SKY),
            ),
        ]);
        Self {
            styles,
            corner_style: CornerStyle::Square,
        }
    }
}

impl Theme {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_corner_style(mut self, corner_style: CornerStyle) -> Self {
        self.corner_style = corner_style;
        self
    }

    pub fn corner_style(&self) -> CornerStyle {
        self.corner_style
    }

    /// Add a named style. Names are ASCII, case-insensitive, and may contain
    /// letters, digits, `_`, or `-`.
    pub fn insert(
        &mut self,
        name: impl AsRef<str>,
        style: TextStyle,
    ) -> Result<Option<TextStyle>, ThemeError> {
        let name = name.as_ref().to_ascii_lowercase();
        if name.is_empty()
            || !name
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
        {
            return Err(ThemeError {
                name,
                kind: ThemeErrorKind::InvalidSyntax,
            });
        }
        if bbcode::is_reserved_style_name(&name) || mbdown::is_structural_tag_name(&name) {
            return Err(ThemeError {
                name,
                kind: ThemeErrorKind::Reserved,
            });
        }
        Ok(self.styles.insert(name, style))
    }

    pub(crate) fn get(&self, name: &str) -> Option<&TextStyle> {
        self.styles.get(name)
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ThemeError {
    name: String,
    kind: ThemeErrorKind,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ThemeErrorKind {
    InvalidSyntax,
    Reserved,
}

impl std::fmt::Display for ThemeError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.kind {
            ThemeErrorKind::InvalidSyntax => {
                write!(formatter, "invalid theme style name {:?}", self.name)
            }
            ThemeErrorKind::Reserved => {
                write!(
                    formatter,
                    "theme style name {:?} is reserved by BBCode",
                    self.name
                )
            }
        }
    }
}

impl std::error::Error for ThemeError {}

/// Renders Markdown and restricted BBCode into ANSI terminal text.
#[derive(Clone, Debug)]
pub struct Renderer {
    width: usize,
    theme: Theme,
    render_front_matter: bool,
}

impl Renderer {
    pub fn new(width: usize) -> Self {
        Self {
            width,
            theme: Theme::new(),
            render_front_matter: false,
        }
    }

    pub fn with_theme(width: usize, theme: Theme) -> Self {
        Self {
            width,
            theme,
            render_front_matter: false,
        }
    }

    /// Configure whether initial YAML/TOML front matter is rendered.
    pub fn with_front_matter(mut self, enabled: bool) -> Self {
        self.render_front_matter = enabled;
        self
    }

    pub fn width(&self) -> usize {
        self.width
    }

    pub fn theme(&self) -> &Theme {
        &self.theme
    }

    pub fn render(&self, input: &str) -> String {
        match mbdown::parse(input) {
            Ok(document) => self.render_document(&document),
            Err(error) => markdown::render_error(&error, &self.theme),
        }
    }

    /// Render an already parsed MBDown syntax tree.
    pub fn render_document(&self, document: &mbdown::Document<'_>) -> String {
        markdown::render_document(document, self.width, &self.theme, self.render_front_matter)
    }

    /// Render with a per-call display width while preserving this renderer's theme.
    pub fn render_at_width(&self, input: &str, width: usize) -> String {
        match mbdown::parse(input) {
            Ok(document) => self.render_document_at_width(&document, width),
            Err(error) => markdown::render_error(&error, &self.theme),
        }
    }

    /// Render a parsed MBDown syntax tree at a per-call display width.
    pub fn render_document_at_width(
        &self,
        document: &mbdown::Document<'_>,
        width: usize,
    ) -> String {
        markdown::render_document(document, width, &self.theme, self.render_front_matter)
    }

    pub fn render_bbcode(&self, input: &str) -> String {
        bbcode::render(input, true, &self.theme)
    }

    pub fn strip_bbcode(&self, input: &str) -> String {
        bbcode::render(input, false, &self.theme)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn theme_rejects_invalid_and_reserved_style_names() {
        let mut theme = Theme::new();
        for name in [
            "bad=name",
            "",
            "red",
            "BOLD",
            "color",
            "blink",
            "inverse",
            "overline",
            "underline-color",
            "link",
            "box",
            "center",
            "right",
            "indent",
            "Columns",
            "column",
        ] {
            assert!(
                theme.insert(name, TextStyle::default()).is_err(),
                "{name} should be rejected"
            );
        }
        assert!(theme.insert("mob", TextStyle::default()).is_ok());
        assert!(theme.insert("quest-target", TextStyle::default()).is_ok());
    }

    #[test]
    fn public_extended_style_builders_render_exact_sgr() {
        let mut theme = Theme::new();
        theme
            .insert(
                "extended",
                TextStyle::new()
                    .blink(BlinkStyle::Rapid)
                    .inverse()
                    .overline()
                    .underline_style(UnderlineStyle::Dashed)
                    .underline_color(Color::Basic(BasicColor::BrightCyan)),
            )
            .unwrap();

        assert_eq!(
            Renderer::with_theme(80, theme).render_bbcode("[extended]x[/extended]"),
            "\x1b[4:5;6;7;53;58;5;14mx\x1b[0m"
        );
    }

    #[test]
    fn semantic_tags_render_and_strip_with_their_theme() {
        let mut theme = Theme::new();
        theme
            .insert(
                "mob",
                TextStyle::new()
                    .bold()
                    .foreground(Color::Basic(BasicColor::BrightMagenta)),
            )
            .unwrap();
        let renderer = Renderer::with_theme(80, theme);

        assert_eq!(
            renderer.render_bbcode("[mob]木人[/mob]"),
            "\x1b[1;95m木人\x1b[0m"
        );
        assert_eq!(renderer.strip_bbcode("[mob]木人[/mob]"), "木人");
        assert_eq!(
            renderer.render_bbcode("[color=mob]木人[/color]"),
            "\x1b[1;95m木人\x1b[0m"
        );
    }

    #[test]
    fn per_call_width_preserves_the_configured_width_and_theme() {
        let mut theme = Theme::new();
        theme
            .insert(
                "accent",
                TextStyle::new().foreground(Color::Basic(BasicColor::Red)),
            )
            .unwrap();
        let renderer = Renderer::with_theme(10, theme);
        let source = "[accent]天地玄黄[/accent]";

        let configured = renderer.render(source);
        let narrow = renderer.render_at_width(source, 6);

        assert_eq!(renderer.width(), 10);
        assert!(!configured.contains('\n'));
        assert!(narrow.contains('\n'));
        assert!(configured.contains("\x1b[31m"));
        assert!(narrow.contains("\x1b[31m"));
    }

    #[test]
    fn front_matter_is_hidden_by_default_and_can_be_rendered() {
        let source = "---\ntitle: Shown\ntags: [one, two]\n---\n# Visible";
        let hidden = strip_terminal_sequences(&Renderer::new(80).render(source));
        assert!(hidden.ends_with("Visible"));
        assert!(!hidden.contains("yaml"));
        assert!(!hidden.contains("title: Shown"));

        let renderer = Renderer::new(80).with_front_matter(true);
        let yaml = strip_terminal_sequences(&renderer.render(source));
        assert!(yaml.contains("yaml"));
        assert!(yaml.contains("title: Shown"));
        assert!(yaml.contains("tags: [one, two]"));
        assert!(yaml.ends_with("Visible"));
        assert!(!yaml.contains("---"));

        let toml =
            strip_terminal_sequences(&renderer.render("+++\ntitle = \"Shown\"\n+++\nVisible"));
        assert!(toml.contains("toml"));
        assert!(toml.contains("title = \"Shown\""));
        assert!(toml.ends_with("Visible"));
        assert!(!toml.contains("+++"));
    }

    #[test]
    fn math_has_native_display_and_source_fallbacks() {
        let rendered = strip_terminal_sequences(
            &Renderer::new(40).render("Inline $x + 1$.\n\n$$\n\\frac{a}{b}\n$$"),
        );

        assert!(rendered.contains("Inline $x + 1$."));
        assert!(rendered.contains("math"));
        assert!(rendered.contains('─'));
        assert!(rendered.contains('a'));
        assert!(rendered.contains('b'));

        let labels = strip_terminal_sequences(&Renderer::new(80).render(concat!(
            "$$\n",
            "\\frac{\\text{营业收入}}{\\text{总资产}} \\times ",
            "\\frac{\\text{净利润}}{\\text{营业收入}} = ",
            "\\frac{\\text{净利润}}{\\text{总资产}} = ",
            "\\operatorname{ROA}\n",
            "$$"
        )));
        assert!(labels.contains("营业收入"));
        assert!(labels.contains("总资产"));
        assert!(labels.contains("ROA"));
        assert!(!labels.contains("text营业收入"));
        assert!(!labels.contains("operatorname"));
        assert!(labels.contains("──────────×────────── = ──────── = ROA"));

        let emoji = strip_terminal_sequences(
            &Renderer::new(80).render("$$\n\\frac{🧑‍💻👩‍💻}{👥} = \\text{程序员浓度}\n$$"),
        );
        assert!(emoji.contains("🧑‍💻👩‍💻"));
        assert!(emoji.contains("👥"));
        assert!(emoji.contains("────── = 程序员浓度"));
        let equation = emoji
            .lines()
            .find(|line| line.contains("程序员浓度"))
            .unwrap();
        assert_eq!(equation.chars().filter(|ch| *ch == '─').count(), 6);

        let fallback = strip_terminal_sequences(&Renderer::new(40).render("$$\n\\left( x\n$$"));
        assert!(fallback.contains("tex"));
        assert!(fallback.contains("\\left( x"));

        let too_wide = strip_terminal_sequences(&Renderer::new(10).render("$$\nabcdefghijk\n$$"));
        assert!(too_wide.contains("tex"));
        assert!(too_wide.contains('a'));
        assert!(too_wide.contains('k'));
    }
}