Resolving Merge Conflicts the Easy Way with SMerge & KMacro

If you’ve ever had to deal with merge conflicts, you know it’s not much fun. Fortunately, Emacs can help.

Piece of Cake

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:

Another Slice

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.

  1. C-x ( – Start recording a keyboard macro.
  2. C-x ^ n – Move to the next conflict.
  3. C-x ^ o – Resolve the conflict by choosing the other version.
  4. C-x ) – Stop recording the macro.

Now, you can apply this macro as many times as you like with:

  1. M-x kmacro-call-macro RET – Run the macro.
  2. RET – Run the macro again; repeat until all conflicts are resolved.
2010/06/17
Previously On Atomized:

Discussion

You did know that emacs automatically starts smerge when one is opening a file which has conflicts? At least in 22 and 23.

And that in 23 keyboard macros has a much easier shortcut – F3 to start, F4 to stop and F4 again to repeat it? :)

Oscar
2010/06/18

I’m aware of the automatic triggering of smerge, but I’ve found it somewhat unreliable. I think it doesn’t examine the complete buffer for conflict markers like my function does, so conflicts far in longer files are missed.

I didn’t know that kmacro got f-key bindings, thanks for the tip.

Ian
2010/06/23

Participate