diff --git a/src/app/browser/window/tab/item/page/content/text/gemini/reader.rs b/src/app/browser/window/tab/item/page/content/text/gemini/reader.rs index 5982eff9..21c8ae21 100644 --- a/src/app/browser/window/tab/item/page/content/text/gemini/reader.rs +++ b/src/app/browser/window/tab/item/page/content/text/gemini/reader.rs @@ -71,9 +71,9 @@ impl Reader { // Append value to buffer buffer.insert_with_tags( &mut buffer.end_iter(), - &match syntax.highlight(&code.value, None) { - Some(highlight) => highlight, - None => code.value.to_string(), + &match syntax.auto_highlight(&code.value, None) { + Ok(highlight) => highlight, + Err(_) => code.value.to_string(), // @TODO handle }, &[&tag.code.text_tag], ); @@ -122,9 +122,9 @@ impl Reader { // Insert multiline code buffer into main buffer buffer.insert_with_tags( &mut buffer.end_iter(), - &match syntax.highlight(&this.value, alt) { - Some(highlight) => highlight, - None => this.value.to_string(), + &match syntax.auto_highlight(&this.value, alt) { + Ok(highlight) => highlight, + Err(_) => this.value.to_string(), // @TODO handle }, &[&tag.code.text_tag], ); diff --git a/src/app/browser/window/tab/item/page/content/text/gemini/reader/syntax.rs b/src/app/browser/window/tab/item/page/content/text/gemini/reader/syntax.rs index f3026f47..57c03010 100644 --- a/src/app/browser/window/tab/item/page/content/text/gemini/reader/syntax.rs +++ b/src/app/browser/window/tab/item/page/content/text/gemini/reader/syntax.rs @@ -1,6 +1,9 @@ use syntect::{ - easy::HighlightLines, highlighting::ThemeSet, parsing::SyntaxSet, + easy::HighlightLines, + highlighting::ThemeSet, + parsing::{SyntaxReference, SyntaxSet}, util::as_24_bit_terminal_escaped, + Error, }; pub const DEFAULT_THEME: &str = "base16-ocean.dark"; @@ -18,18 +21,24 @@ impl Syntax { } } - pub fn highlight(&self, source: &str, extension: Option<&String>) -> Option { - match extension { - Some(extension) => match self.syntax_set.find_syntax_by_extension(extension) { - Some(syntax) => { - let ranges = HighlightLines::new(syntax, &self.theme_set.themes[DEFAULT_THEME]) - .highlight_line(&source, &self.syntax_set) - .unwrap(); // @TODO - Some(as_24_bit_terminal_escaped(&ranges[..], true)) - } - None => None, - }, - None => None, // @TODO detect by source + pub fn auto_highlight(&self, source: &str, alt: Option<&String>) -> Result { + if let Some(name) = alt { + if let Some(syntax_reference) = self.syntax_set.find_syntax_by_name(name) { + return self.highlight(source, syntax_reference); + } } + + if let Some(syntax_reference) = self.syntax_set.find_syntax_by_first_line(source) { + return self.highlight(source, syntax_reference); + } + + Ok(source.to_string()) + } + + fn highlight(&self, source: &str, syntax_reference: &SyntaxReference) -> Result { + let ranges = HighlightLines::new(syntax_reference, &self.theme_set.themes[DEFAULT_THEME]) + .highlight_line(&source, &self.syntax_set)?; + + Ok(as_24_bit_terminal_escaped(&ranges[..], true)) } }