Using vimdiff with git

2015-01-24 in git, vim

I often use Github's compare interface for comparing changes across published commits. However, being a fan of reviewing my changes before forcing the world to see them, I also need a way to check them out locally. In the past I've used p4merge to graphically compare, but the tool has lacks code highlighting and is far enough outside my normal environment that I find myself missing changes. I found myself in vim's man pages, where I conveniently found documentation on their built-in diffing tool: vimdiff.

The vimdiff file1 file2 command, an alias for vim -d file1 file2, opens vim with a split for each file, highlighting differences. You can see in the screenshot on the right a diff of this site's Rakefile, where I removed a reference to a config override that I didn't need.

While diffing files manually is helpful, it's often more helpful to be able to automatically have git open two versions of a file for you. Luckily, git supports vimdiff out of the box. You can either set vimdiff as your global difftool or you can use specify it at diff-time.

git config --global diff.tool vimdiff # now `git difftool` uses vim
git diff --tool vimdiff file # diff file using vimdiff

From here, you can use all of git's difftool options and all of vim's commands. To give an example, the commadn for generating the above screenshot was:

git difftool -t vimdiff --no-prompt head~4..head~3 Rakefile

I mostly use this combo for quick checks before committing, making sure everything is safe to push up.

Bonus: Though not strictly 'vimdiff', there's one more git + vim power combo that I make heavy use of, for similar reasons as above: scanning changes. Running vim -p `git diff --name` will open every changed file as a new tab in vim, making it easy to go through each in turn. An example use case of this is fixing line endings after accidentally changing them.