Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
elisp-string-interpolation.el
(defmacro fmt (str)
"Elisp string interpolation.
Example:
(fmt \"My name is #{user-full-name}, I am running Emacs #{(if (display-graphic-p) \\\"with a GUI\\\" \\\"in a terminal\\\".)}\""
(let ((exprs nil))
(with-temp-buffer
(insert str)
(goto-char 1)
(while (re-search-forward "#{" nil t 1)
(let ((here (point))
(emptyp (eql (char-after) ?})))
(unless emptyp (push (read (buffer-substring (point) (progn (forward-sexp 1) (point)))) exprs))
(delete-region (- here 2) (progn (search-forward "}") (point)))
(unless emptyp (insert "%s"))
(ignore-errors (forward-char 1))))
(append (list 'format (buffer-string)) (reverse exprs)))))
;; evaluating
(fmt "My name is #{user-full-name}, I am running Emacs #{(if (display-graphic-p) \"with a GUI\" \"in a terminal\".)}")
;; => "My name is Jordon Biondo, I am running Emacs with a GUI"
;; how it expands
(cl-prettyexpand '(fmt "My name is #{user-full-name}, I am running Emacs #{(if (display-graphic-p) \"with a GUI\" \"in a terminal\".)}"))
;; =>
(format "My name is %s, I am running Emacs %s"
user-full-name
(if (display-graphic-p) "with a GUI" "in a terminal" \.))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.