3 releases

0.20.14 Oct 5, 2023
0.20.13 Oct 5, 2023
0.20.12 Sep 13, 2023

#945 in Parser implementations

MIT license

14K SLoC

C 10K SLoC // 0.0% comments Rust 4.5K SLoC // 0.0% comments

Tree-sitter Highlight

crates.io badge


Add this crate, and the language-specific crates for whichever languages you want to parse, to your Cargo.toml:

tree-sitter-highlight = "^0.20"
tree-sitter-javascript = "0.19"

Define the list of highlight names that you will recognize:

let highlight_names = [

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(

Configure the recognized names:


Highlight some code:

use tree_sitter_highlight::HighlightEvent;

let highlights = highlighter.highlight(
    b"const x = new Y();",
    |_| None

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).


~77K SLoC