Emacs Lisp: Interactive Form

By Xah Lee. Date: . Last updated: .

Purpose of Interactive Form

The interactive has 2 purposes.

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))

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 "Name: %d" x))

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))

Ways to Call Interactive

There are 3 forms of interactive:

(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.

(defun ask-name-and-age (x y)
  "Ask name and age"
  (interactive
"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 Emacs Lisp: Get User Input]

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

There are about 35 string codes for interactive string.

Reference

Emacs Lisp: Get User Input


Practical Elisp ⭐

Writing Command

Text Processing

Get User Input

File/Buffer

Writing Script