Emacs Lisp: Get User Input

By Xah Lee. Date: . Last updated: .

This page is a collection of emacs lisp idioms for getting user input.

Get User Input as Function's Arguments

Emacs Lisp: Interactive Form

Get Argument from universal-argument

Emacs Lisp: Get universal-argument

Get User Input with Name Completion and Input History

Some commands provide input history, so that user can use key to enter previous input. (For example, shell-command) Also, some commands provide name completion (For example, dired).

The most useful functions for getting user input with completion or history support are:

Here's a example:

(defun ff ()
  "Prompt user to enter a file name, with completion and history support."
  (let ((x (read-file-name "Enter file name:")))
    (message "String is %s." x)))

Try it. You'll have file name completion feature. Pressing will show previous file name you used.

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."
    (read-string "Enter your name:")))
  (message "String is %s." arg))
(defun ff (arg)
  "Prompt user to enter a file path, with file name completion and input history support."
    (read-file-name "Open directory:")))
  (message "Path is %s." arg))
(defun ff (arg)
  "Prompt user to enter a elisp regex and input history support."
    (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

Sometimes you need to query user with a simple yes/no answer. Here's how:

(if (y-or-n-p "Do it?")
      ;; code to do something here
    ;; 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")

Like it? Buy Xah Emacs Tutorial. Thanks.