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.
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
Miscellaneous Event Input
Features).
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 it then calls. This is
done by the command execute-extended-command
(see
section Interactive Call).
To execute a command requires first reading the arguments for
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).
To terminate the execution of a running command, type C-g. This character causes quitting (see section Quitting).
this-command
contains the command that is about to
run, and last-command
describes the previous command.
See section Hooks.
this-command
describes the command that just ran, and last-command
describes the command before that. See section Hooks.
Quitting is suppressed while running
pre-command-hook
and post-command-hook
.
If an error happens while executing one of these hooks, it
terminates execution of the hook, and clears the hook variable to
nil
so as to prevent an infinite loop of errors.
A Lisp function becomes a command when its body contains, at top
level, a form that 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.
This section describes how to write the interactive
form that makes a Lisp function an interactively-callable
command.
A command may be called from Lisp programs like any other function, but then the caller supplies the arguments 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:
nil
; then the command is
called with no arguments. This leads quickly to an error if the
command requires one or more arguments.
(interactive (list (region-beginning) (region-end) (read-string "Foo: " nil 'my-history)))Here's how to avoid the problem, by examining point and the mark only after reading the keyboard input:
(interactive (let ((string (read-string "Foo: " nil 'my-history))) (list (region-beginning) (region-end) string)))
(interactive "bFrobnicate buffer: ")The code letter `b' says to read the name of an existing buffer, with completion. The buffer name is the sole argument passed to the command. The rest of the string is a prompt. If there is a newline character in the string, it terminates the prompt. If the string does not end there, then the rest of the string should contain another code character and prompt, specifying another argument. You can specify any number of arguments in this way. The prompt string can use `%' to include previous argument values (starting with the first argument) in the prompt. This is done using
format
(see section Formatting Strings). For example, here
is how you could read the name of an existing buffer followed by a
new name to give to that buffer:
(interactive "bBuffer to rename: \nsRename buffer %s to: ")If the first character in the string is `*', then an error is signaled if the buffer is read-only. If the first character in the string is `@', and if the key sequence used to invoke the command includes any mouse events, then the window associated with the first of those events is selected before the command is run. You can use `*' and `@' together; the order does not matter. Actual reading of arguments is controlled by the rest of the prompt string (starting with the first character that is not `*' or `@').
The code character descriptions below contain a number of key words, defined here as follows:
completing-read
(see section Completion). ? displays a
list of possible completions.
Here are the code character
descriptions for use with interactive
:
fboundp
). Existing, Completion, Prompt.
commandp
). Existing, Completion, Prompt.
default-directory
(see section
Operating System Environment).
Existing, Completion, Default, Prompt.
default-directory
. Existing, Completion, Default,
Prompt.
nil
as the argument's value. No I/O.
describe-key
and
global-set-key
.
user-variable-p
). See section High-Level Completion Functions.
Existing, Completion, Prompt.
nil
. See section Coding Systems. Completion, Existing,
Prompt.
nil
as the argument value. Completion,
Existing, Prompt.
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:") (delete-other-windows) (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
After the command loop has translated a key sequence into a
command it invokes that command using the function
command-execute
. If the command is a function,
command-execute
calls call-interactively
,
which reads the arguments and calls the command. You can also call
these functions yourself.
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 made from such lambda expressions, autoload objects that
are declared as interactive (non-nil
fourth argument
to autoload
), and some of the primitive functions.
A symbol satisfies commandp
if its function
definition satisfies 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
.
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.
The argument keys, if given, specifies the sequence of events to supply if the command inquires which events were used to invoke it.
commandp
predicate; i.e., it must be an interactively callable function or a
keyboard macro. 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.
The argument keys, if given, specifies the sequence of events to supply if the command inquires which events were used to invoke it.
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, it receives the value prefix-argument.
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 ---------- 1 M-x forward-word RET ---------- Buffer: Minibuffer ---------- => t
t
if the containing function (the one whose code
includes the call to 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.) If the
containing function was called by Lisp evaluation (or with
apply
or funcall
), then it was not called
interactively.
The most common use 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 () (interactive) (when (interactive-p) (message "foo"))) => foo (defun bar () (interactive) (setq foobar (list (foo) (interactive-p)))) => bar ;; Type M-x foo. -| foo ;; Type M-x bar. ;; This does not print anything. foobar => (nil t)
The other way to do this sort of job is to make the command take
an argument print-message
which should be
non-nil
in an interactive call, and use the
interactive
spec to make sure it is
non-nil
. Here's how:
(defun foo (&optional print-message) (interactive "p") (when print-message (message "foo")))
The numeric prefix argument, provided by `p', is
never nil
.
The editor command loop sets several Lisp variables to keep status records for itself and for commands that are run.
The value is copied from this-command
when a
command returns to the command loop, except when the command has
specified a prefix argument for the following command.
This variable is always local to the current terminal and cannot be buffer-local. See section Multiple Displays.
last-command
, but never altered by
Lisp programs.
last-command
, it is normally a symbol with a function
definition. The command loop sets this variable just before running a
command, and copies its value into last-command
when
the command finishes (unless the command specified a prefix
argument for the following command).
Some commands set this
variable during their execution, as a flag for whatever command
runs next. In particular, the functions for killing 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.
If you do not want a particular command to be recognized as the
previous command in the case where it got an error, you must code
that command to prevent this. One way is to set
this-command
to t
at the beginning of the
command, and set this-command
back to its proper value
at the end, like this:
(defun foo (args...) (interactive ...) (let ((old-this-command this-command)) (setq this-command t) ...do the work... (setq this-command old-this-command)))
We do not bind this-command
with let
because that would restore the old value in case of error--a
feature of let
which in this case does precisely what
we want to avoid.
(this-command-keys) ;; Now use C-u C-x C-e to evaluate that. => "^U^X^E"
this-command-keys
, except that it always returns the
events in a vector, so you do never need to deal with the
complexities of storing input events in a string (see section Putting Keyboard Events in
Strings).
One use of this variable is for telling
x-popup-menu
where to pop up a menu. It is also used
internally by y-or-n-p
(see section Yes-or-No Queries).
self-insert-command
, which uses it to decide which
character to insert. last-command-event ;; Now use C-u C-x C-e to evaluate that. => 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.
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.
nil
if object is an input event or
event type. Note that any symbol might be used as an event or an event type.
eventp
cannot distinguish whether a symbol is intended
by Lisp code to be used as an event. Instead, it distinguishes
whether the symbol has actually been used in an event that has been
read as input in the current Emacs session. If a symbol has not yet
been so used, eventp
returns nil
.
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. The event type of a character event is the character itself (an integer); see section Classifying Events.
An input character event consists of a basic code between 0 and 524287, plus any or all of these modifier bits:
It is best to avoid mentioning specific bit numbers in your
program. To test the modifier bits of a character, use the function
event-modifiers
(see section Classifying Events). When making key
bindings, you can use the read syntax for characters with modifier
bits (`\C-', `\M-', and so on). For
making key bindings with define-key
, you can use lists
such as (control hyper ?x)
to specify the characters
(see section Changing Key
Bindings). The function event-convert-list
converts such a list into an event type (see section Classifying Events).
Most keyboards also have
function keys---keys that have names or symbols that are
not characters. Function keys are represented in Emacs Lisp as
symbols; the symbol's name is the function key's label, in lower
case. For example, pressing a key labeled F1 places the
symbol f1
in the input stream.
The event type of a function key event is the event symbol itself. See section Classifying Events.
Here are a few special cases in the symbol-naming convention for function keys:
backspace
, tab
, newline
,
return
, delete
tab
. Most of the time, it's not
useful to distinguish the two. So normally
function-key-map
(see section Translating Input Events) is set up to
map tab
into 9. Thus, a key binding for character code
9 (the character C-i) also applies to tab
.
Likewise for the other symbols in this group. The function
read-char
likewise 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.
left
, up
, right
,
down
kp-add
, kp-decimal
,
kp-divide
, ...
kp-0
, kp-1
, ...
kp-f1
, kp-f2
, kp-f3
,
kp-f4
kp-home
, kp-left
, kp-up
,
kp-right
, kp-down
home
, left
,
...
kp-prior
, kp-next
,
kp-end
, kp-begin
, kp-insert
,
kp-delete
You can use the modifier keys ALT, CTRL, HYPER, META, SHIFT, and SUPER with function keys. The way to represent them is with prefixes in the symbol name:
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; but the order
does not matter in arguments to the key-binding lookup and
modification functions.
Emacs supports four kinds of mouse events: click events, drag events, button-down events, and motion events. All mouse events are represented as lists. The CAR of the list is the event type; this says which mouse button was involved, and which modifier keys were used with it. The event type can also distinguish double or triple button presses (see section Repeat Events). The rest of the list elements give position and time information.
For key lookup, only the event type matters: two events of the same type necessarily run the same command. The command can access 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.
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:
(event-type (window buffer-pos (x . y) timestamp) click-count)
Here is what the elements normally mean:
mouse-1
, mouse-2
,
..., where the buttons are 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
.
(0 . 0)
.
The meanings of buffer-pos, x and y 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
(x . y)
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, y does
not have meaningful data. For the vertical line, x does
not have meaningful data.
In one special case, buffer-pos is a list containing a symbol (one of the symbols listed above) instead of just the symbol. This happens after the imaginary prefix keys for the event are inserted into the input stream. See section Key Sequence Input.
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:
(event-type (window1 buffer-pos1 (x1 . y1) timestamp1) (window2 buffer-pos2 (x2 . y2) timestamp2) click-count)
For a drag event, the name of the symbol event-type
contains the prefix `drag-'. For example, dragging the
mouse with button 2 held down generates a drag-mouse-2
event. 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 that 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.
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.(3) These occur as soon as a button is pressed. They are represented by lists that look exactly like click events (see section Click Events), except that the event-type symbol name contains the prefix `down-'. The `down-' prefix follows modifier key prefixes such as `C-' and `M-'.
The function read-key-sequence
ignores any
button-down events that don't have command bindings; therefore, the
Emacs command loop ignores them too. 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. See section Motion Events.
If you press the same mouse button more than once in quick succession without moving the mouse, Emacs generates 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, you must design the command binding of the double click event 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 is convenient, if the meaning of a double click somehow "builds on" the meaning of a single click--which is recommended user interface design practice for double clicks.
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 drag.
Before the double-click or double-drag event, Emacs generates a double-down event when the user presses the button 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 down event and a click event for the first click, a double-down event when you press the button again, and finally either a double-click or a double-drag event.
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 separate event types for quadruple, quintuple, etc. events. However, you can look at the event list to find out precisely how many times the button was pressed.
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.
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:
(mouse-movement (window buffer-pos (x . y) 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. See section Mouse Tracking.
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.
Most X 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 a 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.
A few other event types represent occurrences within the window system.
(delete-frame (frame))
delete-frame
event is to
delete frame.
(iconify-frame (frame))
ignore
; since the frame has already been iconified,
Emacs has no work to do. The purpose of this event type is so that
you can keep track of such events if you want to.
(make-frame-visible (frame))
ignore
; since the frame has already been made
visible, Emacs has no work to do.
(mouse-wheel position
delta)
(drag-n-drop position
files)
If one of these events arrives in the middle of a key sequence--that is, after a prefix key--then Emacs reorders the events so that this event comes either before or after the multi-event key sequence, not within it.
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))
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))
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 a pair of events like these:
(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) -453816))
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 that 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 where in the buffer to act.
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.
shift
, control
,
meta
, alt
, hyper
and
super
. In addition, the modifiers list of a mouse
event symbol always contains one of click
,
drag
, and down
. The argument event may be an entire event object, or just an event type.
Here are some examples:
(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'.
(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
nil
if object is a mouse movement
event.
(event-convert-list '(control ?a)) => 1 (event-convert-list '(control meta ?a)) => -134217727 (event-convert-list '(control super f1)) => C-s-f1
This section describes convenient functions for accessing the data in a mouse button or motion event.
These two functions return the starting or ending position of a mouse-button event, as a list of this form:
(window buffer-position (x . y) timestamp)
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.
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 five functions take a position list as described above, and return various parts of it.
(x . y)
.
(col . row)
. These are computed
from the x and y values actually found in
position.
These functions are useful for decoding scroll bar events.
(portion .
whole)
containing two integers whose ratio is the
fractional position.
(num .
denom)
---typically a value returned by
scroll-bar-event-ratio
. This function is handy for scaling a position on a scroll bar into a buffer position. Here's how to do that:
(+ (point-min) (scroll-bar-scale (posn-x-y (event-start event)) (- (point-max) (point-min))))
Recall that scroll bar events have two integers forming a ratio, in place of a pair of x and y coordinates.
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 that conceptually contain keyboard characters; for example, they may be key sequences or keyboard macro definitions. However, storing keyboard characters in a string is a complex matter, for reasons of historical compatibility, and it is not always possible.
We recommend that new programs avoid dealing with these complexities by not storing keyboard events in strings. Here is how to do that:
lookup-key
and define-key
. For example,
you can use read-key-sequence-vector
instead of
read-key-sequence
, and
this-command-keys-vector
instead of
this-command-keys
.
define-key
.
listify-key-sequence
(see
section Miscellaneous Event Input
Features) first, to convert it to a list.
The complexities stem from the modifier bits that keyboard input characters can include. Aside from the Meta modifier, none of these modifier bits can be included in a string, and the Meta modifier is allowed only in special cases.
The earliest GNU Emacs versions represented meta characters as
codes in the range of 128 to 255. At that time, the basic character
codes ranged from 0 to 127, so all keyboard character codes did fit
in a string. Many Lisp programs used `\M-' in string
constants to stand for meta characters, especially in arguments to
define-key
and similar functions, and key sequences
and sequences of events were always represented as strings.
When we added support for larger basic character codes beyond 127, and additional modifier bits, we had to change the representation of meta characters. Now the flag that represents the Meta modifier in a character is and such numbers cannot be included in a string.
To support programs with `\M-' in string constants, there are special rules for including certain meta characters in a string. Here are the rules for interpreting a string as a sequence of input characters:
Functions such as read-key-sequence
that construct
strings of keyboard input characters follow these rules: they
construct vectors instead of strings, when the events won't fit in
a string.
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.
However, most programs would do well to avoid these issues by following the recommendations at the beginning of this section.
The editor command loop reads key sequences using the function
read-key-sequence
, which uses read-event
.
These and other functions for event 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. See section Translating
Input Events, for features you can use for translating or
modifying input events while reading them.
For higher-level input facilities, see section Minibuffers.
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.
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.
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"
The function read-key-sequence
suppresses quitting:
C-g typed while reading with this function works like
any other character, and does not set quit-flag
. See
section Quitting.
read-key-sequence
except that it always returns the
key sequence as a vector, never as a string. See section Putting Keyboard Events in
Strings.
If an input character is an upper-case letter
and has no key binding, but its 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 and miscellaneous window 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 type shows nothing special--it
is the same symbol that would normally represent that combination
of mouse button and modifier keys. The information about the window
part 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
. You can define meanings for mouse
clicks in special window parts by defining key sequences using
these imaginary prefix keys.
For example, if you call read-key-sequence
and then
click the mouse on the window's mode line, you get two events, like
this:
(read-key-sequence "Click on the mode line: ") => [mode-line (mouse-1 (#<window 6 on NEWS> mode-line (40 . 63) 5959987))]
The lowest level functions for command input are those that read a single event.
If prompt is non-nil
, it should be a
string to display in the echo area as a prompt. Otherwise,
read-event
does not display any message to indicate it
is waiting for input; instead, it prompts by echoing: it displays
descriptions of the events that led to or were read by the current
command. See section The Echo
Area.
If suppress-input-method is non-nil
,
then the current input method is disabled for reading this event.
If you want to read an event without input-method processing,
always do it this way; don't try binding
input-method-function
(see below).
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.
If read-event
gets an event that is defined as a
help character, in some cases read-event
processes the
event directly without returning. See section Help Functions. Certain other events,
called special events, are also processed directly within
read-event
(see section Special Events).
Here is what happens if you call read-event
and
then press the right-arrow function key:
(read-event) => right
In the first example, the user types the character 1
(ASCII code 49). The second example shows a keyboard macro
definition that calls read-char
from the minibuffer
using eval-expression
. read-char
reads
the keyboard macro's very next character, which is 1.
Then eval-expression
displays its return value in the
echo area.
(read-char) => 49 ;; We assume here you use M-: to evaluate this. (symbol-function 'foo) => "^[:(read-char)^M1" (execute-kbd-macro 'foo) -| 49 => nil
read-event
also invokes the current input method,
if any. If the value of input-method-function
is
non-nil
, it should be a function; when
read-event
reads a printing character (including
SPC) with no modifier bits, it calls that function,
passing the event as an argument.
nil
, its value specifies the current input method
function. Note: Don't bind this variable with
let
. It is often buffer-local, and if you bind it
around reading input (which is exactly when you would bind
it), switching buffers asynchronously while Emacs is waiting will
cause the value to be restored in the wrong buffer.
The input method function should return a list of events which
should be used as input. (If the list is nil
, that
means there is no input, so read-event
waits for
another event.) These events are processed before the events in
unread-command-events
. Events returned by the input
method function are not passed to the input method function again,
even if they are printing characters with no modifier bits.
If the input method function calls read-event
or
read-key-sequence
, it should bind
input-method-function
to nil
first, to
prevent recursion.
The input method function is not called when reading the second
and subsequent event of a key sequence. Thus, these characters are
not subject to input method processing. It is usually a good idea
for the input method processing to test the values of
overriding-local-map
and
overriding-terminal-local-map
; if either of these
variables is non-nil
, the input method should put its
argument into a list and return that list with no further
processing.
You can use the function read-quoted-char
to ask
the user to specify a character, and allow the user to specify a
control or meta character conveniently, either literally or as an
octal character code. The command quoted-insert
uses
this function.
read-char
, except that if the first character read is
an octal digit (0-7), it reads any number of octal digits (but
stopping if a non-octal digit is found), and returns the character
represented by that numeric character code. 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 displayed in the echo area, 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
This section describes how to "peek ahead" at events without
using them up, how to check for pending input, and how to discard
pending input. See also the function read-passwd
(see
section Reading a Password).
The variable is needed because in some cases a function reads an 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 by the functions to read command input.
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 with no special meaning in a search, because these events should exit the search and then execute normally.
The reliable and easy way to extract events from a key sequence
so as to put them in unread-command-events
is to use
listify-key-sequence
(see section Putting Keyboard Events in
Strings).
Normally you add events to the front of this list, so that the events most recently unread will be reread first.
unread-command-events
.
This variable is mostly obsolete now that you can use
unread-command-events
instead; it exists only to
support programs written for Emacs versions 18 and earlier.
t
if there is available input,
nil
otherwise. On rare occasions it may return
t
when no input is available.
In the example below, the Lisp program reads the character
1, ASCII code 49. It becomes the value of
last-input-event
, while C-e (we assume
C-x C-e command is used to evaluate this expression)
remains the value of last-command-event
.
(progn (print (read-char)) (print last-command-event) last-input-event) -| 49 -| 5 => 49
The alias last-input-char
exists for compatibility
with Emacs version 18.
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,
discard-input
discards any characters typed during the
sleep.
(progn (sleep-for 2) (discard-input)) => nil
Special events are handled
at a very low level--as soon as they are read. The
read-event
function processes these events itself, and
never returns them.
Events that are handled in this way do not echo, they are never
grouped into key sequences, and they never appear in the value of
last-command-event
or
(this-command-keys)
. They do not discard a numeric
argument, they cannot be unread with
unread-command-events
, they may not appear in a
keyboard macro, and they are not recorded in a keyboard macro while
you are defining one.
These events do, however, appear in
last-input-event
immediately after they are read, and
this is the way for the event's definition to find the actual
event.
The events types iconify-frame
,
make-frame-visible
and delete-frame
are
normally handled in this way. The keymap which defines how to
handle special events--and which events are special--is in the
variable special-event-map
(see section Active Keymaps).
The wait functions are designed to 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.
t
if sit-for
waited the full
time with no input arriving (see input-pending-p
in
section Miscellaneous Event Input
Features). Otherwise, the value is nil
. The argument seconds need not be an integer. If it is
a floating point number, sit-for
waits for a
fractional number of seconds. Some systems support only a whole
number of seconds; on these systems, seconds is rounded
down.
The optional argument millisec specifies an additional waiting period measured in milliseconds. This adds to the period specified by seconds. If the system doesn't support waiting fractions of a second, 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).
Iconifying or deiconifying a frame makes sit-for
return, because that generates an event. See section Miscellaneous Window System
Events.
The usual purpose of sit-for
is to give the user
time to read text that you display.
nil
.
The argument seconds need not be an integer. If it is
a floating point number, sleep-for
waits for a
fractional number of seconds. Some systems support only a whole
number of seconds; on these systems, seconds is rounded
down.
The optional argument millisec specifies an additional waiting period measured in milliseconds. This adds to the period specified by seconds. If the system doesn't support waiting fractions of a second, 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 a Lisp function is running 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, they combine to form 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 always quit directly.
When C-g does directly quit, it does so by setting
the variable quit-flag
to t
. 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, quitting cannot happen just anywhere;
only at the special places that 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 when you wish to make sure that quitting does not
happen within a "critical section" of the program.
In some functions (such as
read-quoted-char
), C-g is handled in a
special way that 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)
"...documentation..."
(let ((message-log-max nil) done (first t) (code 0) char)
(while (not done)
(let ((inhibit-quit first)
...)
(and prompt (message "%s-" prompt))
(setq char (read-event))
(if inhibit-quit (setq quit-flag nil)))
...set the variable code
...)
code))
nil
, then Emacs quits immediately, unless
inhibit-quit
is non-nil
. Typing
C-g ordinarily sets quit-flag
non-nil
, regardless of inhibit-quit
.
quit-flag
is set to a
value other than nil
. If inhibit-quit
is
non-nil
, then quit-flag
has no special
effect.
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.
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 at all times
represented by a value, which may be nil
, meaning
there is currently 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:
nil
, meaning there is no prefix argument. Its
numeric value is 1, but numerous commands make a distinction
between nil
and the integer 1.
-
. This indicates that M--
or C-u - was typed, without following digits. The
equivalent numeric value is -1, but some commands make a
distinction between the integer -1 and the symbol
-
.
We illustrate these possibilities 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 display-prefix
with
various raw prefix arguments:
M-x display-prefix -| nil C-u M-x display-prefix -| (4) C-u C-u M-x display-prefix -| (16) C-u 3 M-x display-prefix -| 3 M-3 M-x display-prefix -| 3 ; (Same asC-u 3
.) C-u - M-x display-prefix -| - M-- M-x display-prefix -| - ; (Same asC-u -
.) C-u - 7 M-x display-prefix -| -7 M-- 7 M-x display-prefix -| -7 ; (Same asC-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 Using interactive.)
Alternatively, functions may look at the value of the prefix
argument directly in the variable current-prefix-arg
,
but this is less clean.
nil
, the value 1 is returned; if it is
-
, 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.
(interactive "P")
.
universal-argument
that specify
prefix arguments for the following command work by setting this
variable.
The following commands exist to set up prefix arguments for the following command. Do not call them for any other reason.
The Emacs command loop is entered automatically when Emacs starts up. This top-level invocation of the command loop never exits; it keeps running as long as Emacs does. 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 they finish. (The special commands for exiting are always available, but they 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 should have a command to go back to the previous mode. (The e command in Rmail uses this technique.) 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
).
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") (recursive-edit) (forward-word 1)) => simple-rec (simple-rec) => nil
(throw 'exit nil)
.
quit
after exiting the
recursive edit. Its definition is effectively (throw 'exit
t)
. See section Quitting.
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,
the message saying the command is disabled includes that string.
For example:
(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.
this-command-keys
to determine what the user typed to
run the command, and thus find the command itself. See section Hooks. By default, disabled-command-hook
contains a
function that asks the user whether to proceed.
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-: 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.
history-length
), the
oldest elements are deleted as new ones are added. command-history => ((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 usual minibuffer history commands are
available.
A keyboard macro is a canned sequence of input events that can be considered a command and made the definition of a key. The Lisp representation of a keyboard macro is a string or vector containing the events. Don't confuse keyboard macros with Lisp macros (see section Macros).
If kbdmacro is a symbol, then its function definition is used in place of kbdmacro. 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;
kbdmacro is executed that many times. If
count is omitted or nil
,
kbdmacro is executed once. If it is 0,
kbdmacro is executed over and over until it encounters
an error or a failing search.
See section Reading One Event,
for an example of using execute-kbd-macro
.
nil
if no macro is currently
executing. A command can test this variable so as to behave
differently when run from an executing macro. Do not set this
variable yourself.
start-kbd-macro
and
end-kbd-macro
set this variable--do not set it
yourself. The variable is always local to the current terminal and cannot be buffer-local. See section Multiple Displays.
nil
. The variable is always local to the current terminal and cannot be buffer-local. See section Multiple Displays.