Fork me on GitHub
#rewrite-clj
<
2023-11-27
>
martinklepsch17:11:57

Hi 👋 With the zipper API, how would I find the last item in a form? E.g. in this

(-> zloc
     (z/find-value z/next 'ns)
     (z/find-value z/next :require)
     z/up
     to-end) ;; I found to-end in the docs as an example but it seems to be doing something else :) 

borkdude19:11:44

I usually use a combination of z/next + z/end? but probably there's better ways

lread20:11:07

Maybe z/rightmost would help you?

(require '[rewrite-clj.zip :as z])

(def zloc (z/of-string "[[1 2 3] [4 5 6] [7 8 9]]"))

(-> zloc
    z/rightmost
    z/string)
;; => "[[1 2 3] [4 5 6] [7 8 9]]"

(-> zloc
    z/down
    z/rightmost
    z/string)
;; => "[7 8 9]"

(-> zloc
    z/down
    z/rightmost
    z/down
    z/rightmost
    z/string)
;; => "9"

martinklepsch19:11:24

Also is there a way to use append-child to append a linebreak? 🙂

lread21:11:17

Maybe insert-newline-right or insert-newline-left would work for you.

(require '[rewrite-clj.zip :as z])

(def zloc (z/of-string "[[1 2 3] [4 5 6] [7 8 9]]"))

(-> zloc
    z/down
    z/right
    z/insert-newline-right
    z/print-root)
Prints:
[[1 2 3] [4 5 6]
 [7 8 9]]

lread21:11:52

But if you feel you need to append a child, that's fine. But use append-child* instead so that extra whitespace won't be added.

(require '[rewrite-clj.node :as n]
         '[rewrite-clj.zip :as z])

(def zloc (z/of-string "[[1 2 3] [4 5 6] [7 8 9]]"))

(-> zloc
    z/down
    (z/append-child* (n/newlines 1))
    z/print-root)
Prints:
[[1 2 3
] [4 5 6] [7 8 9]]