Looking at a different version of a file in vim

Step 1: Go install fugitive.vim. No really. Tim Pope's description - that it's a git wrapper so awesome it should be illegal - is totally justified. It can do a ton of useful things and is basically indispensable if you use git and vim together in a project.

For this post, I'm mostly interested in the :Gedit command (and it's siblings :Gsplit, :Gvsplit, :Gtabedit, and :Gpedit). They all work the same, but open the resultant file differently (and you can probably guess how based on the names). You can look at :h fugitive-commands for a full definition, but suffice it to say that you can use these functions like this:

:Gedit [revision]

I suppose [revision] could be a sha or something like HEAD~, but I primary find it useful for looking at the current file in a different branch. Before fugitive, I would've closed everything, stashed my changes, checked out the branch I was interested in, opened the file and checked what I was looking for, and then basically followed that process in reverse. Now, with fugitive, I can just do this:

:Gedit master:%

which opens the current file in the master branch. Of course, this works for any branch name. I probably slightly prefer

:Gvsplit master:%

for this command so that I can look at the file in my current branch and the branch of interest side by side. You can use this almost like an interactive cherry-pick. It occasionally happens that I need (or want) some change I added in a different branch in this branch. You could of course run git log to find the sha of it's commit and then git cherry-pick that sha. Or, with fugitive.vim, you could open the file in that branch and just copy it over. Yeah, that sounds easier.

comments powered by Disqus