Emacs Lisp function often start like this:
(lambda () (interactive) ...
What does "(interactive)" do?
Emacs Lisp function often start like this:
(lambda () (interactive) ...
What does "(interactive)" do?
I means that you're including some code for the things you need to make a function callable when bound to a key -- things like getting the argument from CTRL-u.
Have a look at CTRL-h f interactive
for details:
interactive is a special form in `C source code'. (interactive args) Specify a way of parsing arguments for interactive use of a function. For example, write (defun foo (arg) "Doc string" (interactive "p") ...use arg...) to make ARG be the prefix argument when `foo' is called as a command. 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. The argument of `interactive' is usually a string containing a code letter followed by a prompt. (Some code letters do not use I/O to get the argument and do not need prompts.) To prompt for multiple arguments, give a code letter, its prompt, a newline, and another code letter, etc. Prompts are passed to format, and may use % escapes to print the arguments that have already been read.
Just to clarify (it is in the quoted docs that Charlie cites) (interactive)
is not just for key-bound functions, but for any function. Without (interactive)
, it can only be called programmatically, not from M-x
(or via key-binding).
EDIT: Note that just adding "(interactive)" to a function won't necessarily make it work that way, either -- there could be many reasons functions are not interactive. Scoping, dependencies, parameters, etc.
Further more it’s worth mentioning, that interactive
's main purpose in an interactive context (e.g. when user calls function with key binding) let user specify function arguments that otherwise could be only given programmatically.
For instance, consider function sum
returns sum of two numbers.
(defun sum (a b)
(+ a b))
You may call it by (sum 1 2)
but you can do it only in a Lisp program (or in a REPL). If you use the interactive
special form in your function, you can ask the user for the arguments.
(defun sum (a b)
(interactive
(list
(read-number "First num: ")
(read-number "Second num: ")))
(+ a b))
Now M-x sum
will let you type two numbers in the minibuffer, and you can still do (sum 1 2)
as well.
interactive
should return a list that would be used as the argument list if function called interactively.