fix(treesitter): allow passing lang to vim.treesitter.get_node() now correctly takes opts.lang (#26360)

PROBLEM: `vim.treesitter.get_node()` does not recognize the `lang` in
the option table. This option was used in somewhere else, for instance,
`vim.treesitter.dev` (for `inspect_tree`) but was never implemented.

SOLUTION: Make `get_node()` correctly use `opts.lang` when getting a
treesitter parser.
This commit is contained in:
Jongwook Choi 2023-12-04 04:00:49 -05:00 committed by GitHub
parent 589f4761ee
commit cf612c64b0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 18 additions and 1 deletions

View File

@ -616,6 +616,8 @@ get_node({opts}) *vim.treesitter.get_node()*
• pos table|nil 0-indexed (row, col) tuple. Defaults to cursor
position in the current window. Required if {bufnr} is not
the current buffer
• lang string|nil Parser language. (default: from buffer
filetype)
• ignore_injections boolean Ignore injected languages (default
true)

View File

@ -362,6 +362,7 @@ end
--- - bufnr integer|nil Buffer number (nil or 0 for current buffer)
--- - pos table|nil 0-indexed (row, col) tuple. Defaults to cursor position in the
--- current window. Required if {bufnr} is not the current buffer
--- - lang string|nil Parser language. (default: from buffer filetype)
--- - ignore_injections boolean Ignore injected languages (default true)
---
---@return TSNode | nil Node at the given position
@ -392,7 +393,7 @@ function M.get_node(opts)
local ts_range = { row, col, row, col }
local root_lang_tree = M.get_parser(bufnr)
local root_lang_tree = M.get_parser(bufnr, opts.lang)
if not root_lang_tree then
return
end

View File

@ -40,6 +40,20 @@ describe('treesitter node API', function()
assert_alive()
end)
it('get_node() with lang given', function()
-- this buffer doesn't have filetype set!
insert('local foo = function() end')
exec_lua([[
node = vim.treesitter.get_node({
bufnr = 0,
pos = { 0, 6 }, -- on "foo"
lang = 'lua',
})
]])
eq('foo', lua_eval('vim.treesitter.query.get_node_text(node, 0)'))
eq('identifier', lua_eval('node:type()'))
end)
it('can move between siblings', function()
insert([[
int main(int x, int y, int z) {