Created
September 10, 2021 13:03
-
-
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`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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