Skip to content

Instantly share code, notes, and snippets.

@kurohuku
Created December 10, 2010 07:41
Show Gist options
  • Save kurohuku/735921 to your computer and use it in GitHub Desktop.
Save kurohuku/735921 to your computer and use it in GitHub Desktop.
(defmacro define-insertion-template (name template)
(destructuring-bind (vars fmt)
(parse-template template)
(let* ((syms (mapcar
(lambda (v)
`(,v ,(gensym)))
(remove-duplicates vars))))
`(defun ,name ()
(interactive)
(let ,(mapcar 'second syms)
,@(mapcar
(lambda (ss)
`(setf ,(second ss) (read-from-minibuffer ,(format "template var %s:" (car ss)))))
syms)
(insert
(format
,fmt
,@(mapcar
(lambda (var)
(second (assoc var syms)))
vars))))))))
(defun parse-template (template)
(let ((len (length template))
(pos 0)
vars
fmt)
(loop
while (< pos len)
with prev = nil
for ch = (elt template pos)
do
(cond
((and prev (= ch ?$) (= prev ?$))
(push ?$ fmt)
(setf prev nil))
((= ch ?$)
(setf prev ?$))
((and prev (= prev ?$) (= ch ?{))
(let ((str (substring template (1+ pos) (position ?} template :start pos))))
(setf pos (position ?} template :start pos))
(push ?% fmt)
(push ?s fmt)
(push (intern str) vars)))
(t
(push ch fmt)
(setf prev ch)))
(incf pos))
(list (nreverse vars)
(coerce (nreverse fmt) 'string))))
;; example
(define-insertion-template insert-hoge
"aaa ${hoge} bbb ${hoge} ${fuga}")
;; M-x insert-hoge
;; minibuffer) template var hoge: ppp
;; minibuffer) template var fuga: bbb
;; => aaa ppp bbb ppp bbb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment