Emacs Lisp: Get universal-argument
This page shows you how to make your emacs lisp command accept Emacs: Universal Argument (prefix arg)
To make your command aware of universal argument, there are 3 simple ways:
- In the function body, check the builtin variable current-prefix-arg. It holds the value of universal argument.
- Add capital P as prompt string to Emacs Lisp: Interactive Form in your function. It passes the value of current-prefix-arg as your function's first parameter.
- Add capital lowercase p as prompt string to Emacs Lisp: Interactive Form in your function. It passes converted numerical value of current-prefix-arg to your function's first argument.
Example:
(defun xf (x) "print value of `current-prefix-arg'" (interactive "P") (message "%s" x))
Possible Values of Universal Argument
Here's the possible values of current-prefix-arg.
Key Input | Value of current-prefix-arg | Numerical Value |
---|---|---|
none | nil | 1 |
Ctrl+u - | Symbol - | -1 |
Ctrl+u - 2 | Number -2 | -2 |
Ctrl+u 1 | Number 1 | 1 |
Ctrl+u 4 | Number 4 | 4 |
Ctrl+u | List '(4) | 4 |
Ctrl+u Ctrl+u | List '(16) | 16 |
Ctrl+u Ctrl+u Ctrl+u | List '(64) | 64 |
(defun xg () "print `current-prefix-arg'" (interactive ) (message "%s" current-prefix-arg)) ;; try ;; M-x g ;; C-u M-x g ;; C-u C-u M-x g ;; C-u 1 M-x g ;; C-u 2 M-x g
Convert current-prefix-arg to number
The function prefix-numeric-value
converts current-prefix-arg to number.
(defun xh () "print numerical prefix arg received" (message "%s" (prefix-numeric-value current-prefix-arg) ) )