feat(treesitter)!: apply offset! directive to all captures #34383

This commit changes the `offset!` directive so that instead of setting a
`metadata.range` value for the entire pattern, it will set a
`metadata.offset` value. This offset will be applied to the range only
in `vim.treesitter.get_range()`, rather than at directive application
time. This allows the offset to be applied to any and all nodes captured
by the given pattern, and removes the requirement that `#offset!` be
applied to only a single node.

The downside of this change is that plugins which read from
`metadata.range` may be thrown off course, but such plugins should
prefer `vim.treesitter.get_range()` when retrieving ranges anyway.

Note that `#trim!` still sets `metadata.range`, and
`vim.treesitter.get_range()` still reads from `metadata.range`, if it
exists.
This commit is contained in:
Riley Bruins
2025-06-13 06:42:10 -07:00
committed by GitHub
parent 9ec6c19c67
commit 1d5b3b5b4c
6 changed files with 87 additions and 27 deletions

View File

@@ -838,6 +838,38 @@ int x = INT_MAX;
{ 5, 17, 5, 17 }, -- VALUE2 123
}, get_ranges())
end)
it('should apply offsets to quantified captures', function()
local function get_ltree_ranges()
return exec_lua(function()
local result = {}
_G.parser:for_each_tree(function(_, ltree)
table.insert(result, ltree:included_regions())
end)
return result
end)
end
exec_lua(function()
_G.parser = vim.treesitter.get_parser(0, 'c', {
injections = {
c = '((preproc_def (preproc_arg) @injection.content)+ (#set! injection.language "c") (#offset! @injection.content 0 1 0 -1))',
},
})
_G.parser:parse(true)
end)
eq('table', exec_lua('return type(parser:children().c)'))
eq({
{ {} }, -- root tree
{
{
{ 3, 15, 163, 3, 16, 164 }, -- VALUE 123
{ 4, 16, 182, 4, 17, 183 }, -- VALUE1 123
{ 5, 16, 201, 5, 17, 202 }, -- VALUE2 123
},
},
}, get_ltree_ranges())
end)
it('should list all directives', function()
local res_list = exec_lua(function()
local query = vim.treesitter.query