Emacs Lisp: Get User Input
This page is a collection of emacs lisp idioms for getting user input.
Get User Input as Function's Arguments
Get Argument from 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,
Also, some commands provide name completion (For example,
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." (interactive) (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." (interactive (list (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." (interactive (list (read-file-name "Open directory:"))) (message "Path is %s." arg))
(defun ff (arg) "Prompt user to enter a elisp regex and input history support." (interactive (list (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.
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?") (progn ;; code to do something here ) (progn ;; code if user answered no. ) )
y-or-n-p will ask the user to type a “y” or “n” character.
or, buy something from Best Keyboard for Emacs