Last Updated: February 21, 2020
·
850
· squidbidness

Vim: Highlight and jump to trailing whitespace

Here are some commands in my .vimrc that will syntax-highlight any trailing whitespace (git style) with a red background, as well as some mappings to jump straight to any such offenders. The mapped normal mode key-sequences are [<Space> and ]<Space>.

"Highlight extra whitespace on blank lines or after semi-colons
hi FrivolousWhitespace ctermbg=red guibg=#ff0000
match FrivolousWhitespace /\s\+^/


" Jump to trailing whitespace
nnoremap ]<Space> :silent! :SS /\s\+$<CR>
nnoremap [<Space> :silent! :SS ?\s\+$<CR>

The ":SS" command used in these mappings is a function that lets you use search in mappings without it affecting pre-existing search registers or leaving ugly highlighting behind afterwards. (I'd like to credit the source for SafeSearch, but I've lost the link. If anyone knows or owns this command, please let me know in the comments).

" Executes a command (across a given range) and restores the search register
" when done.
" Basically, :SS followed by any command will execute that command (to
" simulate keystrokes, use :normal as the command) and restore the search
" register when it's done. :S is a replacement for :s which works EXACTLY the
" same way (with or without range, flags etc) but doesn't clobber the search
" register in the process
function! SafeSearchCommand(line1, line2, theCommand)
let search = @/
execute a:line1 . "," . a:line2 . a:theCommand
let @/ = search
endfunction
com! -range -nargs=+ SS call SafeSearchCommand(<line1>, <line2>, <q-args>)
" A nicer version of :s that doesn't clobber the search register
com! -range -nargs=* S call SafeSearchCommand(<line1>, <line2>, 's' . <q-args>)