feat: allow modifying expand-position in pre_expand-callback (#1219).

This commit is contained in:
L3MON4D3 2024-08-06 23:21:45 +02:00
parent 7552e6504e
commit 9033373173
3 changed files with 28 additions and 5 deletions

2
DOC.md
View file

@ -3400,6 +3400,8 @@ The node and `event_args` can be accessed through `require("luasnip").session`:
`event_args`:
* `expand_pos`: `{<row>, <column>}`, position at which the snippet will be
expanded. `<row>` and `<column>` are both 0-indexed.
* `expand_pos_mark_id`: `number`, the id of the extmark luasnip uses to track
`expand_pos`. This may be moved around freely.
`event_res`:
* `env_override`: `map string->(string[]|string)`, override or extend the
snippet's environment (`snip.env`).

View file

@ -632,6 +632,12 @@ end
function Snippet:trigger_expand(current_node, pos_id, env, indent_nodes)
local pos = vim.api.nvim_buf_get_extmark_by_id(0, session.ns_id, pos_id, {})
local pre_expand_res = self:event(events.pre_expand, { expand_pos = pos, expand_pos_mark_id = pos_id })
or {}
-- update pos, event-callback might have moved the extmark.
pos = vim.api.nvim_buf_get_extmark_by_id(0, session.ns_id, pos_id, {})
-- find tree-node the snippet should be inserted at (could be before another node).
local _, sibling_snippets, own_indx, parent_node =
node_util.snippettree_find_undamaged_node(pos, {
@ -697,11 +703,6 @@ function Snippet:trigger_expand(current_node, pos_id, env, indent_nodes)
end
end
local pre_expand_res = self:event(events.pre_expand, { expand_pos = pos })
or {}
-- update pos, event-callback might have moved the extmark.
pos = vim.api.nvim_buf_get_extmark_by_id(0, session.ns_id, pos_id, {})
Environ:override(env, pre_expand_res.env_override or {})
if indent_nodes then

View file

@ -1626,4 +1626,24 @@ describe("snippets_basic", function()
{2:-- INSERT --} |]],
})
end)
it("expand-position may be moved in pre_expand.", function()
feed("i.")
exec_lua[[
snip = s("foo", {
t"asdf"
}, {callbacks = {[-1] = { [events.pre_expand] = function(node, event_args)
vim.api.nvim_buf_set_extmark(0, ls.session.ns_id, 0,0, {id = event_args.expand_pos_mark_id})
end}} } )
ls.snip_expand(snip)
]]
screen:expect({
grid = [[
asdf^. |
{0:~ }|
{2:-- INSERT --} |]]})
end)
end)