A Tip For Navigating Clojure Files in Emacs

Here's a little Emacs trick I've starting using recently for navigating Clojure. It's an easy way to get a map of the file you're working on, and jump around it. Once it's working, it looks like this:

Helm Clojure Headlines

To set it up, first you'll need helm, so if you don't have it installed call:

  M-x package-install
  helm

Then, stick this in your .emacs:

(defun helm-clojure-headlines ()
  "Display headlines for the current Clojure file."
  (interactive)
  (helm-mode t)
  (helm :sources '(((name . "Clojure Headlines")
                    (volatile)
                    (headline "^[;(]")))))

Eval it, and you're away. M-x helm-clojure-headlines will bring up the map. You can type a string to narrow down the list. Hitting return will leap to that point in the file. C-n and C-p will move through the list of matches.

How does it work? Mostly through Helm magic. All you really need to think about is the:

(headline "^[;(]")

...part. That's just a regular expression that tells helm which lines in the file are headlines. For Clojure, I like "starts with a semicolon or opening parenthesis".

For a more involved example, I use this version for Objective-C:

(defun helm-objc-headlines ()
  (interactive)
  (helm :sources '(((name . "Objective-C Headlines")
                    (volatile)
                    (headline  "^[-+@]\\|^#pragma mark")))))

A trickier regex, but still a very easy thing to setup for all it supplies. And this trick works for any filetype you can think of a sensible pattern to match against.

Give it a whirl. If you like it, I leave it to you to bind your own shortcut key. Oh, and you might like another, more complex thing I built with helm: The Clojure Cheatsheet for Emacs. :-)