fix(diagnostic): clear stale cache on reset (#21454)

The BufWipeout autocmd is not 100% reliable and may leave stale entries
in the cache. This is sort of a hack/workaround to ensure
`vim.diagnostic.reset` calls don't fail if there are stale cache entries
but instead clears them

Fixes errors like

    Error executing vim.schedule lua callback: /usr/share/nvim/runtime/lua/vim/diagnostic.lua:1458: Invalid buffer id: 22
    stack traceback:
            [C]: in function 'nvim_exec_autocmds'
            /usr/share/nvim/runtime/lua/vim/diagnostic.lua:1458: in function 'reset'

(cherry picked from commit 1743359235)
This commit is contained in:
Mathias Fußenegger
2022-12-18 03:19:15 +01:00
committed by Mathias Fussenegger
parent 9bda3b3e04
commit 48f0545594
2 changed files with 34 additions and 8 deletions

View File

@@ -916,7 +916,7 @@ M.handlers.signs = {
end,
hide = function(namespace, bufnr)
local ns = M.get_namespace(namespace)
if ns.user_data.sign_group then
if ns.user_data.sign_group and vim.api.nvim_buf_is_valid(bufnr) then
vim.fn.sign_unplace(ns.user_data.sign_group, { buffer = bufnr })
end
end,
@@ -971,7 +971,9 @@ M.handlers.underline = {
local ns = M.get_namespace(namespace)
if ns.user_data.underline_ns then
diagnostic_cache_extmarks[bufnr][ns.user_data.underline_ns] = {}
vim.api.nvim_buf_clear_namespace(bufnr, ns.user_data.underline_ns, 0, -1)
if vim.api.nvim_buf_is_valid(bufnr) then
vim.api.nvim_buf_clear_namespace(bufnr, ns.user_data.underline_ns, 0, -1)
end
end
end,
}
@@ -1034,7 +1036,9 @@ M.handlers.virtual_text = {
local ns = M.get_namespace(namespace)
if ns.user_data.virt_text_ns then
diagnostic_cache_extmarks[bufnr][ns.user_data.virt_text_ns] = {}
vim.api.nvim_buf_clear_namespace(bufnr, ns.user_data.virt_text_ns, 0, -1)
if vim.api.nvim_buf_is_valid(bufnr) then
vim.api.nvim_buf_clear_namespace(bufnr, ns.user_data.virt_text_ns, 0, -1)
end
end
end,
}
@@ -1423,11 +1427,15 @@ function M.reset(namespace, bufnr)
M.hide(iter_namespace, iter_bufnr)
end
vim.api.nvim_exec_autocmds('DiagnosticChanged', {
modeline = false,
buffer = iter_bufnr,
data = { diagnostics = {} },
})
if vim.api.nvim_buf_is_valid(iter_bufnr) then
vim.api.nvim_exec_autocmds('DiagnosticChanged', {
modeline = false,
buffer = iter_bufnr,
data = { diagnostics = {} },
})
else
diagnostic_cache[iter_bufnr] = nil
end
end
end