anonymous-commands-in-emacs

Table of Contents

Introduction

Generally, you do not want to make keybindings to anonymous lambdas. Here is the primary reason that comes to mind:

(describe-keymap
 (let ((m (make-sparse-keymap)))
   (define-key m (kbd "f") (lambda () (interactive) 'hi))
   m))

I get help buffer with this content:

Key             Binding
f		[closure]

It is not really useful to just get the info [closure] here.

add-hook

The same thing goes for add-hook. From the doc string:

FUNCTION may be any valid function, but it's recommended to use a function symbol and not a lambda form. Using a symbol will ensure that the function is not re-added if the function is edited, and using lambda forms may also have a negative performance impact when running `add-hook' and `remove-hook'

Some of the hooks functionality is meant for symbols.

Solution

Alias your function:

(defalias 'foo-a (lambda () (interactive) 'hi))
 (describe-keymap
  (let ((m (make-sparse-keymap)))
    (define-key m (kbd "f") 'foo-a)
    (define-key m (kbd "b") (defalias 'foo-b (lambda () (interactive) 'hi2)))
   m))
Key             Binding
b		foo-b
f		foo-a

Foo-b works because defalias returns the symbol.

defun

(defalias 'foo (lambda () (interactive)))

is essentially the same as

(defun foo () (interactive))

Result

I end up just using defun inline. Examples:

(add-hook
 'sh-mode-hook
 (defun mm/add-bash-completion () ...))
(mememacs/leader-def
  "pP" (defun mm/project-switch-project-find-file ()
         (interactive) ...))

After writing this post, I went and fixed the remaining add-hook lambas In my config.

Date: 2022-09-23 Fri 18:59

Email: Benjamin.Schwerdtner@gmail.com

About
href="atom.xml"
Contact