vimtricks.wiki Concise Vim tricks, one at a time.

How do I selectively merge changes between two files in Vim's diff mode?

Answer

:diffget / :diffput

Explanation

When comparing two files side by side with :diffsplit or vim -d, you often want to pull specific changes from one file into another rather than accepting all differences. :diffget and :diffput let you selectively merge individual hunks between buffers.

How it works

  • :diffget (shorthand do) — obtain the change from the other buffer into the current buffer
  • :diffput (shorthand dp) — put the change from the current buffer into the other buffer
  • Place your cursor on a diff hunk (highlighted region) and run the command
  • With more than two buffers, specify which buffer: :diffget 3 or :diffput bufname
  • Use ]c and [c to jump between diff hunks

Example

Open two files in diff mode:

:edit file1.txt
:diffsplit file2.txt

Vim highlights the differences. Navigate to a hunk with ]c, then:

do    " pull this hunk from the other file into current file
dp    " push this hunk from current file to the other file

After resolving changes, run :diffupdate to refresh the diff highlighting.

Tips

  • do and dp are normal-mode shortcuts for :diffget and :diffput respectively
  • Use a range to apply to specific lines: :'<,'>diffget
  • Run :diffoff when done to exit diff mode without closing the buffers
  • Works with three-way diffs for merge conflict resolution — specify the buffer number to get from

Next

How do I ignore whitespace changes when using Vim's diff mode?