将 lambda 绑定到键时出现“错误类型参数: commandp”错误

我在这里得到了一个“错误的类型参数: commandp,(lambda nil (forward-line 5))”。

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

错误是什么? 我相当肯定它很简单,我遗漏了一些明显的东西。

31165 次浏览

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.

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.

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