Skip to content

Instantly share code, notes, and snippets.

@favila
Created September 10, 2021 13:03
Show Gist options
  • Save favila/298ebd06a7212160c0cdf0b5e8dd276a to your computer and use it in GitHub Desktop.
Save favila/298ebd06a7212160c0cdf0b5e8dd276a to your computer and use it in GitHub Desktop.
A "clj template" macro that lets you embed clj expressions in strings. Expands to (str "literal parts" expression parts ...). Designed to replace typical uses of `format`
(def format-spans #"(?x)
(?:( (?: [^\\\{]++ | \\\{ )+ )
|(?:\{ ( (?: [^\\}]*+ | \\} )+ ) }))")
(defmacro cljt [formatstr]
{:pre [(string? formatstr)]}
(if (= formatstr "")
formatstr
`(str ~@(binding [*read-eval* false]
(->> (re-seq format-spans formatstr)
(mapv (fn [[_ literal expr]]
(cond
(some? literal) (str/replace literal "\\{" "{")
(some? expr) (read-string (str/replace expr "\\}" "}"))))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment