Hide diagnostic float when switching windows?

Hey!
I have been experimenting with this a bit but can’t seem to figure out if/how I can hide the diagnostics float vim.diagnostic.open_float() when I switch to another window CTRL+W L.

I have this setup

vim.diagnostic.config({
    virtual_text = false,
    underline = true,
    signs = true,
    float = {
        source = 'if_many',
        focusable = false,
    },
}, nil)

vim.api.nvim_command('autocmd CursorHold * lua vim.diagnostic.open_float(nil, {scope = \'line\', close_events = {"CursorMoved", "CursorMovedI", "BufHidden", "InsertCharPre", "WinLeave"}})')

vim.api.nvim_set_keymap('', '<Leader>d', '<Cmd>lua vim.diagnostic.open_float(nil, {focusable = true, scope = \'line\', close_events = {"CursorMoved", "CursorMovedI", "BufHidden", "InsertCharPre", "WinLeave"}})<CR>', {silent = true})

I tried adding WinLeave to the close_events param and that works, but then I can’t enter my float with my keybind, getting this error

E5108: Error executing lua /usr/local/share/nvim/runtime/lua/vim/lsp/util.lua:1420: Failed to switch to window 1029

I think I solved it, this seems to be the way to do it, temporarily ignoring WinLeave before coming back to the original buffer.

function LspDiagnosticsFocus()
    vim.api.nvim_command('set eventignore=WinLeave')
    vim.api.nvim_command('autocmd CursorMoved <buffer> ++once set eventignore=""')
    vim.diagnostic.open_float(nil, {focusable = true, scope = 'line', close_events = {"CursorMoved", "CursorMovedI", "BufHidden", "InsertCharPre", "WinLeave"}})
end

vim.api.nvim_set_keymap('', '<Leader>d', '<Cmd>lua LspDiagnosticsFocus()<CR>', {silent = true})
1 Like

Hello!

Found your solution very useful, I was also trying this and wanted it to show on cursor hold, so I’m going with something like the following:

vim.cmd [[autocmd CursorHold * lua vim.diagnostic.open_float(0, {scope="cursor", close_events = {"CursorMoved", "CursorMovedI", "BufHidden", "InsertCharPre", "WinLeave"}})]]

However, I would love to close the diagnostic float by pressing escape, however, I can’t seem to do so easily.
Any ideas?

1 Like

how about in Insert mode??