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: • {opts} (`table?`) A table with the following fields:
• {bufnr}? (`integer`, default: 0) Buffer handle, or 0 for • {bufnr}? (`integer`, default: 0) Buffer handle, or 0 for
current. current.
• {on_accept}? (`fun(item: vim.lsp.inline_completion.Item)`) • {on_accept}?
Accept handler, called with the accepted item. If not (`fun(item: vim.lsp.inline_completion.Item): vim.lsp.inline_completion.Item?`)
provided, the default handler is used, which applies changes A callback triggered when a completion item is accepted. You
to the buffer based on the completion item. 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: ~ Return: ~
(`boolean`) `true` if a completion was applied, else `false`. (`boolean`) `true` if a completion was applied, else `false`.

View File

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