Fork me on GitHub
#rewrite-clj
<
2022-01-26
>
orestis07:01:26

Thanks @lee, I ended up with this:

(defn add-namespace [zloc new-ns insert-loc-fn]
  (let [require-loc (-> zloc
                        (z/find-value z/next 'ns)
                        (z/find-value z/next :require)
                        (z/up))
        insert-loc (insert-loc-fn require-loc)
        n-spaces (-> insert-loc z/node meta :col dec)]
    (-> insert-loc
        (z/insert-right* (n/newline-node "\n"))
        (z/right*)
        (z/insert-right* (n/spaces n-spaces))
        (z/right*)
        (z/insert-right* new-ns))))

orestis07:01:44

In my case, I wanted the new form to not be inserted at the end, but rather next to a similar ns, hence the insert-loc-fn that operates on the (:require ...) node. I also had to dec the spaces since :col is the start of the first character of the form.

orestis07:01:25

I also decided to move the cursor instead of doing the insertions in reverse order.