1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
|
# `tree-sitter-highlight`
[](https://travis-ci.org/tree-sitter/tree-sitter)
[](https://ci.appveyor.com/project/maxbrunsfeld/tree-sitter/branch/master)
[](https://crates.io/crates/tree-sitter-highlight)
### Usage
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 tree_sitter_highlight::Highlighter;
let highlighter = Highlighter::new();
```
Load some highlighting queries from the `queries` directory of some language repositories:
```rust
use tree_sitter_highlight::HighlightConfiguration;
let html_language = unsafe { tree_sitter_html() };
let javascript_language = unsafe { tree_sitter_javascript() };
let html_config = HighlightConfiguration::new(
tree_sitter_html::language(),
tree_sitter_html::HIGHLIGHTS_QUERY,
tree_sitter_html::INJECTIONS_QUERY,
"",
).unwrap();
let javascript_config = HighlightConfiguration::new(
tree_sitter_javascript::language(),
tree_sitter_javascript::HIGHLIGHTS_QUERY,
tree_sitter_javascript::INJECTIONS_QUERY,
tree_sitter_javascript::LCOALS_QUERY,
).unwrap();
```
Configure the recognized names:
```rust
javascript_config.configure(&highlight_names);
```
Highlight some code:
```rust
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 of a `script` tag within HTML).
|