Skip to content

Commit 3787ada

Browse files
committed
Improve heuristics for finding ns form
The ns-form? function is too broad in what it accepts. For example, it considers this to be a valid ns form: (let [ns (range 100)] ...) This commit makes the function more restrictive: an ns form must now be a top-level list that starts with the symbol ns. Fixes #247.
1 parent da37b7a commit 3787ada

File tree

2 files changed

+34
-6
lines changed

2 files changed

+34
-6
lines changed

cljfmt/src/cljfmt/core.cljc

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,16 +41,16 @@
4141
(nil? (z/up* zloc)))
4242

4343
(defn- top? [zloc]
44-
(and zloc (not= (z/node zloc) (z/root zloc))))
44+
(some-> zloc z/up root?))
4545

46-
(defn- top [zloc]
46+
(defn- root [zloc]
4747
(if (root? zloc) zloc (recur (z/up zloc))))
4848

4949
(defn- clojure-whitespace? [zloc]
5050
(z/whitespace? zloc))
5151

5252
(defn- surrounding-whitespace? [zloc]
53-
(and (top? (z/up zloc))
53+
(and (not (top? zloc))
5454
(surrounding? zloc clojure-whitespace?)))
5555

5656
(defn remove-surrounding-whitespace [form]
@@ -220,7 +220,9 @@
220220
(= 'ns (z/sexpr zloc))))
221221

222222
(defn- ns-form? [zloc]
223-
(some-> zloc z/down ns-token?))
223+
(and (top? zloc)
224+
(= (z/tag zloc) :list)
225+
(some-> zloc z/down ns-token?)))
224226

225227
(defn- indent-matches? [key sym]
226228
(if (symbol? sym)
@@ -334,7 +336,7 @@
334336
zloc)))
335337

336338
(defn- find-namespace [zloc]
337-
(some-> zloc top (z/find z/next ns-form?) z/down z/next z/sexpr))
339+
(some-> zloc root (z/find z/next ns-form?) z/down z/next z/sexpr))
338340

339341
(defn indent
340342
([form]

cljfmt/test/cljfmt/core_test.cljc

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -281,7 +281,33 @@
281281
" (prn x)))"]
282282
{:indents {'thing.core/defrecord [[:inner 0]]}
283283
#?@(:cljs [:alias-map {"t" "thing.core"}])})
284-
"applies custom indentation to namespaced defrecord"))
284+
"applies custom indentation to namespaced defrecord")
285+
(is (reformats-to?
286+
["(let [ns subs]"
287+
" (ns \"string\"))"
288+
""
289+
"(ns thing.core)"
290+
""
291+
"(defthing foo [x]"
292+
"(+ x 1))"]
293+
["(let [ns subs]"
294+
" (ns \"string\"))"
295+
""
296+
"(ns thing.core)"
297+
""
298+
"(defthing foo [x]"
299+
" (+ x 1))"]
300+
{:indents {'thing.core/defthing [[:inner 0]]
301+
'let [[:inner 0]]}
302+
#?@(:cljs [:alias-map {}])})
303+
"recognises the current namespace as part of a qualifed indent spec, even if preceded by a local var named ns")
304+
(is (reformats-to?
305+
["(let [ns (range 10)]"
306+
" (reduce + ns"
307+
" ))"]
308+
["(let [ns (range 10)]"
309+
" (reduce + ns))"]
310+
"doesn't throw with local vars named ns bound to expressions")))
285311

286312
(testing "function #() syntax"
287313
(is (reformats-to?

0 commit comments

Comments
 (0)