update syntax detection by priority

This commit is contained in:
yggverse 2024-12-02 23:00:47 +02:00
parent 27a8cad8f0
commit a0af227e28
2 changed files with 28 additions and 19 deletions

View File

@ -71,9 +71,9 @@ impl Reader {
// Append value to buffer // Append value to buffer
buffer.insert_with_tags( buffer.insert_with_tags(
&mut buffer.end_iter(), &mut buffer.end_iter(),
&match syntax.highlight(&code.value, None) { &match syntax.auto_highlight(&code.value, None) {
Some(highlight) => highlight, Ok(highlight) => highlight,
None => code.value.to_string(), Err(_) => code.value.to_string(), // @TODO handle
}, },
&[&tag.code.text_tag], &[&tag.code.text_tag],
); );
@ -122,9 +122,9 @@ impl Reader {
// Insert multiline code buffer into main buffer // Insert multiline code buffer into main buffer
buffer.insert_with_tags( buffer.insert_with_tags(
&mut buffer.end_iter(), &mut buffer.end_iter(),
&match syntax.highlight(&this.value, alt) { &match syntax.auto_highlight(&this.value, alt) {
Some(highlight) => highlight, Ok(highlight) => highlight,
None => this.value.to_string(), Err(_) => this.value.to_string(), // @TODO handle
}, },
&[&tag.code.text_tag], &[&tag.code.text_tag],
); );

View File

@ -1,6 +1,9 @@
use syntect::{ use syntect::{
easy::HighlightLines, highlighting::ThemeSet, parsing::SyntaxSet, easy::HighlightLines,
highlighting::ThemeSet,
parsing::{SyntaxReference, SyntaxSet},
util::as_24_bit_terminal_escaped, util::as_24_bit_terminal_escaped,
Error,
}; };
pub const DEFAULT_THEME: &str = "base16-ocean.dark"; pub const DEFAULT_THEME: &str = "base16-ocean.dark";
@ -18,18 +21,24 @@ impl Syntax {
} }
} }
pub fn highlight(&self, source: &str, extension: Option<&String>) -> Option<String> { pub fn auto_highlight(&self, source: &str, alt: Option<&String>) -> Result<String, Error> {
match extension { if let Some(name) = alt {
Some(extension) => match self.syntax_set.find_syntax_by_extension(extension) { if let Some(syntax_reference) = self.syntax_set.find_syntax_by_name(name) {
Some(syntax) => { return self.highlight(source, syntax_reference);
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
} }
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<String, Error> {
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))
} }
} }