This is a little more broad than what OP asked, but for people not wanting to use plugins, and possibly other revision control systems, this little snippet tends to work fairly well:
:r! git show branch:file
It creates a new window and shows the file there by reading the output of the given command into the new buffer. This of course works with any external command, not just git.
Example for bzr (where REV syntax can specify a branch):
:r! bzr cat -r REV file
Example for hg (not sure about branches in hg; don't use it enough)
:r! hg cat -r REV file
Example for svn (
:r! svn cat file@REV
You would still probably want to set the filetype to get syntax highlighting like in the SO posts, but at least you don't have to mess with piping.
Once opened you can save it under a new name with
:w filename or
:saveas filename, since Vim won't have a filename for it yet. If you don't want to be able to edit it, you can also throw in a
:setlocal readonly and/or
-Edit: Automatic Filetype-
It's a little more work, but you can ask Vim to guess the filetype with
But, since Vim doesn't have a name yet, this doesn't always work well (for example, I pulled in some C code and it guessed
We can give it a name by saving it, but we don't want to overwrite a possibly existing file. We can also just set the filename (Thanks @PeterRincker!), but again, we don't want to risk collisions. Since it is unlikely that a file exists that is both the branchname and filename together, we'll concatenate them with some arbitrary separator
:exe "silent file " . "branch" . "-" . "file"
"file" is replaced with the actual filename and
"branch" with the branch name
Of course, at this point we are almost writing a plugin ;-)
Thowing it all together, here it is as a git specific function you could drop in your vimrc:
exe "silent r! git show " . a:branch . ":" . a:file
exe "silent file " . a:branch . "-" . a:file
setlocal readonly "don't allow saving
setlocal nomodified "allow easy quitting without saving
setlocal nomodifiable "don't allow modification
which you could wrap in a command or call directly e.g.
call GitFile("whateverBranch","myfile.c"). You'll get a new window with a buffer named