Elisp: Get User Input
Get User Input with Name Completion and Input History
The most useful functions for getting user input with completion or command history support are:
read-string
read-file-name
read-directory-name
read-regexp
Command history means, user can press ↑ key to enter previous input. (e.g. Alt+x shell-command
)
Also, some commands provide name completion (e.g. Alt+x dired
).
Prompt for File Name
read-file-name
example:
(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.
Prompt for Directory
read-directory-name
example:
(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:")))
Prompt for String
read-string
example:
(defun ff () "Prompt user to enter a string, with input history support." (interactive) (message "String is %s" (read-string "Enter your name:")))
Prompt for Regex String
read-regexp
example:
(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.
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 “y or n” question. Return t if answer is “y” and nil if it is “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")
Get User Input as Function's Arguments
Get User Input from universal-argument
If you have a question, put $5 at patreon and message me on xah discord.
Or support me by Buy Xah Emacs Tutorial