Skip to content

Instantly share code, notes, and snippets.

@nicferrier
Created December 11, 2012 10:37
Show Gist options
  • Save nicferrier/4257637 to your computer and use it in GitHub Desktop.
Save nicferrier/4257637 to your computer and use it in GitHub Desktop.
sformat and some tests
(defun sformat/replacer (text values match-data)
(cond
((functionp values)
;; We don't need to save it, the caller does that
(set-match-data match-data)
;; Call the user function to return the valuyes
(funcall values text))
((hash-table-p values)
(gethash text values))
((sequencep values)
(elt values (string-to-number text)))))
(defun* sformat (template values)
(let ((saved-match-data (match-data))
(vtype
(cond
((or (functionp values)
(hash-table-p values)) :strings)
((or (listp values)
(vectorp values)) :sequence))))
(unwind-protect
(replace-regexp-in-string
(case vtype
(:strings "\\${\\([^}]+\\)}")
(:sequence "\\$\\([0-9]+\\)"))
(lambda (text)
(let ((in-matcher-data (match-data)))
(unwind-protect
(sformat/replacer
(match-string 1 text)
values
saved-match-data)
(set-match-data in-matcher-data)))) template)
(set-match-data saved-match-data))))
(sformat
"help ${name}! I'm ${malady}"
#s(hash-table test equal data ("name" "nic" "malady" "on fire")))
(sformat
"help ${name}! I'm ${malady}"
(lambda (key)
(case (intern key)
('name "nic")
('malady "on a plane!"))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment