4

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?

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

2 Answers2

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
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