The Puma
The Puma

Reputation: 1390

What's the best way to handle highlighting whitespace in Vim?

I have followed Vim's guideline here, and also tried other stuff around the web, and nothing seems work...

I have also tried this:

autocmd InsertEnter * syn clear EOLWS | syn match EOLWS excludenl /\s\+\%#\@!$/  
autocmd InsertLeave * syn clear EOLWS | syn match EOLWS excludenl /\s\+$/  
highlight EOLWS ctermbg=red guibg=red  

and that also doesn't work correctly (only seems to highlight extra whitespace on an empty line).

What is the best way to handle highlighting trailing whitespace (but not while you're typing?)

Upvotes: 2

Views: 193

Answers (2)

Ingo Karkat
Ingo Karkat

Reputation: 172768

While the idea is indeed simple, a comprehensive implementation still has to consider many things and corner cases. Because I wasn't happy with the available plugins, I wrote my ShowTrailingWhitespace plugin, which is highly configurable and allows per-filetype exceptions, too. (The plugin page has links to alternative plugins.)

Upvotes: 0

bundacia
bundacia

Reputation: 1036

I think your first regex is just slightly off. This is what I use:

" highlight empty space at the end of a line                                    
autocmd InsertEnter * syn clear EOLWS | syn match EOLWS excludenl /\s\+\%#\@<!$/
autocmd InsertLeave * syn clear EOLWS | syn match EOLWS excludenl /\s\+$/       
highlight EOLWS ctermbg=red guibg=red                                           

Note the \ before the + and the < before the ! that are missing from yours.

I also have a function mapped to +space (I have set to a comma) to strip all the trailing whitespace in a file:

function! <SID>StripTrailingWhitespace()                                        
    " Preparation: save last search, and cursor position.                       
    let _s=@/                                                                   
    let l = line(".")                                                           
    let c = col(".")                                                            
    " Do the business:                                                          
    %s/\s\+$//e                                                                 
    " Clean up: restore previous search history, and cursor position            
    let @/=_s                                                                   
    call cursor(l, c)                                                           
endfunction                                                                     
nmap <silent> <leader><space> :call <SID>StripTrailingWhitespace()<CR> 

Lots more info here: http://vim.wikia.com/wiki/Highlight_unwanted_spaces

Upvotes: 1

Related Questions