diff options
| author | Nathan Reiner <nathan@nathanreiner.xyz> | 2024-07-25 16:39:49 +0200 |
|---|---|---|
| committer | Nathan Reiner <nathan@nathanreiner.xyz> | 2024-07-25 16:39:49 +0200 |
| commit | 9722d01b078dbf554431a3af3767012fce341b95 (patch) | |
| tree | 81c2bb129bd81923bbf0767e62720882a31a1f56 /src/widgets/luaeditor/treesitter.rs | |
| parent | 21c8643173e87691b47ae9860c6cb095a6ea68b2 (diff) | |
editor add syntax highlighting using treesitter
Diffstat (limited to 'src/widgets/luaeditor/treesitter.rs')
| -rw-r--r-- | src/widgets/luaeditor/treesitter.rs | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/src/widgets/luaeditor/treesitter.rs b/src/widgets/luaeditor/treesitter.rs new file mode 100644 index 0000000..57013f9 --- /dev/null +++ b/src/widgets/luaeditor/treesitter.rs @@ -0,0 +1,75 @@ +use tree_sitter_highlight::{Highlight, HighlightConfiguration, HighlightEvent, Highlighter}; + +static HIGHLIGHT_NAMES: [&'static str; 29] = [ + "attribute", + "boolean", + "comment", + "conditional", + "constant", + "constant.builtin", + "constructor", + "field", + "function", + "function.builtin", + "function.call", + "keyword", + "keyword.function", + "keyword.operator", + "keyword.return", + "label", + "method", + "method.call", + "number", + "operator", + "parameter", + "preproc", + "punctuation.bracket", + "punctuation.delimiter", + "repeat", + "string", + "string.escape", + "variable", + "variable.builtin", +]; + +pub fn new_highlight_configuration() -> HighlightConfiguration { + let mut highlight_config = HighlightConfiguration::new( + tree_sitter_lua::language(), + "lua", + tree_sitter_lua::HIGHLIGHTS_QUERY, + tree_sitter_lua::INJECTIONS_QUERY, + tree_sitter_lua::LOCALS_QUERY, + ) + .unwrap(); + + highlight_config.configure(&HIGHLIGHT_NAMES); + + highlight_config +} + +pub fn highlight_name(h: Highlight) -> &'static str { + HIGHLIGHT_NAMES[h.0] +} + +pub fn highlighter_split<'a>( + s: &'a [u8], + config: &'a HighlightConfiguration, +) -> Vec<(Option<Highlight>, &'a str)> { + let mut splits = Vec::new(); + let mut current = None; + + let mut highlighter = Highlighter::new(); + let highlights = highlighter.highlight(config, s, None, |_| None).unwrap(); + + for event in highlights { + match event.unwrap() { + HighlightEvent::Source { start, end } => { + splits.push((current, std::str::from_utf8(&s[start..end]).unwrap())); + } + HighlightEvent::HighlightStart(s) => current = Some(s), + HighlightEvent::HighlightEnd => current = None, + } + } + + splits +} |