Crates.io | tree-sitter-highlight |
lib.rs | tree-sitter-highlight |
version | |
source | src |
created_at | 2019-02-20 01:57:25.055079 |
updated_at | 2024-12-11 06:50:14.568255 |
description | Library for performing syntax highlighting with Tree-sitter |
homepage | https://tree-sitter.github.io/tree-sitter |
repository | https://github.com/tree-sitter/tree-sitter |
max_upload_size | |
id | 115843 |
Cargo.toml error: | TOML parse error at line 22, column 1 | 22 | autolib = false | ^^^^^^^ unknown field `autolib`, expected one of `name`, `version`, `edition`, `authors`, `description`, `readme`, `license`, `repository`, `homepage`, `documentation`, `build`, `resolver`, `links`, `default-run`, `default_dash_run`, `rust-version`, `rust_dash_version`, `rust_version`, `license-file`, `license_dash_file`, `license_file`, `licenseFile`, `license_capital_file`, `forced-target`, `forced_dash_target`, `autobins`, `autotests`, `autoexamples`, `autobenches`, `publish`, `metadata`, `keywords`, `categories`, `exclude`, `include` |
size | 0 |
Add this crate, and the language-specific crates for whichever languages you want
to parse, to your Cargo.toml
:
[dependencies]
tree-sitter-highlight = "0.22.0"
tree-sitter-javascript = "0.21.3"
Define the list of highlight names that you will recognize:
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:
use tree_sitter_highlight::Highlighter;
let mut highlighter = Highlighter::new();
Load some highlighting queries from the queries
directory of the language repository:
use tree_sitter_highlight::HighlightConfiguration;
let javascript_language = tree_sitter_javascript::language();
let mut javascript_config = HighlightConfiguration::new(
javascript_language,
"javascript",
tree_sitter_javascript::HIGHLIGHT_QUERY,
tree_sitter_javascript::INJECTIONS_QUERY,
tree_sitter_javascript::LOCALS_QUERY,
).unwrap();
Configure the recognized names:
javascript_config.configure(&highlight_names);
Highlight some code:
use tree_sitter_highlight::HighlightEvent;
let highlights = highlighter.highlight(
&javascript_config,
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 a script
tag within HTML).