feat(treesitter): add node_for_range function

This is identical to `named_node_for_range` except that it includes
anonymous nodes. This maintains consistency in the API because we
already have `descendant_for_range` and `named_descendant_for_range`.
This commit is contained in:
Riley Bruins 2024-07-28 13:23:40 -07:00 committed by Christian Clason
parent 01a56a056c
commit bd3b6ec836
4 changed files with 37 additions and 1 deletions

View File

@ -166,7 +166,7 @@ TERMINAL
TREESITTER
TODO
|LanguageTree:node_for_range()| gets anonymous and named nodes for a range
TUI

View File

@ -1366,6 +1366,19 @@ LanguageTree:language_for_range({range})
LanguageTree:named_node_for_range({range}, {opts})
Gets the smallest named node that contains {range}.
Parameters: ~
• {range} (`Range4`) `{ start_line, start_col, end_line, end_col }`
• {opts} (`table?`) A table with the following fields:
• {ignore_injections}? (`boolean`, default: `true`) Ignore
injected languages
Return: ~
(`TSNode?`)
*LanguageTree:node_for_range()*
LanguageTree:node_for_range({range}, {opts})
Gets the smallest node that contains {range}.
Parameters: ~
• {range} (`Range4`) `{ start_line, start_col, end_line, end_col }`
• {opts} (`table?`) A table with the following fields:

View File

@ -1133,6 +1133,18 @@ function LanguageTree:tree_for_range(range, opts)
return nil
end
--- Gets the smallest node that contains {range}.
---
---@param range Range4 `{ start_line, start_col, end_line, end_col }`
---@param opts? vim.treesitter.LanguageTree.tree_for_range.Opts
---@return TSNode?
function LanguageTree:node_for_range(range, opts)
local tree = self:tree_for_range(range, opts)
if tree then
return tree:root():descendant_for_range(unpack(range))
end
end
--- Gets the smallest named node that contains {range}.
---
---@param range Range4 `{ start_line, start_col, end_line, end_col }`

View File

@ -148,4 +148,15 @@ describe('treesitter language API', function()
eq('<node primitive_type>', exec_lua('return tostring(node)'))
end)
it('retrieve an anonymous node given a range', function()
insert([[vim.fn.input()]])
exec_lua([[
langtree = vim.treesitter.get_parser(0, "lua")
node = langtree:node_for_range({0, 3, 0, 3})
]])
eq('.', exec_lua('return node:type()'))
end)
end)