How to set highlights for new windows except from specific filetypes in neovim?

Viewed 43

I'm trying to create a highlight for trailing spaces and tabs for all windows in NeoVim, but I'm having problems to handle exceptions. Basically I want to set it for all windows except terminal windows (which I use the plugin toggleterm) and the help page.

From reading the docs I realised that the WinNew or WinEnter events are fired before the filetype is set, so it basically inherits the filetype from the current window. Because of that my check never works properly. Is there a way to make this check work? I thought of using buffer events, but then I'd be executing this many times unnecessarily since the match applies for the window and not for the buffer.

vim.cmd('highlight ExtraWhitespace ctermbg=lightyellow guibg=lightyellow')
vim.api.nvim_create_autocmd({ 'VimEnter', 'WinNew' }, {
    desc = 'Highlight all tabs and trailing whitespaces',
    pattern = '*',
    callback = function()
        -- TODO: implement blacklist
        if vim.bo.filetype ~= 'toggleterm' or vim.bo.filetype ~= 'help' then
            vim.fn.matchadd('ExtraWhitespace', '\\s\\+$\\|\\t')
        end
    end,
})
1 Answers

Terminal can be opened in any existing window, and so you can't tell this beforehand and can't blacklist anything.

Instead, remove the match after terminal has been opened.

augroup mystuff | au!
    autocmd VimEnter,WinNew 2match Todo /\s\+$\|\t/
    autocmd TermOpen,TerminalWinOpen * 2match none
    "       ^-- Nvim ^-- Vim
augroup end
Related