Created
January 7, 2015 20:01
-
-
Save jordonbiondo/c4e22b4289be130bc59b to your computer and use it in GitHub Desktop.
elisp-string-interpolation.el
This file contains hidden or 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
(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