From 8bd63bd92ded48a23c4f92eb550b3fdbc649c9ed Mon Sep 17 00:00:00 2001 From: Tom Lebreux Date: Sun, 11 Dec 2022 11:25:46 -0500 Subject: [PATCH] Allow ANSI colors in themes --- helix-view/src/theme.rs | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/helix-view/src/theme.rs b/helix-view/src/theme.rs index b2c8a79f76aa..e81b05572ece 100644 --- a/helix-view/src/theme.rs +++ b/helix-view/src/theme.rs @@ -351,8 +351,23 @@ impl ThemePalette { Self { palette: default } } - pub fn hex_string_to_rgb(s: &str) -> Result { - if s.starts_with('#') && s.len() >= 7 { + pub fn string_to_rgb(s: &str) -> Result { + if s.starts_with('#') { + Self::hex_string_to_rgb(s) + } else { + Self::ansi_string_to_rgb(s) + } + } + + fn ansi_string_to_rgb(s: &str) -> Result { + if let Ok(index) = s.parse::() { + return Ok(Color::Indexed(index)); + } + Err(format!("Theme: malformed ANSI: {}", s)) + } + + fn hex_string_to_rgb(s: &str) -> Result { + if s.len() >= 7 { if let (Ok(red), Ok(green), Ok(blue)) = ( u8::from_str_radix(&s[1..3], 16), u8::from_str_radix(&s[3..5], 16), @@ -378,7 +393,7 @@ impl ThemePalette { .get(value) .copied() .ok_or("") - .or_else(|_| Self::hex_string_to_rgb(value)) + .or_else(|_| Self::string_to_rgb(value)) } pub fn parse_modifier(value: &Value) -> Result { @@ -454,7 +469,7 @@ impl TryFrom for ThemePalette { let mut palette = HashMap::with_capacity(map.len()); for (name, value) in map { let value = Self::parse_value_as_str(&value)?; - let color = Self::hex_string_to_rgb(value)?; + let color = Self::string_to_rgb(value)?; palette.insert(name, color); }