s.el的s-lex格式确实是您想要的,但是如果您希望真正能够将代码放入替换块中,而不仅仅是变量名,那么我将其写为概念证明。
(defmacro fmt (str)
"Elisp string interpolation for any expression."
(let ((exprs nil))
(with-temp-buffer
(insert str)
(goto-char 1)
(while (re-search-forward "#{" nil t 1)
(let ((here (point))
(emptyp (eql (char-after) ?})))
(unless emptyp (push (read (buffer-substring (point) (progn (forward-sexp 1) (point)))) exprs))
(delete-region (- here 2) (progn (search-forward "}") (point)))
(unless emptyp (insert "%s"))
(ignore-errors (forward-char 1))))
(append (list 'format (buffer-string)) (reverse exprs)))))
;; demo with variable and code substitution
(fmt "My name is #{user-full-name}, I am running Emacs #{(if (display-graphic-p) \"with a GUI\" \"in a terminal\")}.")
;; results in
"My name is Jordon Biondo, I am running Emacs with a GUI."
如果您疯了,甚至可以将一个fmt
电话嵌入另一个电话fmt
(fmt "#{(fmt\"#{(fmt\\\"#{user-full-name}\\\")}\")}")
;; =>
"Jordon Biondo"
该代码只是扩展为一个format
调用,因此所有替换均按顺序完成并在运行时进行评估。
(cl-prettyexpand '(fmt "Hello, I'm running Emacs #{emacs-version} on a #{system-type} machine with #{(length (window-list))} open windows."))
;; expands to
(format "Hello, I'm running Emacs %s on a %s machine with %s open windows."
emacs-version
system-type
(length (window-list)))
可以使用哪种格式类型而不是始终使用%s进行改进,但这必须在运行时完成,并且会增加开销,但是可以通过将所有格式args包围在一个函数调用中来完成,该函数调用可以很好地格式化对象在类型上,但实际上,您唯一想得到的可能就是浮点数,甚至可以替换(格式为“%f”浮点数),这是您的绝望。
如果我做得更多,我更有可能更新此要点而不是此答案。https://gist.github.com/jordonbiondo/c4e22b4289be130bc59b