Elisp: Interactive Form

By Xah Lee. Date: . Last updated: .

Purpose of Interactive Form

The interactive has 2 purposes.

Ways to Call Interactive

There are 3 forms of interactive:


No argument. This simply makes the function as command, and does not pass any argument to the function.

(interactive string)

The first character in beginning of each line in string tells emacs how to interpret the user input (such as string, number, file name, directory name, regex, lisp expression, key stroke, etc) and what datatype (string, number, etc) it should be converted to as the function's argument. The rest of string are used as prompt.

There are about 35 string codes for interactive string.

(defun ask-name-and-age (x y)
  "Ask name and age"
"sEnter name:
nEnter age:")
  (message "Name is: %s, Age is: %d" x y))
(interactive list)

This is the most general way to fill function arguments when a function is called interactively. This list's elements are passed as arguments to the function. list can be any lisp expression, as long as it return a list, and it can contain code to promt users by calling read-string, read-file-name, etc. [see Elisp: Get User Input]

(defun ask-name-and-age2 (x y)
  "Ask name and age"
    (read-string "Enter name:")
    (read-number "Enter age:")))
  (message "Name is: %s, Age is: %d" x y))

Example: Get String as Argument

(interactive "sprompt_string")

Prompt user, pass answer to the function's first argument, as string.

(defun ask-name (x)
  "Ask name."
  (interactive "sEnter name: ")
  (message "Name: %s" x))

Example: Get Number as Argument

(interactive "nprompt_string")

Prompt user, pass answer to the function's first argument, as number.

(defun ask-age (x)
  "Ask age."
  (interactive "nEnter age: ")
  (message "Age: %d" x))

Example: Get Region Begin End Positions as Argument

(interactive "r")

Pass Region begin position and end position as arguments to function.

(defun print-region-boundary (x y)
  "Prints region start and end positions"
  (interactive "r")
  (message "Region begin at: %d, end at: %d" x y))


Elisp, Get User Input