mbterm 0.1.4

ANSI terminal renderer for MBDown documents
Documentation
use std::sync::OnceLock;

use syntect::easy::HighlightLines;
use syntect::highlighting::{FontStyle, Theme, ThemeSet};
use syntect::parsing::SyntaxSet;
use syntect::util::LinesWithEndings;

use crate::{bbcode, catppuccin, Color, TextStyle};

struct SyntaxAssets {
    syntaxes: SyntaxSet,
    theme: Theme,
}

pub(crate) fn render(source: &str, language: Option<&str>) -> String {
    let source = bbcode::sanitize_terminal_controls(source);
    let Some(language) = language else {
        return styled(&source, TextStyle::new().foreground(catppuccin::TEXT));
    };
    if matches!(language.to_ascii_lowercase().as_str(), "diff" | "patch") {
        return render_diff(&source);
    }
    render_highlighted(&source, language)
        .unwrap_or_else(|| styled(&source, TextStyle::new().foreground(catppuccin::TEXT)))
}

fn assets() -> &'static SyntaxAssets {
    static ASSETS: OnceLock<SyntaxAssets> = OnceLock::new();
    ASSETS.get_or_init(|| {
        let syntaxes = SyntaxSet::load_defaults_newlines();
        let mut themes = ThemeSet::load_defaults().themes;
        let theme = themes
            .remove("base16-ocean.dark")
            .expect("syntect default theme");
        SyntaxAssets { syntaxes, theme }
    })
}

fn render_highlighted(source: &str, language: &str) -> Option<String> {
    let assets = assets();
    let syntax = assets.syntaxes.find_syntax_by_token(language)?;
    let mut highlighter = HighlightLines::new(syntax, &assets.theme);
    let mut output = String::new();
    for line in LinesWithEndings::from(source) {
        for (style, text) in highlighter.highlight_line(line, &assets.syntaxes).ok()? {
            output.push_str(&styled(text, syntax_style(style)));
        }
    }
    Some(output)
}

fn render_diff(source: &str) -> String {
    source
        .split_inclusive('\n')
        .map(|line| {
            let content = line.trim_end_matches('\n');
            let style = if content.starts_with("+++") || content.starts_with("---") {
                TextStyle::new().foreground(catppuccin::YELLOW).bold()
            } else if content.starts_with("@@") {
                TextStyle::new().foreground(catppuccin::SAPPHIRE).bold()
            } else if content.starts_with('+') {
                TextStyle::new().foreground(catppuccin::GREEN)
            } else if content.starts_with('-') {
                TextStyle::new().foreground(catppuccin::RED)
            } else if content.starts_with("diff ")
                || content.starts_with("index ")
                || content.starts_with("new file ")
                || content.starts_with("deleted file ")
            {
                TextStyle::new().foreground(catppuccin::OVERLAY_0).bold()
            } else {
                TextStyle::new().foreground(catppuccin::TEXT)
            };
            let mut rendered = styled(content, style);
            if line.ends_with('\n') {
                rendered.push('\n');
            }
            rendered
        })
        .collect()
}

fn syntax_style(style: syntect::highlighting::Style) -> TextStyle {
    let mut output = TextStyle::new().foreground(catppuccin_syntax_color(style.foreground));
    if style.font_style.contains(FontStyle::BOLD) {
        output = output.bold();
    }
    if style.font_style.contains(FontStyle::ITALIC) {
        output = output.italic();
    }
    if style.font_style.contains(FontStyle::UNDERLINE) {
        output = output.underline();
    }
    output
}

fn catppuccin_syntax_color(color: syntect::highlighting::Color) -> Color {
    match (color.r, color.g, color.b) {
        (191, 97, 106) => return catppuccin::RED,
        (208, 135, 112) => return catppuccin::PEACH,
        (235, 203, 139) => return catppuccin::YELLOW,
        (163, 190, 140) => return catppuccin::GREEN,
        (150, 181, 180) => return catppuccin::TEAL,
        (143, 161, 179) => return catppuccin::BLUE,
        (180, 142, 173) => return catppuccin::MAUVE,
        _ => {}
    }
    catppuccin::SYNTAX
        .into_iter()
        .min_by_key(|candidate| {
            let Color::Rgb(red, green, blue) = *candidate else {
                unreachable!("Catppuccin syntax colors are RGB")
            };
            let red = i32::from(red) - i32::from(color.r);
            let green = i32::from(green) - i32::from(color.g);
            let blue = i32::from(blue) - i32::from(color.b);
            red * red + green * green + blue * blue
        })
        .expect("Catppuccin syntax palette is not empty")
}

fn styled(text: &str, style: TextStyle) -> String {
    let sgr = style.sgr();
    if text.is_empty() || sgr.is_empty() {
        text.to_string()
    } else {
        format!("\x1b[{sgr}m{text}{}", bbcode::RESET)
    }
}

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

    #[test]
    fn highlights_known_languages_without_changing_source_text() {
        let source = "fn main() {\n    let answer = 42;\n}";
        let rendered = render(source, Some("rust"));
        assert_eq!(strip_terminal_sequences(&rendered), source);
        assert!(rendered.contains("\x1b["));
        assert!(rendered.contains("38;2;203;166;247"), "{rendered:?}");
    }

    #[test]
    fn highlights_diff_lines_with_semantic_catppuccin_colors() {
        let source = "@@ -1 +1 @@\n-old\n+new";
        let rendered = render(source, Some("diff"));
        assert_eq!(strip_terminal_sequences(&rendered), source);
        assert!(rendered.contains("38;2;116;199;236"), "{rendered:?}");
        assert!(rendered.contains("38;2;243;139;168"), "{rendered:?}");
        assert!(rendered.contains("38;2;166;227;161"), "{rendered:?}");
    }

    #[test]
    fn removes_terminal_controls_from_code_before_styling() {
        let rendered = render("safe\x1b[31m forged", Some("text"));
        assert_eq!(strip_terminal_sequences(&rendered), "safe forged");
    }
}