A Lisp function becomes a command when its body contains, at top level, a form that calls the special form `
(interactive...)’. This special form does nothing when executed, but its presence in the function definition indicates that interactive calling is permitted. Its argument controls the reading of the function arguments in an interactive call.
Here is a simple example defining a command that displays a message:
(defun hello () "Hello World and you can call it via M-x hello." (interactive) (message "Hello World!"))
‘M-x hello’ calls command
Example of a command that reads a string argument:
(defun hello (someone) "Say hello to SOMEONE via M-x hello." (interactive "sWho do you want to say hello to? ") (message "Hello %s!" someone))
For a complete list of arguments to
‘C-h f interactive’ or the “Defining Commands” section of the EmacsLispManual (
‘C-h i m elisp RET m Defining SPC Commands RET’).
To use multiple arguments, separate their
‘interactive’ entries with a newline:
(defun multiple-hello (someone num) "Say hello to SOMEONE via M-x hello, for NUM times." (interactive "sWho do you want to say hello to? \nnHow many times? ") (dotimes (i num) (insert (format "Hello %s!\n" someone))))
This is useful when you need to do more than is offered by the predefined
‘interactive’ string constructs.
To get the effect of the string constructs
‘p’, respectively, use variable
‘current-prefix-arg’ and function
‘prefix-numeric-value’ applied to that variable.
To get the effect of
‘interactive’ string codes that read user input, use Lisp functions that read input, such as
The following pairs of
‘interactive’ specs are equivalent:
(defun bar (arg) (interactive "p") ...)
(defun bar (arg) (interactive (list (prefix-numeric-value current-prefix-arg)) ...)
(defun foo (arg buf) (interactive "P\nbBuffer: ") ...)
(defun foo (arg buf) (interactive (list current-prefix-arg (read-buffer "Buffer: " (current-buffer) t))) ...)