[Vim] Diff and merge using Vim

After performing a system update on my Linux machine, the package manager placed a copy of an updated configuration file on the system – it couldn’t overwrite them as I had previously modified it. Since I was also using SSH to remote in the Linux machine, I didn’t want to merge the changes using a GUI like Meld. Fortunately, Vim supports diffing and runs within the terminal!

To view the diff between files, you can use vimdiff.

vimdiff {first file} {second file}

Alternatively, if one of the files is currently open in Vim, use diffsplit:

:vert diffsplit {file to diff with}

By default, diffsplit actually splits the view horizontally (i.e. it will place one file above the other). The vert keyword in the above command will make it split vertically. It is also possible to make vertical splits the default by including vertical in diffopt. Personally, I prefer using the vertical split when working with diffs.

Using a vertical split, the diff will be displayed like this:

Diff split

The keys for woking in this mode:

  • Move the cursor between the panes using CTRL+W followed by either an arrow key or one of the moving keys (h, j, k or l).
  • Move to the cursor to the next change using ]c and back to the previous change using [c.
  • Copy changes to the other file using dp and copy changes from the other file using do.
  • Open folds using zo and close them with zc.

One Response to [Vim] Diff and merge using Vim

  1. Francis Barber says:

    I have used this quite a bit for updating config files, but I never knew about “dp” and “do”. Nice.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: