1
1
-- This module highlights reference usages and the corresponding
2
2
-- definition on cursor hold.
3
3
4
+ local configs = require " nvim-treesitter.configs"
4
5
local ts_utils = require " nvim-treesitter.ts_utils"
5
6
local locals = require " nvim-treesitter.locals"
6
7
local api = vim .api
@@ -9,14 +10,19 @@ local cmd = api.nvim_command
9
10
local M = {}
10
11
11
12
local usage_namespace = api .nvim_create_namespace " nvim-treesitter-usages"
13
+ local last_nodes = {}
12
14
13
15
function M .highlight_usages (bufnr )
14
- M .clear_usage_highlights (bufnr )
15
-
16
16
local node_at_point = ts_utils .get_node_at_cursor ()
17
- local references = locals .get_references (bufnr )
17
+ -- Don't calculate usages again if we are on the same node.
18
+ if node_at_point and node_at_point == last_nodes [bufnr ] and M .has_highlights (bufnr ) then
19
+ return
20
+ else
21
+ last_nodes [bufnr ] = node_at_point
22
+ end
18
23
19
- if not node_at_point or not vim .tbl_contains (references , node_at_point ) then
24
+ M .clear_usage_highlights (bufnr )
25
+ if not node_at_point then
20
26
return
21
27
end
22
28
@@ -34,11 +40,16 @@ function M.highlight_usages(bufnr)
34
40
end
35
41
end
36
42
43
+ function M .has_highlights (bufnr )
44
+ return # api .nvim_buf_get_extmarks (bufnr , usage_namespace , 0 , - 1 , {}) > 0
45
+ end
46
+
37
47
function M .clear_usage_highlights (bufnr )
38
48
api .nvim_buf_clear_namespace (bufnr , usage_namespace , 0 , - 1 )
39
49
end
40
50
41
51
function M .attach (bufnr )
52
+ local config = configs .get_module " refactor.highlight_definitions"
42
53
cmd (string.format (" augroup NvimTreesitterUsages_%d" , bufnr ))
43
54
cmd " au!"
44
55
-- luacheck: push ignore 631
@@ -49,13 +60,15 @@ function M.attach(bufnr)
49
60
bufnr
50
61
)
51
62
)
52
- cmd (
53
- string.format (
54
- [[ autocmd CursorMoved <buffer=%d> lua require'nvim-treesitter-refactor.highlight_definitions'.clear_usage_highlights(%d)]] ,
55
- bufnr ,
56
- bufnr
63
+ if config .clear_on_cursor_move then
64
+ cmd (
65
+ string.format (
66
+ [[ autocmd CursorMoved <buffer=%d> lua require'nvim-treesitter-refactor.highlight_definitions'.clear_usage_highlights(%d)]] ,
67
+ bufnr ,
68
+ bufnr
69
+ )
57
70
)
58
- )
71
+ end
59
72
cmd (
60
73
string.format (
61
74
[[ autocmd InsertEnter <buffer=%d> lua require'nvim-treesitter-refactor.highlight_definitions'.clear_usage_highlights(%d)]] ,
@@ -72,6 +85,7 @@ function M.detach(bufnr)
72
85
cmd (string.format (" autocmd! NvimTreesitterUsages_%d CursorHold" , bufnr ))
73
86
cmd (string.format (" autocmd! NvimTreesitterUsages_%d CursorMoved" , bufnr ))
74
87
cmd (string.format (" autocmd! NvimTreesitterUsages_%d InsertEnter" , bufnr ))
88
+ last_nodes [bufnr ] = nil
75
89
end
76
90
77
91
return M
0 commit comments