bartman's blog

GITDiff vim plugin

bartman

Taking a TODO item off my list, I am adding a plugin to vim that splits the current window and presents a diff between the current file and any revision of that file in the current git repository.

Take this script and put it into .vim/plugin/gitdiff.vim and rejoice.

    if exists("loaded_gitdiff") || &compatible
        finish
    endif
    let loaded_gitdiff = 1

    command! -nargs=? GITDiff :call s:GitDiff(<f-args>)

    function! s:GitDiff(...)
        if a:0 == 1
            let rev = a:1
        else
            let rev = 'HEAD'
        endif

        let ftype = &filetype

        let prefix = system("git rev-parse --show-prefix")
        let gitfile = substitute(prefix,'\n$','','') . expand("%")

        " Check out the revision to a temp file
        let tmpfile = tempname()
        let cmd = "git show  " . rev . ":" . gitfile . " > " . tmpfile
        let cmd_output = system(cmd)
        if v:shell_error && cmd_output != ""
            echohl WarningMsg | echon cmd_output
            return
        endif

        " Begin diff
        exe "vert diffsplit" . tmpfile
        exe "set filetype=" . ftype
        set foldmethod=diff
        wincmd l

    endfunction

To use it, run :GITDiff to see the differences the current file and it on HEAD, or :GITDiff commitish to see the differences made since some other commit, branch or tag.

And once you’re done and closed the diff windows, you should run :diffoff to disable the diff highlights.

This is based on similar scripts for rcs, cvs, and svn by Juan Frias.

More links:

Tags: