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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
use std::collections::BTreeMap;
use std::io::{self, IsTerminal, Read, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::{Parser, ValueEnum};
use mbterm::{
    strip_terminal_sequences, BlinkStyle, Color, CornerStyle, Renderer, TextStyle, Theme,
    UnderlineStyle,
};
use serde::Deserialize;
use terminal_size::{terminal_size, Width};

const DEFAULT_WIDTH: usize = 80;

#[derive(Debug, Parser)]
#[command(
    name = "mbterm",
    version,
    about = "Render Markdown or MBDown as terminal text"
)]
struct Args {
    /// Input file. Omit or use - to read UTF-8 text from stdin.
    #[arg(value_name = "FILE")]
    input: Option<PathBuf>,

    /// Output width in terminal columns.
    #[arg(short, long, value_name = "COLUMNS", value_parser = parse_width)]
    width: Option<usize>,

    /// TOML file containing application-defined semantic styles.
    #[arg(short, long, value_name = "FILE")]
    theme: Option<PathBuf>,

    /// When to emit ANSI styles and OSC 8 hyperlinks.
    #[arg(long, value_enum, default_value_t = ColorMode::Auto)]
    color: ColorMode,

    /// Outer corners for boxes, code blocks, and tables.
    #[arg(long, value_enum)]
    corners: Option<CornerConfig>,

    /// Render initial YAML/TOML front matter before the document body.
    #[arg(long)]
    front_matter: bool,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, ValueEnum)]
enum ColorMode {
    #[default]
    Auto,
    Always,
    Never,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, ValueEnum)]
#[serde(rename_all = "kebab-case")]
enum CornerConfig {
    Square,
    Rounded,
}

impl From<CornerConfig> for CornerStyle {
    fn from(value: CornerConfig) -> Self {
        match value {
            CornerConfig::Square => Self::Square,
            CornerConfig::Rounded => Self::Rounded,
        }
    }
}

#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct ThemeConfig {
    corners: Option<CornerConfig>,
    styles: BTreeMap<String, StyleConfig>,
}

#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
enum BlinkConfig {
    Slow,
    Rapid,
}

#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
enum UnderlineKind {
    Single,
    Double,
    Curly,
    Dotted,
    Dashed,
}

#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(untagged)]
enum UnderlineConfig {
    Legacy(bool),
    Style(UnderlineKind),
}

#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct StyleConfig {
    foreground: Option<String>,
    background: Option<String>,
    underline_color: Option<String>,
    bold: bool,
    dim: bool,
    italic: bool,
    underline: Option<UnderlineConfig>,
    blink: Option<BlinkConfig>,
    inverse: bool,
    strike: bool,
    overline: bool,
}

impl StyleConfig {
    fn build(&self, name: &str) -> Result<TextStyle, String> {
        let underline_enabled =
            !matches!(self.underline, None | Some(UnderlineConfig::Legacy(false)));
        if self.foreground.is_none()
            && self.background.is_none()
            && self.underline_color.is_none()
            && !self.bold
            && !self.dim
            && !self.italic
            && !underline_enabled
            && self.blink.is_none()
            && !self.inverse
            && !self.strike
            && !self.overline
        {
            return Err(format!(
                "theme style {name:?} must set a color or text attribute"
            ));
        }

        let mut style = TextStyle::new();
        if let Some(value) = &self.foreground {
            style = style.foreground(parse_color(name, "foreground", value)?);
        }
        if let Some(value) = &self.background {
            style = style.background(parse_color(name, "background", value)?);
        }
        if self.bold {
            style = style.bold();
        }
        if self.dim {
            style = style.dim();
        }
        if self.italic {
            style = style.italic();
        }
        match self.underline {
            None | Some(UnderlineConfig::Legacy(false)) => {}
            Some(UnderlineConfig::Legacy(true))
            | Some(UnderlineConfig::Style(UnderlineKind::Single)) => {
                style = style.underline();
            }
            Some(UnderlineConfig::Style(UnderlineKind::Double)) => {
                style = style.underline_style(UnderlineStyle::Double);
            }
            Some(UnderlineConfig::Style(UnderlineKind::Curly)) => {
                style = style.underline_style(UnderlineStyle::Curly);
            }
            Some(UnderlineConfig::Style(UnderlineKind::Dotted)) => {
                style = style.underline_style(UnderlineStyle::Dotted);
            }
            Some(UnderlineConfig::Style(UnderlineKind::Dashed)) => {
                style = style.underline_style(UnderlineStyle::Dashed);
            }
        }
        match self.blink {
            None => {}
            Some(BlinkConfig::Slow) => style = style.blink(BlinkStyle::Slow),
            Some(BlinkConfig::Rapid) => style = style.blink(BlinkStyle::Rapid),
        }
        if self.inverse {
            style = style.inverse();
        }
        if self.strike {
            style = style.strike();
        }
        if self.overline {
            style = style.overline();
        }
        if let Some(value) = &self.underline_color {
            style = style.underline_color(parse_color(name, "underline_color", value)?);
        }
        Ok(style)
    }
}

fn main() -> ExitCode {
    match run(Args::parse()) {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => {
            eprintln!("mbterm: {error}");
            ExitCode::FAILURE
        }
    }
}

fn run(args: Args) -> Result<(), String> {
    let (source, source_label) = read_source(args.input.as_deref())?;
    let document = mbdown::parse(&source).map_err(|error| format!("{source_label}: {error}"))?;
    let mut theme = load_theme(args.theme.as_deref())?;
    if let Some(corners) = args.corners {
        theme = theme.with_corner_style(corners.into());
    }
    let width = args.width.unwrap_or_else(detected_width);
    let renderer = Renderer::with_theme(width, theme).with_front_matter(args.front_matter);
    let rendered = renderer.render_document(&document);
    let output = if emit_control_sequences(args.color) {
        rendered
    } else {
        strip_terminal_sequences(&rendered)
    };
    write_output(&output)
}

fn read_source(path: Option<&Path>) -> Result<(String, String), String> {
    match path {
        None => read_stdin(),
        Some(path) if path == Path::new("-") => read_stdin(),
        Some(path) => std::fs::read_to_string(path)
            .map(|source| (source, path.display().to_string()))
            .map_err(|error| format!("failed to read {}: {error}", path.display())),
    }
}

fn read_stdin() -> Result<(String, String), String> {
    let mut source = String::new();
    io::stdin()
        .read_to_string(&mut source)
        .map_err(|error| format!("failed to read stdin: {error}"))?;
    Ok((source, "stdin".to_string()))
}

fn load_theme(path: Option<&Path>) -> Result<Theme, String> {
    let mut theme = Theme::new();
    let Some(path) = path else {
        return Ok(theme);
    };
    let source = std::fs::read_to_string(path)
        .map_err(|error| format!("failed to read theme {}: {error}", path.display()))?;
    let config: ThemeConfig = toml::from_str(&source)
        .map_err(|error| format!("failed to parse theme {}: {error}", path.display()))?;
    if let Some(corners) = config.corners {
        theme = theme.with_corner_style(corners.into());
    }
    for (name, config) in config.styles {
        theme
            .insert(&name, config.build(&name)?)
            .map_err(|error| format!("theme {}: {error}", path.display()))?;
    }
    Ok(theme)
}

fn emit_control_sequences(mode: ColorMode) -> bool {
    match mode {
        ColorMode::Always => true,
        ColorMode::Never => false,
        ColorMode::Auto => io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none(),
    }
}

fn write_output(output: &str) -> Result<(), String> {
    let mut stdout = io::stdout().lock();
    let result = stdout
        .write_all(output.as_bytes())
        .and_then(|()| {
            (!output.ends_with('\n'))
                .then(|| stdout.write_all(b"\n"))
                .transpose()
        })
        .and_then(|_| stdout.flush());
    match result {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == io::ErrorKind::BrokenPipe => Ok(()),
        Err(error) => Err(format!("failed to write output: {error}")),
    }
}

fn parse_color(style: &str, field: &str, value: &str) -> Result<Color, String> {
    value.parse().map_err(|_| {
        format!(
            "theme style {style:?} has invalid {field} color {value:?}; expected a named, indexed, or #RRGGBB color"
        )
    })
}

fn parse_width(value: &str) -> Result<usize, String> {
    let width = value
        .parse::<usize>()
        .map_err(|_| format!("invalid display width {value:?}"))?;
    if width == 0 {
        return Err("display width must be greater than zero".to_string());
    }
    Ok(width)
}

fn detected_width() -> usize {
    terminal_size()
        .map(|(Width(width), _)| usize::from(width))
        .filter(|width| *width > 0)
        .unwrap_or(DEFAULT_WIDTH)
}

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

    #[test]
    fn command_line_accepts_files_stdin_width_and_color_policy() {
        let args = Args::try_parse_from([
            "mbterm",
            "--width",
            "72",
            "--color",
            "never",
            "--corners",
            "rounded",
            "--front-matter",
            "document.mb",
        ])
        .unwrap();
        assert_eq!(args.input.as_deref(), Some(Path::new("document.mb")));
        assert_eq!(args.width, Some(72));
        assert_eq!(args.color, ColorMode::Never);
        assert_eq!(args.corners, Some(CornerConfig::Rounded));
        assert!(args.front_matter);

        let stdin = Args::try_parse_from(["mbterm", "-"]).unwrap();
        assert_eq!(stdin.input.as_deref(), Some(Path::new("-")));
    }

    #[test]
    fn fixed_width_must_be_positive() {
        assert_eq!(parse_width("1").unwrap(), 1);
        assert!(parse_width("0").is_err());
        assert!(parse_width("wide").is_err());
    }

    #[test]
    fn plain_output_removes_terminal_sequences_without_losing_text() {
        let rendered = Renderer::new(80).render("[red]warning[/red]");
        assert!(rendered.contains("\x1b["));
        assert_eq!(strip_terminal_sequences(&rendered), "warning");
    }

    #[test]
    fn malformed_structural_markup_is_an_input_error() {
        let error = mbdown::parse("[box]open").unwrap_err();
        assert!(error.to_string().contains("missing [/box]"));
    }

    #[test]
    fn rounded_corners_apply_to_boxes_code_blocks_and_tables() {
        let theme = Theme::new().with_corner_style(CornerStyle::Rounded);
        let rendered = Renderer::with_theme(40, theme).render(concat!(
            "[box]box[/box]\n\n",
            "```text\ncode\n```\n\n",
            "| A | B |\n| --- | --- |\n| one | two |"
        ));
        assert_eq!(rendered.matches('â•­').count(), 3, "{rendered:?}");
        assert_eq!(rendered.matches('â•®').count(), 3, "{rendered:?}");
        assert_eq!(rendered.matches('â•°').count(), 3, "{rendered:?}");
        assert_eq!(rendered.matches('╯').count(), 3, "{rendered:?}");
    }

    #[test]
    fn theme_file_supports_extended_styles_and_emits_exact_sgr() {
        let config: ThemeConfig = toml::from_str(
            r##"
            [styles.notice]
            foreground = "#ff1200"
            background = "17"
            bold = true
            dim = true
            italic = true
            underline = "curly"
            blink = "rapid"
            inverse = true
            strike = true
            overline = true
            underline_color = "bright-white"
            "##,
        )
        .unwrap();
        let mut theme = Theme::new();
        theme
            .insert("notice", config.styles["notice"].build("notice").unwrap())
            .unwrap();
        assert_eq!(
            Renderer::with_theme(80, theme).render_bbcode("[notice]x[/notice]"),
            "\x1b[1;2;3;4:3;6;7;9;53;38;2;255;18;0;48;5;17;58;5;15mx\x1b[0m"
        );
    }

    #[test]
    fn theme_file_supports_legacy_and_named_style_values() {
        let config: ThemeConfig = toml::from_str(concat!(
            "[styles.legacy]\nunderline = true\n",
            "[styles.disabled]\nforeground = \"red\"\nunderline = false\n",
            "[styles.single]\nunderline = \"single\"\n",
            "[styles.double]\nunderline = \"double\"\n",
            "[styles.curly]\nunderline = \"curly\"\n",
            "[styles.dotted]\nunderline = \"dotted\"\n",
            "[styles.dashed]\nunderline = \"dashed\"\n",
            "[styles.slow]\nblink = \"slow\"\n",
            "[styles.rapid]\nblink = \"rapid\"\n",
            "[styles.named]\nunderline_color = \"blue\"\n",
            "[styles.indexed]\nunderline_color = \"196\"\n",
            "[styles.rgb]\nunderline_color = \"#12abef\"\n",
            "[styles.flags]\ninverse = true\noverline = true\n"
        ))
        .unwrap();
        let mut theme = Theme::new();
        for (name, style) in config.styles {
            theme.insert(&name, style.build(&name).unwrap()).unwrap();
        }
        let renderer = Renderer::with_theme(80, theme);
        for (name, expected) in [
            ("legacy", "4"),
            ("disabled", "31"),
            ("single", "4"),
            ("double", "4:2"),
            ("curly", "4:3"),
            ("dotted", "4:4"),
            ("dashed", "4:5"),
            ("slow", "5"),
            ("rapid", "6"),
            ("named", "58;5;4"),
            ("indexed", "58;5;196"),
            ("rgb", "58;2;18;171;239"),
            ("flags", "7;53"),
        ] {
            assert_eq!(
                renderer.render_bbcode(&format!("[{name}]x[/{name}]")),
                format!("\x1b[{expected}mx\x1b[0m"),
                "{name}"
            );
        }
    }

    #[test]
    fn theme_file_shape_and_values_are_strict() {
        for (label, source, parses) in [
            ("top-level unknown", "unknown = true\n", false),
            (
                "style unknown",
                "[styles.notice]\nforeground = \"yellow\"\nunknown = true\n",
                false,
            ),
            (
                "invalid underline",
                "[styles.notice]\nunderline = \"wavy\"\n",
                false,
            ),
            (
                "invalid underline type",
                "[styles.notice]\nunderline = 1\n",
                false,
            ),
            (
                "invalid blink",
                "[styles.notice]\nblink = \"medium\"\n",
                false,
            ),
            ("boolean blink", "[styles.notice]\nblink = true\n", false),
            ("empty", "[styles.notice]\nunderline = false\n", true),
            (
                "invalid underline color",
                "[styles.notice]\nunderline_color = \"not-a-color\"\n",
                true,
            ),
        ] {
            let parsed = toml::from_str::<ThemeConfig>(source);
            assert_eq!(parsed.is_ok(), parses, "{label}: {parsed:?}");
            if let Ok(config) = parsed {
                assert!(config.styles["notice"].build("notice").is_err(), "{label}");
            }
        }
    }

    #[test]
    fn theme_file_configures_rounded_corners() {
        let config: ThemeConfig = toml::from_str("corners = \"rounded\"\n").unwrap();
        assert_eq!(config.corners, Some(CornerConfig::Rounded));
    }
}