fix(lsp): only fire LspDetach for attached buffers (#22468)

If the LSP server fails to start then the client never initializes and
thus never calls its on_attach function and an LspAttach event is
never fired. However, the on_exit function still fires a LspDetach
event, so user autocommands that attempt to "clean up" in LspDetach may
run into problems if they assume that the buffer was already attached.

The solution is to only fire an LspDetach event if the buffer was
already attached in the first place.
This commit is contained in:
Gregory Anders 2023-03-01 09:47:56 -07:00 committed by GitHub
parent f25d126b18
commit 014981c900
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1155,14 +1155,19 @@ function lsp.start_client(config)
pcall(config.on_exit, code, signal, client_id)
end
local client = active_clients[client_id] and active_clients[client_id]
or uninitialized_clients[client_id]
for bufnr, client_ids in pairs(all_buffer_active_clients) do
if client_ids[client_id] then
vim.schedule(function()
if client and client.attached_buffers[bufnr] then
nvim_exec_autocmds('LspDetach', {
buffer = bufnr,
modeline = false,
data = { client_id = client_id },
})
end
local namespace = vim.lsp.diagnostic.get_namespace(client_id)
vim.diagnostic.reset(namespace, bufnr)
@ -1178,8 +1183,6 @@ function lsp.start_client(config)
-- Schedule the deletion of the client object so that it exists in the execution of LspDetach
-- autocommands
vim.schedule(function()
local client = active_clients[client_id] and active_clients[client_id]
or uninitialized_clients[client_id]
active_clients[client_id] = nil
uninitialized_clients[client_id] = nil