Clojure On Emacs - A CIDER Workflow Hack

TLDR; In a few lines of Emacs Lisp, you can speed up your Clojure workflow, and it's easy.

Recently I've been experimenting with clojure.tools.namespace and Stuart Sierra's Reloaded Workflow. If you haven't read that post, you should add it to your reading list. It's a smart way of adding a reset button to your REPL session, to ensure a clean environment without having to restart the JVM.

This post isn't really about that workflow per se, it's just a good use-case to demonstrate a little Emacs/Clojure/CIDER-fu.

If you adopt that workflow, you'll find yourself repeatedly typing this into the REPL:

  (require 'clojure.tools.namespace.repl)
  (clojure.tools.namespace.repl/refresh)

There are a few ways to save that typing, but a little Emacs Lisp is the most satisfying.

It's Simple

The easiest way in is to use the function cider-interactive-eval.

  (defun cider-namespace-refresh ()
    (interactive)
    (cider-interactive-eval
     "(require 'clojure.tools.namespace.repl)
      (clojure.tools.namespace.repl/refresh)"))

  (define-key clojure-mode-map (kbd "M-r") 'cider-namespace-refresh)

Now M-x cider-namespace-refresh, or simply M-r, will run our Clojure string and hit the reset button. Job done.

It's Reusable

It doesn't take much imagination to see how we can re-use this code.

Say this afternoon's development task means you're going to be looking at the value of an atom a lot. These few lines put viewing that atom a single keystroke away:

   (define-key clojure-mode-map (kbd "M-r")
     (lambda ()
       (interactive)
       (cider-interactive-eval
         "(require '[clojure.pprint :refer [pprint]])
          (pprint @interesting-atom)")))

That's a recipe for a function you can set up in a heartbeat, and throw away after a much zippier afternoon.