Vim Tips Wiki

Highlight some whitespace characters

Revision as of 06:17, July 13, 2012 by JohnBot (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
1,614pages on
this wiki
Tip 1274 Printable Monobook Previous Next

created 2006 · complexity basic · author Andreas Hübner · version 7.0

When working on projects with other people, you may need to quickly highlight various whitespace usage issues.

The following script can identify any combination of four types of whitespace issues:

  • Trailing whitespace (space or tab) at end of line.
  • Spaces used for indenting (if project should use only tabs for indenting).
  • Spaces before a tab (probably should be removed or converted to tabs).
  • Tabs not at the start of the line (that is, not used for indents).

After sourcing the following script, you can type \ws (assuming the default leader key) to toggle whitespace highlighting on/off. The buffer local variable b:ws_flags determines what is highlighted (see "default" below).

" Highlight whitespace problems.
" flags is '' to clear highlighting, or is a string to
" specify what to highlight (one or more characters):
"   e  whitespace at end of line
"   i  spaces used for indenting
"   s  spaces before a tab
"   t  tabs not at start of line
function! ShowWhitespace(flags)
  let bad = ''
  let pat = []
  for c in split(a:flags, '\zs')
    if c == 'e'
      call add(pat, '\s\+$')
    elseif c == 'i'
      call add(pat, '^\t*\zs \+')
    elseif c == 's'
      call add(pat, ' \+\ze\t')
    elseif c == 't'
      call add(pat, '[^\t]\zs\t\+')
      let bad .= c
  if len(pat) > 0
    let s = join(pat, '\|')
    exec 'syntax match ExtraWhitespace "'.s.'" containedin=ALL'
    syntax clear ExtraWhitespace
  if len(bad) > 0
    echo 'ShowWhitespace ignored: '.bad

function! ToggleShowWhitespace()
  if !exists('b:ws_show')
    let b:ws_show = 0
  if !exists('b:ws_flags')
    let b:ws_flags = 'est'  " default (which whitespace to show)
  let b:ws_show = !b:ws_show
  if b:ws_show
    call ShowWhitespace(b:ws_flags)
    call ShowWhitespace('')

nnoremap <Leader>ws :call ToggleShowWhitespace()<CR>
highlight ExtraWhitespace ctermbg=darkgreen guibg=darkgreen

See alsoEdit


The original tip had a script with quite a nice toggle, but it highlighted all tabs as well as trailing whitespace. That didn't seem any better than Highlight unwanted spaces, so I've replaced the script and done a very quick test. Please add any thoughts on the code below (bugs? useful?). --JohnBeckett 11:10, 26 August 2008 (UTC)

Around Wikia's network

Random Wiki