Emacs Lisp: Get User Input

By Xah Lee. Date: . Last updated: .

Ask for File Name

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

Note:

Ask for Directory

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

Ask for String

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

Ask for Regex

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

Ask for Number

read-number
Ask user to type a number.
(defun ff ()
  "Prompt user to enter a number, with input history support."
  (interactive)
  (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 completing-read.

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

Query User for Yes/No

y-or-n-p
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?")
    (progn
      ;; code to do something here
    )
  (progn
    ;; code if user answered no.
  )
)

Reference

There are many more commands to query user input. See (info "(elisp) Minibuffers")

Emacs Lisp: Get User Input

ErgoEmacs mascot-s276x226
Buy Xah Emacs Tutorial

Practical Elisp ⭐

Writing Command

Writing Script