How do I highlight trailing whitespace with a custom color in Vim?
Answer
highlight TrailingWhitespace ctermbg=red and match TrailingWhitespace /\s\+$/
Explanation
How it works
Vim's highlight and match commands let you create custom visual indicators. By combining them, you can make trailing whitespace glaringly visible with a colored background.
The setup has two parts:
1. Define a highlight group:
highlight TrailingWhitespace ctermbg=red guibg=red
TrailingWhitespaceis a custom name you choosectermbg=redsets the background color in terminal Vimguibg=redsets the background color in GVim/GUI Vim
2. Create a match pattern:
match TrailingWhitespace /\s\+$/
matchlinks a highlight group to a regex pattern\s\+$matches one or more whitespace characters at the end of a line
For a more robust setup that does not highlight trailing whitespace while you are still typing on the current line, use an autocmd:
autocmd InsertEnter * match TrailingWhitespace /\s\+\%#\@<!$/
autocmd InsertLeave * match TrailingWhitespace /\s\+$/
The \%#\@<! pattern means "not at the cursor position," so trailing spaces on the line you are currently editing are not highlighted until you leave insert mode.
You can also auto-strip trailing whitespace on save:
autocmd BufWritePre * %s/\s\+$//e
Example
Add to your ~/.vimrc:
" Define the highlight color
highlight TrailingWhitespace ctermbg=red guibg=red
" Smart matching: don't highlight current line in insert mode
augroup TrailingSpace
autocmd!
autocmd BufWinEnter * match TrailingWhitespace /\s\+$/
autocmd InsertEnter * match TrailingWhitespace /\s\+\%#\@<!$/
autocmd InsertLeave * match TrailingWhitespace /\s\+$/
augroup END
Now any line with trailing spaces shows a red highlight at the end. This makes it easy to spot unwanted whitespace that can cause issues in diffs, linters, and code reviews.