rewrite-clj 2025-10-08

Hello! I've got a edn file that contains a vector of maps. I'd like to insert a map into that vector and maintain indentation. I'm nearly there, but my naïve implementation leaves me with a trailing space. Happy to hear suggestions of how I might do this differently/more idiomatically. Also would be satisfied if there were a way of removing all trailing space from the file as well if that would get rid of the space I've introduced.

✅ 1

Hiya @grzm, I'll fire up my REPL and take a peek.

Thanks, @lee I did try mucking about with the raw * variants to get at the space but I wasn’t making much clear progress and it felt like I was probably missing a better way to do it.

Going with your current approach and * variant:

(-> baz-zloc
    (z/insert-left* indented-quux-node)
    (z/insert-newline-left)
    (z/insert-space-left (dec baz-zloc-col))
    (z/root-string)
    (str/split-lines))
;; => ["{:vector-of-maps"
;;     " [{:foo :bar}"
;;     "  {:foo :quux}"
;;     "  {:foo :baz}"
;;     "  {:foo :bat}]}"]

Does that look ok to you?

Yup. That looks like what I’d expect.

Nice. Do you know where that space in my example is coming from?

Yeah, insert-left will insert the space node, but you are doing some custom whitespace handling, so I used insert-left* instead, which does not insert a space node.

👍 1

For comparison:

(-> "[1 3]"
    z/of-string
    z/down
    z/rightmost
    (z/insert-left 2)
    z/root-string)
;; => "[1 2 3]"

(-> "[1 3]"
    z/of-string
    z/down
    z/rightmost
    (z/insert-left* 2)
    z/root-string)
;; => "[1 23]"

Preserving formatting can become a bit of a pain. Some folks make their changes with rewrite-clj, then pass the result through cljfmt or zprint to clean up formatting. An option if it gets too hairy.

Thanks @lee. Makes sense. My first time using rewrite-clj and I was happy I got as far as I did. Thanks for helping me over the line !

Anytime @grzm, drop by if you get stuck again.

There is also https://github.com/borkdude/rewrite-edn, I don't think it would help you here... but might be good for some other simple use cases where you want to preserve indentation.

Yeah, I looked at that first and came to the same conclusion for this specific case. Good to keep in mind for another time, though. Back pocket and all that.

👍 1