rewrite-clj

grzm 2025-10-08T23:38:48.729219Z

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
lread 2025-10-08T23:52:58.858109Z

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

grzm 2025-10-08T23:57:53.083319Z

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.

lread 2025-10-09T00:00:33.824059Z

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

lread 2025-10-09T00:01:07.244509Z

Does that look ok to you?

grzm 2025-10-09T00:01:42.392389Z

Yup. That looks like what I’d expect.

grzm 2025-10-09T00:02:39.904359Z

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

lread 2025-10-09T00:04:20.415869Z

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
lread 2025-10-09T00:08:09.155739Z

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

lread 2025-10-09T00:10:27.587929Z

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.

grzm 2025-10-09T00:11:18.379699Z

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 !

lread 2025-10-09T00:11:39.733199Z

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

lread 2025-10-09T00:13:53.664549Z

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.

grzm 2025-10-09T00:14:58.537229Z

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