Recent versions of Emacs support lexical binding for variables in elisp code. Is it also possible to lexically redefine functions? In other words, does Emacs Lisp have something like lexical-flet
?
Asked
Active
Viewed 770 times
4

Ryan C. Thompson
- 40,856
- 28
- 97
- 159
2 Answers
4
In Emacs<24.3, you can (require 'cl)
and then use labels
. In Emacs-24.3 and up, you can also do (require 'cl-lib)
and then use either cl-flet
or cl-labels
.
All of those are "complex macros" that generate code that looks like (let ((fun (lambda (args) (body)))) ... (funcall fun my-args) ...)
, because the underlying language does not natively support local function definitions.

Stefan
- 27,908
- 4
- 53
- 82
-
I'm switching to this as the accepted answer, since it is more complete and gives the full background. – Ryan C. Thompson Dec 13 '12 at 01:37
2
There is labels
but I don't know if that's what you're looking for:
(defun foo ()
42)
(defun bar ()
(foo))
(list
(foo)
(bar)
(labels ((foo ()
12))
(list (foo)
(bar)))
(foo)
(bar))
It returns (42 42 (12 42) 42 42)
.

Ryan C. Thompson
- 40,856
- 28
- 97
- 159

Daimrod
- 4,902
- 23
- 25
-
To me 24.2.1 returns "Symbol's function definition is void: labels" – Miserable Variable Dec 12 '12 at 23:13
-
`(require 'cl)`. If you have a recent enough version, use `(cl-labels ...)` instead. – Hugh Dec 13 '12 at 00:12
-
The docstring says "This is like `flet`, except the bindings are lexical". That's exactly what I wanted. Thanks! – Ryan C. Thompson Dec 13 '12 at 01:17