This is the third post in my side project of learning Clojure, after persistent collections and macros. The language was easy to start with. The workflow took longer. With Java I edit, build, run. With Python I mostly run scripts. Clojure people keep a REPL open for hours and send code to it from the editor. I live in Emacs already (my notes are in Org-mode), so CIDER was the natural choice.
Setup
I use Leiningen 2.7.1. Leiningen 2.8 came out this month and I have not moved to it yet. The project uses
Clojure 1.8.0. Clojure 1.9 is in beta, and spec is still clojure.spec.alpha, so I am waiting for the
final release before I try it here.
lein new app notebook
cd notebook
The generated project.clj is small. I add tools.namespace to a dev profile, because it is only needed
at the REPL:
(defproject notebook "0.1.0-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.8.0"]]
:main ^:skip-aot notebook.core
:target-path "target/%s"
:profiles {:dev {:dependencies [[org.clojure/tools.namespace "0.2.11"]]
:source-paths ["dev"]}
:uberjar {:aot :all}})
In Emacs I install cider from MELPA Stable with M-x package-install. It pulls in clojure-mode. I use
MELPA Stable rather than MELPA because CIDER (the Emacs package) and cider-nrepl (the server-side part)
must have matching versions, and the snapshot builds change often.
You do not need to add cider-nrepl to ~/.lein/profiles.clj any more. Since CIDER 0.11,
cider-jack-in adds it to the Leiningen command line for you. Many older guides still tell you to edit
profiles.clj. If you did that in the past, remove the entry, or you can get version mismatch warnings.
Starting the REPL
Open any .clj file in the project and run cider-jack-in (C-c M-j). It starts lein repl :headless,
connects, and opens a REPL buffer. The first start is slow because the JVM and Leiningen both start up.
After that you keep the same REPL for the whole day.
Evaluating from the buffer
This is the part that changed how I write code. I rarely type into the REPL buffer. I write in the source file and send forms:
| Key | What it does |
|---|---|
C-x C-e |
evaluate the form before the cursor, show the result in the echo area |
C-M-x or C-c C-c |
evaluate the top-level form around the cursor (the whole defn) |
C-c C-k |
load the whole buffer |
C-c C-z |
jump between the source buffer and the REPL |
C-c M-n |
set the REPL namespace to the current buffer’s namespace |
C-c C-d C-d |
show the docstring of the symbol at point |
C-c C-m |
macroexpand the form at point (useful for the macro post) |
The loop is: change a defn, C-M-x, then call it from a (comment ...) block at the bottom of the
file with C-x C-e. The comment form returns nil when the file loads, so the examples in it never run in
production, but I can evaluate each one by hand. It is the same idea as source blocks in an Org file.
(comment
(parse-line "2017-10-01,21.5,45")
(->> (slurp "sample.csv") clojure.string/split-lines (map parse-line) (take 3))
)
Keeping state
A REPL that runs for hours needs a place for long-lived things: a database connection, an HTTP server, a
scheduler. I keep them in one atom in a dev/user.clj file, with start and stop functions:
(ns user
(:require [clojure.tools.namespace.repl :refer [refresh]]
[notebook.core :as core]))
(defonce system (atom nil))
(defn start []
(reset! system (core/start-system {:port 8080})))
(defn stop []
(when-let [s @system]
(core/stop-system s)
(reset! system nil)))
(defn reset []
(stop)
(refresh :after 'user/start))
defonce means that loading the buffer again with C-c C-k does not create a new atom and lose the
running server.
For larger projects, Stuart Sierra’s Component library does the same job with explicit dependencies
between parts of the system. It also builds on his “reloaded” workflow with tools.namespace. For a small
side project, one atom is enough for me.
Reloading namespaces
Evaluating single forms is fast, but over time the REPL drifts away from the files. refresh from
tools.namespace unloads every changed namespace and loads them again in dependency order. CIDER has a
command for it, cider-refresh (C-c C-x), or you call (reset) from the user namespace above.
refresh removes namespaces before it loads them again. That also removes defonce values in those
namespaces, so a running server would be lost without being stopped. This is why reset stops the system
first. The dev folder is on the classpath, so refresh would also reload user when I edit it. I added
(clojure.tools.namespace.repl/disable-reload!) at the top of user.clj, right after the ns form, so
the atom in user survives. I learned this after losing the handle to a running server once and having
to restart the REPL to free the port.
If the code has a compile error, refresh stops in the middle. Some namespaces are then missing, and you
get strange “No such var” errors. Fix the error and run refresh again before you try anything else.
Pitfalls
Stale definitions. If you rename a function, the old name still exists in the REPL. Other code that
still calls the old name keeps working at the REPL and fails in a fresh lein test. I now run lein test
in a terminal before each commit, from a clean JVM. (ns-unmap 'my.ns 'old-name) removes one var by hand.
Protocols and records. Evaluating a defprotocol again creates a new protocol. Records that were
created before still implement the old one, so calls on them fail with “No implementation of method”. A
defrecord evaluated again creates a new Java class with the same name. Old instances are of the old
class, so instance? checks fail even though the names look the same. The fix is to rebuild the data:
stop the system, refresh, start again.
Multimethods. defmulti behaves like defonce. If you change the dispatch function and evaluate the
defmulti again, nothing happens. Use (ns-unmap *ns* 'my-multi) first, then evaluate it again (and its
defmethods).
Wrong namespace. C-x C-e evaluates in the namespace of the buffer, but code typed into the REPL
runs in the REPL’s current namespace. When a function “does not exist”, check the prompt and use
C-c M-n.
Long output. Evaluating something that returns a huge lazy seq can freeze Emacs while it prints. I wrap
experiments in (take 10 ...), or set *print-length* in the REPL.
Single forms or a full reset
While I work on one function, I evaluate single forms. After a change to a record, a protocol or the ns
form, I run (reset). Stale code still surprises me now and then; when the REPL behaves in a way the source
does not explain, (reset) is the first thing to try.