From e4c0fc7beab2a6dd53210263a857f2b3ec29b604 Mon Sep 17 00:00:00 2001 From: Jonas Maier Date: Sat, 23 May 2026 14:48:51 +0200 Subject: customizable syntax highlighting --- src/syntax_highlighting.rs | 53 +++++++++++++++++++++++++++++++++------------- 1 file changed, 38 insertions(+), 15 deletions(-) (limited to 'src/syntax_highlighting.rs') diff --git a/src/syntax_highlighting.rs b/src/syntax_highlighting.rs index 0b1e8c5..b76aa4b 100644 --- a/src/syntax_highlighting.rs +++ b/src/syntax_highlighting.rs @@ -1,28 +1,51 @@ -use crate::parse::{Highlight, HighlightKind, Keyword}; +use std::collections::HashMap; + +use crate::{ + BString, ansi, bstr, + parse::{Highlight, HighlightKind}, +}; pub struct Highlighter { pub enabled: bool, + colors: HashMap, +} + +#[derive(Debug)] +pub enum SetColorError { + NoSuchKeyword, } impl Highlighter { pub fn new() -> Self { - Self { enabled: true } + let mut this = Self { + enabled: true, + colors: HashMap::new(), + }; + let mut sc = |a: &str, b: &str| this.set_color(a.as_bytes(), b.as_bytes()).unwrap(); + use ansi::colors::*; + sc("keywords", GREEN_FG); + sc("braces", CYAN_FG); + sc("string", MAGENTA_FG); + this } - pub fn color(&self, h: HighlightKind) -> &[u8] { - // TODO: configurable - const GREEN: &[u8] = b"\x1b[32m"; - const BLUE: &[u8] = b"\x1b[36m"; - const MAGENTA: &[u8] = b"\x1b[95m"; - const COLOR_RESET: &[u8] = b"\x1b[0m"; - match h { - HighlightKind::Keyword( - Keyword::If | Keyword::Elif | Keyword::Else | Keyword::While, - ) => GREEN, - HighlightKind::Keyword(Keyword::OpenBrace | Keyword::CloseBrace) => BLUE, - HighlightKind::String => MAGENTA, - HighlightKind::None => COLOR_RESET, + pub fn set_color(&mut self, ident: &bstr, color: &bstr) -> Result<(), SetColorError> { + let kinds = HighlightKind::from_identifier(ident); + for kind in kinds.iter() { + self.colors.insert(*kind, color.to_vec()); } + if kinds.is_empty() { + Err(SetColorError::NoSuchKeyword) + } else { + Ok(()) + } + } + + pub fn color(&self, h: HighlightKind) -> &[u8] { + self.colors + .get(&h) + .map(|c| c.as_ref()) + .unwrap_or(ansi::colors::RESET.as_bytes()) } pub fn pretty_print( -- cgit v1.2.3