Editing the ns Form
CIDER can add requires and imports to the ns form of the current buffer,
so you don’t have to jump to the top of the file and back whenever you need
another namespace.
The edits are plain text manipulation, so they work without a REPL. When one is connected, the prompts complete against it.
If you’re coming from clj-refactor, these commands cover what
cljr-add-require-to-ns and cljr-add-import-to-ns do, without yasnippet.
|
Adding a Require
C-c M-n a (cider-ns-add-require) prompts for a namespace, completing
over the namespaces loaded in the REPL, and then for an alias. The alias starts
out as the last segment of the namespace’s name. Edit it, or clear it to
require the namespace without an alias.
Requiring clojure.string as str turns
(ns my.app
(:require [clojure.set :as set]))
into
(ns my.app
(:require [clojure.set :as set]
[clojure.string :as str]))
The :require clause gets created when there isn’t one, ahead of the
:import clause if the ns form has it. Nothing changes when the namespace is
already required, and an alias that another namespace already has is refused.
CIDER doesn’t look into reader conditionals (#?(:clj …)): a require
inside one doesn’t count, and a new require always goes into the top-level
:require clause. In a .cljc file that means it applies to both Clojure and
ClojureScript, so wrap it in a reader conditional yourself if only one side
should see it. The same goes for imports.
Adding an Import
C-c M-n i (cider-ns-add-import) prompts for a fully qualified class
name, completing over the classes the REPL knows about. The class joins an
existing import list for its package, so importing java.util.Map turns
(ns my.app
(:import (java.util Date List)))
into
(ns my.app
(:import (java.util Date List Map)))
Without such a list, the fully qualified name goes into the :import clause,
which gets created when it’s missing.
After an Edit
cider-ns-edit-actions says what happens after a change to the ns form. By
default CIDER sorts the libspecs and, when a REPL is connected, evaluates the
ns form, so a new alias works right away.
To keep the libspecs in the order you wrote them, drop the sorting:
(setq cider-ns-edit-actions '(eval))
CIDER never removes anything from the ns form on its own.
Each change, together with the sorting, is a single undo step.