Emacs lisp:将词法范围传递给函数?

Emacs lisp: Pass lexical scope as to a function?

Python 3 具有函数 locals() ans globals() 允许将当前范围的命名值至少出于只读目的传递给函数。

我想在 emacs lisp 中编写一个字符串插值函数。为此,它需要访问调用作用域的 lexical 变量。由于我想避免在宏更改时重新编译其他文件,因此显而易见的解决方案 - 使用宏 - 不可行。

有没有可能在 emacs lisp 中做到这一点?

我已经尝试过函数 lisp--local-variables,但它不适用于 lexical-bindingt

Elisp 文档中的一些相关引用

(Internally, the lexical environment is an alist of symbol-value pairs, with the final element in the alist being the symbol `t' rather than a cons cell. Such an alist can be passed as the second argument to the `eval' function, in order to specify a lexical environment in which to evaluate a form. *Note Eval::. Most Emacs Lisp programs, however, should not interact directly with lexical environments in this way; only specialized programs like debuggers.)


Currently, an Emacs Lisp closure object is represented by a list with the symbol `closure' as the first element, a list representing the lexical environment as the second element, and the argument list and body forms as the remaining elements:

 ;; lexical binding is enabled.
 (lambda (x) (* x x))
      => (closure (t) (x) (* x x))

However, the fact that the internal structure of a closure is "exposed" to the rest of the Lisp world is considered an internal implementation detail. For this reason, we recommend against directly examining or altering the structure of closure objects.

如果我这样做,我不会做一个字符串插值函数,我会做一个字符串插值宏,returns一段合适的代码来计算正确词法环境中的插值字符串.

毕竟,这是宏真正方便的用途之一。

如果您在 "isolation" 中编写和调试宏(在您在其他代码中大量使用它之前),您对需要重新编译的恐惧应该主要是恐惧。调试完成后,您不需要更改现有功能的宏,如果您需要添加新功能,它也不是已经使用过的任何东西(但是,偶尔重新编译代码可能不是一个坏主意,无论如何) .