Fork me on GitHub
#rewrite-clj
<
2021-04-08
>
mikethompson02:04:20

I have a small pebble in my shoe using rewrite-clj in one of our scripts. Can you point me in the right direction? This URL should explain (hopefully the URL highlights the string "we didn't find a way ..." https://github.com/day8/re-com/blob/master/scripts/add-at-macro/README.md#readme:~:text=we%20didn't%20find%20a%20way%20to%20add%20code%20on%20the%20next%20line%2C%20with%20correct%20indentation Problem: we were able to add the :src (at) code, but we couldn't ever add it correctly formatted/indented. So, in the example given on that page, is there a way to figure out the indentation level of :size (the first child of v-box ) ... and then add that level of indentation in front of the :src being added?

lread12:04:11

@mikethompson, I am glad it is just a small pebble in your shoe and not a thorn in your side!

lread12:04:00

Here’s one naive example that might get you going.

(let [code (str "[v-box\n"
                "  :size \"auto\"\n"
                "  :gap  \"10px\"\n"
                "  :children []]")
      zloc (z/of-string code)
      zloc-arg1 (-> zloc z/down z/right)
      indent-col (-> zloc-arg1 z/node meta :col)]
  (-> zloc-arg1
      (z/insert-left :src)
      (z/insert-left '(at))
      z/insert-newline-left
      (z/insert-space-left (dec indent-col))
      z/print-root))
;; =stdout=>
; [v-box
;   :src (at)
;   :size "auto"
;   :gap  "10px"
;   :children []]
My little example here uses https://cljdoc.org/d/rewrite-clj/rewrite-clj/1.0.605-alpha/doc/user-guide#nodes. If your work through the zipper changes :col for subsequent nodes, then you might consider https://cljdoc.org/d/rewrite-clj/rewrite-clj/1.0.605-alpha/doc/user-guide#position-tracking instead of metadata. Another strategy some people take is to get formatting good enough (usually just inserting newlines) for a final treatment with a dedicated formatting tool like https://github.com/weavejester/cljfmt.

❤️ 6
mikethompson21:04:43

This looks great, thanks! We'll work on it.

mikethompson02:04:17

@UE21H2HHD @U04V15CAJ For the record, Ike has now used this approach. Thanks! https://github.com/day8/re-com/pull/282 This script might be an interesting example to point to from a tutorial point of view. It is well documented, has tests, uses lots of features, and is non trivial without being crazy complicated, and is run via bb.

👍 6
sogaiu15:04:25

probably obvious but zprint and cljstyle might be worth considering in addition to the already mentioned cljfmt

👍 6