-
-
Save creichert/5afb8d7cbfa4e821a7d3948e72239f7e 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