Elisp: Get User Input
This page list ways to get user input.
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:")))
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
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 your name:")))
Ask for Regex String
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:")))
The most general command is read-from-minibuffer
. All the above are implemented on top of it.
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 ido-completing-read
.
(require 'ido) (defun my-pick-one () "Prompt user to pick a choice from a list." (interactive) (let ((choices '("cat" "dog" "dragon" "tiger"))) (message "%s" (ido-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. ) )
(info "(elisp) Yes-or-No Queries")