How do I transfer diff hunks between files in Vim's diff mode?
Answer
dp and do
Explanation
When comparing two files side by side in Vim's diff mode (:diffsplit or vim -d file1 file2), you often want to accept or push individual changes between the files. The dp and do commands let you transfer diff hunks without manual copy-pasting, making conflict resolution and file merging dramatically faster.
How it works
dp(diff put): Pushes the current hunk from the buffer your cursor is in to the other buffer. The other file receives the change.do(diff obtain): Pulls the current hunk from the other buffer into the buffer your cursor is in. Your file receives the change.- Both commands operate on the diff hunk under the cursor. Navigate between hunks with
]c(next) and[c(previous). - After transferring a hunk, Vim automatically updates the diff highlighting.
Example
With two files open in diff mode:
file1.txt | file2.txt
─────────────────┼─────────────────
hello world | hello world
foo | bar ← difference
goodbye | goodbye
With cursor on the foo/bar hunk in file1.txt:
- Press
dp→ pushesfootofile2.txt(both files now havefoo) - Press
do→ obtainsbarfromfile2.txt(both files now havebar)
Tips
- Use
:diffupdateif the highlighting gets out of sync after edits - Combine with
]cand[cfor a rapid workflow:]cto jump to next hunk, thendoordpto resolve it - In a three-way merge,
doanddpwork with the buffer that shares the diff hunk — use:diffget {bufnr}for explicit control - Remember:
dp= "put" (push to other),do= "obtain" (pull from other)