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?

1

1 Answer 1

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.