Emacs Lisp: Interactive Form
Purpose of Interactive Form
interactive has 2 purposes.
- Make function into interactive command. (So it can be called by
execute-extended-command【Alt + x】)
- A mechanism for passing arguments to function when called interactively.
Get String as Argument
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
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
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
No argument. This simply makes the function as command, and does not pass any argument to the function.
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))
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-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