分享來源:Implementing a Clojure threading refactoring in ClojureScript using Light Table
摘要:
作者提供了一套可綁定於 LightTable 按鍵的宏,目的是將如下代碼:
; Turn something like this;
(map #(+ % 1) (filter even? [1 2 3 4 5]))
轉換成如下形式:
;into
(->> [1 2 3 4 5]
(filter even?)
(map #(+ % 1)))
該宏代碼如下:
(defn str->seq-zip [form-str]
(when (seq form-str)
(-> form-str
rdr/read-string
z/seq-zip)))
(defn do-thread-one [cand cand-fn]
(if-not (further-threadable? cand)
cand
(let [promote (-> cand cand-fn z/node)
therest (-> cand cand-fn z/remove)]
(-> therest
z/up
(z/insert-left promote)
(#(z/replace % (unwrap-list-if-one (z/node %))))
z/up))))
(defn- do-thread [orig cand-fn t]
(when (seq orig)
(let [root (if (threaded? orig) orig (wrap-in-thread orig t))]
(loop [cand root]
(if-not (further-threadable? cand)
cand
(recur (do-thread-one cand cand-fn)))))))
接著綁定到 LightTable
(defn replace-cmd [ed replace-fn]
(cmd/exec! :paredit.select.parent)
(when-let [candidate (editor/selection ed)]
(let [bounds (editor/selection-bounds ed)]
(when-let [res (replace-fn candidate)]
(editor/replace-selection ed res))
(editor/move-cursor ed (-> bounds :from (update-in [:ch] inc))))))
之後添加相關編輯器功能 metadata,即是 LightTable Refactoring 工具組成員。