From cf612c64b0fc87c399bc5c72735335c5e73d6de1 Mon Sep 17 00:00:00 2001 From: Jongwook Choi Date: Mon, 4 Dec 2023 04:00:49 -0500 Subject: [PATCH] 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. --- runtime/doc/treesitter.txt | 2 ++ runtime/lua/vim/treesitter.lua | 3 ++- test/functional/treesitter/node_spec.lua | 14 ++++++++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/runtime/doc/treesitter.txt b/runtime/doc/treesitter.txt index 9bdc6b8d24..e3836a357b 100644 --- a/runtime/doc/treesitter.txt +++ b/runtime/doc/treesitter.txt @@ -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) diff --git a/runtime/lua/vim/treesitter.lua b/runtime/lua/vim/treesitter.lua index e7a66c00b2..7b795380fe 100644 --- a/runtime/lua/vim/treesitter.lua +++ b/runtime/lua/vim/treesitter.lua @@ -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 diff --git a/test/functional/treesitter/node_spec.lua b/test/functional/treesitter/node_spec.lua index eef75d0e91..16ead69649 100644 --- a/test/functional/treesitter/node_spec.lua +++ b/test/functional/treesitter/node_spec.lua @@ -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) {