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.

See also:

Using `interactive' with a String Argument

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."
      (message "Hello World!"))

; ‘M-x hello’ calls command ‘hello’ interactively.

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 ‘interactive’, see ‘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))))

Using `interactive' with a Non-String Sexp Argument

Instead of passing a literal string argument to ‘interactive’, you can pass it an EmacsLisp sexp that is evaluated when the command is called, to produce a list of the actual arguments.

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’ and ‘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 ‘read-buffer’, ‘read-string’, and ‘completing-read’.

The following pairs of ‘interactive’ specs are equivalent:

  (defun bar (arg)
    (interactive "p")
  (defun bar (arg)
      (list (prefix-numeric-value current-prefix-arg))
  (defun foo (arg buf)
    (interactive "P\nbBuffer: ")
  (defun foo (arg buf)
      (list current-prefix-arg
            (read-buffer "Buffer: " (current-buffer) t)))

CategoryCode CategoryGlossary