KISS

Be Among the 20% of the Best!

Resolving Git Conflicts in Vim

| comments

git is awesome. Duh! And so is vim. Why not combine them? At least, to resolve git conflicts.

git config

Two git settings to simplify merges:

1
2
git config --global merge.conflictStyle diff3
git config --global rerere.enabled true

diff3 makes git produce conflicted parts from both branches while merging and also the same part from their common ancestor. And rerere is a great feature to record conflicts resolutions to be able to apply them later. Read more here: http://psung.blogspot.com/2011/02/reducing-merge-headaches-git-meets.html.

A few useful aliases from the git SCM wiki:

1
2
edit-unmerged = "!f() { git diff --name-status --diff-filter=U | cut -f2 ; }; vim `f`"
add-unmerged = "!f() { git diff --name-status --diff-filter=U | cut -f2 ; }; git add `f`"

Add these lines into the [alias] section of your ~/.gitconfig file.

vim setup

I’ve come up with this mapping to jump between git conflict markers:

1
2
" jump to next conflict marker in git
map <silent> <F8> /^\(<\{7\}\\|>\{7\}\\|=\{7\}\\|\|\{7\}\)\( \\|$\)<cr>

Add it to your ~/.vimrc. You can also try this great plugin to use git right inside your brain vim: vim-fugitive.

How to use that

So when you have a merge conflict, run git edit-unmerged, which will open all your conflicted files in vim with the conflict markers. To jump between them, use <F8> to forward, and N to backward. And a few useful tricks: use d<F8> to delete the lines up to the next conflict marker; use V<F8>d to delete everything to the next marker, including it.

When you’re done, you need to mark the files as resolved. Two ways:

  1. Mark one-by-one, as you’re resolving them with :Gw. You need the vim-fugitive plugin for that.

  2. Resolve and save everything, and quit vim with :wq, :qa. Then run git add-unmerged.

That’s it. Easy! (I tried using vimdiff to resolve conflicts, but it looks much more complicated with multiple windows in most cases).

You can also check out my recipe on how to handle big git conflicts here: git: easier conflict resolution during a big merge.

Comments