[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26. Keymaps

The bindings between input events and commands are recorded in data structures called keymaps. Each binding in a keymap associates (or binds) an individual event type either with another keymap or with a command. When an event is bound to a keymap, that keymap is used to look up the next input event; this continues until a command is found. The whole process is called key lookup.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.1 Keymap Terminology

A keymap is a table mapping event types to definitions (which can be any Lisp objects, though only certain types are meaningful for execution by the command loop). Given an event (or an event type) and a keymap, XEmacs can get the event’s definition. Events mapped in keymaps include keypresses, button presses, and button releases (see section Events).

A sequence of input events that form a unit is called a key sequence, or key for short. A sequence of one event is always a key sequence, and so are some multi-event sequences.

A keymap determines a binding or definition for any key sequence. If the key sequence is a single event, its binding is the definition of the event in the keymap. The binding of a key sequence of more than one event is found by an iterative process: the binding of the first event is found, and must be a keymap; then the second event’s binding is found in that keymap, and so on until all the events in the key sequence are used up.

If the binding of a key sequence is a keymap, we call the key sequence a prefix key. Otherwise, we call it a complete key (because no more events can be added to it). If the binding is nil, we call the key undefined. Examples of prefix keys are C-c, C-x, and C-x 4. Examples of defined complete keys are X, <RET>, and C-x 4 C-f. Examples of undefined complete keys are C-x C-g, and C-c 3. See section Prefix Keys, for more details.

The rule for finding the binding of a key sequence assumes that the intermediate bindings (found for the events before the last) are all keymaps; if this is not so, the sequence of events does not form a unit—it is not really a key sequence. In other words, removing one or more events from the end of any valid key must always yield a prefix key. For example, C-f C-n is not a key; C-f is not a prefix key, so a longer sequence starting with C-f cannot be a key.

Note that the set of possible multi-event key sequences depends on the bindings for prefix keys; therefore, it can be different for different keymaps, and can change when bindings are changed. However, a one-event sequence is always a key sequence, because it does not depend on any prefix keys for its well-formedness.

At any time, several primary keymaps are active—that is, in use for finding key bindings. These are the global map, which is shared by all buffers; the local keymap, which is usually associated with a specific major mode; and zero or more minor mode keymaps, which belong to currently enabled minor modes. (Not all minor modes have keymaps.) The local keymap bindings shadow (i.e., take precedence over) the corresponding global bindings. The minor mode keymaps shadow both local and global keymaps. See section Active Keymaps, for details.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.2 Format of Keymaps

A keymap is a primitive type that associates events with their bindings. Note that this is different from Emacs 18 and FSF Emacs, where keymaps are lists.

Function: keymapp object

This function returns t if object is a keymap, nil otherwise.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.3 Creating Keymaps

Here we describe the functions for creating keymaps.

Function: make-keymap &optional name

This function constructs and returns a new keymap object. All entries in it are nil, meaning “command undefined”.

Optional argument name specifies a name to assign to the keymap, as in set-keymap-name. This name is only a debugging convenience; it is not used except when printing the keymap.

Function: make-sparse-keymap &optional name

This function constructs and returns a new keymap object. All entries in it are nil, meaning “command undefined”. The only difference between this function and make-keymap is that this function returns a “smaller” keymap (one that is expected to contain fewer entries). As keymaps dynamically resize, this distinction is not great.

Optional argument name specifies a name to assign to the keymap, as in set-keymap-name. This name is only a debugging convenience; it is not used except when printing the keymap.

Function: set-keymap-name keymap new-name

This function assigns a “name” to a keymap. The name is only a debugging convenience; it is not used except when printing the keymap.

Function: keymap-name keymap

This function returns the “name” of a keymap, as assigned using set-keymap-name.

Function: copy-keymap keymap

This function returns a copy of keymap. Any keymaps that appear directly as bindings in keymap are also copied recursively, and so on to any number of levels. However, recursive copying does not take place when the definition of a character is a symbol whose function definition is a keymap; the same symbol appears in the new copy.

(setq map (copy-keymap (current-local-map)))
⇒ #<keymap 3 entries 0x21f80>
(eq map (current-local-map))
    ⇒ nil

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.4 Inheritance and Keymaps

A keymap can inherit the bindings of other keymaps. The other keymaps are called the keymap’s parents, and are set with set-keymap-parents. When searching for a binding for a key sequence in a particular keymap, that keymap itself will first be searched; then, if no binding was found in the map and it has parents, the first parent keymap will be searched; then that keymap’s parent will be searched, and so on, until either a binding for the key sequence is found, or a keymap without a parent is encountered. At this point, the search will continue with the next parent of the most recently encountered keymap that has another parent, etc. Essentially, a depth-first search of all the ancestors of the keymap is conducted.

(current-global-map) is the default parent of all keymaps.

Function: set-keymap-parents keymap parents

This function sets the parent keymaps of keymap to the list parents.

If you change the bindings in one of the keymaps in parents using define-key or other key-binding functions, these changes are visible in keymap unless shadowed by bindings in that map or in earlier-searched ancestors. The converse is not true: if you use define-key to change keymap, that affects the bindings in that map, but has no effect on any of the keymaps in parents.

Function: keymap-parents keymap

This function returns the list of parent keymaps of keymap, or nil if keymap has no parents.

As an alternative to specifying a parent, you can also specify a default binding that is used whenever a key is not otherwise bound in the keymap. This is useful for terminal emulators, for example, which may want to trap all keystrokes and pass them on in some modified format. Note that if you specify a default binding for a keymap, neither the keymap’s parents nor the current global map are searched for key bindings.

Function: set-keymap-default-binding keymap command

This function sets the default binding of keymap to command, or nil if no default is desired.

Function: keymap-default-binding keymap

This function returns the default binding of keymap, or nil if it has none.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.5 Key Sequences

Contrary to popular belief, the world is not ASCII. When running under a window manager, XEmacs can tell the difference between, for example, the keystrokes control-h, control-shift-h, and backspace. You can, in fact, bind different commands to each of these.

A key sequence is a set of keystrokes. A keystroke is a keysym and some set of modifiers (such as <CONTROL> and <META>). A keysym is what is printed on the keys on your keyboard.

A keysym may be represented by a symbol, by a character, or by a character’s Mule code. The A key may be represented by the symbol A, the character ?A, or by the number 65. The break key may be represented only by the symbol break, and non-ASCII X11 keys in general are limited to the symbol form with XEmacs. (3) (4)

A keystroke may be represented by a list: the last element of the list is the key (a symbol, character, or number, as above) and the preceding elements are the symbolic names of modifier keys (<CONTROL>, <META>, <SUPER>, <HYPER>, <ALT>, and <SHIFT>). Thus, the sequence control-b is represented by the forms (control b), (control ?b), and (control 98). A keystroke may also be represented by an event object, as returned by the next-command-event and read-key-sequence functions.

Note that in this context, the keystroke control-b is not represented by the number 2 (the ASCII code for ‘^B’) or the character ?\^B. See below.

The <SHIFT> modifier is somewhat of a special case. You should not (and cannot) use (meta shift a) to mean (meta A), since for characters that have ASCII equivalents, the state of the shift key is implicit in the keysym (‘a’ vs. ‘A’). You also cannot say (shift =) to mean +, as that sort of thing varies from keyboard to keyboard. The <SHIFT> modifier is for use only with characters that do not have a second keysym on the same key, such as backspace and tab.

A key sequence is a vector of keystrokes. As a degenerate case, elements of this vector may also be keysyms if they have no modifiers. That is, the A keystroke is represented by all of these forms:

        A       ?A      65      (A)     (?A)    (65)
        [A]     [?A]    [65]    [(A)]   [(?A)]  [(65)]

the control-a keystroke is represented by these forms:

        (control A)     (control ?A)    (control 65)
        [(control A)]   [(control ?A)]  [(control 65)]

the key sequence control-c control-a is represented by these forms:

        [(control c) (control a)]       [(control ?c) (control ?a)]
        [(control 99) (control 65)]     etc.

Mouse button clicks work just like keypresses: (control button1) means pressing the left mouse button while holding down the control key. [(control c) (shift button3)] means control-c, hold <SHIFT>, click right.

Commands may be bound to the mouse-button up-stroke rather than the down-stroke as well. button1 means the down-stroke, and button1up means the up-stroke. Different commands may be bound to the up and down strokes, though that is probably not what you want, so be careful.

For backward compatibility, a key sequence may also be represented by a string. In this case, it represents the key sequence(s) that would produce that sequence of ASCII characters in a purely ASCII world. For example, a string containing the ASCII backspace character, "\^H", would represent two key sequences: (control h) and backspace. Binding a command to this will actually bind both of those key sequences. Likewise for the following pairs:

                control h       backspace
                control i       tab
                control m       return
                control j       linefeed
                control [       escape
                control @      control space

After binding a command to two key sequences with a form like

        (define-key global-map "\^X\^I" 'command-1)

it is possible to redefine only one of those sequences like so:

        (define-key global-map [(control x) (control i)] 'command-2)
        (define-key global-map [(control x) tab] 'command-3)

Of course, all of this applies only when running under a window system. If you’re talking to XEmacs through a TTY connection, you don’t get any of these features.

Function: event-matches-key-specifier-p event key-specifier

This function returns non-nil if event matches key-specifier, which can be any valid form representing a key sequence. This can be useful, e.g., to determine if the user pressed help-char or quit-char.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.6 Prefix Keys

A prefix key has an associated keymap that defines what to do with key sequences that start with the prefix key. For example, C-x is a prefix key, and it uses a keymap that is also stored in the variable ctl-x-map. Here is a list of the standard prefix keys of XEmacs and their keymaps:

The binding of a prefix key is the keymap to use for looking up the events that follow the prefix key. (It may instead be a symbol whose function definition is a keymap. The effect is the same, but the symbol serves as a name for the prefix key.) Thus, the binding of C-x is the symbol Control-X-prefix, whose function definition is the keymap for C-x commands. (The same keymap is also the value of ctl-x-map.)

Prefix key definitions can appear in any active keymap. 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. Major and minor modes can redefine a key as a prefix by putting a prefix key definition for it in the local map or the minor mode’s map. See section Active Keymaps.

If a key is defined as a prefix in more than one active map, then its various definitions are in effect merged: the commands defined in the minor mode keymaps come first, followed by those in the local map’s prefix definition, and then by those from the global map.

In the following example, we make C-p a prefix key in the local keymap, in such a way that C-p is identical to C-x. Then the binding for C-p C-f is the function find-file, just like C-x C-f. The key sequence C-p 6 is not found in any active keymap.

(use-local-map (make-sparse-keymap))
    ⇒ nil
(local-set-key "\C-p" ctl-x-map)
    ⇒ nil
(key-binding "\C-p\C-f")
    ⇒ find-file
(key-binding "\C-p6")
    ⇒ nil
Function: define-prefix-command symbol &optional mapvar

This function defines symbol as a prefix command: it creates a keymap and stores it as symbol’s function definition. Storing the symbol as the binding of a key makes the key a prefix key that has a name. If optional argument mapvar is not specified, it also sets symbol as a variable, to have the keymap as its value. (If mapvar is given and is not t, its value is stored as the value of symbol.) The function returns symbol.

In Emacs version 18, only the function definition of symbol was set, not the value as a variable.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.7 Active Keymaps

XEmacs normally contains many keymaps; at any given time, just a few of them are active in that they participate in the interpretation of user input. These are the global keymap, the current buffer’s local keymap, and the keymaps of any enabled minor modes.

The global keymap holds the bindings of keys that are defined regardless of the current buffer, such as C-f. The variable global-map holds this keymap, which is always active.

Each buffer may have another keymap, its local keymap, which may contain new or overriding definitions for keys. The current buffer’s local keymap is always active except when overriding-local-map or overriding-terminal-local-map overrides it. Extents and text properties can specify an alternative local map for certain parts of the buffer; see Interaction of Extents with Keyboard and Mouse Events.

Each minor mode may have a keymap; if it does, the keymap is active when the minor mode is enabled.

The variable overriding-local-map and overriding-terminal-local-map, if non-nil, specify other local keymaps that override the buffer’s local map and all the minor mode keymaps.

All the active keymaps are used together to determine what command to execute when a key is entered. XEmacs searches these maps one by one, in order of decreasing precedence, until it finds a binding in one of the maps.

More specifically:

For key-presses, the order of keymaps searched is:

For mouse-clicks, the order of keymaps searched is:

Note that if overriding-local-map or overriding-terminal-local-map is non-nil, only those two maps and the current global map are searched.

The procedure for searching a single keymap is called key lookup; see Key Lookup.

Since every buffer that uses the same major mode normally uses the same local keymap, you can think of the keymap as local to the mode. A change to the local keymap of a buffer (using local-set-key, for example) is seen also in the other buffers that share that keymap.

The local keymaps that are used for Lisp mode, C mode, and several other major modes exist even if they have not yet been used. These local maps are the values of the variables lisp-mode-map, c-mode-map, and so on. For most other modes, which are less frequently used, the local keymap is constructed only when the mode is used for the first time in a session.

The minibuffer has local keymaps, too; they contain various completion and exit commands. See section Introduction to Minibuffers.

See section Standard Keymaps, for a list of standard keymaps.

Function: current-keymaps &optional event-or-keys

This function returns a list of the current keymaps that will be searched for bindings. This lists keymaps such as the current local map and the minor-mode maps, but does not list the parents of those keymaps. event-or-keys controls which keymaps will be listed. If event-or-keys is a mouse event (or a vector whose last element is a mouse event), the keymaps for that mouse event will be listed. Otherwise, the keymaps for key presses will be listed.

Variable: global-map

This variable contains the default global keymap that maps XEmacs keyboard input to commands. The global keymap is normally this keymap. The default global keymap is a full keymap that binds self-insert-command to all of the printing characters.

It is normal practice to change the bindings in the global map, but you should not assign this variable any value other than the keymap it starts out with.

Function: current-global-map

This function returns the current global keymap. This is the same as the value of global-map unless you change one or the other.

⇒ #<keymap global-map 639 entries 0x221>
Function: current-local-map &optional buffer

This function returns buffer’s local keymap, or nil if it has none. buffer defaults to the current buffer.

In the following example, the keymap for the ‘*scratch*’ buffer (using Lisp Interaction mode) has a number of entries, including one prefix key, C-x.

⇒ #<keymap lisp-interaction-mode-map 5 entries 0x558>
(describe-bindings-internal (current-local-map))
⇒  ; Inserted into the buffer:
backspace       backward-delete-char-untabify
linefeed        eval-print-last-sexp
delete          delete-char
C-j             eval-print-last-sexp
C-x             << Prefix Command >>
M-tab           lisp-complete-symbol
M-;             lisp-indent-for-comment
M-C-i           lisp-complete-symbol
M-C-q           indent-sexp
M-C-x           eval-defun
Alt-backspace   backward-kill-sexp
Alt-delete      kill-sexp
C-x x           edebug-defun
Function: current-minor-mode-maps

This function returns a list of the keymaps of currently enabled minor modes.

Function: use-global-map keymap

This function makes keymap the new current global keymap. It returns nil.

It is very unusual to change the global keymap.

Function: use-local-map keymap &optional buffer

This function makes keymap the new local keymap of buffer. buffer defaults to the current buffer. If keymap is nil, then the buffer has no local keymap. use-local-map returns nil. Most major mode commands use this function.

Variable: minor-mode-map-alist

This variable is an alist describing keymaps that may or may not be active according to the values of certain variables. Its elements look like this:

(variable . keymap)

The keymap keymap is active whenever variable has a non-nil value. Typically variable is the variable that enables or disables a minor mode. See section Keymaps and Minor Modes.

Note that elements of minor-mode-map-alist do not have the same structure as elements of minor-mode-alist. The map must be the CDR of the element; a list with the map as the second element will not do.

What’s more, the keymap itself must appear in the CDR. It does not work to store a variable in the CDR and make the map the value of that variable.

When more than one minor mode keymap is active, their order of priority is the order of minor-mode-map-alist. But you should design minor modes so that they don’t interfere with each other. If you do this properly, the order will not matter.

See also minor-mode-key-binding, above. See Keymaps and Minor Modes, for more information about minor modes.

Variable: modeline-map

This variable holds the keymap consulted for mouse-clicks on the modeline of a window. This variable may be buffer-local; its value will be looked up in the buffer of the window whose modeline was clicked upon.

Variable: toolbar-map

This variable holds the keymap consulted for mouse-clicks over a toolbar.

Variable: mouse-grabbed-buffer

If non-nil, a buffer which should be consulted first for all mouse activity. When a mouse-click is processed, it will first be looked up in the local-map of this buffer, and then through the normal mechanism if there is no binding for that click. This buffer’s value of mode-motion-hook will be consulted instead of the mode-motion-hook of the buffer of the window under the mouse. You should bind this, not set it.

Variable: overriding-local-map

If non-nil, this variable holds a keymap to use instead of the buffer’s local keymap and instead of all the minor mode keymaps. This keymap, if any, overrides all other maps that would have been active, except for the current global map.

Variable: overriding-terminal-local-map

If non-nil, this variable holds a keymap to use instead of the buffer’s local keymap and instead of all the minor mode keymaps, but for the selected console only. (In other words, this variable is always console-local; putting a keymap here only applies to keystrokes coming from the selected console. See section Consoles and Devices.) This keymap, if any, overrides all other maps that would have been active, except for the current global map.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.8 Key Lookup

Key lookup is the process of finding the binding of a key sequence from a given keymap. Actual execution of the binding is not part of key lookup.

Key lookup uses just the event type of each event in the key sequence; the rest of the event is ignored. In fact, a key sequence used for key lookup may designate mouse events with just their types (symbols) instead of with entire mouse events (lists). See section Events. Such a pseudo-key-sequence is insufficient for command-execute, but it is sufficient for looking up or rebinding a key.

When the key sequence consists of multiple events, key lookup processes the events sequentially: the binding of the first event is found, and must be a keymap; then the second event’s binding is found in that keymap, and so on until all the events in the key sequence are used up. (The binding thus found for the last event may or may not be a keymap.) Thus, the process of key lookup is defined in terms of a simpler process for looking up a single event in a keymap. How that is done depends on the type of object associated with the event in that keymap.

Let’s use the term keymap entry to describe the value found by looking up an event type in a keymap. (This doesn’t include the item string and other extra elements in menu key bindings because lookup-key and other key lookup functions don’t include them in the returned value.) While any Lisp object may be stored in a keymap as a keymap entry, not all make sense for key lookup. Here is a list of the meaningful kinds of keymap entries:


nil means that the events used so far in the lookup form an undefined key. When a keymap fails to mention an event type at all, and has no default binding, that is equivalent to a binding of nil for that event type.


The events used so far in the lookup form a prefix key. The next event of the key sequence is looked up in keymap.


The events used so far in the lookup form a complete key, and command is its binding. See section What Is a Function?.


The array (either a string or a vector) is a keyboard macro. The events used so far in the lookup form a complete key, and the array is its binding. See Keyboard Macros, for more information. (Note that you cannot use a shortened form of a key sequence here, such as (control y); you must use the full form [(control y)]. See section Key Sequences.)


The meaning of a list depends on the types of the elements of the list.


The function definition of symbol is used in place of symbol. If that too is a symbol, then this process is repeated, any number of times. Ultimately this should lead to an object that is a keymap, a command or a keyboard macro. A list is allowed if it is a keymap or a command, but indirect entries are not understood when found via symbols.

Note that keymaps and keyboard macros (strings and vectors) are not valid functions, so a symbol with a keymap, string, or vector as its function definition is invalid as a function. It is, however, valid as a key binding. If the definition is a keyboard macro, then the symbol is also valid as an argument to command-execute (see section Interactive Call).

The symbol undefined is worth special mention: it means to treat the key as undefined. Strictly speaking, the key is defined, and its binding is the command undefined; but that command does the same thing that is done automatically for an undefined key: it rings the bell (by calling ding) but does not signal an error.

undefined is used in local keymaps to override a global key binding and make the key “undefined” locally. A local binding of nil would fail to do this because it would not override the global binding.

anything else

If any other type of object is found, the events used so far in the lookup form a complete key, and the object is its binding, but the binding is not executable as a command.

In short, a keymap entry may be a keymap, a command, a keyboard macro, a symbol that leads to one of them, or an indirection or nil.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.9 Functions for Key Lookup

Here are the functions and variables pertaining to key lookup.

Function: lookup-key keymap key &optional accept-defaults

This function returns the definition of key in keymap. If the string or vector key is not a valid key sequence according to the prefix keys specified in keymap (which means it is “too long” and has extra events at the end), then the value is a number, the number of events at the front of key that compose a complete key.

If accept-defaults is non-nil, then lookup-key considers default bindings as well as bindings for the specific events in key. Otherwise, lookup-key reports only bindings for the specific sequence key, ignoring default bindings except when you explicitly ask about them.

All the other functions described in this chapter that look up keys use lookup-key.

(lookup-key (current-global-map) "\C-x\C-f")
    ⇒ find-file
(lookup-key (current-global-map) "\C-x\C-f12345")
    ⇒ 2

If key begins with the character whose value is contained in meta-prefix-char, that character is implicitly removed and the <META> modifier added to the key. Thus, the first example below is handled by conversion into the second example.

(lookup-key (current-global-map) "\ef")
    ⇒ forward-word
(lookup-key (current-global-map) "\M-f")
    ⇒ forward-word

Unlike read-key-sequence, this function does not modify the specified events in ways that discard information (see section Key Sequence Input). In particular, it does not convert letters to lower case.

Command: undefined

Used in keymaps to undefine keys. If a key sequence is defined to this, invoking this key sequence causes a “key undefined” error, just as if the key sequence had no binding.

Function: key-binding key &optional accept-defaults

This function returns the binding for key in the current keymaps, trying all the active keymaps. The result is nil if key is undefined in the keymaps.

The argument accept-defaults controls checking for default bindings, as in lookup-key (above).

(key-binding "\C-x\C-f")
    ⇒ find-file
(key-binding '(control home))
    ⇒ beginning-of-buffer
(key-binding [escape escape escape])
    ⇒ keyboard-escape-quit
Function: local-key-binding keys &optional accept-defaults

This function returns the binding for keys in the current local keymap, or nil if it is undefined there.

The argument accept-defaults controls checking for default bindings, as in lookup-key (above).

Function: global-key-binding keys &optional accept-defaults

This function returns the binding for command keys in the current global keymap, or nil if it is undefined there.

The argument accept-defaults controls checking for default bindings, as in lookup-key (above).

Function: minor-mode-key-binding key &optional accept-defaults

This function returns a list of all the active minor mode bindings of key. More precisely, it returns an alist of pairs (modename . binding), where modename is the variable that enables the minor mode, and binding is key’s binding in that mode. If key has no minor-mode bindings, the value is nil.

If the first binding is not a prefix command, all subsequent bindings from other minor modes are omitted, since they would be completely shadowed. Similarly, the list omits non-prefix bindings that follow prefix bindings.

The argument accept-defaults controls checking for default bindings, as in lookup-key (above).

Variable: meta-prefix-char

This variable is the meta-prefix character code. It is used when translating a two-character sequence to a meta character so it can be looked up in a keymap. For useful results, the value should be a prefix event (see section Prefix Keys). The default value is ?\^[ (integer 27), which is the ASCII character usually produced by the <ESC> key.

As long as the value of meta-prefix-char remains ?\^[, key lookup translates <ESC> b into M-b, which is normally defined as the backward-word command. However, if you set meta-prefix-char to ?\^X (i.e. the keystroke C-x) or its equivalent ASCII code 24, then XEmacs will translate C-x b (whose standard binding is the switch-to-buffer command) into M-b.

meta-prefix-char                    ; The default value.
     ⇒ ?\^[   ; Under XEmacs 20.
     ⇒ 27     ; Under XEmacs 19.
(key-binding "\eb")
     ⇒ backward-word
?\C-x                               ; The print representation
                                           ;   of a character.
     ⇒ ?\^X   ; Under XEmacs 20.
     ⇒ 24     ; Under XEmacs 19.
(setq meta-prefix-char 24)
     ⇒ 24
(key-binding "\C-xb")
     ⇒ backward-word            ; Now, typing C-x b is
                                    ;   like typing M-b.

(setq meta-prefix-char ?\e)          ; Avoid confusion!
                                     ; Restore the default value!
     ⇒ ?\^[   ; Under XEmacs 20.
     ⇒ 27     ; Under XEmacs 19.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.10 Changing Key Bindings

The way to rebind a key is to change its entry in a keymap. If you change a binding in the global keymap, the change is effective in all buffers (though it has no direct effect in buffers that shadow the global binding with a local one). If you change the current buffer’s local map, that usually affects all buffers using the same major mode. The global-set-key and local-set-key functions are convenient interfaces for these operations (see section Commands for Binding Keys). You can also use define-key, a more general function; then you must specify explicitly the map to change.

The way to specify the key sequence that you want to rebind is described above (see section Key Sequences).

For the functions below, an error is signaled if keymap is not a keymap or if key is not a string or vector representing a key sequence. You can use event types (symbols) as shorthand for events that are lists.

Function: define-key keymap key binding

This function sets the binding for key in keymap. (If key is more than one event long, the change is actually made in another keymap reached from keymap.) The argument binding can be any Lisp object, but only certain types are meaningful. (For a list of meaningful types, see Key Lookup.) The value returned by define-key is binding.

Every prefix of key must be a prefix key (i.e., bound to a keymap) or undefined; otherwise an error is signaled.

If some prefix of key is undefined, then define-key defines it as a prefix key so that the rest of key may be defined as specified.

Here is an example that creates a sparse keymap and makes a number of bindings in it:

(setq map (make-sparse-keymap))
    ⇒ #<keymap 0 entries 0xbee>
(define-key map "\C-f" 'forward-char)
    ⇒ forward-char
    ⇒ #<keymap 1 entry 0xbee>
(describe-bindings-internal map)
⇒   ; (Inserted in buffer)
C-f             forward-char
;; Build sparse submap for C-x and bind f in that.
(define-key map "\C-xf" 'forward-word)
    ⇒ forward-word
    ⇒ #<keymap 2 entries 0xbee>
(describe-bindings-internal map)
⇒   ; (Inserted in buffer)
C-f             forward-char
C-x             << Prefix Command >>

C-x f           forward-word
;; Bind C-p to the ctl-x-map.
(define-key map "\C-p" ctl-x-map)
;; ctl-x-map
⇒ #<keymap Control-X-prefix 77 entries 0x3bf>
;; Bind C-f to foo in the ctl-x-map.
(define-key map "\C-p\C-f" 'foo)
⇒ foo
    ⇒ #<keymap 3 entries 0xbee>
(describe-bindings-internal map)
⇒   ; (Inserted in buffer)
C-f             forward-char
C-p             << Prefix command Control-X-prefix >>
C-x             << Prefix Command >>

C-p tab         indent-rigidly
C-p $           set-selective-display
C-p '           expand-abbrev
C-p (           start-kbd-macro
C-p )           end-kbd-macro
C-p C-x         exchange-point-and-mark
C-p C-z         suspend-or-iconify-emacs
C-p M-escape    repeat-complex-command
C-p M-C-[       repeat-complex-command

C-x f           forward-word

C-p 4 .         find-tag-other-window
C-p 4 C-o       display-buffer

C-p 5 0         delete-frame
C-p 5 C-f       find-file-other-frame


C-p a i g       inverse-add-global-abbrev
C-p a i l       inverse-add-mode-abbrev

Note that storing a new binding for C-p C-f actually works by changing an entry in ctl-x-map, and this has the effect of changing the bindings of both C-p C-f and C-x C-f in the default global map.

Function: substitute-key-definition olddef newdef keymap &optional oldmap prefix

This function replaces olddef with newdef for any keys in keymap that were bound to olddef. In other words, olddef is replaced with newdef wherever it appears. Prefix keymaps are checked recursively.

The function returns nil.

For example, this redefines C-x C-f, if you do it in an XEmacs with standard bindings:

 'find-file 'find-file-read-only (current-global-map))

If oldmap is non-nil, then its bindings determine which keys to rebind. The rebindings still happen in keymap, not in oldmap. Thus, you can change one map under the control of the bindings in another. For example,

  'delete-backward-char 'my-funny-delete
  my-map global-map)

puts the special deletion command in my-map for whichever keys are globally bound to the standard deletion command.

If argument prefix is non-nil, then only those occurrences of olddef found in keymaps accessible through the keymap bound to prefix in keymap are redefined. See also accessible-keymaps.

Function: suppress-keymap keymap &optional nodigits

This function changes the contents of the full keymap keymap by making all the printing characters undefined. More precisely, it binds them to the command undefined. This makes ordinary insertion of text impossible. suppress-keymap returns nil.

If nodigits is nil, then suppress-keymap defines digits to run digit-argument, and - to run negative-argument. Otherwise it makes them undefined like the rest of the printing characters.

The suppress-keymap function does not make it impossible to modify a buffer, as it does not suppress commands such as yank and quoted-insert. To prevent any modification of a buffer, make it read-only (see section Read-Only Buffers).

Since this function modifies keymap, you would normally use it on a newly created keymap. Operating on an existing keymap that is used for some other purpose is likely to cause trouble; for example, suppressing global-map would make it impossible to use most of XEmacs.

Most often, suppress-keymap is used to initialize local keymaps of modes such as Rmail and Dired where insertion of text is not desirable and the buffer is read-only. Here is an example taken from the file ‘emacs/lisp/dired.el’, showing how the local keymap for Dired mode is set up:

  (setq dired-mode-map (make-keymap))
  (suppress-keymap dired-mode-map)
  (define-key dired-mode-map "r" 'dired-rename-file)
  (define-key dired-mode-map "\C-d" 'dired-flag-file-deleted)
  (define-key dired-mode-map "d" 'dired-flag-file-deleted)
  (define-key dired-mode-map "v" 'dired-view-file)
  (define-key dired-mode-map "e" 'dired-find-file)
  (define-key dired-mode-map "f" 'dired-find-file)

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.11 Commands for Binding Keys

This section describes some convenient interactive interfaces for changing key bindings. They work by calling define-key.

People often use global-set-key in their ‘.emacs’ file for simple customization. For example,

(global-set-key "\C-x\C-\\" 'next-line)


(global-set-key [(control ?x) (control ?\\)] 'next-line)


(global-set-key [?\C-x ?\C-\\] 'next-line)

redefines C-x C-\ to move down a line.

(global-set-key [(meta button1)] 'mouse-set-point)

redefines the first (leftmost) mouse button, typed with the Meta key, to set point where you click.

Command: global-set-key key definition

This function sets the binding of key in the current global map to definition.

(global-set-key key definition)
(define-key (current-global-map) key definition)
Command: global-unset-key key

This function removes the binding of key from the current global map.

One use of this function is in preparation for defining a longer key that uses key as a prefix—which would not be allowed if key has a non-prefix binding. For example:

(global-unset-key "\C-l")
    ⇒ nil
(global-set-key "\C-l\C-l" 'redraw-display)
    ⇒ nil

This function is implemented simply using define-key:

(global-unset-key key)
(define-key (current-global-map) key nil)
Command: local-set-key key definition

This function sets the binding of key in the current local keymap to definition.

(local-set-key key definition)
(define-key (current-local-map) key definition)
Command: local-unset-key key

This function removes the binding of key from the current local map.

(local-unset-key key)
(define-key (current-local-map) key nil)

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.12 Scanning Keymaps

This section describes functions used to scan all the current keymaps, or all keys within a keymap, for the sake of printing help information.

Function: accessible-keymaps keymap &optional prefix

This function returns a list of all the keymaps that can be accessed (via prefix keys) from keymap. The value is an association list with elements of the form (key . map), where key is a prefix key whose definition in keymap is map.

The elements of the alist are ordered so that the key increases in length. The first element is always ([] . keymap), because the specified keymap is accessible from itself with a prefix of no events.

If prefix is given, it should be a prefix key sequence; then accessible-keymaps includes only the submaps whose prefixes start with prefix. These elements look just as they do in the value of (accessible-keymaps); the only difference is that some elements are omitted.

In the example below, the returned alist indicates that the key C-x, which is displayed as ‘[(control x)]’, is a prefix key whose definition is the keymap #<keymap ((control x) #<keymap emacs-lisp-mode-map 8 entries 0x546>) 1 entry 0x8a2>. (The strange notation for the keymap’s name indicates that this is an internal submap of emacs-lisp-mode-map. This is because lisp-interaction-mode-map has set up emacs-lisp-mode-map as its parent, and lisp-interaction-mode-map defines no key sequences beginning with C-x.)

⇒ #<keymap lisp-interaction-mode-map 5 entries 0x558>
(accessible-keymaps (current-local-map))
⇒(([] . #<keymap lisp-interaction-mode-map 5 entries 0x558>)
    ([(control x)] .
     #<keymap ((control x) #<keymap emacs-lisp-mode-map 8 entries 0x546>)
              1 entry 0x8a2>))

The following example shows the results of calling accessible-keymaps on a large, complex keymap. Notice how some keymaps were given explicit names using set-keymap-name; those submaps without explicit names are given descriptive names indicating their relationship to their enclosing keymap.

(accessible-keymaps (current-global-map))
⇒ (([] . #<keymap global-map 639 entries 0x221>)
   ([(control c)] . #<keymap mode-specific-command-prefix 1 entry 0x3cb>)
   ([(control h)] . #<keymap help-map 33 entries 0x4ec>)
   ([(control x)] . #<keymap Control-X-prefix 77 entries 0x3bf>)
   ([(meta escape)] .
      #<keymap ((meta escape) #<keymap global-map 639 entries 0x221>)
               3 entries 0x3e0>)
   ([(meta control \[)] .
      #<keymap ((meta escape) #<keymap global-map 639 entries 0x221>)
               3 entries 0x3e0>)
   ([f1] . #<keymap help-map 33 entries 0x4ec>)
   ([(control x) \4] . #<keymap ctl-x-4-prefix 9 entries 0x3c5>)
   ([(control x) \5] . #<keymap ctl-x-5-prefix 8 entries 0x3c8>)
   ([(control x) \6] . #<keymap 13 entries 0x4d2>)
   ([(control x) a] .
      #<keymap (a #<keymap Control-X-prefix 77 entries 0x3bf>)
               8 entries 0x3ef>)
   ([(control x) n] . #<keymap narrowing-prefix 3 entries 0x3dd>)
   ([(control x) r] . #<keymap rectangle-prefix 18 entries 0x3e9>)
   ([(control x) v] . #<keymap vc-prefix-map 13 entries 0x60e>)
   ([(control x) a i] .
     #<keymap (i #<keymap (a #<keymap Control-X-prefix 77 entries 0x3bf>)
                          8 entries 0x3ef>)
              2 entries 0x3f5>))
Function: map-keymap function keymap &optional sort-first

This function applies function to each element of keymap. function will be called with two arguments: a key-description list, and the binding. The order in which the elements of the keymap are passed to the function is unspecified. If the function inserts new elements into the keymap, it may or may not be called with them later. No element of the keymap will ever be passed to the function more than once.

The function will not be called on elements of this keymap’s parents (see section Inheritance and Keymaps) or upon keymaps which are contained within this keymap (multi-character definitions). It will be called on <META> characters since they are not really two-character sequences.

If the optional third argument sort-first is non-nil, then the elements of the keymap will be passed to the mapper function in a canonical order. Otherwise, they will be passed in hash (that is, random) order, which is faster.

Function: keymap-fullness keymap

This function returns the number of bindings in the keymap.

Function: where-is-internal definition &optional keymaps firstonly noindirect event-or-keys

This function returns a list of key sequences (of any length) that are bound to definition in a set of keymaps.

The argument definition can be any object; it is compared with all keymap entries using eq.

keymaps can be either a keymap (meaning search in that keymap and the current global keymap) or a list of keymaps (meaning search in exactly those keymaps and no others). If keymaps is nil, search in the currently applicable maps for event-or-keys.

If keymaps is a keymap, then the maps searched are keymaps and the global keymap. If keymaps is a list of keymaps, then the maps searched are exactly those keymaps, and no others. If keymaps is nil, then the maps used are the current active keymaps for event-or-keys (this is equivalent to specifying (current-keymaps event-or-keys) as the argument to keymaps).

If firstonly is non-nil, then the value is a single vector representing the first key sequence found, rather than a list of all possible key sequences.

If noindirect is non-nil, where-is-internal doesn’t follow indirect keymap bindings. This makes it possible to search for an indirect definition itself.

This function is used by where-is (see (xemacs)Help section ‘Help’ in The XEmacs Lisp Reference Manual).

(where-is-internal 'describe-function)
    ⇒ ([(control h) d] [(control h) f] [f1 d] [f1 f])
Function: describe-bindings-internal map &optional all shadow prefix mouse-only-p

This function inserts (into the current buffer) a list of all defined keys and their definitions in map. Optional second argument all says whether to include even “uninteresting” definitions, i.e. symbols with a non-nil suppress-keymap property. Third argument shadow is a list of keymaps whose bindings shadow those of map; if a binding is present in any shadowing map, it is not printed. Fourth argument prefix, if non-nil, should be a key sequence; only bindings which start with that key sequence will be printed. Fifth argument mouse-only-p says to only print bindings for mouse clicks.

describe-bindings-internal is used to implement the help command describe-bindings.

Command: describe-bindings &optional prefix mouse-only-p

This function creates a listing of all defined keys and their definitions. It writes the listing in a buffer named ‘*Help*’ and displays it in a window.

If optional argument prefix is non-nil, it should be a prefix key; then the listing includes only keys that start with prefix.

When several characters with consecutive ASCII codes have the same definition, they are shown together, as ‘firstchar..lastchar’. In this instance, you need to know the ASCII codes to understand which characters this means. For example, in the default global map, the characters ‘<SPC> .. ~’ are described by a single line. <SPC> is ASCII 32, ~ is ASCII 126, and the characters between them include all the normal printing characters, (e.g., letters, digits, punctuation, etc.); all these characters are bound to self-insert-command.

If the second optional argument mouse-only-p (prefix arg, interactively) is non-nil then only the mouse bindings are displayed.

[ << ] [ >> ]           [Top] [Contents] [Index] [ ? ]

This document was generated by Aidan Kehoe on December 27, 2016 using texi2html 1.82.