Vim Diff
Thursday, February 21st, 2008For a long time now I’ve wanted to have the current diff of my working copy highlighted in vim. This would help a lot when you’re working in complicated code and want your modifications to pop out in case you’ve missed something. Unfortunately none of the existing tools do exactly what I want, so with the advice of some co-workers I’ve hacked up the svndiff vim script and made it work with git just like I wanted. Now I can turn on or refresh the highlights with Ctl-D and diff against a different branch with “:D <branch>”.

gitdiff.vim
—————
if exists(”loaded_gitdiff”) || &cp
finish
endif
let loaded_gitdiff = 1
map <C-d> :call <SID>Gitdiff()<CR>
map <C-g> :set nodiff<CR>
noremap <unique> <script> <plug>Dh :call <SID>Gitdiff(”h”)<CR>
com! -bar -nargs=? D :call s:Gitdiff(<f-args>)
let g:gitdiff_rev = ”
function! s:Gitdiff(…)
if a:0 == 1
if a:1 == “none”
let g:gitdiff_rev = ”
else
let g:gitdiff_rev = a:1
endif
endif
let ftype = &filetype
let tmpfile = tempname()
let cmd = “cat ” . bufname(”%”) . ” > ” . tmpfile
let cmd_output = system(cmd)
let tmpdiff = tempname()
let cmd = “git diff ” . g:gitdiff_rev . ” ” . bufname(”%”) . ” > ” . tmpdiff
let cmd_output = system(cmd)
if v:shell_error && cmd_output != “”
echohl WarningMsg | echon cmd_output
return
endif
let cmd = “patch -R -p0 ” . tmpfile . ” ” . tmpdiff
let cmd_output = system(cmd)
if v:shell_error && cmd_output != “”
echohl WarningMsg | echon cmd_output
return
endif
if exists(”s:killbuffs”)
2,9999 bdelete
endif
let s:killbuffs = 1
if a:0 > 0 && a:1 == “h”
exe “diffsplit” . tmpfile
else
exe “vert diffsplit” . tmpfile
endif
exe “set filetype=” . ftype
hide
set foldcolumn=0
set foldlevel=100
set diffopt= ” removed filler so we don’t show deleted lines
highlight DiffAdd ctermbg=black ctermfg=DarkGreen
highlight DiffChange ctermbg=black ctermfg=DarkGreen
highlight DiffText ctermbg=black ctermfg=DarkGreen cterm=underline
highlight DiffDelete ctermbg=red ctermfg=white
endfunction
“autocmd CursorHold * call s:Gitdiff()
—————
Tags: vimdiff git