1

I guess many of you are like me, and even if they have been using ViM for years, still learn new features regularly. The last that I learned was

:diffp[atch] patch/name

Now, I want to combine it with git to compare the current version and a previous version. I can do, from ViM,

:!git diff <hash> filename > git.patch
:vert diffp git.patch

ViM will automatically recognise the direction of the patch, and I get to see the older file as a temporary file (/tmp/file).

Now, I have tried to get that in a single command, without having to write a patch file. In particular, I tried

:vert diffp < git diff <hash> filename
:vert diffp `< git diff <hash> filename`
:vert diffp `git diff <hash> filename`

but to no success. Is it at all possible, and if it is, how should one do it?

2

Now, I want to combine it with git to compare the current version and a previous version.

...

Now, I have tried to get that in a single command, without having to write a patch file.

You can easily create a custom command to do this:

command! -nargs=? PreviousVersion diffthis |
      \ vnew |
      \ set buftype=nofile |
      \ set bufhidden=wipe |
      \ set noswapfile |
      \ execute "r!git show ".(!"<args>"?'head^':"<args>").":".expand('#') |
      \ 1d_ |
      \ let &filetype=getbufvar('#', '&filetype') |
      \ execute 'autocmd BufWipeout <buffer> diffoff!' |
      \ diffthis

You can now do :PreviousVersion to get the changes between the current buffer and the last commit (head^) or some arbitrary revision, e.g. :PreviousVersion {revision}

Note: you may want to use <mods> and :new if you want more control over the splitting.

Fugitive.vim

Alternatively, I would recommend using fugitive.vim's :Gdiff command.

I'm not going to lie to you; fugitive.vim may very well be the best Git wrapper of all time.

Use :Gvdiff to do the :Gdiff vertically.

Diff between the current file and the previous commit

:Gdiff head^
:Gvdiff head^

Diff between current file and the index

:Gdiff :0

Diff between current file and some other [revision]

:Gdiff [revision]

Diff between current file and current file 3 commits ago:

:Gdiff ~3

While :Gdiff is useful, I find :Gblame to be more useful. I can "re-blame" at on a certain line or open a commit to see the patch. This article explains how useful git blame can be: Every line of code is always documented.

Vimcasts

Vimcasts has a Fugitive series which I highly recommend. I would suggest looking at episodes: Working with the git index and Resolving merge conflicts with vimdiff.

For more help see

:h :diffthis
:h :vnew
:h :execute
:h :read
:h :delete
:h :_#
:h expand()
:h fugitive-:Gdiff
:h fugitive-revision
:h fugitive-:Gblame
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.