sponsor Vim development Vim logo Vim Book Ad

intermediate Tip #1040: Good leading and trailing whitespace highlighting

 tip karma   Rating 51/24, Viewed by 1953 

Read and edit this tip on the Vim tip wiki. The wiki may have a more recent version of this tip.

created:   November 7, 2005 9:04      complexity:   intermediate
author:   Matt Zyzik      as of Vim:   5.7

highlight WhiteSpaceEOL ctermbg=darkgreen guibg=lightgreen
match WhiteSpaceEOL /^\s*\ \s*\|\s\+$/
autocmd WinEnter * match WhiteSpaceEOL /^\s*\ \s*\|\s\+$/

Put the above lines in your .vimrc, and you can enjoy highlighting of trailing whitespace and also highlighting of any leading whitespace consisting of spaces.
Basically, no highlighting will occur if your leading whitespace is *only* tabs and there is no trailing whitespace.

 rate this tip  Life Changing Helpful Unfulfilling 

<< disable all auto-indenting with 'set nopaste' mode (so that imap work) | Snippets for JavaScript, HTML and Python >>

Additional Notes

Anonymous, November 7, 2005 9:06
this is especially great for programming python
dsm26@stanford.edu, November 7, 2005 10:43
I modified your commands slightly so that I can turn the highlighting on and off.  <Leader>wn turns the highlight on.  <Leader>wf turns the highlighting off.  I'm also only interested in end-of-line whitespace so I modified your regex.

map <unique> <Leader>wn <ESC>:highlight WhiteSpaceEol ctermbg=darkgreen guibg=lightgreen<CR><ESC>:match WhiteSpaceEol /\s\+$/<CR>

map <unique> <Leader>wf <ESC>:highlight WhiteSpaceEol NONE<CR>

Thanks for the tip!
sbutts@computer.org, November 7, 2005 11:31
It's a bit different, but you might also look into list and listchars.
Dubhead, November 7, 2005 18:26
also see
Tip #811: Highlight whitespace errors in files
matt zyzik, November 27, 2006 14:07
I made some progress with this... i now use these:
nnoremap \ws1 :match WhiteSpaceEOL /\(^\s*\)\@<=\ \\|\s\+$/<cr>
nnoremap \ws2 :match WhiteSpaceEOL /^\ \+\\|\s\+$\\|\ \+\ze\t\\|\t\zs\ \+/<cr>

They now only highlight the spaces (errors). The second has a faster execution time.
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to the maillist. Help Bram help Uganda.
Sponsored by Web Concept Group Inc. SourceForge.net Logo