Go to the first, previous, next, last section, table of contents.

Make a Function Interactive

You make a function interactive by placing a list that begins with the special form interactive immediately after the documentation. A user can invoke an interactive function by typing M-x and then the name of the function; or by typing the keys to which it is bound, for example, by typing C-n for next-line or C-x h for mark-whole-buffer.

Interestingly, when you call an interactive function interactively, the value returned is not automatically displayed in the echo area. This is because you often call an interactive function for its side effects, such as moving forward by a word or line, and not for the value returned. If the returned value were displayed in the echo area each time you typed a key, it would be very distracting.

Both the use of the special form interactive and one way to display a value in the echo area can be illustrated by creating an interactive version of multiply-by-seven.

Here is the code:

(defun multiply-by-seven (number)       ; Interactive version.
  "Multiply NUMBER by seven."
  (interactive "p")
  (message "The result is %d" (* 7 number)))

You can install this code by placing your cursor after it and typing C-x C-e. The name of the function will appear in your echo area. Then, you can use this code by typing C-u and a number and then typing M-x multiply-by-seven and pressing RET. The phrase `The result is ...' followed by the product will appear in the echo area.

Speaking more generally, you invoke a function like this in either of two ways:

  1. By typing a prefix argument that contains the number to be passed, and then typing M-x and the name of the function, as with C-u 3 M-x forward-sentence; or,
  2. By typing whatever key or keychord the function is bound to, as with C-u 3 M-e.

Both the examples just mentioned work identically to move point forward three sentences. (Since multiply-by-seven is not bound to a key, it could not be used as an example of key binding.)

(See section Some Keybindings, to learn how to bind a command to a key.)

A prefix argument is passed to an interactive function by typing the META key followed by a number, for example, M-3 M-e, or by typing C-u and then a number, for example, C-u 3 M-e (if you type C-u without a number, it defaults to 4).

Go to the first, previous, next, last section, table of contents.