Skip to content

Commit

Permalink
feat: allow modifying expand-position in pre_expand-callback (#1219).
Browse files Browse the repository at this point in the history
  • Loading branch information
L3MON4D3 committed Aug 6, 2024
1 parent 7552e65 commit 9033373
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 5 deletions.
2 changes: 2 additions & 0 deletions DOC.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
Expand Down
11 changes: 6 additions & 5 deletions lua/luasnip/nodes/snippet.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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, {
Expand Down Expand Up @@ -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
Expand Down
20 changes: 20 additions & 0 deletions tests/integration/snippet_basics_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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)

0 comments on commit 9033373

Please sign in to comment.