/
var.clj
86 lines (65 loc) · 1.93 KB
/
var.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
(ns cljstyle.format.var
(:require
[cljstyle.format.zloc :as zl]
[rewrite-clj.zip :as z]))
(defn- def?
"True if the node at this location is a `def` symbol."
[zloc]
(and (zl/token? zloc)
(z/leftmost? zloc)
(= 'def (zl/form-symbol zloc))))
(defn- def-form?
"True if the node at this location is a `def` form declaring a var."
[zloc _]
(and (z/list? zloc)
(def? (z/down zloc))))
(defn- name?
"True if the node at this location is the form representing the name of the
defined value."
[zloc]
(def? (z/left zloc)))
(defn- docstring?
"True if the node at this location is a var docstring."
[zloc]
(and (zl/string? zloc)
(name? (z/left zloc))
(z/right zloc)))
(defn- around-doc-space?
"True if the node at this location is whitespace surrounding a var docstring."
[zloc]
(and (z/whitespace? zloc)
(or (docstring? (z/right zloc))
(docstring? (z/left zloc)))))
(defn- pre-body-space?
"True if the node at this location is whitespace preceding a var definition
body."
[zloc]
(and (z/whitespace? zloc)
(z/right zloc)
(let [left (z/left zloc)]
(or (name? left)
(docstring? left)))))
;; ## Editing Functions
(defn- edit-def
"Reformat a definition form. Returns a zipper located at the root of the
edited form."
[zloc _rule-config]
(loop [zloc (z/down zloc)]
(cond
;; Join def symbol and name.
(zl/whitespace-after? def? zloc)
(recur (zl/line-join zloc))
;; Break around doc strings.
(around-doc-space? zloc)
(recur (zl/line-break zloc))
;; Break if multiline, else preserve.
(and (pre-body-space? zloc)
(zl/multiline? (z/up zloc)))
(recur (zl/line-break zloc))
:else
(if (z/rightmost? zloc)
(z/up zloc)
(recur (z/right* zloc))))))
(def format-defs
"Rule to format var definition forms."
[:vars nil def-form? edit-def])