feat(lsp): on_accept can return item to customize behavior #37092

Problem:
`on_accept` is a bit cumbersome to customize.

Solution:
* Before: users had to override the entire `on_accept` logic for their changes to be applied.
* Now: users can modify the item and return it to apply the modified changes, or return `nil` to fully customize how the changes are applied.
This commit is contained in:
Yi Ming
2025-12-26 13:08:12 +08:00
committed by GitHub
parent c03d635a12
commit e855a23c02
2 changed files with 19 additions and 9 deletions

View File

@@ -2327,10 +2327,13 @@ get({opts}) *vim.lsp.inline_completion.get()*
• {opts} (`table?`) A table with the following fields:
• {bufnr}? (`integer`, default: 0) Buffer handle, or 0 for
current.
• {on_accept}? (`fun(item: vim.lsp.inline_completion.Item)`)
Accept handler, called with the accepted item. If not
provided, the default handler is used, which applies changes
to the buffer based on the completion item.
• {on_accept}?
(`fun(item: vim.lsp.inline_completion.Item): vim.lsp.inline_completion.Item?`)
A callback triggered when a completion item is accepted. You
can use it to modify the completion item that is about to be
accepted and return it to apply the changes, or return `nil`
to prevent the changes from being applied to the buffer so
you can implement custom behavior.
Return: ~
(`boolean`) `true` if a completion was applied, else `false`.

View File

@@ -438,10 +438,12 @@ end
--- (default: 0)
---@field bufnr? integer
---
--- Accept handler, called with the accepted item.
--- If not provided, the default handler is used,
--- which applies changes to the buffer based on the completion item.
---@field on_accept? fun(item: vim.lsp.inline_completion.Item)
--- A callback triggered when a completion item is accepted.
--- You can use it to modify the completion item that is about to be accepted
--- and return it to apply the changes,
--- or return `nil` to prevent the changes from being applied to the buffer
--- so you can implement custom behavior.
---@field on_accept? fun(item: vim.lsp.inline_completion.Item): vim.lsp.inline_completion.Item?
--- Accept the currently displayed completion candidate to the buffer.
---
@@ -474,8 +476,13 @@ function M.get(opts)
return
end
-- Note that we do not intend for `on_accept`
-- to take effect when there is no current item.
if on_accept then
on_accept(item)
item = on_accept(item)
if item then
completor:accept(item)
end
else
completor:accept(item)
end