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

How do I apply or reverse a diff change from one side to the other when using Vim's built-in diff mode?

Answer

do and dp

Explanation

When comparing files with :vimdiff or :diffthis, Vim highlights each difference as a hunk. Rather than manually selecting and copying text between panes, you can use do (diff obtain) and dp (diff put) to move changes between windows with a single keystroke, making conflict resolution and file merging much faster.

How it works

  • do (:diffget) — obtain the change from the other window into the current window. The current pane's version is overwritten with the other pane's version for that hunk.
  • dp (:diffput) — put the change from the current window into the other window. The other pane's version is overwritten with the current pane's version for that hunk.

Both commands operate on the diff hunk under or nearest to the cursor.

Example

With two files open side by side in diff mode:

Left pane (modified)    │  Right pane (original)
─────────────────────────┼──────────────────────
foo = bar               │  foo = baz
  • With cursor on the highlighted line in the left pane: dp copies bar to the right pane
  • With cursor on the highlighted line in the right pane: do copies baz to the left pane

Tips

  • When there are more than two diff windows, specify the source buffer explicitly: :diffget {buf} or :diffput {buf}
  • Run :diffupdate after making manual edits to refresh the diff highlighting
  • Use ]c and [c to jump to the next and previous diff hunk
  • :only closes all diff panes except the current one once you are done merging

Next

How do I run normal mode commands in a script without triggering user-defined key mappings?