summaryrefslogtreecommitdiff
path: root/src/widgets/luaeditor/treesitter.rs
blob: 1474434e9388dc6c37155b0ccc0606c025956ffa (plain)
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
use tree_sitter_highlight::{Highlight, HighlightConfiguration, HighlightEvent, Highlighter};

static HIGHLIGHT_NAMES: [&str; 29] = [
    "attribute",
    "boolean",
    "comment",
    "conditional",
    "constant",
    "constant.builtin",
    "constructor",
    "field",
    "function",
    "function.builtin",
    "function.call",
    "keyword",
    "keyword.function",
    "keyword.operator",
    "keyword.return",
    "label",
    "method",
    "method.call",
    "number",
    "operator",
    "parameter",
    "preproc",
    "punctuation.bracket",
    "punctuation.delimiter",
    "repeat",
    "string",
    "string.escape",
    "variable",
    "variable.builtin",
];

pub fn new_highlight_configuration() -> HighlightConfiguration {
    let mut highlight_config = HighlightConfiguration::new(
        tree_sitter_lua::language(),
        "lua",
        tree_sitter_lua::HIGHLIGHTS_QUERY,
        tree_sitter_lua::INJECTIONS_QUERY,
        tree_sitter_lua::LOCALS_QUERY,
    )
    .unwrap();

    highlight_config.configure(&HIGHLIGHT_NAMES);

    highlight_config
}

pub fn highlight_name(h: Highlight) -> &'static str {
    HIGHLIGHT_NAMES[h.0]
}

pub fn highlighter_split<'a>(
    s: &'a [u8],
    config: &'a HighlightConfiguration,
) -> Vec<(Option<Highlight>, &'a str)> {
    let mut splits = Vec::new();
    let mut current = None;

    let mut highlighter = Highlighter::new();
    let highlights = highlighter.highlight(config, s, None, |_| None).unwrap();

    for event in highlights {
        match event.unwrap() {
            HighlightEvent::Source { start, end } => {
                let group = std::str::from_utf8(&s[start..end]).unwrap();

                for line in group.lines() {
                    splits.push((current, line));
                    splits.push((current, "\n"));
                }

                if !group.ends_with('\n') {
                    splits.pop();
                }
            }
            HighlightEvent::HighlightStart(s) => current = Some(s),
            HighlightEvent::HighlightEnd => current = None,
        }
    }

    splits
}