Introduction to Vim-Diff

Compare and merge tool for Vim users.

·

2 min read

Table of contents

Vim-Diff is a great tool to compare two scripts and do instant merging from one to another. It is fast and very efficient to work with. Vim-Diff comes with Vim as a default functionality.

Usage

To activate Vim-Diff, there must be two script files (buffers) open in the same Vim window. To create such a thing, when you have a single file open in Vim, in command mode type :vnew. This creates a new buffer in the same window. In the new one, you can place the other script to be compared. Then, type; :windo diffthis This activates Vim-Diff. Voalá! The differences will be highlighted in both buffers.

vim-diff.png

To switch between windows, use Ctrl+w+w. Optional ones; Ctrl+w+h (move to the left window) or Ctrl+w+l (move to the right window). Since this still requires three key-strokes, you can reduce this by mapping Ctrl+movements keys into those in vimrc as follows.

"this mapping makes switching between buffers easier.
nnoremap <C-H> <C-W>h
nnoremap <C-J> <C-W>j
nnoremap <C-K> <C-W>k
nnoremap <C-L> <C-W>l

Instead of copy/paste from one script to another, we can use vim commands to merge the difference across the scripts. There are two commands for this; do and dp.

do

do command means diff-obtain. The change under the cursor is replaced by the content of the other file making them identical. If you are in script A, it will merge from B to A.

dp

dp command means diff-put. It puts changes under the cursor into the other file making them identical (thus removing the diff). In this case, if you are in script A, it will merge from A to B.

Additional commands

Jump to the next diff. ]c

Jump to the previous diff. [c

To stop the difference, in the command mode, type :diffoff I hope you find this blog post useful. If you have any questions about this, do not hesitate to contact me.