"Wrong type argument: commandp" error when binding a lambda to a key
Asked Answered
H

4

104

I am getting a "Wrong type argument: commandp, (lambda nil (forward-line 5))" here.

(global-set-key [?\M-n] (lambda () (forward-line 5)))

What is the error? I'm fairly sure it's simple & I'm missing something obvious.

Hosbein answered 9/8, 2009 at 6:59 Comment(2)
You're missing a closing parentheses. Probably not in your code though, only in the question.Dipterous
As a side note: when you quote the anonymous function like that it won't be compiled. I imagine it's no big deal in your case, though.Countervail
I
151

global-set-key expects an interactive command. (lambda () (interactive) (forward-line 5)) ought to work.

By the way, C-h f commandp is a pretty good starting point for errors like that.

Iorgo answered 9/8, 2009 at 7:4 Comment(3)
I think there are no down sides. From the documentation: >> The "call" to ‘interactive’ is actually a declaration rather than a function; it tells ‘call-interactively’ how to read arguments to pass to the function. When actually called, ‘interactive’ just returns nil.Francklyn
So according to (commandp) documentation, lambda functions with top level call to (interactive) work, but how can I define a function with (defun) that would work?Adage
peterhil: The commandp docs are just very specific, and its description does already cover what defun produces (which is a lambda expression assigned to the function cell of a symbol). As to your question, the only difference in syntax is wrt the name / lack thereof: substitute defun foo in place of lambda and you have yourself a named function instead of an anonymous one. (And you should use named functions when binding keys in almost every instance.)Uncompromising
S
42

The correct form should be this -

(global-set-key (kbd "M-n") (lambda () (interactive) (forward-line 5)))

The problem was that you forgot to put (interactive) (as brendan mentioned).

By the way, you will notice that I used the (kbd) function for specifying the key-binding. That function is immensely useful since you can put the key-bindings almost literally.

Solothurn answered 9/8, 2009 at 7:46 Comment(0)
T
2

I've also seen this error on a new machine where I am using my usual .emacs file but haven't installed my packages, and the command to be executed is in one of those packages. (Because a command that can't be executed definitely isn't interactive!)

Topcoat answered 18/6, 2018 at 18:45 Comment(0)
E
0

providing a function defined with defun should work the same way as a lambda, as long as it satisfies the same requirements.

So

(defun my-move-forward ()
 (interactive)
 (forward-line 5))

should work.

Employer answered 5/3, 2024 at 14:41 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.