This section describes key bindings, which map keys to commands, and keymaps, which record key bindings. It also explains how to customize key bindings.
Recall that a command is a Lisp function whose definition provides for interactive use. Like every Lisp function, a command has a function name which usually consists of lower-case letters and hyphens.
The bindings between key sequences and command functions are recorded in data structures called keymaps. Emacs has many of these, each used on particular occasions.
Recall that a key sequence (key, for short) is a sequence of input events that have a meaning as a unit. Input events include characters, function keys and mouse buttons--all the inputs that you can send to the computer with your terminal. A key sequence gets its meaning from its binding, which says what command it runs. The function of keymaps is to record these bindings.
The global keymap is the most important keymap because it is always in effect. The global keymap defines keys for Fundamental mode; most of these definitions are common to most or all major modes. Each major or minor mode can have its own keymap which overrides the global definitions of some keys.
For example, a self-inserting character such as g is self-inserting because the global keymap binds it to the command self-insert-command. The standard Emacs editing characters such as C-a also get their standard meanings from the global keymap. Commands to rebind keys, such as M-x global-set-key, actually work by storing the new binding in the proper place in the global map. Section 32.4.5.
Meta characters work differently; Emacs translates each Meta character into a pair of characters starting with ESC. When you type the character M-a in a key sequence, Emacs replaces it with ESC a. A meta key comes in as a single input event, but becomes two events for purposes of key bindings. The reason for this is historical, and we might change it someday.
Most modern keyboards have function keys as well as character keys. Function keys send input events just as character keys do, and keymaps can have bindings for them.
On many terminals, typing a function key actually sends the computer a sequence of characters; the precise details of the sequence depends on which function key and on the model of terminal you are using. (Often the sequence starts with ESC [.) If Emacs understands your terminal type properly, it recognizes the character sequences forming function keys wherever they occur in a key sequence (not just at the beginning). Thus, for most purposes, you can pretend the function keys reach Emacs directly and ignore their encoding as character sequences.
Mouse buttons also produce input events. These events come with other data--the window and position where you pressed or released the button, and a time stamp. But only the choice of button matters for key bindings; the other data matters only if a command looks at it. (Commands designed for mouse invocation usually do look at the other data.)
A keymap records definitions for single events. Interpreting a key sequence of multiple events involves a chain of keymaps. The first keymap gives a definition for the first event; this definition is another keymap, which is used to look up the second event in the sequence, and so on.
Key sequences can mix function keys and characters. For example, C-x SELECT is meaningful. If you make SELECT a prefix key, then SELECT C-n makes sense. You can even mix mouse events with keyboard events, but we recommend against it, because such sequences are inconvenient to type in.
As a user, you can redefine any key; but it might be best to stick to key sequences that consist of C-c followed by a letter. These keys are "reserved for users," so they won't conflict with any properly designed Emacs extension. The function keys F5 through F9 are also reserved for users. If you redefine some other key, your definition may be overridden by certain extensions or major modes which redefine the same key.
A prefix key such as C-x or ESC has its own keymap, which holds the definition for the event that immediately follows that prefix.
The definition of a prefix key is usually the keymap to use for looking up the following event. The definition can also be a Lisp symbol whose function definition is the following keymap; the effect is the same, but it provides a command name for the prefix key that can be used as a description of what the prefix key is for. Thus, the binding of C-x is the symbol Ctl-X-Prefix, whose function definition is the keymap for C-x commands. The definitions of C-c, C-x, C-h and ESC as prefix keys appear in the global map, so these prefix keys are always available.
Aside from ordinary prefix keys, there is a fictitious "prefix key" which represents the menu bar; see , for special information about menu bar key bindings. Mouse button events that invoke pop-up menus are also prefix keys; see , for more details.
Some prefix keymaps are stored in variables with names:
ctl-x-map is the variable name for the map used for characters that follow C-x.
help-map is for characters that follow C-h.
esc-map is for characters that follow ESC. Thus, all Meta characters are actually defined by this map.
ctl-x-4-map is for characters that follow C-x 4.
mode-specific-map is for characters that follow C-c.
So far we have explained the ins and outs of the global map. Major modes customize Emacs by providing their own key bindings in local keymaps. For example, C mode overrides TAB to make it indent the current line for C code. Portions of text in the buffer can specify their own keymaps to substitute for the keymap of the buffer's major mode.
Minor modes can also have local keymaps. Whenever a minor mode is in effect, the definitions in its keymap override both the major mode's local keymap and the global keymap.
The local keymaps for Lisp mode and several other major modes always exist even when not in use. These are kept in variables named lisp-mode-map and so on. For major modes less often used, the local keymap is normally constructed only when the mode is used for the first time in a session. This is to save space. If you wish to change one of these keymaps, you must use the major mode's mode hook--see below.
All minor mode keymaps are created in advance. There is no way to defer their creation until the first time the minor mode is enabled.
A local keymap can locally redefine a key as a prefix key by defining it as a prefix keymap. If the key is also defined globally as a prefix, then its local and global definitions (both keymaps) effectively combine: both of them are used to look up the event that follows the prefix key. Thus, if the mode's local keymap defines C-c as another keymap, and that keymap defines C-z as a command, this provides a local meaning for C-c C-z. This does not affect other sequences that start with C-c; if those sequences don't have their own local bindings, their global bindings remain in effect.
Another way to think of this is that Emacs handles a multi-event key sequence by looking in several keymaps, one by one, for a binding of the whole key sequence. First it checks the minor mode keymaps for minor modes that are enabled, then it checks the major mode's keymap, and then it checks the global keymap. This is not precisely how key lookup works, but it's good enough for understanding ordinary circumstances.
To change the local bindings of a major mode, you must change the mode's local keymap. Normally you must wait until the first time the mode is used, because most major modes don't create their keymaps until then. If you want to specify something in your ~/.emacs file to change a major mode's bindings, you must use the mode's mode hook to delay the change until the mode is first used.
For example, the command texinfo-mode to select Texinfo mode runs the hook texinfo-mode-hook. Here's how you can use the hook to add local bindings (not very useful, we admit) for C-c n and C-c p in Texinfo mode:
(add-hook 'texinfo-mode-hook '(lambda () (define-key texinfo-mode-map "\C-cp" 'backward-paragraph) (define-key texinfo-mode-map "\C-cn" 'forward-paragraph)))
The minibuffer has its own set of local keymaps; they contain various completion and exit commands.
minibuffer-local-map is used for ordinary input (no completion).
minibuffer-local-ns-map is similar, except that SPC exits just like RET. This is used mainly for Mocklisp compatibility.
minibuffer-local-completion-map is for permissive completion.
minibuffer-local-must-match-map is for strict completion and for cautious completion.
The way to redefine an Emacs key is to change its entry in a keymap. You can change the global keymap, in which case the change is effective in all major modes (except those that have their own overriding local definitions for the same key). Or you can change the current buffer's local map, which affects all buffers using the same major mode.
Define key globally to run cmd.
Define key locally (in the major mode now in effect) to run cmd.
Make key undefined in the global map.
Make key undefined locally (in the major mode now in effect).
For example, suppose you like to execute commands in a subshell within an Emacs buffer, instead of suspending Emacs and executing commands in your login shell. Normally, C-z is bound to the function suspend-emacs (when not using the X Window System), but you can change C-z to invoke an interactive subshell within Emacs, by binding it to shell as follows:
M-x global-set-key RET C-z shell RET
global-set-key reads the command name after the key. After you press the key, a message like this appears so that you can confirm that you are binding the key you want:
Set key C-z to command:
You can redefine function keys and mouse events in the same way; just type the function key or click the mouse when it's time to specify the key to rebind.
You can rebind a key that contains more than one event in the same way. Emacs keeps reading the key to rebind until it is a complete key (that is, not a prefix key). Thus, if you type C-f for key, that's the end; the minibuffer is entered immediately to read cmd. But if you type C-x, another character is read; if that is 4, another character is read, and so on. For example,
M-x global-set-key RET C-x 4 $ spell-other-window RET
redefines C-x 4 $ to run the (fictitious) command spell-other-window.
The two-character keys consisting of C-c followed by a letter are reserved for user customizations. Lisp programs are not supposed to define these keys, so the bindings you make for them will be available in all major modes and will never get in the way of anything.
You can remove the global definition of a key with global-unset-key. This makes the key undefined; if you type it, Emacs will just beep. Similarly, local-unset-key makes a key undefined in the current major mode keymap, which makes the global definition (or lack of one) come back into effect in that major mode.
If you have redefined (or undefined) a key and you subsequently wish to retract the change, undefining the key will not do the job--you need to redefine the key with its standard definition. To find the name of the standard definition of a key, go to a Fundamental mode buffer and use C-h c. The documentation of keys in this manual also lists their command names.
If you want to prevent yourself from invoking a command by mistake, it is better to disable the command than to undefine the key. A disabled command is less work to invoke when you really want to. Section 32.4.11.
If you have a set of key bindings that you like to use all the time, you can specify them in your .emacs file by using their Lisp syntax. (Section 32.7.)
The simplest method for doing this works for ASCII characters and Meta-modified ASCII characters only. This method uses a string to represent the key sequence you want to rebind. For example, here's how to bind C-z to shell:
(global-set-key "\C-z" 'shell)
This example uses a string constant containing one character, C-z. The single-quote before the command name, shell, marks it as a constant symbol rather than a variable. If you omit the quote, Emacs would try to evaluate shell immediately as a variable. This probably causes an error; it certainly isn't what you want.
Here is another example that binds a key sequence two characters long:
(global-set-key "\C-xl" 'make-symbolic-link)
When the key sequence includes function keys or mouse button events, or non-ASCII characters such as C-= or H-a, you must use the more general method of rebinding, which uses a vector to specify the key sequence.
The way to write a vector in Emacs Lisp is with square brackets around the vector elements. Use spaces to separate the elements. If an element is a symbol, simply write the symbol's name--no other delimiters or punctuation are needed. If a vector element is a character, write it as a Lisp character constant: ? followed by the character as it would appear in a string.
Here are examples of using vectors to rebind C-= (a control character outside of ASCII), H-a (a Hyper character; ASCII doesn't have Hyper at all), F7 (a function key), and C-Mouse-1 (a keyboard-modified mouse button):
(global-set-key [?\C-=] 'make-symbolic-link) (global-set-key [?\H-a] 'make-symbolic-link) (global-set-key [f7] 'make-symbolic-link) (global-set-key [C-mouse-1] 'make-symbolic-link)
You can use a vector for the simple cases too. Here's how to rewrite the first two examples, above, to use vectors:
(global-set-key [?\C-z] 'shell) (global-set-key [?\C-x ?l] 'make-symbolic-link)
Key sequences can contain function keys as well as ordinary characters. Just as Lisp characters (actually integers) represent keyboard characters, Lisp symbols represent function keys. If the function key has a word as its label, then that word is also the name of the corresponding Lisp symbol. Here are the conventional Lisp names for common function keys:
Cursor arrow keys.
Other cursor repositioning keys.
Miscellaneous function keys.
Numbered function keys (across the top of the keyboard).
Keypad keys (to the right of the regular keyboard), with names or punctuation.
Keypad keys with digits.
Keypad PF keys.
These names are conventional, but some systems (especially when using X) may use different names. To make certain what symbol is used for a given function key on your terminal, type C-h c followed by that key.
A key sequence which contains function key symbols (or anything but ASCII characters) must be a vector rather than a string. The vector syntax uses spaces between the elements, and square brackets around the whole vector. Thus, to bind function key f1 to the command rmail, write the following:
(global-set-key [f1] 'rmail)
To bind the right-arrow key to the command forward-char, you can use this expression:
(global-set-key [right] 'forward-char)
This uses the Lisp syntax for a vector containing the symbol right. (This binding is present in Emacs by default.)
Section 32.4.6, for more information about using vectors for rebinding.
You can mix function keys and characters in a key sequence. This example binds C-x NEXT to the command forward-page.
(global-set-key [?\C-x next] 'forward-page)
where ?\C-x is the Lisp character constant for the character C-x. The vector element next is a symbol and therefore does not take a question mark.
You can use the modifier keys CTRL, META, HYPER, SUPER, ALT and SHIFT with function keys. To represent these modifiers, add the strings C-, M-, H-, s-, A- and S- at the front of the symbol name. Thus, here is how to make Hyper-Meta-RIGHT move forward a word:
(global-set-key [H-M-right] 'forward-word)
TAB, RET, BS, LFD, ESC and DEL started out as names for certain ASCII control characters, used so often that they have special keys of their own. Later, users found it convenient to distinguish in Emacs between these keys and the "same" control characters typed with the CTRL key.
Emacs distinguishes these two kinds of input, when the keyboard reports these keys to Emacs. It treats the "special" keys as function keys named tab, return, backspace, linefeed, escape, and delete. These function keys translate automatically into the corresponding ASCII characters if they have no bindings of their own. As a result, neither users nor Lisp programs need to pay attention to the distinction unless they care to.
If you do not want to distinguish between (for example) TAB and C-i, make just one binding, for the ASCII character TAB (octal code 011). If you do want to distinguish, make one binding for this ASCII character, and another for the "function key" tab.
With an ordinary ASCII terminal, there is no way to distinguish between TAB and C-i (and likewise for other such pairs), because the terminal sends the same character in both cases.
If your keyboard has keys that send non-ASCII characters, such as accented letters, rebinding these keys is a bit tricky. There are two solutions you can use. One is to specify a keyboard coding system, using set-keyboard-coding-system (Section 20.8). Then you can bind these keys in the usual way, like this:
(global-set-key [?char] 'some-function)
Type C-q followed by the key you want to bind, to insert char.
If you don't specify the keyboard coding system, that approach won't work. Instead, you need to find out the actual code that the terminal sends. The easiest way to do this in Emacs is to create an empty buffer with C-x b temp RET, make it unibyte with M-x toggle-enable-multibyte-characters RET, then type the key to insert the character into this buffer.
Move point before the character, then type C-x =. This displays a message in the minibuffer, showing the character code in three ways, octal, decimal and hexadecimal, all within a set of parentheses. Use the second of the three numbers, the decimal one, inside the vector to bind:
(global-set-key [decimal-code] 'some-function)
If you bind 8-bit characters like this in your init file, you my find it convenient to specify that it is unibyte. Section 20.2.
Emacs uses Lisp symbols to designate mouse buttons, too. The ordinary mouse events in Emacs are click events; these happen when you press a button and release it without moving the mouse. You can also get drag events, when you move the mouse while holding the button down. Drag events happen when you finally let go of the button.
The symbols for basic click events are mouse-1 for the leftmost button, mouse-2 for the next, and so on. Here is how you can redefine the second mouse button to split the current window:
(global-set-key [mouse-2] 'split-window-vertically)
The symbols for drag events are similar, but have the prefix drag- before the word mouse. For example, dragging the first button generates a drag-mouse-1 event.
You can also define bindings for events that occur when a mouse button is pressed down. These events start with down- instead of drag-. Such events are generated only if they have key bindings. When you get a button-down event, a corresponding click or drag event will always follow.
If you wish, you can distinguish single, double, and triple clicks. A double click means clicking a mouse button twice in approximately the same place. The first click generates an ordinary click event. The second click, if it comes soon enough, generates a double-click event instead. The event type for a double-click event starts with double-: for example, double-mouse-3.
This means that you can give a special meaning to the second click at the same place, but it must act on the assumption that the ordinary single click definition has run when the first click was received.
This constrains what you can do with double clicks, but user interface designers say that this constraint ought to be followed in any case. A double click should do something similar to the single click, only "more so." The command for the double-click event should perform the extra work for the double click.
If a double-click event has no binding, it changes to the corresponding single-click event. Thus, if you don't define a particular double click specially, it executes the single-click command twice.
Emacs also supports triple-click events whose names start with triple-. Emacs does not distinguish quadruple clicks as event types; clicks beyond the third generate additional triple-click events. However, the full number of clicks is recorded in the event list, so you can distinguish if you really want to. We don't recommend distinct meanings for more than three clicks, but sometimes it is useful for subsequent clicks to cycle through the same set of three meanings, so that four clicks are equivalent to one click, five are equivalent to two, and six are equivalent to three.
Emacs also records multiple presses in drag and button-down events. For example, when you press a button twice, then move the mouse while holding the button, Emacs gets a double-drag- event. And at the moment when you press it down for the second time, Emacs gets a double-down- event (which is ignored, like all button-down events, if it has no binding).
The variable double-click-time specifies how long may elapse between clicks that are recognized as a pair. Its value is measured in milliseconds. If the value is nil, double clicks are not detected at all. If the value is t, then there is no time limit.
The symbols for mouse events also indicate the status of the modifier keys, with the usual prefixes C-, M-, H-, s-, A- and S-. These always precede double- or triple-, which always precede drag- or down-.
A frame includes areas that don't show text from the buffer, such as the mode line and the scroll bar. You can tell whether a mouse button comes from a special area of the screen by means of dummy "prefix keys." For example, if you click the mouse in the mode line, you get the prefix key mode-line before the ordinary mouse-button symbol. Thus, here is how to define the command for clicking the first button in a mode line to run scroll-up:
(global-set-key [mode-line mouse-1] 'scroll-up)
Here is the complete list of these dummy prefix keys and their meanings:
The mouse was in the mode line of a window.
The mouse was in the vertical line separating side-by-side windows. (If you use scroll bars, they appear in place of these vertical lines.)
The mouse was in a vertical scroll bar. (This is the only kind of scroll bar Emacs currently supports.)
You can put more than one mouse button in a key sequence, but it isn't usual to do so.
Disabling a command marks the command as requiring confirmation before it can be executed. The purpose of disabling a command is to prevent beginning users from executing it by accident and being confused.
An attempt to invoke a disabled command interactively in Emacs displays a window containing the command's name, its documentation, and some instructions on what to do immediately; then Emacs asks for input saying whether to execute the command as requested, enable it and execute it, or cancel. If you decide to enable the command, you are asked whether to do this permanently or just for the current session. Enabling permanently works by automatically editing your .emacs file.
The direct mechanism for disabling a command is to put a non-nil disabled property on the Lisp symbol for the command. Here is the Lisp program to do this:
(put 'delete-region 'disabled t)
If the value of the disabled property is a string, that string is included in the message printed when the command is used:
(put 'delete-region 'disabled "It's better to use `kill-region' instead.\n")
You can make a command disabled either by editing the .emacs file directly or with the command M-x disable-command, which edits the .emacs file for you. Likewise, M-x enable-command edits .emacs to enable a command permanently. Section 32.7.
Whether a command is disabled is independent of what key is used to invoke it; disabling also applies if the command is invoked using M-x. Disabling a command has no effect on calling it as a function from Lisp programs.
Note that you should avoid the string syntax for binding 8-bit characters, since they will be interpreted as meta keys. .