In my ~/.vimrc
, I have:
highlight TrailingWhitespace ctermbg=blue
autocmd BufReadPost * syn match TrailingWhitespace /\s\+\%#\@<!$/
This highlights trailing spaces, except when I am still typing at the end of the line. (I obtained the regex pattern from the Vim wiki).
What I want to do now is to change the trailing whitespace pattern only inside a gitcommit diff. Background:
When doing
git commit --verbose
, a diff will be shown at the bottom of the git commit template opened in Vim. The syntax file responsible for git commits issyntax/gitcommit.vim
.The first column of a diff is either
+
(i.e. line added),-
(i.e. line deleted), or+
. However, if a blank line is unchanged, the diff for that line will show
That is why I want to change trailing whitespace detection pattern for gitcommit diffs. I want to ignore the first column. To that end, I created a file ~/.vim/after/syntax/gitcommit.vim
:
" HACK: disable the usual highlighting for trailing whitespace by using a regex
" pattern that never matches anything.
syn match TrailingWhitespace /.^/ containedin=gitcommitDiff
" Ignore the first column when finding trailing whitespace.
syn match diffTrailingWhitespace /^..\{-}\zs\s\+$/ containedin=gitcommitDiff
highlight diffTrailingWhitespace ctermbg=cyan
At this point, the vim configuration seems to work as intended: trailing whitespace is highlighted, and special rules are used for highlighting trailing whitespace in gitcommit diff. The problem is that this all looks like a hack. I wonder if there is a more straightforward, or less hacky way of achieving the same result. Could you provide a better solution?
listchars
andtrail
?listchars
is that I won't be able to use different colors fornbsp
,space
,tab
, andtrail
.syn clear TrailingWhitespace
if you want to avoid the "HACK" in your gitcommit.vim.