mbterm 0.1.0

ANSI terminal renderer for MBDown documents
Documentation
//! 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,
}

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

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

    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)
    }

    /// 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)
    }

    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"));
    }
}