Elisp: Get User Input

By Xah Lee. Date: . Last updated: .

This page list ways to get user input.

Ask for File Name

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

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

Note, many query user input commands support command history. Command history means, user can press key to use previous input. (e.g. Alt+x shell-command) Also, some commands provide name completion (e.g. Alt+x dired).

Ask for Directory

Ask user to give a directory name.
(defun ff ()
  "Prompt user to enter a dir path, with path completion and input history support."
  (message "Path is %s" (read-directory-name "Directory:")))

Ask for String

Ask user to type a string.
(defun ff ()
  "Prompt user to enter a string, with input history support."
  (message "String is %s" (read-string "Enter your name:")))

Ask for Regex String

Ask user to type a regex.
(defun ff ()
  "Prompt user to enter a elisp regex, with input history support."
  (message "Regex is %s" (read-regexp "Type a regex:")))

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

(info "(elisp) Minibuffers")

Ask for Number

Ask user to type a number.
(defun ff ()
  "Prompt user to enter a number, with input history support."
  (let (n)
    (setq n (read-number "Type a number: " 10))
    (message "Number is %s" n)))

Select from a List

The best way to ask user to select from a list, is by ido-completing-read.

(require 'ido)

(defun my-pick-one ()
  "Prompt user to pick a choice from a list."
  (let ((choices '("cat" "dog" "dragon" "tiger")))
    (message "%s" (ido-completing-read "Open bookmark:" choices ))))

Query User for Yes/No

Ask user a yes or no question. Return t if user types “y” and nil if user types “n”.
(if (y-or-n-p "Do it?")
      ;; code to do something here
    ;; code if user answered no.

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

Get User Input as Function's Arguments

Elisp: Interactive Form

Get User Input from universal-argument

Elisp: Get universal-argument

Practical Emacs Lisp


Basic Functions

Writing Command

Writing Script