Skip to content

Instantly share code, notes, and snippets.

@twlz0ne
Last active March 21, 2018 12:27
Show Gist options
  • Save twlz0ne/cd18687182cba84bd704ecd01288a9dc to your computer and use it in GitHub Desktop.
Save twlz0ne/cd18687182cba84bd704ecd01288a9dc to your computer and use it in GitHub Desktop.
Format a string using named placeholders in #emacs-lisp
(defun format-spec+ (fmt specs)
(with-temp-buffer
(insert fmt)
(goto-char (point-max))
(let ((objs '()))
(while (re-search-backward "%\\([-0-9\\-\\.]*\\){\\([^}]+\\)}\\([a-zA-Z]\\)" nil t)
(let ((num (match-string 1))
(var (match-string 2))
(typ (match-string 3)))
(replace-match (concat "%" num typ))
(setq objs (append (list (cdr (assq (intern var) specs))) objs))
))
(apply 'format (buffer-string) objs)
)))
(princ (format-spec+ ":%-10{key}s %{val}d\n" '((key . "foo") (val . 100))))
(princ (format-spec+ "%10{val}d :%{key}s\n" '((key . "bar") (val . 200))))
(princ (format-spec+ ":%-10{key}s %{val}d, :%-10{key}s %{val}d\n" '((key . "quux") (val . 300))))
;; =>
;; :foo 100
;; 200 :bar
;; :quux 300, :quux 300
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment