A command is a function that the user can call by name or by a key. Commands are grouped by modes, which change the key bindings, the syntax table, the highlighting and the hooks of a buffer. This page describes the syntax that makes a function a command, the keymap and key notation, the forms that define major and minor modes, hooks and timers.
Interactive commands
A function becomes a command when its body holds an (interactive …) form, normally right after the documentation string. The form does nothing when the function is called from Lisp. When the command is called interactively, the argument of interactive says how to compute the arguments of the function. It is either a string or a Lisp form.
(defun my-insert-stars (count)
"Insert COUNT asterisks at point."
(interactive "p")
(insert (make-string count ?*)))
In the string form, each argument is described by one code letter at the start of a line, optionally followed by a prompt. Lines are separated by a newline (\n). A prompt that ends with a space is conventional.
(interactive "sSearch for: \nnCount: ")
| Code | Argument |
|---|---|
a | a function name (symbol with a function definition), read with completion |
b | the name of an existing buffer |
B | a buffer name; the buffer need not exist |
c | a character |
C | a command name |
d | the position of point, as a number; no input is read |
D | a directory name |
e | the event that invoked the command, usually a mouse event; no input is read |
f | the name of an existing file |
F | a file name; the file need not exist |
G | like F, but without completion |
i | an unused argument, always nil |
k | a key sequence, as a string or vector |
K | a key sequence for defining a binding (it is not translated or case-folded) |
m | the position of the mark, as a number; no input is read |
M | a string read with the current input method |
n | a number, read in the minibuffer |
N | the numeric prefix argument; if there is none, a number is read as for n |
p | the numeric prefix argument; no input is read |
P | the raw prefix argument; no input is read |
r | the region: two arguments, the smaller position first |
s | a string |
S | a symbol |
U | the up-event of the last mouse down-event, or nil |
v | the name of a variable that is a user option |
x | a Lisp expression, read but not evaluated |
X | a Lisp expression, read and evaluated |
z | a coding system name |
Z | a coding system name if there is a prefix argument, otherwise nil |
R | the beginning and end of the region when it is active, otherwise nil twice (Emacs 31); the same as (list (use-region-beginning) (use-region-end)) |
Three characters may come before a code letter:
| Mark | Effect |
|---|---|
* | signal an error if the buffer is read-only |
@ | select the window of the first mouse event in the key sequence |
^ | if the command was invoked by a shift-translated key, activate the mark as shift-selection does |
The letters that read from the minibuffer are covered on Minibuffer.
The list form and the modes list
When the argument of interactive is not a string, it is a form that is evaluated and must return the list of arguments. This lets a command compute values or read input with any function.
(defun my-delete-region-or-line (beg end)
(interactive
(if (use-region-p)
(list (region-beginning) (region-end))
(list (line-beginning-position) (line-beginning-position 2))))
(delete-region beg end))
After the argument, interactive accepts a list of mode symbols (Emacs 28). It says in which major or minor modes the command is meant to be used. Completion on M-x can then hide the command in other buffers, and the command-modes property records the list.
(defun my-sort-entries ()
(interactive nil my-list-mode)
(sort-lines nil (point-min) (point-max)))
The manual describes the way the modes list is used by read-extended-command-predicate. Other helper functions are listed below.
| Function or variable | Use |
|---|---|
called-interactively-p | true when the calling function was invoked as a command; the argument 'any is the usual choice |
call-interactively | call a command, computing its arguments from its interactive form |
funcall-interactively | call a function with given arguments, but make called-interactively-p return true |
command-execute | run a command as if typed; also runs keyboard macros and string or vector values |
commandp | true when the object can be called as a command |
this-command, last-command | the command being run, and the one before it; commands compare them to know when they are repeated |
real-this-command | the command as read from the key, before a command may have changed this-command |
current-prefix-arg, prefix-arg | the prefix argument of the current command, and the one for the next |
prefix-numeric-value | convert a raw prefix argument to a number |
A raw prefix argument is nil (none), a number (from M-3 or C-u 3), a list such as (4) or (16) (from C-u and C-u C-u), or the symbol - (from M--). The code p converts it by prefix-numeric-value, where (4) becomes 4 and - becomes -1.
Key sequences and events
Emacs turns input into events. A key sequence is a string or vector of events.
| Event | Form |
|---|---|
| character | an integer. The low bits are the character code. Modifier bits are added above them: Meta is 227, Control 226, Shift 225, Hyper 224, Super 223, Alt 222. The characters C-a to C-z are the ASCII control codes 1 to 26. |
| function key | a symbol such as f1, return, home, left, delete; a modified one is a symbol with a prefix, C-f1 or M-return |
| mouse event | a list (TYPE POSITION …), where TYPE is a symbol such as mouse-1, down-mouse-1, drag-mouse-1 or double-mouse-1 and POSITION describes the window, the buffer position and the pixel |
| other | list events such as (switch-frame FRAME) and (focus-in FRAME) |
The read syntax of characters, ?\C-x and ?\M-x, is on Lexical structure. In a string, only Meta of an ASCII character can be written (as 128 plus the code). In a vector any event can appear: [?\C-x ?\C-f], [f5], [C-f5], [remap kill-line].
Keymaps
A keymap is a list that begins with the symbol keymap. It maps events to bindings: a command, another keymap (making the event a prefix key), a string or vector (a keyboard macro), a symbol whose function cell holds one of these, or nil. A full keymap, from make-keymap, keeps character bindings in a char-table. A sparse keymap, from make-sparse-keymap, is a plain alist. The read syntax of a small one is a quoted list.
(keymap (24 keymap (6 . find-file)) (f5 . revert-buffer))
The first binding binds C-x C-f: 24 is C-x, 6 is C-f.
| Function | Use |
|---|---|
make-sparse-keymap, make-keymap | create a keymap; the optional argument is a prompt string for menus |
keymap-set | bind a key written in the key description syntax to a command (Emacs 29) |
keymap-global-set, keymap-local-set | bind in the global or the current local keymap |
keymap-lookup | find what a key does, in one map or in the active maps |
keymap-unset | remove a binding |
key-valid-p | true when a string is a valid key description |
define-key | the older function; its key is a string or vector of events, as in (define-key map (kbd "C-c a") #'my-cmd) |
kbd | turn a key description into the string or vector that define-key wants |
define-keymap | create a keymap and bind many keys at once (Emacs 29); keywords :full, :parent, :keymap, :suppress, :name, :prefix; the key :menu adds a menu |
defvar-keymap | the same, but stores the map in a variable of the given name (Emacs 29) |
set-keymap-parent | make one keymap inherit from another |
global-map, current-global-map | the keymap used in every buffer |
use-local-map, current-local-map | set or return the buffer’s local keymap, usually a major mode’s map |
The key description syntax of keymap-set is a string of words separated by spaces. Each word is a key, with optional modifier prefixes: C-x, M-a, s-<f5>, C-M-<return>. Function keys are written in angle brackets, <f5>. Special names are RET, TAB, SPC, ESC, DEL and LFD. The prefix letters are A-, C-, H-, M-, s- and S-.
(defvar-keymap my-mode-map
:doc "Keymap for `my-mode'."
:parent special-mode-map
"C-c C-c" #'my-mode-commit
"<f5>" #'my-mode-refresh
"n" #'my-mode-next)
(keymap-global-set "C-c m" #'my-menu)
Lookup order
For a key typed in a buffer, Emacs looks in these keymaps and uses the first that gives a binding:
- the
keymaptext or overlay property at point, andoverriding-local-maporoverriding-terminal-local-mapwhen they are set (they replace the next two) - the maps of the minor modes that are on, in the order of
minor-mode-map-alistandminor-mode-overriding-map-alist(alsoemulation-mode-map-alists, which come first) - the buffer’s local map (the major mode’s map)
- the global map
A binding for the event remap followed by a command name, as in [remap kill-line], replaces that command wherever it would otherwise be found by its own keys.
Menus
A menu is a keymap with a prompt string, whose bindings are written (EVENT ITEM-STRING . COMMAND) under the pseudo event menu-bar. The macro easy-menu-define is the usual way to write one: (easy-menu-define my-menu my-mode-map "Doc." '("My" ["Run" my-run t])). Each item is a vector of name, command and an enabling form.
Major modes
A buffer has one major mode, held in the buffer-local variable major-mode. The default is fundamental-mode, which has no special behaviour. Modes for text derive from text-mode, programming modes from prog-mode, and modes whose buffers are read-only views from special-mode. The macro define-derived-mode defines one.
(define-derived-mode my-mode prog-mode "My"
"Major mode for My files."
:syntax-table my-mode-syntax-table
:abbrev-table nil
(setq-local comment-start "# ")
(setq-local font-lock-defaults '(my-font-lock-keywords))
(setq-local indent-line-function #'my-indent-line))
The arguments are the new mode, its parent (nil for none), the mode-line name and an optional documentation string, then keywords and the body. The macro creates:
- the command
my-mode, which switches to the mode: it runschange-major-mode-hook, kills the local variables, calls the parent mode, setsmajor-modeandmode-name, and runs the body, then the hooks; - the hook variable
my-mode-hook, run last, after the hook of the parent; - the keymap
my-mode-map, with the parent’s map as its parent (unless already defined); - the syntax table
my-mode-syntax-tableand the abbrev tablemy-mode-abbrev-table, likewise inheriting.
The keywords are :syntax-table, :abbrev-table, :group, :after-hook (a form evaluated after the hooks) and :interactive (Emacs 28; nil makes the mode not a command). derived-mode-p tests whether the current mode is derived from a given one. The text on the mode line is chosen by mode-line-format.
Choosing a mode for a file
| Variable | Chooses the mode by |
|---|---|
auto-mode-alist | a regular expression matched against the file name, with mode symbols: ("\\.el\\'" . emacs-lisp-mode). A third element non-nil makes Emacs strip a version suffix and try again. |
magic-mode-alist | a regular expression or a function matched against the beginning of the buffer; it is checked before auto-mode-alist |
magic-fallback-mode-alist | like the previous, but checked after auto-mode-alist |
interpreter-mode-alist | the interpreter named in a #! first line |
major-mode-remap-alist | replaces a chosen mode by another, for example (c-mode . c-ts-mode); a user option (Emacs 29) |
major-mode-remap-defaults | the same, for use by packages and not by users (Emacs 30); the function major-mode-remap looks up both |
The mode cookie of the first line (-*- mode: my -*-) overrides these; see File structure.
Font-lock, syntax and indentation
Font-lock is the highlighting. A mode sets font-lock-defaults, a list whose first element is the keywords, or a list of them. The keywords variable is a list of items:
| Item | Meaning |
|---|---|
"regexp" | highlight every match with font-lock-keyword-face |
(REGEXP . FACE) | highlight matches of the regexp in the face |
(REGEXP . N) | highlight the subexpression N |
(REGEXP (N FACE) …) | several subexpressions with different faces |
(REGEXP N FACE OVERRIDE LAXMATCH) | the full form: override t replaces earlier faces, keep and prepend merge, and LAXMATCH allows a missing subexpression |
FUNCTION or (FUNCTION . …) | a function called with the search limit; it finds a match and sets the match data |
(MATCHER SUBEXP-HIGHLIGHTER …) | anchored highlighting, for items that follow a match |
The faces are in the variables font-lock-keyword-face, font-lock-function-name-face, font-lock-variable-name-face, font-lock-string-face, font-lock-comment-face, font-lock-type-face, font-lock-constant-face, font-lock-builtin-face, font-lock-warning-face and others. font-lock-add-keywords adds keywords to a mode or to the current buffer from another file.
Other elements of font-lock-defaults are KEYWORDS-ONLY (t disables string and comment highlighting by syntax), CASE-FOLD, and an alist that overrides syntax entries. The syntax table of the mode decides which text is a string or a comment; see Regexps and syntax tables. When that is not enough, syntax-propertize-function sets syntax-table text properties over a region before it is highlighted.
Indentation is done by the function in indent-line-function, which TAB calls through indent-for-tab-command. indent-region-function indents a region and electric-indent-mode triggers it on newline.
Minor modes
Any number of minor modes can be on in a buffer. Each is a command that toggles a variable with the same name as the mode (my-minor-mode), which is buffer-local unless the mode is global.
(define-minor-mode my-minor-mode
"Highlight trailing blanks."
:lighter " Tr"
:keymap (define-keymap "C-c t" #'my-trim)
(if my-minor-mode
(add-hook 'before-save-hook #'my-trim nil t)
(remove-hook 'before-save-hook #'my-trim t)))
| Keyword | Meaning |
|---|---|
:global | non-nil makes a global mode: one variable, not buffer-local |
:init-value | the initial value of the variable, normally nil |
:lighter | the string shown on the mode line, usually with a leading space |
:keymap | a keymap, or an alist of key and command, for the mode; it is stored in my-minor-mode-map and added to minor-mode-map-alist |
:variable | a place to hold the state instead of the default variable, for example (my-state . my-setter) |
:after-hook | a form evaluated after the mode hooks have run |
:interactive | nil makes the mode not a command; a list of major modes says where it is useful (Emacs 28) |
:group, :type and others | passed to the defcustom that defines the variable |
A minor mode command takes an argument: nil or a positive number turns it on, toggle flips it, and zero or a negative number turns it off. Called interactively, it toggles. The mode runs my-minor-mode-hook, and then my-minor-mode-on-hook or my-minor-mode-off-hook. define-globalized-minor-mode defines a global mode that turns another one on in every buffer, using a function named by the third argument (default: the mode itself); its :predicate keyword (Emacs 28) restricts the major modes it applies to.
Hooks
A hook is a variable that holds a list of functions to call at an event. The names end in -hook (called without arguments) or -functions (called with arguments; “abnormal” hooks).
| Function | Use |
|---|---|
add-hook HOOK FUNCTION &optional DEPTH LOCAL | add a function. DEPTH is a number from -100 to 100 (or t for 90, nil for 0) that orders the functions; smaller runs first. LOCAL non-nil changes only the buffer-local value, which holds t to mean “and the global value too”. |
remove-hook HOOK FUNCTION &optional LOCAL | remove a function |
run-hooks | run the hooks in turn, each with no arguments |
run-hook-with-args | run with arguments |
run-hook-with-args-until-success, …-until-failure | stop at the first non-nil or nil value |
run-mode-hooks | what major modes use to run their hooks, delaying them while a file is set up |
| Common hook | When it runs |
|---|---|
after-init-hook, emacs-startup-hook | after the init file is loaded; the second after the command line is processed as well |
pre-command-hook, post-command-hook | before and after every command |
find-file-hook | after a file is visited |
before-save-hook, after-save-hook | around saving a file |
kill-buffer-hook | when a buffer is killed |
change-major-mode-hook | before a major mode is changed |
MODE-hook | at the end of a mode command, for example emacs-lisp-mode-hook |
Timers
| Function | Use |
|---|---|
run-with-timer SECS REPEAT FUNCTION &rest ARGS | call a function after SECS seconds, and every REPEAT seconds if REPEAT is not nil |
run-at-time | the same, with a time of day or an absolute time |
run-with-idle-timer SECS REPEAT FUNCTION &rest ARGS | call it after Emacs has been idle for SECS seconds |
cancel-timer | stop a timer returned by the functions above |
(defvar my-timer (run-with-idle-timer 30 t #'garbage-collect))
(cancel-timer my-timer)
Not described
Known, not yet covered
- Reference: abbrevs and abbrev tables, windows, frames and display (faces, fringes, images) are named only here. The same holds for the mode-line construct and the menu and tool-bar keymaps.
- Reference: keyboard macros,
repeat-mode, input methods and the rest of the event-reading functions (read-event,read-key-sequence) are not described. - Reference: tree-sitter modes and the
treesit-*functions are not covered.
See also
- Minibuffer – reading input for the interactive codes
- Regexps and syntax tables – the syntax table of a mode
- Packages and autoloads – autoloading commands and modes
- Command Loop – the manual chapter on commands
- Keymaps – the manual chapter on keymaps
- Major and Minor Modes – the manual chapter on modes and hooks