Created
November 1, 2015 20:11
-
-
Save cbowdon/012d623920bd28453bf8 to your computer and use it in GitHub Desktop.
Macro to add string interpolation to Emacs Lisp
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
(defmacro template (text) | |
"Expand text like \"Hello <<name>>\" to (format \"Hello %s\" name)." | |
(let ((pattern "<<\\(.*?\\)>>")) | |
;; The regexp matches anything between delimiters, non-greedily | |
(with-temp-buffer | |
(save-excursion (insert text)) | |
(let ((matches '())) | |
(while (re-search-forward pattern nil t) | |
(push (match-string 1) matches) | |
(replace-match "%s" t t)) | |
`(format ,(buffer-string) ,@(reverse (mapcar 'read matches))))))) | |
;;; Example usage: | |
;;(defvar animal "fox") | |
;;(defvar sound "oOOoee") | |
;;(template "What does the <<animal>> say? <<(string-join (make-list 10 sound))>>!") | |
;;; -> "What does the fox say? oOOoeeoOOoeeoOOoeeoOOoeeoOOoeeoOOoeeoOOoeeoOOoeeoOOoeeoOOoee!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment