Git - Compare and edit different revisions of a file using Vim
Say, you want to open a copy of a file (under a git repository) and use it as a reference while making changes to the original file. This can be done easily using a number of methods.
One such method is (after you are inside the git repository):
(assuming the file is README.rst) $ cat README.rst | vim -
You'll probably need to set the filetype, as Vim does not detect the filetype through stdin for many formats. Then do :split README.rst
inside Vim, and you have a reference as well as an editable copy of the same file.
But, what if you had modified README.rst without committing the changes?
In such a case, you can use git difftool
, which will open the committed and uncommitted files in the diff tool of your choice. I prefer vimdiff.
Note: You can set the diff tool of your choice globally in the following way (assuming you too prefer vimdiff):
$ git config --global diff.tool vimdiff
Now, git difftool
opens the files in read-only mode. To make changes, activate the Vim pane where you want to make the changes and type :set noreadonly
. If you don't want the files diffed (the colours can be distracting if viewed for a long time :P), you can turn it off using :diffoff
.
Using a specific revision of a file
Another situation can be when you want to use a specific revision of a file as a reference. In such a case, you can do:
$ git difftool e521890:README.rst README.rst
where "e521890" is the short SHA-1 sum of the commit (you can obviously use the full SHA-1 sum as well).
Yet another way to achieve the above is by using git show
, in the following manner:
$ git show e521890:README.rst > /tmp/README.rst $ vimdiff /tmp/README.rst README.rst or $ vim -o /tmp/README.rst README.rst
One benefit of this method is that you don't have to turn off the read-only mode, and you can open the files without diff mode as well.