1
1
local ts_utils = require (' nvim-treesitter.ts_utils' )
2
+ local parsers = require (' nvim-treesitter.parsers' )
2
3
local M = {}
3
4
4
5
function M .current_node ()
5
6
local window = vim .api .nvim_get_current_win ()
6
7
return ts_utils .get_node_at_cursor (window )
7
8
end
8
9
10
+ --- This is a full copy of nvim_treesiter get_node_at_cursor with support for custom cursor position
11
+ --- @param cursor ? Table Cursor position tuple {row , col }
12
+ --- @param winnr ? number
13
+ --- @param ignore_injected_langs ? boolean
14
+ function M .get_node_at_cursor (cursor , winnr , ignore_injected_langs )
15
+ winnr = winnr or 0
16
+ cursor = cursor or vim .api .nvim_win_get_cursor (winnr )
17
+ local cursor_range = { cursor [1 ] - 1 , cursor [2 ] }
18
+
19
+ local buf = vim .api .nvim_win_get_buf (winnr )
20
+ local root_lang_tree = parsers .get_parser (buf )
21
+ if not root_lang_tree then
22
+ return
23
+ end
24
+
25
+ local root
26
+ if ignore_injected_langs then
27
+ for _ , tree in ipairs (root_lang_tree :trees ()) do
28
+ local tree_root = tree :root ()
29
+ if tree_root and ts_utils .is_in_node_range (tree_root , cursor_range [1 ], cursor_range [2 ]) then
30
+ root = tree_root
31
+ break
32
+ end
33
+ end
34
+ else
35
+ root = ts_utils .get_root_for_position (cursor_range [1 ], cursor_range [2 ], root_lang_tree )
36
+ end
37
+
38
+ if not root then
39
+ return
40
+ end
41
+
42
+ return root :named_descendant_for_range (cursor_range [1 ], cursor_range [2 ], cursor_range [1 ], cursor_range [2 ])
43
+ end
44
+
9
45
-- walks the tree to find a headline
10
46
function M .find_headline (node )
11
47
if node :type () == ' headline' then
@@ -21,9 +57,9 @@ function M.find_headline(node)
21
57
end
22
58
23
59
-- returns the nearest headline
24
- function M .closest_headline ()
60
+ function M .closest_headline (cursor )
25
61
vim .treesitter .get_parser (0 , ' org' , {}):parse ()
26
- return M .find_headline (M .current_node ( ))
62
+ return M .find_headline (M .get_node_at_cursor ( cursor ))
27
63
end
28
64
29
65
function M .find_parent_type (node , type )
0 commit comments