ErgoEmacsEmacsLispBlogEmacsLispBuy Tutorial
Web Hosting by 1&1

Emacs Lisp Idioms: Prompting for User Input

Xah Lee, , …,

This page is a collection of emacs lisp idioms for querying for user input. For other idioms for writing interactive commands, see: Emacs Lisp Idioms (for writing interactive commands).

Get User Input as Arguments

Often you want a command that prompts user to enter some input.

Use this code (interactive "‹single letter code›‹promp string›"). Example:

(defun query-friend-name (x)
  "…"
  (interactive "sEnter friend's name: ")
  (message "Name: %s" x)
)

The line (interactive "sEnter friend's name:") will ask user to input something, taken as string, and emacs will pass it as the value of your command's argument.

The interactive can be used to get other types of input. Here are some basic examples.

The prompt text can follow the single-letter code string.

If your function takes multiple inputs, you can promp user multiple times, using a single interactive call, by joining the promp code string with \n in between, like this:

(defun query-user (x y)
  "…"
  (interactive "sEnter friend's name: \nnEnter friend's age: ")
  (message "Name is: %s, Age is: %d" x y)
)

(info "(elisp) Defining Commands")

Getting Argument from universal-argument 【Ctrl+u】

The (interactive "P") will pass the arg from universal-argument as your command's first argument.

See: Emacs Lisp: Writing Command to Accept universal-argument.

Getting User Input with Name Completion and Input History

Some commands provide input history, so that user can use key to enter previous input. (⁖ shell-commandAlt+!】) Also, some commands provide name completion (⁖ “dired” 【Ctrl+x d】).

The most useful functions for getting user input with completion or history support are: {read-string, read-file-name, read-directory-name, read-regexp}.

These can be used together with interactive. You can call interactive without any special code, but have it return a list. The elements of this list will be fed to your function. Examples:

(defun ff (arg)
  "Prompt user to enter a string, with input history support."
  (interactive (list (read-string "Your name is:")) )
  (message "String is 「%s」." arg) )

(defun ff (arg)
  "Prompt user to enter a file path, with file name completion and input history support."
  (interactive (list (read-file-name "Open directory:")) )
  (message "Path is 「%s」." arg) )

(defun ff (arg)
  "Prompt user to enter a elisp regex and input history support."
  (interactive (list (read-regexp "Type a regex:")) )
  (message "Regex is 「%s」." arg) )

The most general command is read-from-minibuffer. All the above are implemented on top of it.

(info "(elisp) Minibuffers")

Query User for Yes/No

(if (y-or-n-p "Do it?")
    (progn
      ;; code to do something here
    )
  (progn
    ;; code if user answered no.
  )
)

The y-or-n-p will ask the user to type a “y” or “n” character.

(info "(elisp) Yes-or-No Queries")

Summery

blog comments powered by Disqus