feat(lsp): apply additionalTextEdits on completion accept
This commit is contained in:
@@ -94,6 +94,79 @@ function M.setup()
|
||||
end,
|
||||
})
|
||||
|
||||
-- Apply the LSP item's additionalTextEdits (auto-imports, etc.) and
|
||||
-- run its post-accept command whenever an item's text was committed to
|
||||
-- the buffer. This covers both explicit accept (<C-y>) and
|
||||
-- acceptance-by-continuing-to-type, since Vim keeps the inserted text
|
||||
-- in both cases. Only <C-e>/discard leaves v:completed_item empty.
|
||||
vim.api.nvim_create_autocmd("CompleteDone", {
|
||||
group = GROUP,
|
||||
callback = function(ev)
|
||||
local completed = vim.v.completed_item or {}
|
||||
local original = vim.tbl_get(
|
||||
completed,
|
||||
"user_data",
|
||||
"nvim",
|
||||
"lsp",
|
||||
"completion_item"
|
||||
)
|
||||
if not original then
|
||||
return
|
||||
end
|
||||
local client_id =
|
||||
vim.tbl_get(completed, "user_data", "nvim", "lsp", "client_id")
|
||||
local client = client_id and vim.lsp.get_client_by_id(client_id)
|
||||
if not client then
|
||||
return
|
||||
end
|
||||
|
||||
local function apply(item)
|
||||
if item.additionalTextEdits then
|
||||
vim.lsp.util.apply_text_edits(
|
||||
item.additionalTextEdits,
|
||||
ev.buf,
|
||||
client.offset_encoding
|
||||
)
|
||||
end
|
||||
if item.command then
|
||||
client:request("workspace/executeCommand", {
|
||||
command = item.command.command,
|
||||
arguments = item.command.arguments,
|
||||
}, nil, ev.buf)
|
||||
end
|
||||
end
|
||||
|
||||
-- Prefer the resolved item when we have it (servers like
|
||||
-- rust-analyzer only provide additionalTextEdits in resolve
|
||||
-- responses). If we haven't cached one yet and the original is
|
||||
-- missing edits, resolve on the fly.
|
||||
local cached = popup:resolved_for(completed.word)
|
||||
if cached then
|
||||
apply(cached)
|
||||
elseif
|
||||
client:supports_method(
|
||||
vim.lsp.protocol.Methods.completionItem_resolve
|
||||
)
|
||||
and not original.additionalTextEdits
|
||||
and not original.command
|
||||
then
|
||||
client:request(
|
||||
vim.lsp.protocol.Methods.completionItem_resolve,
|
||||
original,
|
||||
function(err, resolved)
|
||||
if err or not resolved then
|
||||
return
|
||||
end
|
||||
apply(resolved)
|
||||
end,
|
||||
ev.buf
|
||||
)
|
||||
else
|
||||
apply(original)
|
||||
end
|
||||
end,
|
||||
})
|
||||
|
||||
---@param key string
|
||||
---@param action fun()
|
||||
local function scroll_map(key, action)
|
||||
|
||||
Reference in New Issue
Block a user