rewrite-clj

martinklepsch 2023-11-27T17:40:57.917099Z

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 :) 

borkdude 2023-11-27T19:59:44.978219Z

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

lread 2023-11-27T20:54:07.285489Z

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"

martinklepsch 2023-11-27T19:57:24.523409Z

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

lread 2023-11-27T21:02:17.666489Z

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]]

lread 2023-11-27T21:15:52.136279Z

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]]