From 014981c9006f9b96b8045e609dc27f4a84da5263 Mon Sep 17 00:00:00 2001 From: Gregory Anders <8965202+gpanders@users.noreply.github.com> Date: Wed, 1 Mar 2023 09:47:56 -0700 Subject: 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. --- runtime/lua/vim/lsp.lua | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) (limited to 'runtime/lua/vim') diff --git a/runtime/lua/vim/lsp.lua b/runtime/lua/vim/lsp.lua index a6d550f48f..a56e141c29 100644 --- a/runtime/lua/vim/lsp.lua +++ b/runtime/lua/vim/lsp.lua @@ -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() - nvim_exec_autocmds('LspDetach', { - buffer = bufnr, - modeline = false, - data = { client_id = client_id }, - }) + 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 -- cgit