tree-sitter-highlight
Add this crate, and the language-specific crates for whichever languages you want to parse, to your Cargo.toml
:
toml
[dependencies]
tree-sitter-highlight = "0.19"
tree-sitter-html = "0.19"
tree-sitter-javascript = "0.19"
Define the list of highlight names that you will recognize:
rust
let highlight_names = &[
"attribute",
"constant",
"function.builtin",
"function",
"keyword",
"operator",
"property",
"punctuation",
"punctuation.bracket",
"punctuation.delimiter",
"string",
"string.special",
"tag",
"type",
"type.builtin",
"variable",
"variable.builtin",
"variable.parameter",
];
Create a highlighter. You need one of these for each thread that you're using for syntax highlighting:
```rust use treesitterhighlight::Highlighter;
let highlighter = Highlighter::new(); ```
Load some highlighting queries from the queries
directory of some language repositories:
```rust use treesitterhighlight::HighlightConfiguration;
let htmllanguage = unsafe { treesitterhtml() }; let javascriptlanguage = unsafe { treesitterjavascript() };
let htmlconfig = HighlightConfiguration::new( treesitterhtml::language(), treesitterhtml::HIGHLIGHTSQUERY, treesitterhtml::INJECTIONS_QUERY, "", ).unwrap();
let javascriptconfig = HighlightConfiguration::new( treesitterjavascript::language(), treesitterjavascript::HIGHLIGHTSQUERY, treesitterjavascript::INJECTIONSQUERY, treesitterjavascript::LCOALSQUERY, ).unwrap(); ```
Configure the recognized names:
rust
javascript_config.configure(&highlight_names);
Highlight some code:
```rust use treesitterhighlight::HighlightEvent;
let highlights = highlighter.highlight( &javascriptconfig, b"const x = new Y();", None, || None ).unwrap();
for event in highlights { match event.unwrap() { HighlightEvent::Source {start, end} => { eprintln!("source: {}-{}", start, end); }, HighlightEvent::HighlightStart(s) => { eprintln!("highlight style started: {:?}", s); }, HighlightEvent::HighlightEnd => { eprintln!("highlight style ended"); }, } } ```
The last parameter to highlight
is a language injection callback. This allows other languages to be retrieved when Tree-sitter detects an embedded document (for example, a piece of JavaScript code inside of a script
tag within HTML).