From bd3b6ec8360e0dd6edfe74c3d0013fd2b98b989e Mon Sep 17 00:00:00 2001 From: Riley Bruins Date: Sun, 28 Jul 2024 13:23:40 -0700 Subject: 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`. --- runtime/doc/news.txt | 2 +- runtime/doc/treesitter.txt | 13 +++++++++++++ runtime/lua/vim/treesitter/languagetree.lua | 12 ++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) (limited to 'runtime') diff --git a/runtime/doc/news.txt b/runtime/doc/news.txt index 2514ee8a92..2ddda72ae8 100644 --- a/runtime/doc/news.txt +++ b/runtime/doc/news.txt @@ -166,7 +166,7 @@ TERMINAL TREESITTER -• TODO +• |LanguageTree:node_for_range()| gets anonymous and named nodes for a range TUI diff --git a/runtime/doc/treesitter.txt b/runtime/doc/treesitter.txt index 2249f4865c..cd8a4d8ec5 100644 --- a/runtime/doc/treesitter.txt +++ b/runtime/doc/treesitter.txt @@ -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: diff --git a/runtime/lua/vim/treesitter/languagetree.lua b/runtime/lua/vim/treesitter/languagetree.lua index 3523ea95e0..03803f5869 100644 --- a/runtime/lua/vim/treesitter/languagetree.lua +++ b/runtime/lua/vim/treesitter/languagetree.lua @@ -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 }` -- cgit