naughie
naughie

Reputation: 315

Highlight trailing spaces in Neovim except for floating windows

I use NeoVim v0.4.2.

I want to highlight trailing spaces, so first I added the following to my vimrc:

augroup TrailingSpace
  au!
  au VimEnter,WinEnter * highlight link TrailingSpaces Error
  au VimEnter,WinEnter * match TrailingSpaces /\s\+$/
augroup END

But if then I open a floating window, such as an explorer by Defx, the window looks very awkward, like

file1---------------
file2            [T]
file3.txt-----------

(- represents that it is highlighted as Error.)

So I do not want to highlight trailing spaces in floating windows. I tried then the following instead:

augroup TrailingSpace
  au!
  au VimEnter,BufWinEnter * call HighlightTrailingSpaces()
augroup END

function! HighlightTrailingSpaces() abort
    if &filetype ==# 'defx'
        highlight clear TrailingSpaces
    else
        highlight link TrailingSpaces Error
    endif
    match TrailingSpaces /\s\+$/
endfunction

but this did not help me.

I have no idea at all how to highlight trailing spaces without highlighting in floating windows. Are there any useful functions (autocmd events?) for my purpose?

Upvotes: 0

Views: 1200

Answers (1)

Saad Parwaiz
Saad Parwaiz

Reputation: 131

If you read through :h BufWinEnter it gets called as soon as a buffer is "displayed" in the window. At that point defx hasn't set the filetype which is why your intital if condition never gets triggered.

So, what you want to do instead is this:

augroup TrailingSpace
  au!
  au VimEnter,WinEnter * highlight link TrailingSpaces Error
  au VimEnter,WinEnter * match TrailingSpaces /\s\+$/
  au FileType defx highlight clear TrailingSpaces
augroup END

A slightly better option might be creating a file at after/ftplugin/defx.vim and adding au FileType defx highlight clear TrailingSpaces inside the file

Upvotes: 0

Related Questions