forked from folke/trouble.nvim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtreesitter.lua
87 lines (72 loc) · 2.19 KB
/
treesitter.lua
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
---@alias trouble.LangRegions table<string, number[][][]>
local M = {}
M.cache = {} ---@type table<number, table<string,{parser: vim.treesitter.LanguageTree, highlighter:vim.treesitter.highlighter, enabled:boolean}>>
local ns = vim.api.nvim_create_namespace("trouble.treesitter")
local TSHighlighter = vim.treesitter.highlighter
local function wrap(name)
return function(_, win, buf, ...)
if not M.cache[buf] then
return false
end
for _, hl in pairs(M.cache[buf] or {}) do
if hl.enabled then
TSHighlighter.active[buf] = hl.highlighter
TSHighlighter[name](_, win, buf, ...)
end
end
TSHighlighter.active[buf] = nil
end
end
M.did_setup = false
function M.setup()
if M.did_setup then
return
end
M.did_setup = true
vim.api.nvim_set_decoration_provider(ns, {
on_win = wrap("_on_win"),
on_line = wrap("_on_line"),
})
vim.api.nvim_create_autocmd("BufWipeout", {
group = vim.api.nvim_create_augroup("trouble.treesitter.hl", { clear = true }),
callback = function(ev)
M.cache[ev.buf] = nil
end,
})
end
---@param buf number
---@param regions trouble.LangRegions
function M.attach(buf, regions)
M.setup()
M.cache[buf] = M.cache[buf] or {}
for lang in pairs(M.cache[buf]) do
M.cache[buf][lang].enabled = regions[lang] ~= nil
end
for lang in pairs(regions) do
M._attach_lang(buf, lang, regions[lang])
end
end
---@param buf number
---@param lang? string
function M._attach_lang(buf, lang, regions)
lang = lang or "markdown"
lang = lang == "markdown" and "markdown_inline" or lang
M.cache[buf] = M.cache[buf] or {}
if not M.cache[buf][lang] then
local ok, parser = pcall(vim.treesitter.languagetree.new, buf, lang)
if not ok then
local msg = "nvim-treesitter parser missing `" .. lang .. "`"
vim.notify_once(msg, vim.log.levels.WARN, { title = "trouble.nvim" })
return
end
parser:set_included_regions(vim.deepcopy(regions))
M.cache[buf][lang] = {
parser = parser,
highlighter = TSHighlighter.new(parser),
}
end
M.cache[buf][lang].enabled = true
local parser = M.cache[buf][lang].parser
parser:set_included_regions(vim.deepcopy(regions))
end
return M