-
Notifications
You must be signed in to change notification settings - Fork 177
/
Copy pathformat.clj
66 lines (59 loc) · 1.92 KB
/
format.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
(ns cider.nrepl.middleware.format
"Code and EDN formatting functionality."
(:refer-clojure :exclude [read-string])
(:require
[cider.nrepl.middleware.util.error-handling :refer [with-safe-transport]]
[cljfmt.core :as fmt]
[clojure.string :as str]
[clojure.tools.reader.edn :as edn]
[clojure.tools.reader.reader-types :as readers]
[clojure.walk :as walk]
[nrepl.middleware.print :as print])
(:import
(java.io StringWriter)))
;;; Code formatting
(defn- keyword->symbol [kw]
(.sym ^clojure.lang.Keyword kw))
(defn- generate-user-indents [indents]
(reduce-kv
(fn [acc kw rule]
(assoc acc
(keyword->symbol kw)
(walk/postwalk #(cond-> % (string? %) keyword) rule)))
fmt/default-indents
indents))
(defn format-code-reply
[{:keys [code options]}]
(let [opts (some-> options
(select-keys [:indents :alias-map])
(update :indents generate-user-indents)
(update :alias-map #(reduce-kv (fn [m k v] (assoc m (name k) v)) {} %)))]
{:formatted-code (fmt/reformat-string code opts)}))
;;; EDN formatting
(defn- read-edn
"Returns a vector of EDN forms, read from the string s."
[s]
(let [reader (readers/string-push-back-reader s)
sentinel (Object.)]
(loop [forms []]
(let [form (edn/read {:eof sentinel} reader)]
(if (= sentinel form)
forms
(recur (conj forms form)))))))
(defn- format-edn
[edn print-fn]
(->> (read-edn edn)
(map (fn [value]
(let [writer (StringWriter.)]
(print-fn value writer)
(str writer))))
(str/join "\n")
(str/trim)))
(defn format-edn-reply
[{:keys [edn ::print/print-fn]}]
{:formatted-edn (format-edn edn print-fn)})
;;; Middleware op handling
(defn handle-format [handler msg]
(with-safe-transport handler msg
"format-code" format-code-reply
"format-edn" format-edn-reply))