2019-08-31 A simple tip with overlays and diffs

A few days ago I had an interesting problem. I had to resolve a particlarly nasty Git merge. It involved several files with lines’ lengths in the triple digits and a fair number of very small changes. Seeing those changes (in smerge-mode), even after refining the diffs, was tricky – there were many very small patches (sometimes two, sometimes four characters) of changed text and I was quite afraid that I would miss some of them. I searched for a command to “go to the next patch of changes”, but to no avail. Then I decided to write my own.

I started with going to one of these patches and pressing C-u C-x =. This way I learned how Emacs highlights them – using overlays (not text properties). (By the way, this explains the performance hit we experience when viewing very large diffs with these changes highlighted – overlays do not scale. In such cases, I often turn the diff hunk refinement off – D t in Magit.)

I vaguely remembered that Emacs can search for the next overlay or something like that. It turned out that I was right. There is a function next-overlay-change, which starts at a given point and finds the nearest boundary of an overlay. (By the way, there also exist similar functions for text properties and a version which looks for both. Consult the manual for the details.)

The only thing that was left was to wrap it up in some kind of UI. Here’s what I came up with – it is extremely bare-bones (in particular, it also stops at the end of the overlay, which was not useful for me – but I aimed for simplicity and speed of hacking up my solution, not for perfect elegance) but only took 1-2 minutes to write.

(defun goto-next-overlay-change ()
  "Goto the `next-overlay-change'."
  (interactive)
  (goto-char (next-overlay-change (point))))

As usual, this shows where Emacs really shines – it’s extremely well self-documented (including C-u C-x =) and flexible (coding a solution required typing a few lines of Lisp and calling local-set-key with some unused key).

CategoryEnglish, CategoryBlog, CategoryEmacs