If you’ve ever had to deal with merge conflicts, you know it’s not much fun. Fortunately, Emacs can help.
The first component we’re going to work with is smerge. SMerge is invaluable; it’s a minor mode which allows you to quickly navigate between conflicts and choose which you’d like to keep. Normally, you must invoke it explicitly with M-x smerge-mode, but there’s an easier way.
(defun sm-try-smerge ()
(save-excursion
(goto-char (point-min))
(when (re-search-forward "^<<<<<<< " nil t)
(smerge-mode 1))))
(add-hook 'find-file-hook 'sm-try-smerge t)
Throw this in your .emacs, and smerge-mode will be enabled for files which contain conflict markers. If you’re a Git user (and you should be), the markers will have the branch names they came from tacked on the end. The minor mode will disable itself when there are no more conflicts left in the buffer.
All SMerge’s bindings start with a shared prefix, which is C-c ^ by default. This is somewhat cumbersome, but you can change it in customize (M-x customize-variable RET smerge-command-prefix RET). The bindings you’ll want to be familiar with are:
C-c ^ n – Move to the next conflict.C-c ^ p – Move to the previous conflict.C-c ^ RET – Keep the version of the code point resides in.C-c ^ m – Keep my version of the code. This is the version that was in the branch you merged to.C-c ^ o – Keep the other version of the code. This is the version that was in the branch you merged from.C-c ^ a – Keep all versions of the code. You’ll probably need to edit it to completely resolve the conflict.Let’s say that you have a file where you want to resolve each conflict the same way. You either want to keep the changes from the branch you merged, or the changes you've made in your branch. SMerge helps a lot with this, but there’s not reason to kill your fingers when you have KMacro. Let’s assume that you want changes in the branch you merged to take precedence.
C-x ( – Start recording a keyboard macro.C-x ^ n – Move to the next conflict.C-x ^ o – Resolve the conflict by choosing the other version.C-x ) – Stop recording the macro.Now, you can apply this macro as many times as you like with:
M-x kmacro-call-macro RET – Run the macro.RET – Run the macro again; repeat until all conflicts are resolved.
Discussion