Go to the previous, next section.

Command Loop

When you run Emacs, it enters the editor command loop almost immediately. This loop reads key sequences, executes their definitions, and displays the results. In this chapter, we describe how these things are done, and the subroutines that allow Lisp programs to do them.

Command Loop Overview

The first thing the command loop must do is read a key sequence, which is a sequence of events that translates into a command. It does this by calling the function read-key-sequence. Your Lisp code can also call this function (see section Key Sequence Input). Lisp programs can also do input at a lower level with read-event (see section Reading One Event) or discard pending input with discard-input (see section Peeking and Discarding).

The key sequence is translated into a command through the currently active keymaps. See section Key Lookup, for information on how this is done. The result should be a keyboard macro or an interactively callable function. If the key is M-x, then it reads the name of another command, which is used instead. This is done by the command execute-extended-command (see section Interactive Call).

Once the command is chosen, it must be executed, which includes reading arguments to be given to it. This is done by calling command-execute (see section Interactive Call). For commands written in Lisp, the interactive specification says how to read the arguments. This may use the prefix argument (see section Prefix Command Arguments) or may read with prompting in the minibuffer (see section Minibuffers). For example, the command find-file has an interactive specification which says to read a file name using the minibuffer. The command's function body does not use the minibuffer; if you call this command from Lisp code as a function, you must supply the file name string as an ordinary Lisp function argument.

If the command is a string or vector (i.e., a keyboard macro) then execute-kbd-macro is used to execute it. You can call this function yourself (see section Keyboard Macros).

If a command runs away, typing C-g terminates its execution immediately. This is called quitting (see section Quitting).

Variable: pre-command-hook

The editor command loop runs this normal hook before each command.

Variable: post-command-hook

The editor command loop runs this normal hook after each command, and also when the command loop is entered, or reentered after an error or quit.

Defining Commands

A Lisp function becomes a command when its body contains, at top level, a form which calls the special form interactive. This form does nothing when actually executed, but its presence serves as a flag to indicate that interactive calling is permitted. Its argument controls the reading of arguments for an interactive call.

Using interactive

This section describes how to write the interactive form that makes a Lisp function an interactively-callable command.

Special Form: interactive arg-descriptor

This special form declares that the function in which it appears is a command, and that it may therefore be called interactively (via M-x or by entering a key sequence bound to it). The argument arg-descriptor declares the way the arguments to the command are to be computed when the command is called interactively.

A command may be called from Lisp programs like any other function, but then the arguments are supplied by the caller and arg-descriptor has no effect.

The interactive form has its effect because the command loop (actually, its subroutine call-interactively) scans through the function definition looking for it, before calling the function. Once the function is called, all its body forms including the interactive form are executed, but at this time interactive simply returns nil without even evaluating its argument.

There are three possibilities for the argument arg-descriptor:

Code Characters for interactive

The code character descriptions below contain a number of key words, defined here as follows:

Provide completion. TAB, SPC, and RET perform name completion because the argument is read using completing-read (see section Completion). ? displays a list of possible completions.

Require the name of an existing object. An invalid name is not accepted; the commands to exit the minibuffer do not exit if the current input is not valid.

A default value of some sort is used if the user enters no text in the minibuffer. The default depends on the code character.

No I/O
This code letter computes an argument without reading any input. Therefore, it does not use a prompt string, and any prompt string you supply is ignored.

A prompt immediately follows the code character. The prompt ends either with the end of the string or with a newline.

This code character is meaningful only at the beginning of the interactive string, and it does not look for a prompt or a newline. It is a single, isolated character.

Here are the code character descriptions for use with interactive:

Signal an error if the current buffer is read-only. Special.

Select the window mentioned in the first mouse event in the key sequence that invoked this command. Special.

A function name (i.e., a symbol which is fboundp). Existing, Completion, Prompt.

The name of an existing buffer. By default, uses the name of the current buffer (see section Buffers). Existing, Completion, Default, Prompt.

A buffer name. The buffer need not exist. By default, uses the name of a recently used buffer other than the current buffer. Completion, Prompt.

A character. The cursor does not move into the echo area. Prompt.

A command name (i.e., a symbol satisfying commandp). Existing, Completion, Prompt.

The position of point as a number (see section Point). No I/O.

A directory name. The default is the current default directory of the current buffer, default-directory (see section Operating System Environment). Existing, Completion, Default, Prompt.

The first or next mouse event in the key sequence that invoked the command. More precisely, `e' gets events which are lists, so you can look at the data in the lists. See section Input Events. No I/O.

You can use `e' more than once in a single command's interactive specification. If the key sequence which invoked the command has n events with parameters, the nth `e' provides the nth list event. Events which are not lists, such as function keys and ASCII characters, do not count where `e' is concerned.

Even though `e' does not use a prompt string, you must follow it with a newline if it is not the last code character.

A file name of an existing file (see section File Names). The default directory is default-directory. Existing, Completion, Default, Prompt.

A file name. The file need not exist. Completion, Default, Prompt.

A key sequence (see section Keymap Terminology). This keeps reading events until a command (or undefined command) is found in the current key maps. The key sequence argument is represented as a string or vector. The cursor does not move into the echo area. Prompt.

This kind of input is used by commands such as describe-key and global-set-key.

The position of the mark as a number. No I/O.

A number read with the minibuffer. If the input is not a number, the user is asked to try again. The prefix argument, if any, is not used. Prompt.

The raw prefix argument. If the prefix argument is nil, then a number is read as with n. Requires a number. Prompt.

The numeric prefix argument. (Note that this `p' is lower case.) No I/O.

The raw prefix argument. (Note that this `P' is upper case.) See section Prefix Command Arguments. No I/O.

Point and the mark, as two numeric arguments, smallest first. This is the only code letter that specifies two successive arguments rather than one. No I/O.

Arbitrary text, read in the minibuffer and returned as a string (see section Reading Text Strings with the Minibuffer). Terminate the input with either LFD or RET. (C-q may be used to include either of these characters in the input.) Prompt.

An interned symbol whose name is read in the minibuffer. Any whitespace character terminates the input. (Use C-q to include whitespace in the string.) Other characters that normally terminate a symbol (e.g., parentheses and brackets) do not do so here. Prompt.

A variable declared to be a user option (i.e., satisfying the predicate user-variable-p). See section High-Level Completion Functions. Existing, Completion, Prompt.

A Lisp object specified in printed representation, terminated with a LFD or RET. The object is not evaluated. See section Reading Lisp Objects with the Minibuffer. Prompt.

A Lisp form is read as with x, but then evaluated so that its value becomes the argument for the command. Prompt.

Examples of Using interactive

Here are some examples of interactive:

(defun foo1 ()              ; foo1 takes no arguments,
    (interactive)           ;   just moves forward two words.
    (forward-word 2))
     => foo1

(defun foo2 (n)             ; foo2 takes one argument,
    (interactive "p")       ;   which is the numeric prefix.
    (forward-word (* 2 n)))
     => foo2

(defun foo3 (n)             ; foo3 takes one argument,
    (interactive "nCount:") ;   which is read with the Minibuffer.
    (forward-word (* 2 n)))
     => foo3

(defun three-b (b1 b2 b3)
  "Select three existing buffers.
Put them into three windows, selecting the last one."
    (interactive "bBuffer1:\nbBuffer2:\nbBuffer3:")
    (split-window (selected-window) 8)
    (switch-to-buffer b1)
    (other-window 1)
    (split-window (selected-window) 8)
    (switch-to-buffer b2)
    (other-window 1)
    (switch-to-buffer b3))
     => three-b
(three-b "*scratch*" "declarations.texi" "*mail*")
     => nil

Interactive Call

After the command loop has translated a key sequence into a definition, it invokes that definition using the function command-execute. If the definition is a function that is a command, command-execute calls call-interactively, which reads the arguments and calls the command. You can also call these functions yourself.

Function: commandp object

Returns t if object is suitable for calling interactively; that is, if object is a command. Otherwise, returns nil.

The interactively callable objects include strings and vectors (treated as keyboard macros), lambda expressions that contain a top-level call to interactive, byte-code function objects, autoload objects that are declared as interactive (non-nil fourth argument to autoload), and some of the primitive functions.

A symbol is commandp if its function definition is commandp.

Keys and keymaps are not commands. Rather, they are used to look up commands (see section Keymaps).

See documentation in section Access to Documentation Strings, for a realistic example of using commandp.

Function: call-interactively command &optional record-flag

This function calls the interactively callable function command, reading arguments according to its interactive calling specifications. An error is signaled if command cannot be called interactively (i.e., it is not a command). Note that keyboard macros (strings and vectors) are not accepted, even though they are considered commands.

If record-flag is non-nil, then this command and its arguments are unconditionally added to the list command-history. Otherwise, the command is added only if it uses the minibuffer to read an argument. See section Command History.

Function: command-execute command &optional record-flag

This function executes command as an editing command. The argument command must satisfy the commandp predicate; i.e., it must be an interactively callable function or a string.

A string or vector as command is executed with execute-kbd-macro. A function is passed to call-interactively, along with the optional record-flag.

A symbol is handled by using its function definition in its place. A symbol with an autoload definition counts as a command if it was declared to stand for an interactively callable function. Such a definition is handled by loading the specified library and then rechecking the definition of the symbol.

Command: execute-extended-command prefix-argument

This function reads a command name from the minibuffer using completing-read (see section Completion). Then it uses command-execute to call the specified command. Whatever that command returns becomes the value of execute-extended-command.

If the command asks for a prefix argument, the value prefix-argument is supplied. If execute-extended-command is called interactively, the current raw prefix argument is used for prefix-argument, and thus passed on to whatever command is run.

execute-extended-command is the normal definition of M-x, so it uses the string `M-x ' as a prompt. (It would be better to take the prompt from the events used to invoke execute-extended-command, but that is painful to implement.) A description of the value of the prefix argument, if any, also becomes part of the prompt.

(execute-extended-command 1)
---------- Buffer: Minibuffer ----------
M-x forward-word RET
---------- Buffer: Minibuffer ----------
     => t

Function: interactive-p

This function returns t if the containing function (the one that called interactive-p) was called interactively, with the function call-interactively. (It makes no difference whether call-interactively was called from Lisp or directly from the editor command loop.) Note that if the containing function was called by Lisp evaluation (or with apply or funcall), then it was not called interactively.

The usual application of interactive-p is for deciding whether to print an informative message. As a special exception, interactive-p returns nil whenever a keyboard macro is being run. This is to suppress the informative messages and speed execution of the macro.

For example:

(defun foo ()
  (and (interactive-p)
       (message "foo")))
     => foo

(defun bar ()
  (setq foobar (list (foo) (interactive-p))))
     => bar

;; Type M-x foo.
     -| foo

;; Type M-x bar.
;; This does not print anything.

     => (nil t)

Information from the Command Loop

The editor command loop sets several Lisp variables to keep status records for itself and for commands that are run.

Variable: last-command

This variable records the name of the previous command executed by the command loop (the one before the current command). Normally the value is a symbol with a function definition, but this is not guaranteed.

The value is set by copying the value of this-command when a command returns to the command loop, except when the command specifies a prefix argument for the following command.

Variable: this-command

This variable records the name of the command now being executed by the editor command loop. Like last-command, it is normally a symbol with a function definition.

This variable is set by the command loop just before the command is run, and its value is copied into last-command when the command finishes (unless the command specifies a prefix argument for the following command).

Some commands change the value of this variable during their execution, simply as a flag for whatever command runs next. In particular, the functions that kill text set this-command to kill-region so that any kill commands immediately following will know to append the killed text to the previous kill.

Function: this-command-keys

This function returns a string or vector containing the key sequence that invoked the present command, plus any previous commands that generated the prefix argument for this command. The value is a string if all those events were characters. See section Input Events.

;; Now type C-u C-x C-e.
     => "^U^X^E"

Variable: last-nonmenu-event

This variable holds the last input event read as part of a key sequence, aside from events resulting from mouse menus.

One use of this variable is to figure out a good default location to pop up another menu.

Variable: last-command-event

Variable: last-command-char

This variable is set to the last input event that was read by the command loop as part of a command. The principal use of this variable is in self-insert-command, which uses it to decide which character to insert.

;; Now type C-u C-x C-e.
     => 5

The value is 5 because that is the ASCII code for C-e.

The alias last-command-char exists for compatibility with Emacs version 18.

Variable: last-event-frame

This variable records which frame the last input event was directed to. Usually this is the frame that was selected when the event was generated, but if that frame has redirected input focus to another frame, the value is the frame to which the event was redirected. See section Input Focus.

Variable: echo-keystrokes

This variable determines how much time should elapse before command characters echo. Its value must be an integer, which specifies the number of seconds to wait before echoing. If the user types a prefix key (say C-x) and then delays this many seconds before continuing, the key C-x is echoed in the echo area. Any subsequent characters in the same command will be echoed as well.

If the value is zero, then command input is not echoed.

Input Events

The Emacs command loop reads a sequence of input events that represent keyboard or mouse activity. The events for keyboard activity are characters or symbols; mouse events are always lists. This section describes the representation and meaning of input events in detail.

A command invoked using events that are lists can get the full values of these events using the `e' interactive code. See section Code Characters for interactive.

A key sequence that starts with a mouse event is read using the keymaps of the buffer in the window that the mouse was in, not the current buffer. This does not imply that clicking in a window selects that window or its buffer--that is entirely under the control of the command binding of the key sequence.

Function: eventp object

This function returns non-nil if event is an input event.

Keyboard Events

There are two kinds of input you can get from the keyboard: ordinary keys, and function keys. Ordinary keys correspond to characters; the events they generate are represented in Lisp as characters. In Emacs versions 18 and earlier, characters were the only events.

An input character event consists of a basic code between 0 and 255, plus any or all of these modifier bits:

The 2**23 bit in the character code indicates a character typed with the meta key held down.

The 2**22 bit in the character code indicates a non-ASCII control character.

ASCII control characters such as C-a have special basic codes of their own, so Emacs needs no special bit to indicate them. Thus, the code for C-a is just 1.

But if you type a control combination not in ASCII, such as % with the control key, the numeric value you get is the code for % plus 2**22 (assuming the terminal supports non-ASCII control characters).

The 2**21 bit in the character code indicates an ASCII control character typed with the shift key held down.

For letters, the basic code indicates upper versus lower case; for digits and punctuation, the shift key selects an entirely different character with a different basic code. In order to keep within the ASCII character set whenever possible, Emacs avoids using the 2**21 bit for those characters.

However, ASCII provides no way to distinguish C-A from C-A, so Emacs uses the 2**21 bit in C-A and not in C-a.

The 2**20 bit in the character code indicates a character typed with the hyper key held down.

The 2**19 bit in the character code indicates a character typed with the super key held down.

The 2**18 bit in the character code indicates a character typed with the alt key held down. (On some terminals, the key labeled ALT is actually the meta key.)

In the future, Emacs may support a larger range of basic codes. We may also move the modifier bits to larger bit numbers. Therefore, you should avoid mentioning specific bit numbers in your program. Instead, the way to test the modifier bits of a character is with the function event-modifiers (see section Classifying Events).

Function Keys

Most keyboards also have function keys---keys which have names or symbols that are not characters. Function keys are represented in Lisp as symbols; the symbol's name is the function key's label. For example, pressing a key labeled F1 places the symbol f1 in the input stream.

For all keyboard events, the event type (which classifies the event for key lookup purposes) is identical to the event--it is the character or the symbol. See section Classifying Events.

Here are a few special cases in the symbol naming convention for function keys:

backspace, tab, newline, return, delete
These keys correspond to common ASCII control characters that have special keys on most keyboards.

In ASCII, C-i and TAB are the same character. Emacs lets you distinguish them if you wish, by returning the former as the integer 9, and the latter as the symbol tab.

Most of the time, it's not useful to distinguish the two. So normally function-key-map is set up to map tab into 9. Thus, a key binding for character code 9 also applies to tab. Likewise for the other symbols in this group. The function read-char also converts these events into characters.

In ASCII, BS is really C-h. But backspace converts into the character code 127 (DEL), not into code 8 (BS). This is what most users prefer.

kp-add, kp-decimal, kp-divide, ...
Keypad keys (to the right of the regular keyboard).
kp-0, kp-1, ...
Keypad keys with digits.
kp-f1, kp-f2, kp-f3, kp-f4
Keypad PF keys.
left, up, right, down
Cursor arrow keys

You can use the modifier keys CTRL, META, HYPER, SUPER, ALT and SHIFT with function keys. The way to represent them is with prefixes in the symbol name:

The alt modifier.
The control modifier.
The hyper modifier.
The meta modifier.
The shift modifier.
The super modifier.

Thus, the symbol for the key F3 with META held down is M-F3. When you use more than one prefix, we recommend you write them in alphabetical order (though the order does not matter in arguments to the key-binding lookup and modification functions).

Click Events

When the user presses a mouse button and releases it at the same location, that generates a click event. Mouse click events have this form:

 (window buffer-pos
  (column . row) timestamp)

Here is what the elements normally mean:

This is a symbol that indicates which mouse button was used. It is one of the symbols mouse-1, mouse-2, ..., where the buttons are numbered numbered left to right.

You can also use prefixes `A-', `C-', `H-', `M-', `S-' and `s-' for modifiers alt, control, hyper, meta, shift and super, just as you would with function keys.

This symbol also serves as the event type of the event. Key bindings describe events by their types; thus, if there is a key binding for mouse-1, that binding would apply to all events whose event-type is mouse-1.

This is the window in which the click occurred.

These are the column and row of the click, relative to the top left corner of window, which is (0 . 0).

This is the buffer position of the character clicked on.

This is the time at which the event occurred, in milliseconds. (Since this value wraps around the entire range of Emacs Lisp integers in about five hours, it is useful only for relating the times of nearby events.)

This is the number of rapid repeated presses so far of the same mouse button. See section Repeat Events.

The meanings of buffer-pos, row and column are somewhat different when the event location is in a special part of the screen, such as the mode line or a scroll bar.

If the location is in a scroll bar, then buffer-pos is the symbol vertical-scroll-bar or horizontal-scroll-bar, and the pair (column . row) is replaced with a pair (portion . whole), where portion is the distance of the click from the top or left end of the scroll bar, and whole is the length of the entire scroll bar.

If the position is on a mode line or the vertical line separating window from its neighbor to the right, then buffer-pos is the symbol mode-line or vertical-line. For the mode line, row does not have meaningful data. For the vertical line, column does not have meaningful data.

buffer-pos may be a list containing a symbol (one of the symbols listed above) instead of just the symbol. This is what happens after the imaginary prefix keys for these events are inserted into the input stream. See section Key Sequence Input.

Drag Events

With Emacs, you can have a drag event without even changing your clothes. A drag event happens every time the user presses a mouse button and then moves the mouse to a different character position before releasing the button. Like all mouse events, drag events are represented in Lisp as lists. The lists record both the starting mouse position and the final position, like this:

 (window1 buffer-pos1
  (column1 . row1) timestamp1)
 (window2 buffer-pos2
  (column2 . row2) timestamp2)

For a drag event, the name of the symbol event-type contains the prefix `drag-'. The second and third elements of the event give the starting and ending position of the drag. Aside from that, the data have the same meanings as in a click event (see section Click Events). You can access the second element of any mouse event in the same way, with no need to distinguish drag events from others.

The `drag-' prefix follows the modifier key prefixes such as `C-' and `M-'.

If read-key-sequence receives a drag event which has no key binding, and the corresponding click event does have a binding, it changes the drag event into a click event at the drag's starting position. This means that you don't have to distinguish between click and drag events unless you want to.

Button-Down Events

Click and drag events happen when the user releases a mouse button. They cannot happen earlier, because there is no way to distinguish a click from a drag until the button is released.

If you want to take action as soon as a button is pressed, you need to handle button-down events.(2). These occur as soon as a button is pressed. They are represented by lists which look exactly like click events (see section Click Events), except that the name of event-type contains the prefix `down-'. The `down-' prefix follows the modifier key prefixes such as `C-' and `M-'.

The function read-key-sequence, and the Emacs command loop, ignore any button-down events that don't have command bindings. This means that you need not worry about defining button-down events unless you want them to do something. The usual reason to define a button-down event is so that you can track mouse motion (by reading motion events) until the button is released.

Repeat Events

If you press the same mouse button more than once in quick succession without moving the mouse, Emacs uses special repeat mouse events for the second and subsequent presses.

The most common repeat events are double-click events. Emacs generates a double-click event when you click a button twice; the event happens when you release the button (as is normal for all click events).

The event type of a double-click event contains the prefix double. Thus, a double click on the second mouse button with meta held down comes to the Lisp program as M-double-mouse-2. If a double-click event has no binding, the binding of the corresponding ordinary click event is used to execute it. Thus, you need not pay attention to the double click feature unless you really want to.

When the user performs a double click, Emacs generates first an ordinary click event, and then a double-click event. Therefore, the command binding of the double click event must be written to assume that the single-click command has already run. It must produce the desired results of a double click, starting from the results of a single click.

This means that it is most convenient to give double clicks a meaning that somehow "builds on" the meaning of a single click. This is what user interface experts recommend that double clicks should do.

If you click a button, then press it down again and start moving the mouse with the button held down, then you get a double-drag event when you ultimately release the button. Its event type contains `double-drag' instead of just `drag'. If a double-drag event has no binding, Emacs looks for an alternate binding as if the event were an ordinary click.

Before the double-click or double-drag event, Emacs generates a double-down event when the button is pressed down for the second time. Its event type contains `double-down' instead of just `down'. If a double-down event has no binding, Emacs looks for an alternate binding as if the event were an ordinary button-down event. If it finds no binding that way either, the double-down event is ignored.

To summarize, when you click a button and then press it again right away, Emacs generates a double-down event, followed by either a double-click or a double-drag.

If you click a button twice and then press it again, all in quick succession, Emacs generates a triple-down event, followed by either a triple-click or a triple-drag. The event types of these events contain `triple' instead of `double'. If any triple event has no binding, Emacs uses the binding that it would use for the corresponding double event.

If you click a button three or more times and then press it again, the events for the presses beyond the third are all triple events. Emacs does not have quadruple, quintuple, etc. events as separate event types. However, you can look at the event list to find out precisely how many times the button was pressed.

Function: event-click-count event

This function returns the number of consecutive button presses that led up to event. If event is a double-down, double-click or double-drag event, the value is 2. If event is a triple event, the value is 3 or greater. If event is an ordinary mouse event (not a repeat event), the value is 1.

Variable: double-click-time

To count as double- and triple-clicks, mouse clicks must be at the same location as the first click, and the number of milliseconds between the first release and the second must be less than the value of double-click-time. Setting double-click-time to nil disables multi-click detection entirely. Setting it to t removes the time limit; Emacs then detects multi-clicks by position only.

Motion Events

Emacs sometimes generates mouse motion events to describe motion of the mouse without any button activity. Mouse motion events are represented by lists that look like this:

 (window buffer-pos
  (column . row) timestamp))

The second element of the list describes the current position of the mouse, just as in a click event (see section Click Events).

The special form track-mouse enables generation of motion events within its body. Outside of track-mouse forms, Emacs does not generate events for mere motion of the mouse, and these events do not appear.

Special Form: track-mouse body...

This special form executes body, with generation of mouse motion events enabled. Typically body would use read-event to read the motion events and modify the display accordingly.

When the user releases the button, that generates a click event. Normally body should return when it sees the click event, and discard the event.

Focus Events

Window systems provide general ways for the user to control which window gets keyboard input. This choice of window is called the focus. When the user does something to switch between Emacs frames, that generates a focus event. The normal definition of a focus event, in the global keymap, is to select a new frame within Emacs, as the user would expect. See section Input Focus.

Focus events are represented in Lisp as lists that look like this:

(switch-frame new-frame)

where new-frame is the frame switched to.

In X windows, most window managers are set up so that just moving the mouse into a window is enough to set the focus there. Emacs appears to do this, because it changes the cursor to solid in the new frame. However, there is no need for the Lisp program to know about the focus change until some other kind of input arrives. So Emacs generates the focus event only when the user actually types a keyboard key or presses a mouse button in the new frame; just moving the mouse between frames does not generate a focus event.

A focus event in the middle of a key sequence would garble the sequence. So Emacs never generates a focus event in the middle of a key sequence. If the user changes focus in the middle of a key sequence--that is, after a prefix key--then Emacs reorders the events so that the focus event comes either before or after the multi-event key sequence, and not within it.

Event Examples

If the user presses and releases the left mouse button over the same location, that generates a sequence of events like this:

(down-mouse-1 (#<window 18 on NEWS> 2613 (0 . 38) -864320))
(mouse-1      (#<window 18 on NEWS> 2613 (0 . 38) -864180))

Or, while holding the control key down, the user might hold down the second mouse button, and drag the mouse from one line to the next. That produces two events, as shown here:

(C-down-mouse-2 (#<window 18 on NEWS> 3440 (0 . 27) -731219))
(C-drag-mouse-2 (#<window 18 on NEWS> 3440 (0 . 27) -731219)
                (#<window 18 on NEWS> 3510 (0 . 28) -729648))

Or, while holding down the meta and shift keys, the user might press the second mouse button on the window's mode line, and then drag the mouse into another window. That produces the following pair of events:

(M-S-down-mouse-2 (#<window 18 on NEWS> mode-line (33 . 31) -457844))
(M-S-drag-mouse-2 (#<window 18 on NEWS> mode-line (33 . 31) -457844)
                  (#<window 20 on carlton-sanskrit.tex> 161 (33 . 3)

Classifying Events

Every event has an event type which classifies the event for key binding purposes. For a keyboard event, the event type equals the event value; thus, the event type for a character is the character, and the event type for a function key symbol is the symbol itself. For events which are lists, the event type is the symbol in the CAR of the list. Thus, the event type is always a symbol or a character.

Two events of the same type are equivalent where key bindings are concerned; thus, they always run the same command. That does not necessarily mean they do the same things, however, as some commands look at the whole event to decide what to do. For example, some commands use the location of a mouse event to decide what text to act on.

Sometimes broader classifications of events are useful. For example, you might want to ask whether an event involved the META key, regardless of which other key or mouse button was used.

The functions event-modifiers and event-basic-type are provided to get such information conveniently.

Function: event-modifiers event

This function returns a list of the modifiers that event has. The modifiers are symbols; they include shift, control, meta, alt, hyper and super. In addition, the property of a mouse event symbol always has one of click, drag, and down among the modifiers. For example:

(event-modifiers ?a)
     => nil
(event-modifiers ?\C-a)
     => (control)
(event-modifiers ?\C-%)
     => (control)
(event-modifiers ?\C-\S-a)
     => (control shift)
(event-modifiers 'f5)
     => nil
(event-modifiers 's-f5)
     => (super)
(event-modifiers 'M-S-f5)
     => (meta shift)
(event-modifiers 'mouse-1)
     => (click)
(event-modifiers 'down-mouse-1)
     => (down)

The modifiers list for a click event explicitly contains click, but the event symbol name itself does not contain `click'.

Function: event-basic-type event

This function returns the key or mouse button that event describes, with all modifiers removed. For example:

(event-basic-type ?a)
     => 97
(event-basic-type ?A)
     => 97
(event-basic-type ?\C-a)
     => 97
(event-basic-type ?\C-\S-a)
     => 97
(event-basic-type 'f5)
     => f5
(event-basic-type 's-f5)
     => f5
(event-basic-type 'M-S-f5)
     => f5
(event-basic-type 'down-mouse-1)
     => mouse-1

Function: mouse-movement-p object

This function returns non-nil if object is a mouse movement event.

Accessing Events

This section describes convenient functions for accessing the data in an event which is a list.

The following functions return the starting or ending position of a mouse-button event. The position is a list of this form:

(window buffer-position (col . row) timestamp)

Function: event-start event

This returns the starting position of event.

If event is a click or button-down event, this returns the location of the event. If event is a drag event, this returns the drag's starting position.

Function: event-end event

This returns the ending position of event.

If event is a drag event, this returns the position where the user released the mouse button. If event is a click or button-down event, the value is actually the starting position, which is the only position such events have.

These four functions take a position-list as described above, and return various parts of it.

Function: posn-window position

Return the window that position is in.

Function: posn-point position

Return the buffer location in position.

Function: posn-col-row position

Return the row and column in position, as a list (col . row).

Function: posn-timestamp position

Return the timestamp of position.

Function: scroll-bar-scale ratio total

This function multiples (in effect) ratio by total, rounding the result to an integer. ratio is not a number, but rather a pair (num . denom).

This is handy for scaling a position on a scroll bar into a buffer position. Here's how to do that:

(+ (point-min)
      (posn-col-row (event-start event))
      (- (point-max) (point-min))))

Putting Keyboard Events in Strings

In most of the places where strings are used, we conceptualize the string as containing text characters--the same kind of characters found in buffers or files. Occasionally Lisp programs use strings which conceptually contain keyboard characters; for example, they may be key sequences or keyboard macro definitions. There are special rules for how to put keyboard characters into a string, because they are not limited to the range of 0 to 255 as text characters are.

A keyboard character typed using the META key is called a meta character. The numeric code for such an event includes the 2**23 bit; it does not even come close to fitting in a string. However, earlier Emacs versions used a different representation for these characters, which gave them codes in the range of 128 to 255. That did fit in a string, and many Lisp programs contain string constants that use `\M-' to express meta characters, especially as the argument to define-key and similar functions.

We provide backward compatibility to run those programs with special rules for how to put a keyboard character event in a string. Here are the rules:

Functions such as read-key-sequence that can construct strings containing events follow these rules.

When you use the read syntax `\M-' in a string, it produces a code in the range of 128 to 255--the same code that you get if you modify the corresponding keyboard event to put it in the string. Thus, meta events in strings work consistently regardless of how they get into the strings.

New programs can avoid dealing with these rules by using vectors instead of strings for key sequences when there is any possibility that these issues might arise.

The reason we changed the representation of meta characters as keyboard events is to make room for basic character codes beyond 127, and support meta variants of such larger character codes.

Reading Input

The editor command loop reads keyboard input using the function read-key-sequence, which uses read-event. These and other functions for keyboard input are also available for use in Lisp programs. See also momentary-string-display in section Temporary Displays, and sit-for in section Waiting for Elapsed Time or Input. See section Terminal Input, for functions and variables for controlling terminal input modes and debugging terminal input.

For higher-level input facilities, see section Minibuffers.

Key Sequence Input

The command loop reads input a key sequence at a time, by calling read-key-sequence. Lisp programs can also call this function; for example, describe-key uses it to read the key to describe.

Function: read-key-sequence prompt

This function reads a key sequence and returns it as a string or vector. It keeps reading events until it has accumulated a full key sequence; that is, enough to specify a non-prefix command using the currently active keymaps.

If the events are all characters and all can fit in a string, then read-key-sequence returns a string (see section Putting Keyboard Events in Strings). Otherwise, it returns a vector, since a vector can hold all kinds of events--characters, symbols, and lists. The elements of the string or vector are the events in the key sequence.

Quitting is suppressed inside read-key-sequence. In other words, a C-g typed while reading with this function is treated like any other character, and does not set quit-flag. See section Quitting.

The argument prompt is either a string to be displayed in the echo area as a prompt, or nil, meaning not to display a prompt.

In the example below, the prompt `?' is displayed in the echo area, and the user types C-x C-f.

(read-key-sequence "?")

---------- Echo Area ----------
?C-x C-f
---------- Echo Area ----------

     => "^X^F"

Variable: num-input-keys

This variable's value is the number of key sequences processed so far in this Emacs session. This includes key sequences read from the terminal and key sequences read from keyboard macros being executed.

If an input character is an upper case letter and has no key binding, but the lower case equivalent has one, then read-key-sequence converts the character to lower case. Note that lookup-key does not perform case conversion in this way.

The function read-key-sequence also transforms some mouse events. It converts unbound drag events into click events, and discards unbound button-down events entirely. It also reshuffles focus events so that they never appear in a key sequence with any other events.

When mouse events occur in special parts of a window, such as a mode line or a scroll bar, the event itself shows nothing special--only the symbol that would normally represent that mouse button and modifier keys. The information about the screen region is kept elsewhere in the event--in the coordinates. But read-key-sequence translates this information into imaginary prefix keys, all of which are symbols: mode-line, vertical-line, horizontal-scroll-bar and vertical-scroll-bar.

For example, if you call read-key-sequence and then click the mouse on the window's mode line, this is what happens:

(read-key-sequence "Click on the mode line: ")
     => [mode-line
           (#<window 6 on NEWS> mode-line
            (40 . 63) 5959987))]

You can define meanings for mouse clicks in special window regions by defining key sequences using these imaginary prefix keys.

Reading One Event

The lowest level functions for command input are those which read a single event.

Function: read-event

This function reads and returns the next event of command input, waiting if necessary until an event is available. Events can come directly from the user or from a keyboard macro.

The function read-event does not display any message to indicate it is waiting for input; use message first, if you wish to display one. If you have not displayed a message, read-event does prompting: it displays descriptions of the events that led to or were read by the current command. See section The Echo Area.

If cursor-in-echo-area is non-nil, then read-event moves the cursor temporarily to the echo area, to the end of any message displayed there. Otherwise read-event does not move the cursor.

Here is what happens if you call read-event and then press the right-arrow function key:

     => right

Function: read-char

This function reads and returns a character of command input. It discards any events that are not characters until it gets a character.

In the first example, the user types 1 (which is ASCII code 49). The second example shows a keyboard macro definition that calls read-char from the minibuffer. read-char reads the keyboard macro's very next character, which is 1. The value of this function is displayed in the echo area by the command eval-expression.

     => 49

(symbol-function 'foo)
     => "^[^[(read-char)^M1"
(execute-kbd-macro foo)
     -| 49
     => nil

Quoted Character Input

You can use the function read-quoted-char when you want the user to specify a character, and allow the user to specify a control or meta character conveniently with quoting or as an octal character code. The command quoted-insert calls this function.

Function: read-quoted-char &optional prompt

This function is like read-char, except that if the first character read is an octal digit (0-7), it reads up to two more octal digits (but stopping if a non-octal digit is found) and returns the character represented by those digits as an octal number.

Quitting is suppressed when the first character is read, so that the user can enter a C-g. See section Quitting.

If prompt is supplied, it specifies a string for prompting the user. The prompt string is always printed in the echo area and followed by a single `-'.

In the following example, the user types in the octal number 177 (which is 127 in decimal).

(read-quoted-char "What character")

---------- Echo Area ----------
What character-177
---------- Echo Area ----------

     => 127

Peeking and Discarding

Variable: unread-command-events

This variable holds a list of events waiting to be read as command input. The events are used in the order they appear in the list.

The variable is used because in some cases a function reads a event and then decides not to use it. Storing the event in this variable causes it to be processed normally by the command loop or when the functions to read command input are called.

For example, the function that implements numeric prefix arguments reads any number of digits. When it finds a non-digit event, it must unread the event so that it can be read normally by the command loop. Likewise, incremental search uses this feature to unread events it does not recognize.

Variable: unread-command-char

This variable holds a character to be read as command input. A value of -1 means "empty".

This variable is pretty much obsolete now that you can use unread-command-events instead; it exists only to support programs written for Emacs versions 18 and earlier.

Function: listify-key-sequence key

This function converts the string or vector key to a list of events which you can put in unread-command-events. Converting a vector is simple, but converting a string is tricky because of the special representation used for meta characters in a string (see section Putting Keyboard Events in Strings).

Function: input-pending-p

This function determines whether any command input is currently available to be read. It returns immediately, with value t if there is input, nil otherwise. On rare occasions it may return t when no input is available.

Variable: last-input-event

Variable: last-input-char

This variable records the last terminal input event read, whether as part of a command or explicitly by a Lisp program.

In the example below, a character is read (the character 1, ASCII code 49). It becomes the value of last-input-char, while C-e (from the C-x C-e command used to evaluate this expression) remains the value of last-command-char.

(progn (print (read-char))
       (print last-command-char)
     -| 49
     -| 5
     => 49

The alias last-input-char exists for compatibility with Emacs version 18.

Function: discard-input

This function discards the contents of the terminal input buffer and cancels any keyboard macro that might be in the process of definition. It returns nil.

In the following example, the user may type a number of characters right after starting the evaluation of the form. After the sleep-for finishes sleeping, any characters that have been typed are discarded.

(progn (sleep-for 2)
     => nil

Waiting for Elapsed Time or Input

The waiting commands are designed to make Emacs wait for a certain amount of time to pass or until there is input. For example, you may wish to pause in the middle of a computation to allow the user time to view the display. sit-for pauses and updates the screen, and returns immediately if input comes in, while sleep-for pauses without updating the screen.

Function: sit-for seconds &optional millisec nodisp

This function performs redisplay (provided there is no pending input from the user), then waits seconds seconds, or until input is available. The result is t if sit-for waited the full time with no input arriving (see input-pending-p in section Peeking and Discarding). Otherwise, the value is nil.

The optional argument millisec specifies an additional waiting period measured in milliseconds. This adds to the period specified by seconds. Not all operating systems support waiting periods other than multiples of a second; on those that do not, you get an error if you specify nonzero millisec.

Redisplay is always preempted if input arrives, and does not happen at all if input is available before it starts. Thus, there is no way to force screen updating if there is pending input; however, if there is no input pending, you can force an update with no delay by using (sit-for 0).

If nodisp is non-nil, then sit-for does not redisplay, but it still returns as soon as input is available (or when the timeout elapses).

The usual purpose of sit-for is to give the user time to read text that you display.

Function: sleep-for seconds &optional millisec

This function simply pauses for seconds seconds without updating the display. It pays no attention to available input. It returns nil.

The optional argument millisec specifies an additional waiting period measured in milliseconds. This adds to the period specified by seconds. Not all operating systems support waiting periods other than multiples of a second; on those that do not, you get an error if you specify nonzero millisec.

Use sleep-for when you wish to guarantee a delay.

See section Time of Day, for functions to get the current time.


Typing C-g while the command loop has run a Lisp function causes Emacs to quit whatever it is doing. This means that control returns to the innermost active command loop.

Typing C-g while the command loop is waiting for keyboard input does not cause a quit; it acts as an ordinary input character. In the simplest case, you cannot tell the difference, because C-g normally runs the command keyboard-quit, whose effect is to quit. However, when C-g follows a prefix key, the result is an undefined key. The effect is to cancel the prefix key as well as any prefix argument.

In the minibuffer, C-g has a different definition: it aborts out of the minibuffer. This means, in effect, that it exits the minibuffer and then quits. (Simply quitting would return to the command loop within the minibuffer.) The reason why C-g does not quit directly when the command reader is reading input is so that its meaning can be redefined in the minibuffer in this way. C-g following a prefix key is not redefined in the minibuffer, and it has its normal effect of canceling the prefix key and prefix argument. This too would not be possible if C-g quit directly.

C-g causes a quit by setting the variable quit-flag to a non-nil value. Emacs checks this variable at appropriate times and quits if it is not nil. Setting quit-flag non-nil in any way thus causes a quit.

At the level of C code, quits cannot happen just anywhere; only at the special places which check quit-flag. The reason for this is that quitting at other places might leave an inconsistency in Emacs's internal state. Because quitting is delayed until a safe place, quitting cannot make Emacs crash.

Certain functions such as read-key-sequence or read-quoted-char prevent quitting entirely even though they wait for input. Instead of quitting, C-g serves as the requested input. In the case of read-key-sequence, this serves to bring about the special behavior of C-g in the command loop. In the case of read-quoted-char, this is so that C-q can be used to quote a C-g.

You can prevent quitting for a portion of a Lisp function by binding the variable inhibit-quit to a non-nil value. Then, although C-g still sets quit-flag to t as usual, the usual result of this--a quit--is prevented. Eventually, inhibit-quit will become nil again, such as when its binding is unwound at the end of a let form. At that time, if quit-flag is still non-nil, the requested quit happens immediately. This behavior is ideal for a "critical section", where you wish to make sure that quitting does not happen within that part of the program.

In some functions (such as read-quoted-char), C-g is handled in a special way which does not involve quitting. This is done by reading the input with inhibit-quit bound to t and setting quit-flag to nil before inhibit-quit becomes nil again. This excerpt from the definition of read-quoted-char shows how this is done; it also shows that normal quitting is permitted after the first character of input.

(defun read-quoted-char (&optional prompt)
  (let ((count 0) (code 0) char)
    (while (< count 3)
      (let ((inhibit-quit (zerop count))
            (help-form nil))
        (and prompt (message "%s-" prompt))
        (setq char (read-char))
        (if inhibit-quit (setq quit-flag nil)))
    (logand 255 code)))

Variable: quit-flag

If this variable is non-nil, then Emacs quits immediately, unless inhibit-quit is non-nil. Typing C-g sets quit-flag non-nil, regardless of inhibit-quit.

Variable: inhibit-quit

This variable determines whether Emacs should quit when quit-flag is set to a value other than nil. If inhibit-quit is non-nil, then quit-flag has no special effect.

Command: keyboard-quit

This function signals the quit condition with (signal 'quit nil). This is the same thing that quitting does. (See signal in section Errors.)

You can specify a character other than C-g to use for quitting. See the function set-input-mode in section Terminal Input.

Prefix Command Arguments

Most Emacs commands can use a prefix argument, a number specified before the command itself. (Don't confuse prefix arguments with prefix keys.) The prefix argument is represented by a value that is always available (though it may be nil, meaning there is no prefix argument). Each command may use the prefix argument or ignore it.

There are two representations of the prefix argument: raw and numeric. The editor command loop uses the raw representation internally, and so do the Lisp variables that store the information, but commands can request either representation.

Here are the possible values of a raw prefix argument:

The various possibilities may be illustrated by calling the following function with various prefixes:

(defun display-prefix (arg)
  "Display the value of the raw prefix arg."
  (interactive "P")
  (message "%s" arg))

Here are the results of calling print-prefix with various raw prefix arguments:

        M-x print-prefix  -| nil

C-u     M-x print-prefix  -| (4)

C-u C-u M-x print-prefix  -| (16)

C-u 3   M-x print-prefix  -| 3

M-3     M-x print-prefix  -| 3      ; (Same as C-u 3.)

C-u -   M-x print-prefix  -| -      

M- -    M-x print-prefix  -| -      ; (Same as C-u -.)

C-u -7  M-x print-prefix  -| -7     

M- -7   M-x print-prefix  -| -7     ; (Same as C-u -7.)

Emacs uses two variables to store the prefix argument: prefix-arg and current-prefix-arg. Commands such as universal-argument that set up prefix arguments for other commands store them in prefix-arg. In contrast, current-prefix-arg conveys the prefix argument to the current command, so setting it has no effect on the prefix arguments for future commands.

Normally, commands specify which representation to use for the prefix argument, either numeric or raw, in the interactive declaration. (See section Interactive Call.) Alternatively, functions may look at the value of the prefix argument directly in the variable current-prefix-arg, but this is less clean.

Do not call the functions universal-argument, digit-argument, or negative-argument unless you intend to let the user enter the prefix argument for the next command.

Command: universal-argument

This command reads input and specifies a prefix argument for the following command. Don't call this command yourself unless you know what you are doing.

Command: digit-argument arg

This command adds to the prefix argument for the following command. The argument arg is the raw prefix argument as it was before this command; it is used to compute the updated prefix argument. Don't call this command yourself unless you know what you are doing.

Command: negative-argument arg

This command adds to the numeric argument for the next command. The argument arg is the raw prefix argument as it was before this command; its value is negated to form the new prefix argument. Don't call this command yourself unless you know what you are doing.

Function: prefix-numeric-value arg

This function returns the numeric meaning of a valid raw prefix argument value, arg. The argument may be a symbol, a number, or a list. If it is nil, the value 1 is returned; if it is any other symbol, the value -1 is returned. If it is a number, that number is returned; if it is a list, the CAR of that list (which should be a number) is returned.

Variable: current-prefix-arg

This variable is the value of the raw prefix argument for the current command. Commands may examine it directly, but the usual way to access it is with (interactive "P").

Variable: prefix-arg

The value of this variable is the raw prefix argument for the next editing command. Commands that specify prefix arguments for the following command work by setting this variable.

Recursive Editing

The Emacs command loop is entered automatically when Emacs starts up. This top-level invocation of the command loop is never exited until the Emacs is killed. Lisp programs can also invoke the command loop. Since this makes more than one activation of the command loop, we call it recursive editing. A recursive editing level has the effect of suspending whatever command invoked it and permitting the user to do arbitrary editing before resuming that command.

The commands available during recursive editing are the same ones available in the top-level editing loop and defined in the keymaps. Only a few special commands exit the recursive editing level; the others return to the recursive editing level when finished. (The special commands for exiting are always available, but do nothing when recursive editing is not in progress.)

All command loops, including recursive ones, set up all-purpose error handlers so that an error in a command run from the command loop will not exit the loop.

Minibuffer input is a special kind of recursive editing. It has a few special wrinkles, such as enabling display of the minibuffer and the minibuffer window, but fewer than you might suppose. Certain keys behave differently in the minibuffer, but that is only because of the minibuffer's local map; if you switch windows, you get the usual Emacs commands.

To invoke a recursive editing level, call the function recursive-edit. This function contains the command loop; it also contains a call to catch with tag exit, which makes it possible to exit the recursive editing level by throwing to exit (see section Explicit Nonlocal Exits: catch and throw). If you throw a value other than t, then recursive-edit returns normally to the function that called it. The command C-M-c (exit-recursive-edit) does this. Throwing a t value causes recursive-edit to quit, so that control returns to the command loop one level up. This is called aborting, and is done by C-] (abort-recursive-edit).

Most applications should not use recursive editing, except as part of using the minibuffer. Usually it is more convenient for the user if you change the major mode of the current buffer temporarily to a special major mode, which has a command to go back to the previous mode. (This technique is used by the w command in Rmail.) Or, if you wish to give the user different text to edit "recursively", create and select a new buffer in a special mode. In this mode, define a command to complete the processing and go back to the previous buffer. (The m command in Rmail does this.)

Recursive edits are useful in debugging. You can insert a call to debug into a function definition as a sort of breakpoint, so that you can look around when the function gets there. debug invokes a recursive edit but also provides the other features of the debugger.

Recursive editing levels are also used when you type C-r in query-replace or use C-x q (kbd-macro-query).

Function: recursive-edit

This function invokes the editor command loop. It is called automatically by the initialization of Emacs, to let the user begin editing. When called from a Lisp program, it enters a recursive editing level.

In the following example, the function simple-rec first advances point one word, then enters a recursive edit, printing out a message in the echo area. The user can then do any editing desired, and then type C-M-c to exit and continue executing simple-rec.

(defun simple-rec ()
  (forward-word 1)
  (message "Recursive edit in progress.")
  (forward-word 1))
     => simple-rec
     => nil

Command: exit-recursive-edit

This function exits from the innermost recursive edit (including minibuffer input). Its definition is effectively (throw 'exit nil).

Command: abort-recursive-edit

This function aborts the command that requested the innermost recursive edit (including minibuffer input), by signaling quit after exiting the recursive edit. Its definition is effectively (throw 'exit t). See section Quitting.

Command: top-level

This function exits all recursive editing levels; it does not return a value, as it jumps completely out of any computation directly back to the main command loop.

Function: recursion-depth

This function returns the current depth of recursive edits. When no recursive edit is active, it returns 0.

Disabling Commands

Disabling a command marks the command as requiring user confirmation before it can be executed. Disabling is used for commands which might be confusing to beginning users, to prevent them from using the commands by accident.

The low-level mechanism for disabling a command is to put a non-nil disabled property on the Lisp symbol for the command. These properties are normally set up by the user's `.emacs' file with Lisp expressions such as this:

(put 'upcase-region 'disabled t)

For a few commands, these properties are present by default and may be removed by the `.emacs' file.

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
     "Text deleted this way cannot be yanked back!\n")

See section `Disabling' in The GNU Emacs Manual, for the details on what happens when a disabled command is invoked interactively. Disabling a command has no effect on calling it as a function from Lisp programs.

Command: enable-command command

Allow command to be executed without special confirmation from now on. The user's `.emacs' file is optionally altered so that this will apply to future sessions.

Command: disable-command command

Require special confirmation to execute command from now on. The user's `.emacs' file is optionally altered so that this will apply to future sessions.

Variable: disabled-command-hook

This variable is a normal hook that is run instead of a disabled command, when the user runs the disabled command interactively. The hook functions can use this-command-keys to determine what the user typed to run the command, and thus find the command itself.

By default, disabled-command-hook contains a function that asks the user whether to proceed.

Command History

The command loop keeps a history of the complex commands that have been executed, to make it convenient to repeat these commands. A complex command is one for which the interactive argument reading uses the minibuffer. This includes any M-x command, any M-ESC command, and any command whose interactive specification reads an argument from the minibuffer. Explicit use of the minibuffer during the execution of the command itself does not cause the command to be considered complex.

Variable: command-history

This variable's value is a list of recent complex commands, each represented as a form to evaluate. It continues to accumulate all complex commands for the duration of the editing session, but all but the first (most recent) thirty elements are deleted when a garbage collection takes place (see section Garbage Collection).

=> ((switch-to-buffer "chistory.texi")
    (describe-key "^X^[")
    (visit-tags-table "~/emacs/src/")
    (find-tag "repeat-complex-command"))

This history list is actually a special case of minibuffer history (see section Minibuffer History), with one special twist: the elements are expressions rather than strings.

There are a number of commands devoted to the editing and recall of previous commands. The commands repeat-complex-command, and list-command-history are described in the user manual (see section `Repetition' in The GNU Emacs Manual). Within the minibuffer, the history commands used are the same ones available in any minibuffer.

Keyboard Macros

A keyboard macro is a canned sequence of input events that can be considered a command and made the definition of a key. Don't confuse keyboard macros with Lisp macros (see section Macros).

Function: execute-kbd-macro macro &optional count

This function executes macro as a sequence of events. If macro is a string or vector, then the events in it are executed exactly as if they had been input by the user. The sequence is not expected to be a single key sequence; normally a keyboard macro definition consists of several key sequences concatenated.

If macro is a symbol, then its function definition is used in place of macro. If that is another symbol, this process repeats. Eventually the result should be a string or vector. If the result is not a symbol, string, or vector, an error is signaled.

The argument count is a repeat count; macro is executed that many times. If count is omitted or nil, macro is executed once. If it is 0, macro is executed over and over until it encounters an error or a failing search.

Variable: last-kbd-macro

This variable is the definition of the most recently defined keyboard macro. Its value is a string or vector, or nil.

Variable: executing-macro

This variable contains the string or vector that defines the keyboard macro that is currently executing. It is nil if no macro is currently executing.

Variable: defining-kbd-macro

This variable indicates whether a keyboard macro is being defined. It is set to t by start-kbd-macro, and nil by end-kbd-macro. You can use this variable to make a command behave differently when run from a keyboard macro (perhaps indirectly by calling interactive-p). However, do not set this variable yourself.

The commands are described in the user's manual (see section `Keyboard Macros' in The GNU Emacs Manual).

Go to the previous, next section.