Skip to content

Instantly share code, notes, and snippets.

@cbowdon
Created November 1, 2015 20:11
Show Gist options
  • Save cbowdon/012d623920bd28453bf8 to your computer and use it in GitHub Desktop.
Save cbowdon/012d623920bd28453bf8 to your computer and use it in GitHub Desktop.
Macro to add string interpolation to Emacs Lisp
(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