20 releases

new 0.22.5 Apr 14, 2024
0.22.2 Mar 17, 2024
0.20.1 Nov 21, 2021
0.19.2 Mar 8, 2021
0.1.5 Mar 13, 2019

#260 in Parser implementations

Download history 6882/week @ 2023-12-23 15619/week @ 2023-12-30 24795/week @ 2024-01-06 17946/week @ 2024-01-13 13805/week @ 2024-01-20 14352/week @ 2024-01-27 13272/week @ 2024-02-03 12352/week @ 2024-02-10 12525/week @ 2024-02-17 13580/week @ 2024-02-24 14087/week @ 2024-03-02 24693/week @ 2024-03-09 23445/week @ 2024-03-16 22945/week @ 2024-03-23 23665/week @ 2024-03-30 21472/week @ 2024-04-06

95,774 downloads per month
Used in 38 crates (22 directly)

MIT license

660KB
16K SLoC

C 11K SLoC // 0.0% comments Rust 4.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.21.0"
tree-sitter-javascript = "0.20.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::INJECTION_QUERY,
    tree_sitter_javascript::LOCALS_QUERY,
    false,
).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
~74K SLoC