27 releases (8 breaking)

new 0.24.4 Nov 10, 2024
0.23.2 Oct 1, 2024
0.22.6 May 5, 2024
0.22.2 Mar 17, 2024
0.1.5 Mar 13, 2019

#327 in Parser implementations

Download history 27285/week @ 2024-07-27 24858/week @ 2024-08-03 24170/week @ 2024-08-10 25935/week @ 2024-08-17 26364/week @ 2024-08-24 19129/week @ 2024-08-31 27697/week @ 2024-09-07 27764/week @ 2024-09-14 27405/week @ 2024-09-21 28080/week @ 2024-09-28 30617/week @ 2024-10-05 28673/week @ 2024-10-12 23673/week @ 2024-10-19 21018/week @ 2024-10-26 33702/week @ 2024-11-02 22216/week @ 2024-11-09

105,803 downloads per month
Used in 50 crates (32 directly)

MIT license

680KB
17K SLoC

C 12K SLoC // 0.1% comments Rust 5K SLoC // 0.0% comments

Tree-sitter Highlight

crates.io badge

Usage

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

Dependencies

~2.4–4MB
~80K SLoC