Skip to content

Instantly share code, notes, and snippets.

@jordonbiondo
Created January 7, 2015 20:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jordonbiondo/c4e22b4289be130bc59b to your computer and use it in GitHub Desktop.
Save jordonbiondo/c4e22b4289be130bc59b to your computer and use it in GitHub Desktop.
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