1@c -*-texinfo-*-
2@c This is part of the GNU Emacs Lisp Reference Manual.
3@c Copyright (C) 1990--1995, 1998--1999, 2001--2021 Free Software
4@c Foundation, Inc.
5@c See the file elisp.texi for copying conditions.
6@node Command Loop
7@chapter Command Loop
8@cindex editor command loop
9@cindex command loop
10
11  When you run Emacs, it enters the @dfn{editor command loop} almost
12immediately.  This loop reads key sequences, executes their definitions,
13and displays the results.  In this chapter, we describe how these things
14are done, and the subroutines that allow Lisp programs to do them.
15
16@menu
17* Command Overview::    How the command loop reads commands.
18* Defining Commands::   Specifying how a function should read arguments.
19* Interactive Call::    Calling a command, so that it will read arguments.
20* Distinguish Interactive::     Making a command distinguish interactive calls.
21* Command Loop Info::   Variables set by the command loop for you to examine.
22* Adjusting Point::     Adjustment of point after a command.
23* Input Events::        What input looks like when you read it.
24* Reading Input::       How to read input events from the keyboard or mouse.
25* Special Events::      Events processed immediately and individually.
26* Waiting::             Waiting for user input or elapsed time.
27* Quitting::            How @kbd{C-g} works.  How to catch or defer quitting.
28* Prefix Command Arguments::    How the commands to set prefix args work.
29* Recursive Editing::   Entering a recursive edit,
30                          and why you usually shouldn't.
31* Disabling Commands::  How the command loop handles disabled commands.
32* Command History::     How the command history is set up, and how accessed.
33* Keyboard Macros::     How keyboard macros are implemented.
34@end menu
35
36@node Command Overview
37@section Command Loop Overview
38
39  The first thing the command loop must do is read a key sequence,
40which is a sequence of input events that translates into a command.
41It does this by calling the function @code{read-key-sequence}.  Lisp
42programs can also call this function (@pxref{Key Sequence Input}).
43They can also read input at a lower level with @code{read-key} or
44@code{read-event} (@pxref{Reading One Event}), or discard pending
45input with @code{discard-input} (@pxref{Event Input Misc}).
46
47  The key sequence is translated into a command through the currently
48active keymaps.  @xref{Key Lookup}, for information on how this is done.
49The result should be a keyboard macro or an interactively callable
50function.  If the key is @kbd{M-x}, then it reads the name of another
51command, which it then calls.  This is done by the command
52@code{execute-extended-command} (@pxref{Interactive Call}).
53
54  Prior to executing the command, Emacs runs @code{undo-boundary} to
55create an undo boundary.  @xref{Maintaining Undo}.
56
57  To execute a command, Emacs first reads its arguments by calling
58@code{command-execute} (@pxref{Interactive Call}).  For commands
59written in Lisp, the @code{interactive} specification says how to read
60the arguments.  This may use the prefix argument (@pxref{Prefix
61Command Arguments}) or may read with prompting in the minibuffer
62(@pxref{Minibuffers}).  For example, the command @code{find-file} has
63an @code{interactive} specification which says to read a file name
64using the minibuffer.  The function body of @code{find-file} does not
65use the minibuffer, so if you call @code{find-file} as a function from
66Lisp code, you must supply the file name string as an ordinary Lisp
67function argument.
68
69  If the command is a keyboard macro (i.e., a string or vector),
70Emacs executes it using @code{execute-kbd-macro} (@pxref{Keyboard
71Macros}).
72
73@defvar pre-command-hook
74This normal hook is run by the editor command loop before it executes
75each command.  At that time, @code{this-command} contains the command
76that is about to run, and @code{last-command} describes the previous
77command.  @xref{Command Loop Info}.
78@end defvar
79
80@defvar post-command-hook
81This normal hook is run by the editor command loop after it executes
82each command (including commands terminated prematurely by quitting or
83by errors).  At that time, @code{this-command} refers to the command
84that just ran, and @code{last-command} refers to the command before
85that.
86
87This hook is also run when Emacs first enters the command loop (at
88which point @code{this-command} and @code{last-command} are both
89@code{nil}).
90@end defvar
91
92  Quitting is suppressed while running @code{pre-command-hook} and
93@code{post-command-hook}.  If an error happens while executing one of
94these hooks, it does not terminate execution of the hook; instead
95the error is silenced and the function in which the error occurred
96is removed from the hook.
97
98  A request coming into the Emacs server (@pxref{Emacs Server,,,
99emacs, The GNU Emacs Manual}) runs these two hooks just as a keyboard
100command does.
101
102@node Defining Commands
103@section Defining Commands
104@cindex defining commands
105@cindex commands, defining
106@cindex functions, making them interactive
107@cindex interactive function
108
109  The special form @code{interactive} turns a Lisp function into a
110command.  The @code{interactive} form must be located at top-level in
111the function body, usually as the first form in the body; this applies
112to both lambda expressions (@pxref{Lambda Expressions}) and
113@code{defun} forms (@pxref{Defining Functions}).  This form does
114nothing during the actual execution of the function; its presence
115serves as a flag, telling the Emacs command loop that the function can
116be called interactively.  The argument of the @code{interactive} form
117specifies how the arguments for an interactive call should be read.
118
119@cindex @code{interactive-form} property
120  Alternatively, an @code{interactive} form may be specified in a
121function symbol's @code{interactive-form} property.  A non-@code{nil}
122value for this property takes precedence over any @code{interactive}
123form in the function body itself.  This feature is seldom used.
124
125@anchor{The interactive-only property}
126@cindex @code{interactive-only} property
127  Sometimes, a function is only intended to be called interactively,
128never directly from Lisp.  In that case, give the function a
129non-@code{nil} @code{interactive-only} property, either directly
130or via @code{declare} (@pxref{Declare Form}).  This causes the
131byte compiler to warn if the command is called from Lisp.  The output
132of @code{describe-function} will include similar information.
133The value of the property can be: a string, which the byte-compiler
134will use directly in its warning (it should end with a period, and not
135start with a capital, e.g., @code{"use (system-name) instead."}); @code{t}; any
136other symbol, which should be an alternative function to use in Lisp
137code.
138
139Generic functions (@pxref{Generic Functions}) cannot be turned into
140commands by adding the @code{interactive} form to them.
141
142@menu
143* Using Interactive::     General rules for @code{interactive}.
144* Interactive Codes::     The standard letter-codes for reading arguments
145                             in various ways.
146* Interactive Examples::  Examples of how to read interactive arguments.
147* Command Modes::         Specifying that commands are for a specific mode.
148* Generic Commands::      Select among command alternatives.
149@end menu
150
151@node Using Interactive
152@subsection Using @code{interactive}
153@cindex arguments, interactive entry
154@cindex interactive spec, using
155
156  This section describes how to write the @code{interactive} form that
157makes a Lisp function an interactively-callable command, and how to
158examine a command's @code{interactive} form.
159
160@defspec interactive &optional arg-descriptor &rest modes
161This special form declares that a function is a command, and that it
162may therefore be called interactively (via @kbd{M-x} or by entering a
163key sequence bound to it).  The argument @var{arg-descriptor} declares
164how to compute the arguments to the command when the command is called
165interactively.
166
167A command may be called from Lisp programs like any other function, but
168then the caller supplies the arguments and @var{arg-descriptor} has no
169effect.
170
171@cindex @code{interactive-form}, symbol property
172The @code{interactive} form must be located at top-level in the
173function body, or in the function symbol's @code{interactive-form}
174property (@pxref{Symbol Properties}).  It has its effect because the
175command loop looks for it before calling the function
176(@pxref{Interactive Call}).  Once the function is called, all its body
177forms are executed; at this time, if the @code{interactive} form
178occurs within the body, the form simply returns @code{nil} without
179even evaluating its argument.
180
181The @var{modes} list allows specifying which modes the command is
182meant to be used in.  See @ref{Command Modes} for more details about
183the effect of specifying @var{modes}, and when to use it.
184
185By convention, you should put the @code{interactive} form in the
186function body, as the first top-level form.  If there is an
187@code{interactive} form in both the @code{interactive-form} symbol
188property and the function body, the former takes precedence.  The
189@code{interactive-form} symbol property can be used to add an
190interactive form to an existing function, or change how its arguments
191are processed interactively, without redefining the function.
192@end defspec
193
194There are three possibilities for the argument @var{arg-descriptor}:
195
196@itemize @bullet
197@item
198It may be omitted or @code{nil}; then the command is called with no
199arguments.  This leads quickly to an error if the command requires one
200or more arguments.
201
202@item
203It may be a string; its contents are a sequence of elements separated
204by newlines, one for each argument@footnote{Some elements actually
205supply two arguments.}.  Each element consists of a code character
206(@pxref{Interactive Codes}) optionally followed by a prompt (which
207some code characters use and some ignore).  Here is an example:
208
209@smallexample
210(interactive "P\nbFrobnicate buffer: ")
211@end smallexample
212
213@noindent
214The code letter @samp{P} sets the command's first argument to the raw
215command prefix (@pxref{Prefix Command Arguments}).  @samp{bFrobnicate
216buffer: } prompts the user with @samp{Frobnicate buffer: } to enter
217the name of an existing buffer, which becomes the second and final
218argument.
219
220The prompt string can use @samp{%} to include previous argument values
221(starting with the first argument) in the prompt.  This is done using
222@code{format-message} (@pxref{Formatting Strings}).  For example, here is how
223you could read the name of an existing buffer followed by a new name to
224give to that buffer:
225
226@smallexample
227@group
228(interactive "bBuffer to rename: \nsRename buffer %s to: ")
229@end group
230@end smallexample
231
232@cindex @samp{*} in @code{interactive}
233@cindex read-only buffers in interactive
234If @samp{*} appears at the beginning of the string, then an error is
235signaled if the buffer is read-only.
236
237@cindex @samp{@@} in @code{interactive}
238If @samp{@@} appears at the beginning of the string, and if the key
239sequence used to invoke the command includes any mouse events, then
240the window associated with the first of those events is selected
241before the command is run.
242
243@cindex @samp{^} in @code{interactive}
244@cindex shift-selection, and @code{interactive} spec
245If @samp{^} appears at the beginning of the string, and if the command
246was invoked through @dfn{shift-translation}, set the mark and activate
247the region temporarily, or extend an already active region, before the
248command is run.  If the command was invoked without shift-translation,
249and the region is temporarily active, deactivate the region before the
250command is run.  Shift-translation is controlled on the user level by
251@code{shift-select-mode}; see @ref{Shift Selection,,, emacs, The GNU
252Emacs Manual}.
253
254You can use @samp{*}, @samp{@@}, and @code{^} together; the order does
255not matter.  Actual reading of arguments is controlled by the rest of
256the prompt string (starting with the first character that is not
257@samp{*}, @samp{@@}, or @samp{^}).
258
259@item
260It may be a Lisp expression that is not a string; then it should be a
261form that is evaluated to get a list of arguments to pass to the
262command.  Usually this form will call various functions to read input
263from the user, most often through the minibuffer (@pxref{Minibuffers})
264or directly from the keyboard (@pxref{Reading Input}).
265
266Providing point or the mark as an argument value is also common, but
267if you do this @emph{and} read input (whether using the minibuffer or
268not), be sure to get the integer values of point or the mark after
269reading.  The current buffer may be receiving subprocess output; if
270subprocess output arrives while the command is waiting for input, it
271could relocate point and the mark.
272
273Here's an example of what @emph{not} to do:
274
275@smallexample
276(interactive
277 (list (region-beginning) (region-end)
278       (read-string "Foo: " nil 'my-history)))
279@end smallexample
280
281@noindent
282Here's how to avoid the problem, by examining point and the mark after
283reading the keyboard input:
284
285@smallexample
286(interactive
287 (let ((string (read-string "Foo: " nil 'my-history)))
288   (list (region-beginning) (region-end) string)))
289@end smallexample
290
291@strong{Warning:} the argument values should not include any data
292types that can't be printed and then read.  Some facilities save
293@code{command-history} in a file to be read in the subsequent
294sessions; if a command's arguments contain a data type that prints
295using @samp{#<@dots{}>} syntax, those facilities won't work.
296
297There are, however, a few exceptions: it is ok to use a limited set of
298expressions such as @code{(point)}, @code{(mark)},
299@code{(region-beginning)}, and @code{(region-end)}, because Emacs
300recognizes them specially and puts the expression (rather than its
301value) into the command history.  To see whether the expression you
302wrote is one of these exceptions, run the command, then examine
303@code{(car command-history)}.
304@end itemize
305
306@cindex examining the @code{interactive} form
307@defun interactive-form function
308This function returns the @code{interactive} form of @var{function}.
309If @var{function} is an interactively callable function
310(@pxref{Interactive Call}), the value is the command's
311@code{interactive} form @code{(interactive @var{spec})}, which
312specifies how to compute its arguments.  Otherwise, the value is
313@code{nil}.  If @var{function} is a symbol, its function definition is
314used.
315@end defun
316
317@node Interactive Codes
318@subsection Code Characters for @code{interactive}
319@cindex interactive code description
320@cindex description for interactive codes
321@cindex codes, interactive, description of
322@cindex characters for interactive codes
323
324  The code character descriptions below contain a number of key words,
325defined here as follows:
326
327@table @b
328@item Completion
329@cindex interactive completion
330Provide completion.  @key{TAB}, @key{SPC}, and @key{RET} perform name
331completion because the argument is read using @code{completing-read}
332(@pxref{Completion}).  @kbd{?} displays a list of possible completions.
333
334@item Existing
335Require the name of an existing object.  An invalid name is not
336accepted; the commands to exit the minibuffer do not exit if the current
337input is not valid.
338
339@item Default
340@cindex default argument string
341A default value of some sort is used if the user enters no text in the
342minibuffer.  The default depends on the code character.
343
344@item No I/O
345This code letter computes an argument without reading any input.
346Therefore, it does not use a prompt string, and any prompt string you
347supply is ignored.
348
349Even though the code letter doesn't use a prompt string, you must follow
350it with a newline if it is not the last code character in the string.
351
352@item Prompt
353A prompt immediately follows the code character.  The prompt ends either
354with the end of the string or with a newline.
355
356@item Special
357This code character is meaningful only at the beginning of the
358interactive string, and it does not look for a prompt or a newline.
359It is a single, isolated character.
360@end table
361
362@cindex reading interactive arguments
363  Here are the code character descriptions for use with @code{interactive}:
364
365@table @samp
366@item *
367Signal an error if the current buffer is read-only.  Special.
368
369@item @@
370Select the window mentioned in the first mouse event in the key
371sequence that invoked this command.  Special.
372
373@item ^
374If the command was invoked through shift-translation, set the mark and
375activate the region temporarily, or extend an already active region,
376before the command is run.  If the command was invoked without
377shift-translation, and the region is temporarily active, deactivate
378the region before the command is run.  Special.
379
380@item a
381A function name (i.e., a symbol satisfying @code{fboundp}).  Existing,
382Completion, Prompt.
383
384@item b
385The name of an existing buffer.  By default, uses the name of the
386current buffer (@pxref{Buffers}).  Existing, Completion, Default,
387Prompt.
388
389@item B
390A buffer name.  The buffer need not exist.  By default, uses the name of
391a recently used buffer other than the current buffer.  Completion,
392Default, Prompt.
393
394@item c
395A character.  The cursor does not move into the echo area.  Prompt.
396
397@item C
398A command name (i.e., a symbol satisfying @code{commandp}).  Existing,
399Completion, Prompt.
400
401@item d
402@cindex position argument
403The position of point, as an integer (@pxref{Point}).  No I/O.
404
405@item D
406A directory.  The default is the current default directory of the
407current buffer, @code{default-directory} (@pxref{File Name Expansion}).
408Existing, Completion, Default, Prompt.
409
410@item e
411The first or next non-keyboard event in the key sequence that invoked
412the command.  More precisely, @samp{e} gets events that are lists, so
413you can look at the data in the lists.  @xref{Input Events}.  No I/O.
414
415You use @samp{e} for mouse events and for special system events
416(@pxref{Misc Events}).  The event list that the command receives
417depends on the event.  @xref{Input Events}, which describes the forms
418of the list for each event in the corresponding subsections.
419
420You can use @samp{e} more than once in a single command's interactive
421specification.  If the key sequence that invoked the command has
422@var{n} events that are lists, the @var{n}th @samp{e} provides the
423@var{n}th such event.  Events that are not lists, such as function keys
424and @acronym{ASCII} characters, do not count where @samp{e} is concerned.
425
426@item f
427A file name of an existing file (@pxref{File Names}).  The default
428directory is @code{default-directory}.  Existing, Completion, Default,
429Prompt.
430
431@item F
432A file name.  The file need not exist.  Completion, Default, Prompt.
433
434@item G
435A file name.  The file need not exist.  If the user enters just a
436directory name, then the value is just that directory name, with no
437file name within the directory added.  Completion, Default, Prompt.
438
439@item i
440An irrelevant argument.  This code always supplies @code{nil} as
441the argument's value.  No I/O.
442
443@item k
444A key sequence (@pxref{Key Sequences}).  This keeps reading events
445until a command (or undefined command) is found in the current key
446maps.  The key sequence argument is represented as a string or vector.
447The cursor does not move into the echo area.  Prompt.
448
449If @samp{k} reads a key sequence that ends with a down-event, it also
450reads and discards the following up-event.  You can get access to that
451up-event with the @samp{U} code character.
452
453This kind of input is used by commands such as @code{describe-key} and
454@code{keymap-global-set}.
455
456@item K
457A key sequence on a form that can be used as input to functions like
458@code{keymap-set}.  This works like @samp{k}, except that it
459suppresses, for the last input event in the key sequence, the
460conversions that are normally used (when necessary) to convert an
461undefined key into a defined one (@pxref{Key Sequence Input}), so this
462form is usually used when prompting for a new key sequence that is to
463be bound to a command.
464
465@item m
466@cindex marker argument
467The position of the mark, as an integer.  No I/O.
468
469@item M
470Arbitrary text, read in the minibuffer using the current buffer's input
471method, and returned as a string (@pxref{Input Methods,,, emacs, The GNU
472Emacs Manual}).  Prompt.
473
474@item n
475A number, read with the minibuffer.  If the input is not a number, the
476user has to try again.  @samp{n} never uses the prefix argument.
477Prompt.
478
479@item N
480The numeric prefix argument; but if there is no prefix argument, read
481a number as with @kbd{n}.  The value is always a number.  @xref{Prefix
482Command Arguments}.  Prompt.
483
484@item p
485@cindex numeric prefix argument usage
486The numeric prefix argument.  (Note that this @samp{p} is lower case.)
487No I/O.
488
489@item P
490@cindex raw prefix argument usage
491The raw prefix argument.  (Note that this @samp{P} is upper case.)  No
492I/O.
493
494@item r
495@cindex region argument
496Point and the mark, as two numeric arguments, smallest first.  This is
497the only code letter that specifies two successive arguments rather than
498one.  This will signal an error if the mark is not set in the buffer
499which is current when the command is invoked.  If Transient Mark mode
500is turned on (@pxref{The Mark}) --- as it is by default --- and user
501option @code{mark-even-if-inactive} is @code{nil}, Emacs will signal
502an error even if the mark @emph{is} set, but is inactive.  No I/O.
503
504@item s
505Arbitrary text, read in the minibuffer and returned as a string
506(@pxref{Text from Minibuffer}).  Terminate the input with either
507@kbd{C-j} or @key{RET}.  (@kbd{C-q} may be used to include either of
508these characters in the input.)  Prompt.
509
510@item S
511An interned symbol whose name is read in the minibuffer.  Terminate
512the input with either @kbd{C-j} or @key{RET}.  Other characters that
513normally terminate a symbol (e.g., whitespace, parentheses and
514brackets) do not do so here.  Prompt.
515
516@item U
517A key sequence or @code{nil}.  Can be used after a @samp{k} or
518@samp{K} argument to get the up-event that was discarded (if any)
519after @samp{k} or @samp{K} read a down-event.  If no up-event has been
520discarded, @samp{U} provides @code{nil} as the argument.  No I/O.
521
522@item v
523A variable declared to be a user option (i.e., satisfying the
524predicate @code{custom-variable-p}).  This reads the variable using
525@code{read-variable}.  @xref{Definition of read-variable}.  Existing,
526Completion, Prompt.
527
528@item x
529A Lisp object, specified with its read syntax, terminated with a
530@kbd{C-j} or @key{RET}.  The object is not evaluated.  @xref{Object from
531Minibuffer}.  Prompt.
532
533@item X
534@cindex evaluated expression argument
535A Lisp form's value.  @samp{X} reads as @samp{x} does, then evaluates
536the form so that its value becomes the argument for the command.
537Prompt.
538
539@item z
540A coding system name (a symbol).  If the user enters null input, the
541argument value is @code{nil}.  @xref{Coding Systems}.  Completion,
542Existing, Prompt.
543
544@item Z
545A coding system name (a symbol)---but only if this command has a prefix
546argument.  With no prefix argument, @samp{Z} provides @code{nil} as the
547argument value.  Completion, Existing, Prompt.
548@end table
549
550@node Interactive Examples
551@subsection Examples of Using @code{interactive}
552@cindex examples of using @code{interactive}
553@cindex @code{interactive}, examples of using
554
555  Here are some examples of @code{interactive}:
556
557@example
558@group
559(defun foo1 ()              ; @r{@code{foo1} takes no arguments,}
560    (interactive)           ;   @r{just moves forward two words.}
561    (forward-word 2))
562     @result{} foo1
563@end group
564
565@group
566(defun foo2 (n)             ; @r{@code{foo2} takes one argument,}
567    (interactive "^p")      ;   @r{which is the numeric prefix.}
568                            ; @r{under @code{shift-select-mode},}
569                            ;   @r{will activate or extend region.}
570    (forward-word (* 2 n)))
571     @result{} foo2
572@end group
573
574@group
575(defun foo3 (n)             ; @r{@code{foo3} takes one argument,}
576    (interactive "nCount:") ;   @r{which is read with the Minibuffer.}
577    (forward-word (* 2 n)))
578     @result{} foo3
579@end group
580
581@group
582(defun three-b (b1 b2 b3)
583  "Select three existing buffers.
584Put them into three windows, selecting the last one."
585@end group
586    (interactive "bBuffer1:\nbBuffer2:\nbBuffer3:")
587    (delete-other-windows)
588    (split-window (selected-window) 8)
589    (switch-to-buffer b1)
590    (other-window 1)
591    (split-window (selected-window) 8)
592    (switch-to-buffer b2)
593    (other-window 1)
594    (switch-to-buffer b3))
595     @result{} three-b
596@group
597(three-b "*scratch*" "declarations.texi" "*mail*")
598     @result{} nil
599@end group
600@end example
601
602@node Command Modes
603@subsection Specifying Modes For Commands
604@cindex commands, mode-specific
605@cindex commands, specify as mode-specific
606@cindex mode-specific commands
607
608Many commands in Emacs are general, and not tied to any specific mode.
609For instance, @kbd{M-x kill-region} can be used in pretty much any
610mode that has editable text, and commands that display information
611(like @kbd{M-x list-buffers}) can be used in pretty much any context.
612
613Many other commands, however, are specifically tied to a mode, and
614make no sense outside of that context.  For instance, @code{M-x
615dired-diff} will just signal an error if used outside of a Dired
616buffer.
617
618Emacs therefore has a mechanism for specifying what mode (or modes) a
619command ``belongs'' to:
620
621@lisp
622(defun dired-diff (...)
623  ...
624  (interactive "p" dired-mode)
625  ...)
626@end lisp
627
628This will mark the command as applicable to @code{dired-mode} only (or
629any modes that are derived from @code{dired-mode}).  Any number of
630modes can be added to the @code{interactive} form.
631
632@vindex read-extended-command-predicate
633Specifying modes affects command completion in @kbd{M-S-x}
634(@code{execute-extended-command-for-buffer}, @pxref{Interactive
635Call}).  It may also affect completion in @kbd{M-x}, depending on the
636value of @code{read-extended-command-predicate}.
637
638For instance, when using the
639@code{command-completion-default-include-p} predicate as the value of
640@code{read-extended-command-predicate}, @kbd{M-x} won't list commands
641that have been marked as being applicable to a specific mode (unless
642you are in a buffer that uses that mode, of course).  This goes for
643both major and minor modes.  (By contrast, @kbd{M-S-x} always omits
644inapplicable commands from the completion candidates.)
645
646By default, @code{read-extended-command-predicate} is @code{nil}, and
647completion in @kbd{M-x} lists all the commands that match what the
648user has typed, whether those commands are or aren't marked as
649applicable to the current buffer's mode.
650
651Marking commands to be applicable to a mode will also make @kbd{C-h m}
652list these commands (if they aren't bound to any keys).
653
654If using this extended @code{interactive} form isn't convenient
655(because the code is supposed to work in older versions of Emacs that
656don't support the extended @code{interactive} form), the following
657equivalent declaration (@pxref{Declare Form}) can be used instead:
658
659@lisp
660(declare (modes dired-mode))
661@end lisp
662
663Which commands to tag with modes is to some degree a matter of taste,
664but commands that clearly do not work outside of the mode should be
665tagged.  This includes commands that will signal an error if called
666from somewhere else, but also commands that are destructive when
667called from an unexpected mode.  (This usually includes most of the
668commands that are written for special (i.e., non-editing) modes.)
669
670Some commands may be harmless, and ``work'' when called from other
671modes, but should still be tagged with a mode if they don't actually
672make much sense to use elsewhere.  For instance, many special modes
673have commands to exit the buffer bound to @kbd{q}, and may not do
674anything but issue a message like "Goodbye from this mode" and then
675call @code{kill-buffer}.  This command will ``work'' from any mode,
676but it is highly unlikely that anybody would actually want to use the
677command outside the context of this special mode.
678
679Many modes have a set of different commands that start the mode in
680different ways (e.g., @code{eww-open-in-new-buffer} and
681@code{eww-open-file}).  Commands like that should never be tagged as
682mode-specific, as they can be issued by the user from pretty much any
683context.
684
685@node Generic Commands
686@subsection Select among Command Alternatives
687@cindex generic commands
688@cindex alternatives, defining
689
690The macro @code{define-alternatives} can be used to define
691@dfn{generic commands}.  These are interactive functions whose
692implementation can be selected from several alternatives, as a matter
693of user preference.
694
695@defmac define-alternatives command &rest customizations
696Define the new command @var{command}, a symbol.
697
698When a user runs @kbd{M-x @var{command} @key{RET}} for the first time,
699Emacs prompts for which real form of the command to use, and records
700the selection by way of a custom variable.  Using a prefix argument
701repeats this process of choosing an alternative.
702
703The variable @code{@var{command}-alternatives} should contain an alist
704with alternative implementations of @var{command}.
705Until this variable is set, @code{define-alternatives} has no effect.
706
707If @var{customizations} is non-@code{nil}, it should consist of
708alternating @code{defcustom} keywords (typically @code{:group} and
709@code{:version}) and values to add to the declaration of
710@code{@var{command}-alternatives}.
711@end defmac
712
713@node Interactive Call
714@section Interactive Call
715@cindex interactive call
716
717  After the command loop has translated a key sequence into a command,
718it invokes that command using the function @code{command-execute}.  If
719the command is a function, @code{command-execute} calls
720@code{call-interactively}, which reads the arguments and calls the
721command.  You can also call these functions yourself.
722
723  Note that the term ``command'', in this context, refers to an
724interactively callable function (or function-like object), or a
725keyboard macro.  It does not refer to the key sequence used to invoke
726a command (@pxref{Keymaps}).
727
728@defun commandp object &optional for-call-interactively
729This function returns @code{t} if @var{object} is a command.
730Otherwise, it returns @code{nil}.
731
732Commands include strings and vectors (which are treated as keyboard
733macros), lambda expressions that contain a top-level
734@code{interactive} form (@pxref{Using Interactive}), byte-code
735function objects made from such lambda expressions, autoload objects
736that are declared as interactive (non-@code{nil} fourth argument to
737@code{autoload}), and some primitive functions.  Also, a symbol is
738considered a command if it has a non-@code{nil}
739@code{interactive-form} property, or if its function definition
740satisfies @code{commandp}.
741
742If @var{for-call-interactively} is non-@code{nil}, then
743@code{commandp} returns @code{t} only for objects that
744@code{call-interactively} could call---thus, not for keyboard macros.
745
746See @code{documentation} in @ref{Accessing Documentation}, for a
747realistic example of using @code{commandp}.
748@end defun
749
750@defun call-interactively command &optional record-flag keys
751This function calls the interactively callable function @var{command},
752providing arguments according to its interactive calling specifications.
753It returns whatever @var{command} returns.
754
755If, for instance, you have a function with the following signature:
756
757@example
758(defun foo (begin end)
759  (interactive "r")
760  ...)
761@end example
762
763then saying
764
765@example
766(call-interactively 'foo)
767@end example
768
769will call @code{foo} with the region (@code{point} and @code{mark}) as
770the arguments.
771
772An error is signaled if @var{command} is not a function or if it
773cannot be called interactively (i.e., is not a command).  Note that
774keyboard macros (strings and vectors) are not accepted, even though
775they are considered commands, because they are not functions.  If
776@var{command} is a symbol, then @code{call-interactively} uses its
777function definition.
778
779@cindex record command history
780If @var{record-flag} is non-@code{nil}, then this command and its
781arguments are unconditionally added to the list @code{command-history}.
782Otherwise, the command is added only if it uses the minibuffer to read
783an argument.  @xref{Command History}.
784
785The argument @var{keys}, if given, should be a vector which specifies
786the sequence of events to supply if the command inquires which events
787were used to invoke it.  If @var{keys} is omitted or @code{nil}, the
788default is the return value of @code{this-command-keys-vector}.
789@xref{Definition of this-command-keys-vector}.
790@end defun
791
792@defun funcall-interactively function &rest arguments
793This function works like @code{funcall} (@pxref{Calling Functions}),
794but it makes the call look like an interactive invocation: a call to
795@code{called-interactively-p} inside @var{function} will return
796@code{t}.  If @var{function} is not a command, it is called without
797signaling an error.
798@end defun
799
800@defun command-execute command &optional record-flag keys special
801@cindex keyboard macro execution
802This function executes @var{command}.  The argument @var{command} must
803satisfy the @code{commandp} predicate; i.e., it must be an interactively
804callable function or a keyboard macro.
805
806A string or vector as @var{command} is executed with
807@code{execute-kbd-macro}.  A function is passed to
808@code{call-interactively} (see above), along with the
809@var{record-flag} and @var{keys} arguments.
810
811If @var{command} is a symbol, its function definition is used in its
812place.  A symbol with an @code{autoload} definition counts as a
813command if it was declared to stand for an interactively callable
814function.  Such a definition is handled by loading the specified
815library and then rechecking the definition of the symbol.
816
817The argument @var{special}, if given, means to ignore the prefix
818argument and not clear it.  This is used for executing special events
819(@pxref{Special Events}).
820@end defun
821
822@deffn Command execute-extended-command prefix-argument
823@cindex read command name
824This function reads a command name from the minibuffer using
825@code{completing-read} (@pxref{Completion}).  Then it uses
826@code{command-execute} to call the specified command.  Whatever that
827command returns becomes the value of @code{execute-extended-command}.
828
829@cindex execute with prefix argument
830If the command asks for a prefix argument, it receives the value
831@var{prefix-argument}.  If @code{execute-extended-command} is called
832interactively, the current raw prefix argument is used for
833@var{prefix-argument}, and thus passed on to whatever command is run.
834
835@c !!! Should this be @kindex?
836@cindex @kbd{M-x}
837@code{execute-extended-command} is the normal definition of @kbd{M-x},
838so it uses the string @w{@samp{M-x }} as a prompt.  (It would be better
839to take the prompt from the events used to invoke
840@code{execute-extended-command}, but that is painful to implement.)  A
841description of the value of the prefix argument, if any, also becomes
842part of the prompt.
843
844@example
845@group
846(execute-extended-command 3)
847---------- Buffer: Minibuffer ----------
8483 M-x forward-word @key{RET}
849---------- Buffer: Minibuffer ----------
850     @result{} t
851@end group
852@end example
853
854@vindex read-extended-command-predicate
855@findex command-completion-default-include-p
856This command heeds the @code{read-extended-command-predicate}
857variable, which can filter out commands that are not applicable to the
858current major mode (or enabled minor modes).  By default, the value of
859this variable is @code{nil}, and no commands are filtered out.
860However, customizing it to invoke the function
861@code{command-completion-default-include-p} will perform
862mode-dependent filtering.  @code{read-extended-command-predicate} can
863be any predicate function; it will be called with two parameters: the
864command's symbol and the current buffer.  If should return
865non-@code{nil} if the command is to be included when completing in
866that buffer.
867@end deffn
868
869@kindex @kbd{M-X}
870@kindex @kbd{M-S-x}
871@deffn Command execute-extended-command-for-buffer prefix-argument
872This is like @code{execute-extended-command}, but limits the commands
873offered for completion to those commands that are of particular
874relevance to the current major mode (and enabled minor modes).  This
875includes commands that are tagged with the modes (@pxref{Using
876Interactive}), and also commands that are bound to locally active
877keymaps.  This command is the normal definition of @kbd{M-S-x}
878(that's ``meta shift x'').
879@end deffn
880
881@node Distinguish Interactive
882@section Distinguish Interactive Calls
883@cindex distinguish interactive calls
884@cindex is this call interactive
885
886  Sometimes a command should display additional visual feedback (such
887as an informative message in the echo area) for interactive calls
888only.  There are three ways to do this.  The recommended way to test
889whether the function was called using @code{call-interactively} is to
890give it an optional argument @code{print-message} and use the
891@code{interactive} spec to make it non-@code{nil} in interactive
892calls.  Here's an example:
893
894@example
895(defun foo (&optional print-message)
896  (interactive "p")
897  (when print-message
898    (message "foo")))
899@end example
900
901@noindent
902We use @code{"p"} because the numeric prefix argument is never
903@code{nil}.  Defined in this way, the function does display the
904message when called from a keyboard macro.
905
906  The above method with the additional argument is usually best,
907because it allows callers to say ``treat this call as interactive''.
908But you can also do the job by testing @code{called-interactively-p}.
909
910@defun called-interactively-p kind
911This function returns @code{t} when the calling function was called
912using @code{call-interactively}.
913
914The argument @var{kind} should be either the symbol @code{interactive}
915or the symbol @code{any}.  If it is @code{interactive}, then
916@code{called-interactively-p} returns @code{t} only if the call was
917made directly by the user---e.g., if the user typed a key sequence
918bound to the calling function, but @emph{not} if the user ran a
919keyboard macro that called the function (@pxref{Keyboard Macros}).  If
920@var{kind} is @code{any}, @code{called-interactively-p} returns
921@code{t} for any kind of interactive call, including keyboard macros.
922
923If in doubt, use @code{any}; the only known proper use of
924@code{interactive} is if you need to decide whether to display a
925helpful message while a function is running.
926
927A function is never considered to be called interactively if it was
928called via Lisp evaluation (or with @code{apply} or @code{funcall}).
929@end defun
930
931@noindent
932Here is an example of using @code{called-interactively-p}:
933
934@example
935@group
936(defun foo ()
937  (interactive)
938  (when (called-interactively-p 'any)
939    (message "Interactive!")
940    'foo-called-interactively))
941@end group
942
943@group
944;; @r{Type @kbd{M-x foo}.}
945     @print{} Interactive!
946@end group
947
948@group
949(foo)
950     @result{} nil
951@end group
952@end example
953
954@noindent
955Here is another example that contrasts direct and indirect calls to
956@code{called-interactively-p}.
957
958@example
959@group
960(defun bar ()
961  (interactive)
962  (message "%s" (list (foo) (called-interactively-p 'any))))
963@end group
964
965@group
966;; @r{Type @kbd{M-x bar}.}
967     @print{} (nil t)
968@end group
969@end example
970
971@node Command Loop Info
972@section Information from the Command Loop
973@cindex command loop variables
974
975The editor command loop sets several Lisp variables to keep status
976records for itself and for commands that are run.  With the exception of
977@code{this-command} and @code{last-command} it's generally a bad idea to
978change any of these variables in a Lisp program.
979
980@defvar last-command
981This variable records the name of the previous command executed by the
982command loop (the one before the current command).  Normally the value
983is a symbol with a function definition, but this is not guaranteed.
984
985The value is copied from @code{this-command} when a command returns to
986the command loop, except when the command has specified a prefix
987argument for the following command.
988
989This variable is always local to the current terminal and cannot be
990buffer-local.  @xref{Multiple Terminals}.
991@end defvar
992
993@defvar real-last-command
994This variable is set up by Emacs just like @code{last-command},
995but never altered by Lisp programs.
996@end defvar
997
998@defvar last-repeatable-command
999This variable stores the most recently executed command that was not
1000part of an input event.  This is the command @code{repeat} will try to
1001repeat, @xref{Repeating,,, emacs, The GNU Emacs Manual}.
1002@end defvar
1003
1004@defvar this-command
1005@cindex current command
1006This variable records the name of the command now being executed by
1007the editor command loop.  Like @code{last-command}, it is normally a symbol
1008with a function definition.
1009
1010The command loop sets this variable just before running a command, and
1011copies its value into @code{last-command} when the command finishes
1012(unless the command specified a prefix argument for the following
1013command).
1014
1015@cindex kill command repetition
1016Some commands set this variable during their execution, as a flag for
1017whatever command runs next.  In particular, the functions for killing text
1018set @code{this-command} to @code{kill-region} so that any kill commands
1019immediately following will know to append the killed text to the
1020previous kill.
1021@end defvar
1022
1023If you do not want a particular command to be recognized as the previous
1024command in the case where it got an error, you must code that command to
1025prevent this.  One way is to set @code{this-command} to @code{t} at the
1026beginning of the command, and set @code{this-command} back to its proper
1027value at the end, like this:
1028
1029@example
1030(defun foo (args@dots{})
1031  (interactive @dots{})
1032  (let ((old-this-command this-command))
1033    (setq this-command t)
1034    @r{@dots{}do the work@dots{}}
1035    (setq this-command old-this-command)))
1036@end example
1037
1038@noindent
1039We do not bind @code{this-command} with @code{let} because that would
1040restore the old value in case of error---a feature of @code{let} which
1041in this case does precisely what we want to avoid.
1042
1043@defvar this-original-command
1044This has the same value as @code{this-command} except when command
1045remapping occurs (@pxref{Remapping Commands}).  In that case,
1046@code{this-command} gives the command actually run (the result of
1047remapping), and @code{this-original-command} gives the command that
1048was specified to run but remapped into another command.
1049@end defvar
1050
1051@defvar current-minibuffer-command
1052This has the same value as @code{this-command}, but is bound
1053recursively when entering a minibuffer.  This variable can be used
1054from minibuffer hooks and the like to determine what command opened
1055the current minibuffer session.
1056@end defvar
1057
1058@defun this-command-keys
1059This function returns a string or vector containing the key sequence
1060that invoked the present command.  Any events read by the command
1061using @code{read-event} without a timeout get tacked on to the end.
1062
1063However, if the command has called @code{read-key-sequence}, it
1064returns the last read key sequence.  @xref{Key Sequence Input}.  The
1065value is a string if all events in the sequence were characters that
1066fit in a string.  @xref{Input Events}.
1067
1068@example
1069@group
1070(this-command-keys)
1071;; @r{Now use @kbd{C-u C-x C-e} to evaluate that.}
1072     @result{} "^X^E"
1073@end group
1074@end example
1075@end defun
1076
1077@defun this-command-keys-vector
1078@anchor{Definition of this-command-keys-vector}
1079Like @code{this-command-keys}, except that it always returns the events
1080in a vector, so you don't need to deal with the complexities of storing
1081input events in a string (@pxref{Strings of Events}).
1082@end defun
1083
1084@defun clear-this-command-keys &optional keep-record
1085This function empties out the table of events for
1086@code{this-command-keys} to return.  Unless @var{keep-record} is
1087non-@code{nil}, it also empties the records that the function
1088@code{recent-keys} (@pxref{Recording Input}) will subsequently return.
1089This is useful after reading a password, to prevent the password from
1090echoing inadvertently as part of the next command in certain cases.
1091@end defun
1092
1093@defvar last-nonmenu-event
1094This variable holds the last input event read as part of a key sequence,
1095not counting events resulting from mouse menus.
1096
1097One use of this variable is for telling @code{x-popup-menu} where to pop
1098up a menu.  It is also used internally by @code{y-or-n-p}
1099(@pxref{Yes-or-No Queries}).
1100@end defvar
1101
1102@defvar last-command-event
1103This variable is set to the last input event that was read by the
1104command loop as part of a command.  The principal use of this variable
1105is in @code{self-insert-command}, which uses it to decide which
1106character to insert.
1107
1108@example
1109@group
1110last-command-event
1111;; @r{Now use @kbd{C-u C-x C-e} to evaluate that.}
1112     @result{} 5
1113@end group
1114@end example
1115
1116@noindent
1117The value is 5 because that is the @acronym{ASCII} code for @kbd{C-e}.
1118@end defvar
1119
1120@defvar last-event-frame
1121This variable records which frame the last input event was directed to.
1122Usually this is the frame that was selected when the event was
1123generated, but if that frame has redirected input focus to another
1124frame, the value is the frame to which the event was redirected.
1125@xref{Input Focus}.
1126
1127If the last event came from a keyboard macro, the value is @code{macro}.
1128@end defvar
1129
1130@node Adjusting Point
1131@section Adjusting Point After Commands
1132@cindex adjusting point
1133@cindex invisible/intangible text, and point
1134@cindex @code{display} property, and point display
1135@cindex @code{composition} property, and point display
1136
1137  Emacs cannot display the cursor when point is in the middle of a
1138sequence of text that has the @code{display} or @code{composition}
1139property, or is invisible.  Therefore, after a command finishes and
1140returns to the command loop, if point is within such a sequence, the
1141command loop normally moves point to the edge of the sequence, making this
1142sequence effectively intangible.
1143
1144  A command can inhibit this feature by setting the variable
1145@code{disable-point-adjustment}:
1146
1147@defvar disable-point-adjustment
1148If this variable is non-@code{nil} when a command returns to the
1149command loop, then the command loop does not check for those text
1150properties, and does not move point out of sequences that have them.
1151
1152The command loop sets this variable to @code{nil} before each command,
1153so if a command sets it, the effect applies only to that command.
1154@end defvar
1155
1156@defvar global-disable-point-adjustment
1157If you set this variable to a non-@code{nil} value, the feature of
1158moving point out of these sequences is completely turned off.
1159@end defvar
1160
1161@node Input Events
1162@section Input Events
1163@cindex events
1164@cindex input events
1165
1166The Emacs command loop reads a sequence of @dfn{input events} that
1167represent keyboard or mouse activity, or system events sent to Emacs.
1168The events for keyboard activity are characters or symbols; other
1169events are always lists.  This section describes the representation
1170and meaning of input events in detail.
1171
1172@defun eventp object
1173This function returns non-@code{nil} if @var{object} is an input event
1174or event type.
1175
1176Note that any non-@code{nil} symbol might be used as an event or an
1177event type; @code{eventp} cannot distinguish whether a symbol is
1178intended by Lisp code to be used as an event.
1179@end defun
1180
1181@menu
1182* Keyboard Events::             Ordinary characters -- keys with symbols on them.
1183* Function Keys::               Function keys -- keys with names, not symbols.
1184* Mouse Events::                Overview of mouse events.
1185* Click Events::                Pushing and releasing a mouse button.
1186* Drag Events::                 Moving the mouse before releasing the button.
1187* Button-Down Events::          A button was pushed and not yet released.
1188* Repeat Events::               Double and triple click (or drag, or down).
1189* Motion Events::               Just moving the mouse, not pushing a button.
1190* Touchscreen Events::          Tapping and moving fingers on a touchscreen.
1191* Focus Events::                Moving the mouse between frames.
1192* Xwidget Events::              Events generated by xwidgets.
1193* Misc Events::                 Other events the system can generate.
1194* Event Examples::              Examples of the lists for mouse events.
1195* Classifying Events::          Finding the modifier keys in an event symbol.
1196                                Event types.
1197* Accessing Mouse::             Functions to extract info from mouse events.
1198* Accessing Scroll::            Functions to get info from scroll bar events.
1199* Strings of Events::           Special considerations for putting
1200                                  keyboard character events in a string.
1201@end menu
1202
1203@node Keyboard Events
1204@subsection Keyboard Events
1205@cindex keyboard events
1206
1207@cindex character event
1208There are two kinds of input you can get from the keyboard: ordinary
1209keys, and function keys.  Ordinary keys correspond to (possibly
1210modified) characters; the events they generate are represented in Lisp
1211as characters.  The event type of a @dfn{character event} is the
1212character itself (an integer), which might have some modifier bits
1213set; see @ref{Classifying Events}.
1214
1215@cindex modifier bits (of input character)
1216@cindex basic code (of input character)
1217An input character event consists of a @dfn{basic code} between 0 and
1218524287, plus any or all of these @dfn{modifier bits}:
1219
1220@table @asis
1221@item meta
1222The
1223@tex
1224@math{2^{27}}
1225@end tex
1226@ifnottex
12272**27
1228@end ifnottex
1229bit in the character code indicates a character
1230typed with the meta key held down.
1231
1232@item control
1233The
1234@tex
1235@math{2^{26}}
1236@end tex
1237@ifnottex
12382**26
1239@end ifnottex
1240bit in the character code indicates a non-@acronym{ASCII}
1241control character.
1242
1243@sc{ascii} control characters such as @kbd{C-a} have special basic
1244codes of their own, so Emacs needs no special bit to indicate them.
1245Thus, the code for @kbd{C-a} is just 1.
1246
1247But if you type a control combination not in @acronym{ASCII}, such as
1248@kbd{%} with the control key, the numeric value you get is the code
1249for @kbd{%} plus
1250@tex
1251@math{2^{26}}
1252@end tex
1253@ifnottex
12542**26
1255@end ifnottex
1256(assuming the terminal supports non-@acronym{ASCII}
1257control characters), i.e.@: with the 27th bit set.
1258
1259@item shift
1260The
1261@tex
1262@math{2^{25}}
1263@end tex
1264@ifnottex
12652**25
1266@end ifnottex
1267bit (the 26th bit) in the character event code indicates an
1268@acronym{ASCII} control character typed with the shift key held down.
1269
1270For letters, the basic code itself indicates upper versus lower case;
1271for digits and punctuation, the shift key selects an entirely different
1272character with a different basic code.  In order to keep within the
1273@acronym{ASCII} character set whenever possible, Emacs avoids using the
1274@tex
1275@math{2^{25}}
1276@end tex
1277@ifnottex
12782**25
1279@end ifnottex
1280bit for those character events.
1281
1282However, @acronym{ASCII} provides no way to distinguish @kbd{C-A} from
1283@kbd{C-a}, so Emacs uses the
1284@tex
1285@math{2^{25}}
1286@end tex
1287@ifnottex
12882**25
1289@end ifnottex
1290bit in @kbd{C-A} and not in
1291@kbd{C-a}.
1292
1293@item hyper
1294The
1295@tex
1296@math{2^{24}}
1297@end tex
1298@ifnottex
12992**24
1300@end ifnottex
1301bit in the character event code indicates a character
1302typed with the hyper key held down.
1303
1304@item super
1305The
1306@tex
1307@math{2^{23}}
1308@end tex
1309@ifnottex
13102**23
1311@end ifnottex
1312bit in the character event code indicates a character
1313typed with the super key held down.
1314
1315@item alt
1316The
1317@tex
1318@math{2^{22}}
1319@end tex
1320@ifnottex
13212**22
1322@end ifnottex
1323bit in the character event code indicates a character typed with the
1324alt key held down.  (The key labeled @key{Alt} on most keyboards is
1325actually treated as the meta key, not this.)
1326@end table
1327
1328  It is best to avoid mentioning specific bit numbers in your program.
1329To test the modifier bits of a character, use the function
1330@code{event-modifiers} (@pxref{Classifying Events}).  When making key
1331bindings with @code{keymap-set}, you specify these events using
1332strings like @samp{C-H-x} instead (for ``control hyper x'')
1333(@pxref{Changing Key Bindings}).
1334
1335@node Function Keys
1336@subsection Function Keys
1337
1338@cindex function keys
1339Most keyboards also have @dfn{function keys}---keys that have names or
1340symbols that are not characters.  Function keys are represented in
1341Emacs Lisp as symbols; the symbol's name is the function key's label,
1342in lower case.  For example, pressing a key labeled @key{F1} generates
1343an input event represented by the symbol @code{f1}.
1344
1345The event type of a function key event is the event symbol itself.
1346@xref{Classifying Events}.
1347
1348Here are a few special cases in the symbol-naming convention for
1349function keys:
1350
1351@table @asis
1352@item @code{backspace}, @code{tab}, @code{newline}, @code{return}, @code{delete}
1353These keys correspond to common @acronym{ASCII} control characters that have
1354special keys on most keyboards.
1355
1356In @acronym{ASCII}, @kbd{C-i} and @key{TAB} are the same character.  If the
1357terminal can distinguish between them, Emacs conveys the distinction to
1358Lisp programs by representing the former as the integer 9, and the
1359latter as the symbol @code{tab}.
1360
1361Most of the time, it's not useful to distinguish the two.  So normally
1362@code{local-function-key-map} (@pxref{Translation Keymaps}) is set up
1363to map @code{tab} into 9.  Thus, a key binding for character code 9
1364(the character @kbd{C-i}) also applies to @code{tab}.  Likewise for
1365the other symbols in this group.  The function @code{read-char}
1366likewise converts these events into characters.
1367
1368In @acronym{ASCII}, @key{BS} is really @kbd{C-h}.  But @code{backspace}
1369converts into the character code 127 (@key{DEL}), not into code 8
1370(@key{BS}).  This is what most users prefer.
1371
1372@item @code{left}, @code{up}, @code{right}, @code{down}
1373Cursor arrow keys
1374@item @code{kp-add}, @code{kp-decimal}, @code{kp-divide}, @dots{}
1375Keypad keys (to the right of the regular keyboard).
1376@item @code{kp-0}, @code{kp-1}, @dots{}
1377Keypad keys with digits.
1378@item @code{kp-f1}, @code{kp-f2}, @code{kp-f3}, @code{kp-f4}
1379Keypad PF keys.
1380@item @code{kp-home}, @code{kp-left}, @code{kp-up}, @code{kp-right}, @code{kp-down}
1381Keypad arrow keys.  Emacs normally translates these into the
1382corresponding non-keypad keys @code{home}, @code{left}, @dots{}
1383@item @code{kp-prior}, @code{kp-next}, @code{kp-end}, @code{kp-begin}, @code{kp-insert}, @code{kp-delete}
1384Additional keypad duplicates of keys ordinarily found elsewhere.  Emacs
1385normally translates these into the like-named non-keypad keys.
1386@end table
1387
1388You can use the modifier keys @key{ALT}, @key{CTRL}, @key{HYPER},
1389@key{META}, @key{SHIFT}, and @key{SUPER} with function keys.  The way to
1390represent them is with prefixes in the symbol name:
1391
1392@table @samp
1393@item A-
1394The alt modifier.
1395@item C-
1396The control modifier.
1397@item H-
1398The hyper modifier.
1399@item M-
1400The meta modifier.
1401@item S-
1402The shift modifier.
1403@item s-
1404The super modifier.
1405@end table
1406
1407Thus, the symbol for the key @key{F3} with @key{META} held down is
1408@code{M-f3}.  When you use more than one prefix, we recommend you
1409write them in alphabetical order; but the order does not matter in
1410arguments to the key-binding lookup and modification functions.
1411
1412@node Mouse Events
1413@subsection Mouse Events
1414
1415Emacs supports four kinds of mouse events: click events, drag events,
1416button-down events, and motion events.  All mouse events are represented
1417as lists.  The @sc{car} of the list is the event type; this says which
1418mouse button was involved, and which modifier keys were used with it.
1419The event type can also distinguish double or triple button presses
1420(@pxref{Repeat Events}).  The rest of the list elements give position
1421and time information.
1422
1423For key lookup, only the event type matters: two events of the same type
1424necessarily run the same command.  The command can access the full
1425values of these events using the @samp{e} interactive code.
1426@xref{Interactive Codes}.
1427
1428A key sequence that starts with a mouse event is read using the keymaps
1429of the buffer in the window that the mouse was in, not the current
1430buffer.  This does not imply that clicking in a window selects that
1431window or its buffer---that is entirely under the control of the command
1432binding of the key sequence.
1433
1434@node Click Events
1435@subsection Click Events
1436@cindex click event
1437@cindex mouse click event
1438@cindex mouse wheel event
1439
1440When the user presses a mouse button and releases it at the same
1441location, that generates a @dfn{click} event.  Depending on how your
1442window-system reports mouse-wheel events, turning the mouse wheel can
1443generate either a mouse click or a mouse-wheel event.  All mouse event
1444share the same format:
1445
1446@example
1447(@var{event-type} @var{position} @var{click-count})
1448@end example
1449
1450@table @asis
1451@item @var{event-type}
1452This is a symbol that indicates which mouse button was used.  It is
1453one of the symbols @code{mouse-1}, @code{mouse-2}, @dots{}, where the
1454buttons are numbered left to right.  For mouse-wheel event, it can be
1455@code{wheel-up} or @code{wheel-down}.
1456
1457You can also use prefixes @samp{A-}, @samp{C-}, @samp{H-}, @samp{M-},
1458@samp{S-} and @samp{s-} for modifiers alt, control, hyper, meta, shift
1459and super, just as you would with function keys.
1460
1461This symbol also serves as the event type of the event.  Key bindings
1462describe events by their types; thus, if there is a key binding for
1463@code{mouse-1}, that binding would apply to all events whose
1464@var{event-type} is @code{mouse-1}.
1465
1466@item @var{position}
1467@cindex mouse position list
1468This is a @dfn{mouse position list} specifying where the mouse event
1469occurred; see below for details.
1470
1471@item @var{click-count}
1472This is the number of rapid repeated presses so far of the same mouse
1473button or the number of repeated turns of the wheel.  @xref{Repeat
1474Events}.
1475@end table
1476
1477  To access the contents of a mouse position list in the
1478@var{position} slot of a mouse event, you should typically use the
1479functions documented in @ref{Accessing Mouse}.
1480
1481The explicit format of the list depends on where the event occurred.
1482For clicks in the text area, mode line, header line, tab line, or in
1483the fringe or marginal areas, the mouse position list has the form
1484
1485@example
1486(@var{window} @var{pos-or-area} (@var{x} . @var{y}) @var{timestamp}
1487 @var{object} @var{text-pos} (@var{col} . @var{row})
1488 @var{image} (@var{dx} . @var{dy}) (@var{width} . @var{height}))
1489@end example
1490
1491@noindent
1492The meanings of these list elements are as follows:
1493
1494@table @asis
1495@item @var{window}
1496The window in which the mouse event occurred.
1497
1498@item @var{pos-or-area}
1499The buffer position of the character clicked on in the text area; or,
1500if the event was outside the text area, the window area where it
1501occurred.  It is one of the symbols @code{mode-line},
1502@code{header-line}, @code{tab-line}, @code{vertical-line},
1503@code{left-margin}, @code{right-margin}, @code{left-fringe}, or
1504@code{right-fringe}.
1505
1506In one special case, @var{pos-or-area} is a list containing a symbol
1507(one of the symbols listed above) instead of just the symbol.  This
1508happens after the imaginary prefix keys for the event are registered
1509by Emacs.  @xref{Key Sequence Input}.
1510
1511@item @var{x}, @var{y}
1512The relative pixel coordinates of the event.  For events in the text
1513area of a window, the coordinate origin @code{(0 . 0)} is taken to be
1514the top left corner of the text area.  @xref{Window Sizes}.  For
1515events in a mode line, header line or tab line, the coordinate origin
1516is the top left corner of the window itself.  For fringes, margins,
1517and the vertical border, @var{x} does not have meaningful data.
1518For fringes and margins, @var{y} is relative to the bottom edge of the
1519header line.  In all cases, the @var{x} and @var{y} coordinates
1520increase rightward and downward respectively.
1521
1522@item @var{timestamp}
1523The time at which the event occurred, as an integer number of
1524milliseconds since a system-dependent initial time.
1525
1526@item @var{object}
1527Either @code{nil}, which means the event occurred on buffer text, or a
1528cons cell of the form @w{(@var{string} . @var{string-pos})} if there
1529is a string from a text property or an overlay at the event position.
1530
1531@table @asis
1532@item @var{string}
1533The string which was clicked on, including any properties.
1534
1535@item @var{string-pos}
1536The position in the string where the click occurred.
1537@end table
1538
1539@item @var{text-pos}
1540For clicks on a marginal area or on a fringe, this is the buffer
1541position of the first visible character in the corresponding line in
1542the window.  For clicks on the mode line, the header line or the tab
1543line, this is @code{nil}.  For other events, it is the buffer position
1544closest to the click.
1545
1546@item @var{col}, @var{row}
1547These are the actual column and row coordinate numbers of the glyph
1548under the @var{x}, @var{y} position.  If @var{x} lies beyond the last
1549column of actual text on its line, @var{col} is reported by adding
1550fictional extra columns that have the default character width.
1551Row 0 is taken to be the header line if the window has one, or Row 1
1552if the window also has the tab line, or the topmost row of
1553the text area otherwise.  Column 0 is taken to be the leftmost
1554column of the text area for clicks on a window text area, or the
1555leftmost mode line or header line column for clicks there.  For clicks
1556on fringes or vertical borders, these have no meaningful data.  For
1557clicks on margins, @var{col} is measured from the left edge of the
1558margin area and @var{row} is measured from the top of the margin area.
1559
1560@item @var{image}
1561If there is an image at the click location, this is the image object
1562as returned by @code{find-image} (@pxref{Defining Images}); otherwise
1563this is @code{nil}.
1564
1565@item @var{dx}, @var{dy}
1566These are the pixel coordinates of the click, relative to the top left
1567corner of @var{object}, which is @code{(0 . 0)}.  If @var{object} is
1568@code{nil}, which stands for a buffer, the coordinates are relative to
1569the top left corner of the character glyph clicked on.
1570
1571@item @var{width}, @var{height}
1572If the click is on a character, either from buffer text or from
1573overlay or display string, these are the pixel width and height of
1574that character's glyph; otherwise they are dimensions of @var{object}
1575clicked on.
1576@end table
1577
1578For clicks on a scroll bar, @var{position} has this form:
1579
1580@example
1581(@var{window} @var{area} (@var{portion} . @var{whole}) @var{timestamp} @var{part})
1582@end example
1583
1584@table @asis
1585@item @var{window}
1586The window whose scroll bar was clicked on.
1587
1588@item @var{area}
1589This is the symbol @code{vertical-scroll-bar}.
1590
1591@item @var{portion}
1592The number of pixels from the top of the scroll bar to the click
1593position.  On some toolkits, including GTK+, Emacs cannot extract this
1594data, so the value is always @code{0}.
1595
1596@item @var{whole}
1597The total length, in pixels, of the scroll bar.  On some toolkits,
1598including GTK+, Emacs cannot extract this data, so the value is always
1599@code{0}.
1600
1601@item @var{timestamp}
1602The time at which the event occurred, in milliseconds.  On some
1603toolkits, including GTK+, Emacs cannot extract this data, so the value
1604is always @code{0}.
1605
1606@item @var{part}
1607The part of the scroll bar on which the click occurred.  It is one of
1608the symbols @code{handle} (the scroll bar handle), @code{above-handle}
1609(the area above the handle), @code{below-handle} (the area below the
1610handle), @code{up} (the up arrow at one end of the scroll bar), or
1611@code{down} (the down arrow at one end of the scroll bar).
1612@c The 'top', 'bottom', and 'end-scroll' codes don't seem to be used.
1613@end table
1614
1615For clicks on the frame's internal border (@pxref{Frame Layout}),
1616the frame's tool bar (@pxref{Tool Bar}) or tab bar, @var{position}
1617has this form:
1618
1619@example
1620 (@var{frame} @var{part} (@var{X} . @var{Y}) @var{timestamp})
1621@end example
1622
1623@table @asis
1624@item @var{frame}
1625The frame whose internal border or tool bar or tab bar was clicked on.
1626
1627@item @var{part}
1628The part of the frame which was clicked on.  This can be one
1629of the following:
1630
1631@table @code
1632@cindex tool-bar mouse events
1633@item tool-bar
1634The frame has a tool bar, and the event was in the tool-bar area.
1635
1636@cindex tab-bar mouse events
1637@item tab-bar
1638The frame has a tab bar, and the event was in the tab-bar area.
1639
1640@item left-edge
1641@itemx top-edge
1642@itemx right-edge
1643@itemx bottom-edge
1644The click was on the corresponding border at an offset of at least one
1645canonical character from the border's nearest corner.
1646
1647@item top-left-corner
1648@itemx top-right-corner
1649@itemx bottom-right-corner
1650@itemx bottom-left-corner
1651The click was on the corresponding corner of the internal border.
1652
1653@item nil
1654The frame does not have an internal border, and the event was not on
1655the tab bar or the tool bar.  This usually happens on text-mode
1656frames.  This can also happen on GUI frames with internal border if
1657the frame doesn't have its @code{drag-internal-border} parameter
1658(@pxref{Mouse Dragging Parameters}) set to a non-@code{nil} value.
1659@end table
1660
1661@end table
1662
1663
1664@node Drag Events
1665@subsection Drag Events
1666@cindex drag event
1667@cindex mouse drag event
1668
1669With Emacs, you can have a drag event without even changing your
1670clothes.  A @dfn{drag event} happens every time the user presses a mouse
1671button and then moves the mouse to a different character position before
1672releasing the button.  Like all mouse events, drag events are
1673represented in Lisp as lists.  The lists record both the starting mouse
1674position and the final position, like this:
1675
1676@example
1677(@var{event-type}
1678 (@var{window1} START-POSITION)
1679 (@var{window2} END-POSITION))
1680@end example
1681
1682For a drag event, the name of the symbol @var{event-type} contains the
1683prefix @samp{drag-}.  For example, dragging the mouse with button 2
1684held down generates a @code{drag-mouse-2} event.  The second and third
1685elements of the event give the starting and ending position of the
1686drag, as mouse position lists (@pxref{Click Events}).  You can access
1687the second element of any mouse event in the same way.  However, the
1688drag event may end outside the boundaries of the frame that was
1689initially selected.  In that case, the third element's position list
1690contains that frame in place of a window.
1691
1692The @samp{drag-} prefix follows the modifier key prefixes such as
1693@samp{C-} and @samp{M-}.
1694
1695If @code{read-key-sequence} receives a drag event that has no key
1696binding, and the corresponding click event does have a binding, it
1697changes the drag event into a click event at the drag's starting
1698position.  This means that you don't have to distinguish between click
1699and drag events unless you want to.
1700
1701@node Button-Down Events
1702@subsection Button-Down Events
1703@cindex button-down event
1704
1705Click and drag events happen when the user releases a mouse button.
1706They cannot happen earlier, because there is no way to distinguish a
1707click from a drag until the button is released.
1708
1709If you want to take action as soon as a button is pressed, you need to
1710handle @dfn{button-down} events.@footnote{Button-down is the
1711conservative antithesis of drag.}  These occur as soon as a button is
1712pressed.  They are represented by lists that look exactly like click
1713events (@pxref{Click Events}), except that the @var{event-type} symbol
1714name contains the prefix @samp{down-}.  The @samp{down-} prefix follows
1715modifier key prefixes such as @samp{C-} and @samp{M-}.
1716
1717The function @code{read-key-sequence} ignores any button-down events
1718that don't have command bindings; therefore, the Emacs command loop
1719ignores them too.  This means that you need not worry about defining
1720button-down events unless you want them to do something.  The usual
1721reason to define a button-down event is so that you can track mouse
1722motion (by reading motion events) until the button is released.
1723@xref{Motion Events}.
1724
1725@node Repeat Events
1726@subsection Repeat Events
1727@cindex repeat events
1728@cindex double-click events
1729@cindex triple-click events
1730@cindex mouse events, repeated
1731
1732If you press the same mouse button more than once in quick succession
1733without moving the mouse, Emacs generates special @dfn{repeat} mouse
1734events for the second and subsequent presses.
1735
1736The most common repeat events are @dfn{double-click} events.  Emacs
1737generates a double-click event when you click a button twice; the event
1738happens when you release the button (as is normal for all click
1739events).
1740
1741The event type of a double-click event contains the prefix
1742@samp{double-}.  Thus, a double click on the second mouse button with
1743@key{meta} held down comes to the Lisp program as
1744@code{M-double-mouse-2}.  If a double-click event has no binding, the
1745binding of the corresponding ordinary click event is used to execute
1746it.  Thus, you need not pay attention to the double click feature
1747unless you really want to.
1748
1749When the user performs a double click, Emacs generates first an ordinary
1750click event, and then a double-click event.  Therefore, you must design
1751the command binding of the double click event to assume that the
1752single-click command has already run.  It must produce the desired
1753results of a double click, starting from the results of a single click.
1754
1755This is convenient, if the meaning of a double click somehow builds
1756on the meaning of a single click---which is recommended user interface
1757design practice for double clicks.
1758
1759If you click a button, then press it down again and start moving the
1760mouse with the button held down, then you get a @dfn{double-drag} event
1761when you ultimately release the button.  Its event type contains
1762@samp{double-drag} instead of just @samp{drag}.  If a double-drag event
1763has no binding, Emacs looks for an alternate binding as if the event
1764were an ordinary drag.
1765
1766Before the double-click or double-drag event, Emacs generates a
1767@dfn{double-down} event when the user presses the button down for the
1768second time.  Its event type contains @samp{double-down} instead of just
1769@samp{down}.  If a double-down event has no binding, Emacs looks for an
1770alternate binding as if the event were an ordinary button-down event.
1771If it finds no binding that way either, the double-down event is
1772ignored.
1773
1774To summarize, when you click a button and then press it again right
1775away, Emacs generates a down event and a click event for the first
1776click, a double-down event when you press the button again, and finally
1777either a double-click or a double-drag event.
1778
1779If you click a button twice and then press it again, all in quick
1780succession, Emacs generates a @dfn{triple-down} event, followed by
1781either a @dfn{triple-click} or a @dfn{triple-drag}.  The event types of
1782these events contain @samp{triple} instead of @samp{double}.  If any
1783triple event has no binding, Emacs uses the binding that it would use
1784for the corresponding double event.
1785
1786If you click a button three or more times and then press it again, the
1787events for the presses beyond the third are all triple events.  Emacs
1788does not have separate event types for quadruple, quintuple, etc.@:
1789events.  However, you can look at the event list to find out precisely
1790how many times the button was pressed.
1791
1792@defun event-click-count event
1793This function returns the number of consecutive button presses that led
1794up to @var{event}.  If @var{event} is a double-down, double-click or
1795double-drag event, the value is 2.  If @var{event} is a triple event,
1796the value is 3 or greater.  If @var{event} is an ordinary mouse event
1797(not a repeat event), the value is 1.
1798@end defun
1799
1800@defopt double-click-fuzz
1801To generate repeat events, successive mouse button presses must be at
1802approximately the same screen position.  The value of
1803@code{double-click-fuzz} specifies the maximum number of pixels the
1804mouse may be moved (horizontally or vertically) between two successive
1805clicks to make a double-click.
1806
1807This variable is also the threshold for motion of the mouse to count
1808as a drag.
1809@end defopt
1810
1811@defopt double-click-time
1812To generate repeat events, the number of milliseconds between
1813successive button presses must be less than the value of
1814@code{double-click-time}.  Setting @code{double-click-time} to
1815@code{nil} disables multi-click detection entirely.  Setting it to
1816@code{t} removes the time limit; Emacs then detects multi-clicks by
1817position only.
1818@end defopt
1819
1820@node Motion Events
1821@subsection Motion Events
1822@cindex motion event
1823@cindex mouse motion events
1824
1825Emacs sometimes generates @dfn{mouse motion} events to describe motion
1826of the mouse without any button activity.  Mouse motion events are
1827represented by lists that look like this:
1828
1829@example
1830(mouse-movement POSITION)
1831@end example
1832
1833@noindent
1834@var{position} is a mouse position list (@pxref{Click Events}),
1835specifying the current position of the mouse cursor.  As with the
1836end-position of a drag event, this position list may represent a
1837location outside the boundaries of the initially selected frame, in
1838which case the list contains that frame in place of a window.
1839
1840The special form @code{track-mouse} enables generation of motion
1841events within its body.  Outside of @code{track-mouse} forms, Emacs
1842does not generate events for mere motion of the mouse, and these
1843events do not appear.  @xref{Mouse Tracking}.
1844
1845@defvar mouse-fine-grained-tracking
1846When non-@code{nil}, mouse motion events are generated even for very
1847small movements.  Otherwise, motion events are not generated as long
1848as the mouse cursor remains pointing to the same glyph in the text.
1849@end defvar
1850
1851@node Touchscreen Events
1852@subsection Touchscreen Events
1853@cindex touchscreen events
1854@cindex support for touchscreens
1855
1856Some window systems provide support for input devices that react to
1857the user's touching the screen and moving fingers while touching the
1858screen.  These input devices are known as touchscreens, and Emacs
1859reports the events they generate as @dfn{touchscreen events}.
1860
1861Most individual events generated by a touchscreen only have meaning as
1862part of a larger sequence of other events: for instance, the simple
1863operation of tapping the touchscreen involves the user placing and
1864raising a finger on the touchscreen, and swiping the display to
1865scroll it involves placing a finger, moving it many times upwards or
1866downwards, and then raising the finger.
1867
1868@cindex touch point, in touchscreen events
1869While a simplistic model consisting of one finger is adequate for taps
1870and scrolling, more complicated gestures require support for keeping
1871track of multiple fingers, where the position of each finger is
1872represented by a @dfn{touch point}.  For example, a ``pinch to zoom''
1873gesture might consist of the user placing two fingers and moving them
1874individually in opposite directions, where the distance between the
1875positions of their individual points determine the amount by which to
1876zoom the display, and the center of an imaginary line between those
1877positions determines where to pan the display after zooming.
1878
1879The low-level touchscreen events described below can be used to
1880implement all the touch sequences described above.  In those events,
1881each point is represented by a cons of an arbitrary number identifying
1882the point and a mouse position list (@pxref{Click Events}) specifying
1883the position of the finger when the event occurred.
1884
1885@table @code
1886@cindex @code{touchscreen-begin} event
1887@item (touchscreen-begin @var{point})
1888This event is sent when @var{point} is created by the user pressing a
1889finger against the touchscreen.
1890
1891@cindex @code{touchscreen-update} event
1892@item (touchscreen-update @var{points})
1893This event is sent when a point on the touchscreen has changed
1894position.  @var{points} is a list of touch points containing the
1895up-to-date positions of each touch point currently on the touchscreen.
1896
1897@cindex @code{touchscreen-end} event
1898@item (touchscreen-end @var{point})
1899This event is sent when @var{point} is no longer present on the
1900display, because another program took the grab, or because the user
1901raised the finger from the touchscreen.
1902@end table
1903
1904@node Focus Events
1905@subsection Focus Events
1906@cindex focus event
1907
1908Window systems provide general ways for the user to control which window
1909gets keyboard input.  This choice of window is called the @dfn{focus}.
1910When the user does something to switch between Emacs frames, that
1911generates a @dfn{focus event}.  The normal definition of a focus event,
1912in the global keymap, is to select a new frame within Emacs, as the user
1913would expect.  @xref{Input Focus}, which also describes hooks related
1914to focus events.
1915
1916Focus events are represented in Lisp as lists that look like this:
1917
1918@example
1919(switch-frame @var{new-frame})
1920@end example
1921
1922@noindent
1923where @var{new-frame} is the frame switched to.
1924
1925Some X window managers are set up so that just moving the mouse into a
1926window is enough to set the focus there.  Usually, there is no need
1927for a Lisp program to know about the focus change until some other
1928kind of input arrives.  Emacs generates a focus event only when the
1929user actually types a keyboard key or presses a mouse button in the
1930new frame; just moving the mouse between frames does not generate a
1931focus event.
1932
1933A focus event in the middle of a key sequence would garble the
1934sequence.  So Emacs never generates a focus event in the middle of a key
1935sequence.  If the user changes focus in the middle of a key
1936sequence---that is, after a prefix key---then Emacs reorders the events
1937so that the focus event comes either before or after the multi-event key
1938sequence, and not within it.
1939
1940@node Xwidget Events
1941@subsection Xwidget events
1942
1943Xwidgets (@pxref{Xwidgets}) can send events to update Lisp programs on
1944their status.  These events are dubbed @code{xwidget-events}, and
1945contain various data describing the nature of the change.
1946
1947@table @code
1948@cindex @code{xwidget-event} event
1949@item (xwidget-event @var{kind} @var{xwidget} @var{arg})
1950This event is sent whenever some kind of update occurs in
1951@var{xwidget}.  There are several types of updates, identified by
1952their @var{kind}.
1953
1954@cindex xwidget callbacks
1955It is a special event (@pxref{Special Events}), which should be
1956handled by adding a callback to an xwidget that is called whenever an
1957xwidget event for @var{xwidget} is received.
1958
1959You can add a callback by setting the @code{callback} of an xwidget's
1960property list, which should be a function that accepts @var{xwidget}
1961and @var{kind} as arguments.
1962
1963@table @code
1964@cindex @code{load-changed} xwidget event
1965@item load-changed
1966This xwidget event indicates that the @var{xwidget} has reached a
1967particular point of the page-loading process.  When these events are
1968sent, @var{arg} will contain a string that futher describes the status
1969of the widget:
1970
1971@table @samp
1972@cindex @samp{load-started} in xwidgets
1973@item load-started
1974This means the widget has begun a page-loading operation.
1975
1976@cindex @samp{load-finished} in xwidgets
1977@item load-finished
1978This means the @var{xwidget} has finished processing whatever
1979page-loading operation that it was previously performing.
1980
1981@cindex @samp{load-redirected} in xwidgets
1982@item load-redirected
1983This means the @var{xwidget} has encountered and followed a redirect
1984during the page-loading operation.
1985
1986@cindex @samp{load-committed} in xwidgets
1987@item load-committed
1988This means the @var{xwidget} has committed to a given URL during the
1989page-loading operation, i.e.@: the URL is the final URL that will be
1990rendered by @var{xwidget} during the current page-loading operation.
1991@end table
1992
1993@cindex @code{download-callback} xwidget events
1994@item download-callback
1995This event indicates that a download of some kind has been completed.
1996@end table
1997
1998In the above events, there can be arguments after @var{arg}, which
1999itself indicates the URL from which the download file was retrieved:
2000the first argument after @var{arg} indicates the MIME type of the
2001download, as a string, while the second argument contains the full
2002file name of the downloaded file.
2003
2004@table @code
2005@cindex @code{download-started} xwidget events
2006@item download-started
2007This event indicates that a download has been started.  In these
2008events, @var{arg} contains the URL of the file that is currently being
2009downloaded.
2010
2011@cindex @code{javascript-callback} xwidget events
2012@item javascript-callback
2013This event contains JavaScript callback data.  These events are used
2014internally by @code{xwidget-webkit-execute-script}.
2015@end table
2016
2017@cindex @code{xwidget-display-event} event
2018@item (xwidget-display-event @var{xwidget} @var{source})
2019This event is sent whenever an xwidget requests that another xwidget
2020be displayed.  @var{xwidget} is the xwidget that should be displayed,
2021and @var{source} is the xwidget that asked to display @var{xwidget}.
2022
2023It is also a special event which should be handled through callbacks.
2024You can add such a callback by setting the @code{display-callback} of
2025@var{source}'s property list, which should be a function that accepts
2026@var{xwidget} and @var{source} as arguments.
2027
2028@var{xwidget}'s buffer will be set to a temporary buffer.  When
2029displaying the widget, care should be taken to replace the buffer with
2030the buffer in which the xwidget will be displayed, using
2031@code{set-xwidget-buffer}  (@pxref{Xwidgets}).
2032@end table
2033
2034@node Misc Events
2035@subsection Miscellaneous System Events
2036
2037A few other event types represent occurrences within the system.
2038
2039@table @code
2040@cindex @code{delete-frame} event
2041@item (delete-frame (@var{frame}))
2042This kind of event indicates that the user gave the window manager
2043a command to delete a particular window, which happens to be an Emacs frame.
2044
2045The standard definition of the @code{delete-frame} event is to delete @var{frame}.
2046
2047@cindex @code{iconify-frame} event
2048@item (iconify-frame (@var{frame}))
2049This kind of event indicates that the user iconified @var{frame} using
2050the window manager.  Its standard definition is @code{ignore}; since the
2051frame has already been iconified, Emacs has no work to do.  The purpose
2052of this event type is so that you can keep track of such events if you
2053want to.
2054
2055@cindex @code{make-frame-visible} event
2056@item (make-frame-visible (@var{frame}))
2057This kind of event indicates that the user deiconified @var{frame} using
2058the window manager.  Its standard definition is @code{ignore}; since the
2059frame has already been made visible, Emacs has no work to do.
2060
2061@cindex @code{touch-end} event
2062@item (touch-end (@var{position}))
2063This kind of event indicates that the user's finger moved off the
2064mouse wheel or the touchpad.  The @var{position} element is a mouse
2065position list (@pxref{Click Events}), specifying the position of the
2066mouse cursor when the finger moved off the mouse wheel.
2067
2068@cindex @code{wheel-up} event
2069@cindex @code{wheel-down} event
2070@item (wheel-up @var{position} @var{clicks} @var{lines} @var{pixel-delta})
2071@itemx (wheel-down @var{position} @var{clicks} @var{lines} @var{pixel-delta})
2072These kinds of event are generated by moving a mouse wheel.  The
2073@var{position} element is a mouse position list (@pxref{Click
2074Events}), specifying the position of the mouse cursor when the event
2075occurred.
2076
2077@var{clicks}, if present, is the number of times that the wheel was
2078moved in quick succession.  @xref{Repeat Events}.  @var{lines}, if
2079present and not @code{nil}, is the number of screen lines that should
2080be scrolled.  @var{pixel-delta}, if present, is a cons cell of the
2081form @w{@code{(@var{x} . @var{y})}}, where @var{x} and @var{y} are the
2082numbers of pixels by which to scroll in each axis, a.k.a.@:
2083@dfn{pixelwise deltas}.
2084
2085@cindex pixel-resolution wheel events
2086You can use these @var{x} and @var{y} pixelwise deltas to determine
2087how much the mouse wheel has actually moved at pixel resolution.  For
2088example, the pixelwise deltas could be used to scroll the display at
2089pixel resolution, exactly according to the user's turning the mouse
2090wheel.
2091
2092@vindex mouse-wheel-up-event
2093@vindex mouse-wheel-down-event
2094This kind of event is generated only on some kinds of systems.  On some
2095systems, @code{mouse-4} and @code{mouse-5} are used instead.  For
2096portable code, use the variables @code{mouse-wheel-up-event} and
2097@code{mouse-wheel-down-event} defined in @file{mwheel.el} to determine
2098what event types to expect for the mouse wheel.
2099
2100@cindex @code{pinch} event
2101@item (pinch @var{position} @var{dx} @var{dy} @var{scale} @var{angle})
2102This kind of event is generated by the user performing a ``pinch''
2103gesture by placing two fingers on a touchpad and moving them towards
2104or away from each other.  @var{position} is a mouse position list
2105(@pxref{Click Events}) that provides the position of the mouse pointer
2106when the event occurred, @var{dx} is the change in the horizontal
2107distance between the fingers since the last event in the same sequence,
2108@var{dy} is the vertical movement of the fingers since the last event
2109in the same sequence, @var{scale} is the ratio of the current distance
2110between the fingers to that distance at the start of the sequence, and
2111@var{angle} is the angular difference in degrees between the direction
2112of the line connecting the fingers in this event and the direction of
2113that line in the last event of the same sequence.
2114
2115As pinch events are only sent at the beginning or during a pinch
2116sequence, they do not report gestures where the user moves two fingers
2117on a touchpad in a rotating fashion without pinching the fingers.
2118
2119All arguments after @var{position} are floating point numbers.
2120
2121This event is usually sent as part of a sequence, which begins with
2122the user placing two fingers on the touchpad, and ends with the user
2123removing those fingers.  @var{dx}, @var{dy}, and @var{angle} will be
2124@code{0.0} in the first event of a sequence; subsequent events will
2125report non-zero values for these members of the event structure.
2126
2127@var{dx} and @var{dy} are reported in imaginary relative units, in
2128which @code{1.0} is the width and height of the touchpad
2129respectively.  They are usually interpreted as being relative to the
2130size of the object beneath the gesture: image, window, etc.
2131
2132@cindex @code{drag-n-drop} event
2133@item (drag-n-drop @var{position} @var{files})
2134This kind of event is generated when a group of files is
2135selected in an application outside of Emacs, and then dragged and
2136dropped onto an Emacs frame.
2137
2138The element @var{position} is a list describing the position of the
2139event, in the same format as used in a mouse-click event (@pxref{Click
2140Events}), and @var{files} is the list of file names that were dragged
2141and dropped.  The usual way to handle this event is by visiting these
2142files.
2143
2144This kind of event is generated, at present, only on some kinds of
2145systems.
2146
2147@cindex @code{help-echo} event
2148@item help-echo
2149This kind of event is generated when a mouse pointer moves onto a
2150portion of buffer text which has a @code{help-echo} text property.
2151The generated event has this form:
2152
2153@example
2154(help-echo @var{frame} @var{help} @var{window} @var{object} @var{pos})
2155@end example
2156
2157@noindent
2158The precise meaning of the event parameters and the way these
2159parameters are used to display the help-echo text are described in
2160@ref{Text help-echo}.
2161
2162@cindex @code{sigusr1} event
2163@cindex @code{sigusr2} event
2164@cindex user signals
2165@item sigusr1
2166@itemx sigusr2
2167These events are generated when the Emacs process receives
2168the signals @code{SIGUSR1} and @code{SIGUSR2}.  They contain no
2169additional data because signals do not carry additional information.
2170They can be useful for debugging (@pxref{Error Debugging}).
2171
2172To catch a user signal, bind the corresponding event to an interactive
2173command in the @code{special-event-map} (@pxref{Controlling Active Maps}).
2174The command is called with no arguments, and the specific signal event is
2175available in @code{last-input-event} (@pxref{Event Input Misc}.  For
2176example:
2177
2178@smallexample
2179(defun sigusr-handler ()
2180  (interactive)
2181  (message "Caught signal %S" last-input-event))
2182
2183(keymap-set special-event-map "<sigusr1>" 'sigusr-handler)
2184@end smallexample
2185
2186To test the signal handler, you can make Emacs send a signal to itself:
2187
2188@smallexample
2189(signal-process (emacs-pid) 'sigusr1)
2190@end smallexample
2191
2192@cindex @code{language-change} event
2193@item language-change
2194This kind of event is generated on MS-Windows when the input language
2195has changed.  This typically means that the keyboard keys will send to
2196Emacs characters from a different language.  The generated event has
2197this form:
2198
2199@smallexample
2200(language-change @var{frame} @var{codepage} @var{language-id})
2201@end smallexample
2202
2203@noindent
2204Here @var{frame} is the frame which was current when the input
2205language changed; @var{codepage} is the new codepage number; and
2206@var{language-id} is the numerical ID of the new input language.  The
2207coding-system (@pxref{Coding Systems}) that corresponds to
2208@var{codepage} is @code{cp@var{codepage}} or
2209@code{windows-@var{codepage}}.  To convert @var{language-id} to a
2210string (e.g., to use it for various language-dependent features, such
2211as @code{set-language-environment}), use the
2212@code{w32-get-locale-info} function, like this:
2213
2214@smallexample
2215;; Get the abbreviated language name, such as "ENU" for English
2216(w32-get-locale-info language-id)
2217;; Get the full English name of the language,
2218;; such as "English (United States)"
2219(w32-get-locale-info language-id 4097)
2220;; Get the full localized name of the language
2221(w32-get-locale-info language-id t)
2222@end smallexample
2223@end table
2224
2225  If one of these events arrives in the middle of a key sequence---that
2226is, after a prefix key---then Emacs reorders the events so that this
2227event comes either before or after the multi-event key sequence, not
2228within it.
2229
2230  Some of these special events, such as @code{delete-frame}, invoke
2231Emacs commands by default; others are not bound.  If you want to
2232arrange for a special event to invoke a command, you can do that via
2233@code{special-event-map}.  The command you bind to a function key in
2234that map can then examine the full event which invoked it in
2235@code{last-input-event}.  @xref{Special Events}.
2236
2237@node Event Examples
2238@subsection Event Examples
2239
2240If the user presses and releases the left mouse button over the same
2241location, that generates a sequence of events like this:
2242
2243@smallexample
2244(down-mouse-1 (#<window 18 on NEWS> 2613 (0 . 38) -864320))
2245(mouse-1      (#<window 18 on NEWS> 2613 (0 . 38) -864180))
2246@end smallexample
2247
2248While holding the control key down, the user might hold down the
2249second mouse button, and drag the mouse from one line to the next.
2250That produces two events, as shown here:
2251
2252@smallexample
2253(C-down-mouse-2 (#<window 18 on NEWS> 3440 (0 . 27) -731219))
2254(C-drag-mouse-2 (#<window 18 on NEWS> 3440 (0 . 27) -731219)
2255                (#<window 18 on NEWS> 3510 (0 . 28) -729648))
2256@end smallexample
2257
2258While holding down the meta and shift keys, the user might press the
2259second mouse button on the window's mode line, and then drag the mouse
2260into another window.  That produces a pair of events like these:
2261
2262@smallexample
2263(M-S-down-mouse-2 (#<window 18 on NEWS> mode-line (33 . 31) -457844))
2264(M-S-drag-mouse-2 (#<window 18 on NEWS> mode-line (33 . 31) -457844)
2265                  (#<window 20 on carlton-sanskrit.tex> 161 (33 . 3)
2266                   -453816))
2267@end smallexample
2268
2269The frame with input focus might not take up the entire screen, and
2270the user might move the mouse outside the scope of the frame.  Inside
2271the @code{track-mouse} special form, that produces an event like this:
2272
2273@smallexample
2274(mouse-movement (#<frame *ielm* 0x102849a30> nil (563 . 205) 532301936))
2275@end smallexample
2276
2277To handle a SIGUSR1 signal, define an interactive function, and
2278bind it to the @code{signal usr1} event sequence:
2279
2280@smallexample
2281(defun usr1-handler ()
2282  (interactive)
2283  (message "Got USR1 signal"))
2284(keymap-global-set "<signal> <usr1>" 'usr1-handler)
2285@end smallexample
2286
2287@node Classifying Events
2288@subsection Classifying Events
2289@cindex event type
2290@cindex classifying events
2291
2292  Every event has an @dfn{event type}, which classifies the event for
2293key binding purposes.  For a keyboard event, the event type equals the
2294event value; thus, the event type for a character is the character, and
2295the event type for a function key symbol is the symbol itself.  For
2296events that are lists, the event type is the symbol in the @sc{car} of
2297the list.  Thus, the event type is always a symbol or a character.
2298
2299  Two events of the same type are equivalent where key bindings are
2300concerned; thus, they always run the same command.  That does not
2301necessarily mean they do the same things, however, as some commands look
2302at the whole event to decide what to do.  For example, some commands use
2303the location of a mouse event to decide where in the buffer to act.
2304
2305  Sometimes broader classifications of events are useful.  For example,
2306you might want to ask whether an event involved the @key{META} key,
2307regardless of which other key or mouse button was used.
2308
2309  The functions @code{event-modifiers} and @code{event-basic-type} are
2310provided to get such information conveniently.
2311
2312@defun event-modifiers event
2313This function returns a list of the modifiers that @var{event} has.  The
2314modifiers are symbols; they include @code{shift}, @code{control},
2315@code{meta}, @code{alt}, @code{hyper} and @code{super}.  In addition,
2316the modifiers list of a mouse event symbol always contains one of
2317@code{click}, @code{drag}, and @code{down}.  For double or triple
2318events, it also contains @code{double} or @code{triple}.
2319
2320The argument @var{event} may be an entire event object, or just an
2321event type.  If @var{event} is a symbol that has never been used in an
2322event that has been read as input in the current Emacs session, then
2323@code{event-modifiers} can return @code{nil}, even when @var{event}
2324actually has modifiers.
2325
2326Here are some examples:
2327
2328@example
2329(event-modifiers ?a)
2330     @result{} nil
2331(event-modifiers ?A)
2332     @result{} (shift)
2333(event-modifiers ?\C-a)
2334     @result{} (control)
2335(event-modifiers ?\C-%)
2336     @result{} (control)
2337(event-modifiers ?\C-\S-a)
2338     @result{} (control shift)
2339(event-modifiers 'f5)
2340     @result{} nil
2341(event-modifiers 's-f5)
2342     @result{} (super)
2343(event-modifiers 'M-S-f5)
2344     @result{} (meta shift)
2345(event-modifiers 'mouse-1)
2346     @result{} (click)
2347(event-modifiers 'down-mouse-1)
2348     @result{} (down)
2349@end example
2350
2351The modifiers list for a click event explicitly contains @code{click},
2352but the event symbol name itself does not contain @samp{click}.
2353Similarly, the modifiers list for an @acronym{ASCII} control
2354character, such as @samp{C-a}, contains @code{control}, even though
2355reading such an event via @code{read-char} will return the value 1
2356with the control modifier bit removed.
2357@end defun
2358
2359@defun event-basic-type event
2360This function returns the key or mouse button that @var{event}
2361describes, with all modifiers removed.  The @var{event} argument is as
2362in @code{event-modifiers}.  For example:
2363
2364@example
2365(event-basic-type ?a)
2366     @result{} 97
2367(event-basic-type ?A)
2368     @result{} 97
2369(event-basic-type ?\C-a)
2370     @result{} 97
2371(event-basic-type ?\C-\S-a)
2372     @result{} 97
2373(event-basic-type 'f5)
2374     @result{} f5
2375(event-basic-type 's-f5)
2376     @result{} f5
2377(event-basic-type 'M-S-f5)
2378     @result{} f5
2379(event-basic-type 'down-mouse-1)
2380     @result{} mouse-1
2381@end example
2382@end defun
2383
2384@defun mouse-movement-p object
2385This function returns non-@code{nil} if @var{object} is a mouse movement
2386event.  @xref{Motion Events}.
2387@end defun
2388
2389@node Accessing Mouse
2390@subsection Accessing Mouse Events
2391@cindex mouse events, data in
2392@cindex keyboard events, data in
2393
2394  This section describes convenient functions for accessing the data in
2395a mouse button or motion event.  Keyboard event data can be accessed
2396using the same functions, but data elements that aren't applicable to
2397keyboard events are zero or @code{nil}.
2398
2399  The following two functions return a mouse position list
2400(@pxref{Click Events}), specifying the position of a mouse event.
2401
2402@defun event-start event
2403This returns the starting position of @var{event}.
2404
2405If @var{event} is a click or button-down event, this returns the
2406location of the event.  If @var{event} is a drag event, this returns the
2407drag's starting position.
2408@end defun
2409
2410@defun event-end event
2411This returns the ending position of @var{event}.
2412
2413If @var{event} is a drag event, this returns the position where the user
2414released the mouse button.  If @var{event} is a click or button-down
2415event, the value is actually the starting position, which is the only
2416position such events have.
2417@end defun
2418
2419@defun posnp object
2420This function returns non-@code{nil} if @var{object} is a mouse
2421position list, in the format documented in @ref{Click Events}); and
2422@code{nil} otherwise.
2423@end defun
2424
2425@cindex mouse position list, accessing
2426  These functions take a mouse position list as argument, and return
2427various parts of it:
2428
2429@defun posn-window position
2430Return the window that @var{position} is in.  If @var{position}
2431represents a location outside the frame where the event was initiated,
2432return that frame instead.
2433@end defun
2434
2435@defun posn-area position
2436Return the window area recorded in @var{position}.  It returns @code{nil}
2437when the event occurred in the text area of the window; otherwise, it
2438is a symbol identifying the area in which the event occurred.
2439@end defun
2440
2441@defun posn-point position
2442Return the buffer position in @var{position}.  When the event occurred
2443in the text area of the window, in a marginal area, or on a fringe,
2444this is an integer specifying a buffer position.  Otherwise, the value
2445is undefined.
2446@end defun
2447
2448@defun posn-x-y position
2449Return the pixel-based x and y coordinates in @var{position}, as a
2450cons cell @w{@code{(@var{x} . @var{y})}}.  These coordinates are
2451relative to the window given by @code{posn-window}.
2452
2453This example shows how to convert the window-relative coordinates in
2454the text area of a window into frame-relative coordinates:
2455
2456@example
2457(defun frame-relative-coordinates (position)
2458  "Return frame-relative coordinates from POSITION.
2459POSITION is assumed to lie in a window text area."
2460  (let* ((x-y (posn-x-y position))
2461         (window (posn-window position))
2462         (edges (window-inside-pixel-edges window)))
2463    (cons (+ (car x-y) (car edges))
2464          (+ (cdr x-y) (cadr edges)))))
2465@end example
2466@end defun
2467
2468@defun posn-col-row position
2469This function returns a cons cell @w{@code{(@var{col} .  @var{row})}},
2470containing the estimated column and row corresponding to buffer
2471position described by @var{position}.  The return value is given in
2472units of the frame's default character width and default line height
2473(including spacing), as computed from the @var{x} and @var{y} values
2474corresponding to @var{position}.  (So, if the actual characters have
2475non-default sizes, the actual row and column may differ from these
2476computed values.)
2477
2478Note that @var{row} is counted from the top of the text area.  If the
2479window given by @var{position} possesses a header line (@pxref{Header
2480Lines}) or a tab line, they are @emph{not} included in the @var{row}
2481count.
2482@end defun
2483
2484@defun posn-actual-col-row position
2485Return the actual row and column in @var{position}, as a cons cell
2486@w{@code{(@var{col} . @var{row})}}.  The values are the actual row and
2487column numbers in the window given by @var{position}.  @xref{Click
2488Events}, for details.  The function returns @code{nil} if
2489@var{position} does not include actual position values; in that case
2490@code{posn-col-row} can be used to get approximate values.
2491
2492Note that this function doesn't account for the visual width of
2493characters on display, like the number of visual columns taken by a
2494tab character or an image.  If you need the coordinates in canonical
2495character units, use @code{posn-col-row} instead.
2496@end defun
2497
2498@defun posn-string position
2499Return the string object described by @var{position}, either
2500@code{nil} (which means @var{position} describes buffer text), or a
2501cons cell @w{@code{(@var{string} . @var{string-pos})}}.
2502@end defun
2503
2504@defun posn-image position
2505Return the image object in @var{position}, either @code{nil} (if
2506there's no image at @var{position}), or an image spec @w{@code{(image
2507@dots{})}}.
2508@end defun
2509
2510@defun posn-object position
2511Return the image or string object described by @var{position}, either
2512@code{nil} (which means @var{position} describes buffer text), an
2513image @w{@code{(image @dots{})}}, or a cons cell
2514@w{@code{(@var{string} . @var{string-pos})}}.
2515@end defun
2516
2517@defun posn-object-x-y position
2518Return the pixel-based x and y coordinates relative to the upper left
2519corner of the object described by @var{position}, as a cons cell
2520@w{@code{(@var{dx} . @var{dy})}}.  If the @var{position} describes
2521buffer text, return the relative coordinates of the buffer-text character
2522closest to that position.
2523@end defun
2524
2525@defun posn-object-width-height position
2526Return the pixel width and height of the object described by
2527@var{position}, as a cons cell @code{(@var{width} . @var{height})}.
2528If the @var{position} describes a buffer position, return the size of
2529the character at that position.
2530@end defun
2531
2532@cindex timestamp of a mouse event
2533@defun posn-timestamp position
2534Return the timestamp in @var{position}.  This is the time at which the
2535event occurred, in milliseconds.
2536@end defun
2537
2538  These functions compute a position list given particular buffer
2539position or screen position.  You can access the data in this position
2540list with the functions described above.
2541
2542@defun posn-at-point &optional pos window
2543This function returns a position list for position @var{pos} in
2544@var{window}.  @var{pos} defaults to point in @var{window};
2545@var{window} defaults to the selected window.
2546
2547@code{posn-at-point} returns @code{nil} if @var{pos} is not visible in
2548@var{window}.
2549@end defun
2550
2551@defun posn-at-x-y x y &optional frame-or-window whole
2552This function returns position information corresponding to pixel
2553coordinates @var{x} and @var{y} in a specified frame or window,
2554@var{frame-or-window}, which defaults to the selected window.
2555The coordinates @var{x} and @var{y} are relative to the
2556text area of the selected window.
2557If @var{whole} is @code{non-nil}, the @var{x} coordinate is relative
2558to the entire window area including scroll bars, margins and fringes.
2559@end defun
2560
2561@node Accessing Scroll
2562@subsection Accessing Scroll Bar Events
2563@cindex scroll bar events, data in
2564
2565  These functions are useful for decoding scroll bar events.
2566
2567@defun scroll-bar-event-ratio event
2568This function returns the fractional vertical position of a scroll bar
2569event within the scroll bar.  The value is a cons cell
2570@code{(@var{portion} . @var{whole})} containing two integers whose ratio
2571is the fractional position.
2572@end defun
2573
2574@defun scroll-bar-scale ratio total
2575This function multiplies (in effect) @var{ratio} by @var{total},
2576rounding the result to an integer.  The argument @var{ratio} is not a
2577number, but rather a pair @code{(@var{num} . @var{denom})}---typically a
2578value returned by @code{scroll-bar-event-ratio}.
2579
2580This function is handy for scaling a position on a scroll bar into a
2581buffer position.  Here's how to do that:
2582
2583@example
2584(+ (point-min)
2585   (scroll-bar-scale
2586      (posn-x-y (event-start event))
2587      (- (point-max) (point-min))))
2588@end example
2589
2590Recall that scroll bar events have two integers forming a ratio, in place
2591of a pair of x and y coordinates.
2592@end defun
2593
2594@node Strings of Events
2595@subsection Putting Keyboard Events in Strings
2596@cindex keyboard events in strings
2597@cindex strings with keyboard events
2598
2599  In most of the places where strings are used, we conceptualize the
2600string as containing text characters---the same kind of characters found
2601in buffers or files.  Occasionally Lisp programs use strings that
2602conceptually contain keyboard characters; for example, they may be key
2603sequences or keyboard macro definitions.  However, storing keyboard
2604characters in a string is a complex matter, for reasons of historical
2605compatibility, and it is not always possible.
2606
2607  We recommend that new programs avoid dealing with these complexities
2608by not storing keyboard events in strings containing control
2609characters or the like, but instead store them in the common Emacs
2610format as understood by @code{key-valid-p}.
2611
2612  If you read a key sequence with @code{read-key-sequence-vector} (or
2613@code{read-key-sequence}), or access a key sequence with
2614@code{this-command-keys-vector} (or @code{this-command-keys}), you can
2615transform this to the recommended format by using @code{key-description}.
2616
2617  The complexities stem from the modifier bits that keyboard input
2618characters can include.  Aside from the Meta modifier, none of these
2619modifier bits can be included in a string, and the Meta modifier is
2620allowed only in special cases.
2621
2622  The earliest GNU Emacs versions represented meta characters as codes
2623in the range of 128 to 255.  At that time, the basic character codes
2624ranged from 0 to 127, so all keyboard character codes did fit in a
2625string.  Many Lisp programs used @samp{\M-} in string constants to stand
2626for meta characters, especially in arguments to @code{define-key} and
2627similar functions, and key sequences and sequences of events were always
2628represented as strings.
2629
2630  When we added support for larger basic character codes beyond 127, and
2631additional modifier bits, we had to change the representation of meta
2632characters.  Now the flag that represents the Meta modifier in a
2633character is
2634@tex
2635@math{2^{27}}
2636@end tex
2637@ifnottex
26382**27
2639@end ifnottex
2640and such numbers cannot be included in a string.
2641
2642  To support programs with @samp{\M-} in string constants, there are
2643special rules for including certain meta characters in a string.
2644Here are the rules for interpreting a string as a sequence of input
2645characters:
2646
2647@itemize @bullet
2648@item
2649If the keyboard character value is in the range of 0 to 127, it can go
2650in the string unchanged.
2651
2652@item
2653The meta variants of those characters, with codes in the range of
2654@tex
2655@math{2^{27}}
2656@end tex
2657@ifnottex
26582**27
2659@end ifnottex
2660to
2661@tex
2662@math{2^{27} + 127},
2663@end tex
2664@ifnottex
26652**27+127,
2666@end ifnottex
2667can also go in the string, but you must change their
2668numeric values.  You must set the
2669@tex
2670@math{2^{7}}
2671@end tex
2672@ifnottex
26732**7
2674@end ifnottex
2675bit instead of the
2676@tex
2677@math{2^{27}}
2678@end tex
2679@ifnottex
26802**27
2681@end ifnottex
2682bit, resulting in a value between 128 and 255.  Only a unibyte string
2683can include these codes.
2684
2685@item
2686Non-@acronym{ASCII} characters above 256 can be included in a multibyte string.
2687
2688@item
2689Other keyboard character events cannot fit in a string.  This includes
2690keyboard events in the range of 128 to 255.
2691@end itemize
2692
2693  Functions such as @code{read-key-sequence} that construct strings of
2694keyboard input characters follow these rules: they construct vectors
2695instead of strings, when the events won't fit in a string.
2696
2697  When you use the read syntax @samp{\M-} in a string, it produces a
2698code in the range of 128 to 255---the same code that you get if you
2699modify the corresponding keyboard event to put it in the string.  Thus,
2700meta events in strings work consistently regardless of how they get into
2701the strings.
2702
2703  However, most programs would do well to avoid these issues by
2704following the recommendations at the beginning of this section.
2705
2706@node Reading Input
2707@section Reading Input
2708@cindex read input
2709@cindex keyboard input
2710
2711  The editor command loop reads key sequences using the function
2712@code{read-key-sequence}, which uses @code{read-event}.  These and other
2713functions for event input are also available for use in Lisp programs.
2714See also @code{momentary-string-display} in @ref{Temporary Displays},
2715and @code{sit-for} in @ref{Waiting}.  @xref{Terminal Input}, for
2716functions and variables for controlling terminal input modes and
2717debugging terminal input.
2718
2719  For higher-level input facilities, see @ref{Minibuffers}.
2720
2721@menu
2722* Key Sequence Input::          How to read one key sequence.
2723* Reading One Event::           How to read just one event.
2724* Event Mod::                   How Emacs modifies events as they are read.
2725* Invoking the Input Method::   How reading an event uses the input method.
2726* Quoted Character Input::      Asking the user to specify a character.
2727* Event Input Misc::            How to reread or throw away input events.
2728@end menu
2729
2730@node Key Sequence Input
2731@subsection Key Sequence Input
2732@cindex key sequence input
2733
2734  The command loop reads input a key sequence at a time, by calling
2735@code{read-key-sequence}.  Lisp programs can also call this function;
2736for example, @code{describe-key} uses it to read the key to describe.
2737
2738@defun read-key-sequence prompt &optional continue-echo dont-downcase-last switch-frame-ok command-loop
2739This function reads a key sequence and returns it as a string or
2740vector.  It keeps reading events until it has accumulated a complete key
2741sequence; that is, enough to specify a non-prefix command using the
2742currently active keymaps.  (Remember that a key sequence that starts
2743with a mouse event is read using the keymaps of the buffer in the
2744window that the mouse was in, not the current buffer.)
2745
2746If the events are all characters and all can fit in a string, then
2747@code{read-key-sequence} returns a string (@pxref{Strings of Events}).
2748Otherwise, it returns a vector, since a vector can hold all kinds of
2749events---characters, symbols, and lists.  The elements of the string or
2750vector are the events in the key sequence.
2751
2752Reading a key sequence includes translating the events in various
2753ways.  @xref{Translation Keymaps}.
2754
2755The argument @var{prompt} is either a string to be displayed in the
2756echo area as a prompt, or @code{nil}, meaning not to display a prompt.
2757The argument @var{continue-echo}, if non-@code{nil}, means to echo
2758this key as a continuation of the previous key.
2759
2760Normally any upper case event is converted to lower case if the
2761original event is undefined and the lower case equivalent is defined.
2762The argument @var{dont-downcase-last}, if non-@code{nil}, means do not
2763convert the last event to lower case.  This is appropriate for reading
2764a key sequence to be defined.
2765
2766The argument @var{switch-frame-ok}, if non-@code{nil}, means that this
2767function should process a @code{switch-frame} event if the user
2768switches frames before typing anything.  If the user switches frames
2769in the middle of a key sequence, or at the start of the sequence but
2770@var{switch-frame-ok} is @code{nil}, then the event will be put off
2771until after the current key sequence.
2772
2773The argument @var{command-loop}, if non-@code{nil}, means that this
2774key sequence is being read by something that will read commands one
2775after another.  It should be @code{nil} if the caller will read just
2776one key sequence.
2777
2778In the following example, Emacs displays the prompt @samp{?} in the
2779echo area, and then the user types @kbd{C-x C-f}.
2780
2781@example
2782(read-key-sequence "?")
2783
2784@group
2785---------- Echo Area ----------
2786?@kbd{C-x C-f}
2787---------- Echo Area ----------
2788
2789     @result{} "^X^F"
2790@end group
2791@end example
2792
2793The function @code{read-key-sequence} suppresses quitting: @kbd{C-g}
2794typed while reading with this function works like any other character,
2795and does not set @code{quit-flag}.  @xref{Quitting}.
2796@end defun
2797
2798@defun read-key-sequence-vector prompt &optional continue-echo dont-downcase-last switch-frame-ok command-loop
2799This is like @code{read-key-sequence} except that it always
2800returns the key sequence as a vector, never as a string.
2801@xref{Strings of Events}.
2802@end defun
2803
2804@cindex upper case key sequence
2805@cindex downcasing in @code{lookup-key}
2806@cindex shift-translation
2807@vindex translate-upper-case-key-bindings
2808If an input character is upper-case (or has the shift modifier) and
2809has no key binding, but its lower-case equivalent has one, then
2810@code{read-key-sequence} converts the character to lower case.  (This
2811behaviour can be disabled by setting the
2812@code{translate-upper-case-key-bindings} user option to @code{nil}.)
2813Note that @code{lookup-key} does not perform case conversion in this
2814way.
2815
2816@vindex this-command-keys-shift-translated
2817When reading input results in such a @dfn{shift-translation}, Emacs
2818sets the variable @code{this-command-keys-shift-translated} to a
2819non-@code{nil} value.  Lisp programs can examine this variable if they
2820need to modify their behavior when invoked by shift-translated keys.
2821For example, the function @code{handle-shift-selection} examines the
2822value of this variable to determine how to activate or deactivate the
2823region (@pxref{The Mark, handle-shift-selection}).
2824
2825The function @code{read-key-sequence} also transforms some mouse events.
2826It converts unbound drag events into click events, and discards unbound
2827button-down events entirely.  It also reshuffles focus events and
2828miscellaneous window events so that they never appear in a key sequence
2829with any other events.
2830
2831@cindex @code{tab-line}, prefix key
2832@cindex @code{header-line}, prefix key
2833@cindex @code{mode-line}, prefix key
2834@cindex @code{vertical-line}, prefix key
2835@cindex @code{horizontal-scroll-bar}, prefix key
2836@cindex @code{vertical-scroll-bar}, prefix key
2837@cindex @code{menu-bar}, prefix key
2838@cindex @code{tab-bar}, prefix key
2839@cindex @code{left-margin}, prefix key
2840@cindex @code{right-margin}, prefix key
2841@cindex @code{left-fringe}, prefix key
2842@cindex @code{right-fringe}, prefix key
2843@cindex @code{right-divider}, prefix key
2844@cindex @code{bottom-divider}, prefix key
2845@cindex mouse events, in special parts of window or frame
2846When mouse events occur in special parts of a window or frame, such as a mode
2847line or a scroll bar, the event type shows nothing special---it is the
2848same symbol that would normally represent that combination of mouse
2849button and modifier keys.  The information about the window part is kept
2850elsewhere in the event---in the coordinates.  But
2851@code{read-key-sequence} translates this information into imaginary
2852prefix keys, all of which are symbols: @code{tab-line}, @code{header-line},
2853@code{horizontal-scroll-bar}, @code{menu-bar}, @code{tab-bar}, @code{mode-line},
2854@code{vertical-line}, @code{vertical-scroll-bar}, @code{left-margin},
2855@code{right-margin}, @code{left-fringe}, @code{right-fringe},
2856@code{right-divider}, and @code{bottom-divider}.  You can define meanings for
2857mouse clicks in special window parts by defining key sequences using these
2858imaginary prefix keys.
2859
2860For example, if you call @code{read-key-sequence} and then click the
2861mouse on the window's mode line, you get two events, like this:
2862
2863@example
2864(read-key-sequence "Click on the mode line: ")
2865     @result{} [mode-line
2866         (mouse-1
2867          (#<window 6 on NEWS> mode-line
2868           (40 . 63) 5959987))]
2869@end example
2870
2871@defvar num-input-keys
2872This variable's value is the number of key sequences processed so far in
2873this Emacs session.  This includes key sequences read from the terminal
2874and key sequences read from keyboard macros being executed.
2875@end defvar
2876
2877@node Reading One Event
2878@subsection Reading One Event
2879@cindex reading a single event
2880@cindex event, reading only one
2881
2882  The lowest level functions for command input are @code{read-event},
2883@code{read-char}, and @code{read-char-exclusive}.
2884
2885If you need a function to read a character using the minibuffer, use
2886@code{read-char-from-minibuffer} (@pxref{Multiple Queries}).
2887
2888@defun read-event &optional prompt inherit-input-method seconds
2889This function reads and returns the next event of command input,
2890waiting if necessary until an event is available.
2891
2892The returned event may come directly from the user, or from a keyboard
2893macro.  It is not decoded by the keyboard's input coding system
2894(@pxref{Terminal I/O Encoding}).
2895
2896If the optional argument @var{prompt} is non-@code{nil}, it should be
2897a string to display in the echo area as a prompt.  If @var{prompt} is
2898@code{nil} or the string @samp{""}, @code{read-event} does not display
2899any message to indicate it is waiting for input; instead, it prompts
2900by echoing: it displays descriptions of the events that led to or were
2901read by the current command.  @xref{The Echo Area}.
2902
2903If @var{inherit-input-method} is non-@code{nil}, then the current input
2904method (if any) is employed to make it possible to enter a
2905non-@acronym{ASCII} character.  Otherwise, input method handling is disabled
2906for reading this event.
2907
2908If @code{cursor-in-echo-area} is non-@code{nil}, then @code{read-event}
2909moves the cursor temporarily to the echo area, to the end of any message
2910displayed there.  Otherwise @code{read-event} does not move the cursor.
2911
2912If @var{seconds} is non-@code{nil}, it should be a number specifying
2913the maximum time to wait for input, in seconds.  If no input arrives
2914within that time, @code{read-event} stops waiting and returns
2915@code{nil}.  A floating point @var{seconds} means to wait
2916for a fractional number of seconds.  Some systems support only a whole
2917number of seconds; on these systems, @var{seconds} is rounded down.
2918If @var{seconds} is @code{nil}, @code{read-event} waits as long as
2919necessary for input to arrive.
2920
2921If @var{seconds} is @code{nil}, Emacs is considered idle while waiting
2922for user input to arrive.  Idle timers---those created with
2923@code{run-with-idle-timer} (@pxref{Idle Timers})---can run during this
2924period.  However, if @var{seconds} is non-@code{nil}, the state of
2925idleness remains unchanged.  If Emacs is non-idle when
2926@code{read-event} is called, it remains non-idle throughout the
2927operation of @code{read-event}; if Emacs is idle (which can happen if
2928the call happens inside an idle timer), it remains idle.
2929
2930If @code{read-event} gets an event that is defined as a help character,
2931then in some cases @code{read-event} processes the event directly without
2932returning.  @xref{Help Functions}.  Certain other events, called
2933@dfn{special events}, are also processed directly within
2934@code{read-event} (@pxref{Special Events}).
2935
2936Here is what happens if you call @code{read-event} and then press the
2937right-arrow function key:
2938
2939@example
2940@group
2941(read-event)
2942     @result{} right
2943@end group
2944@end example
2945@end defun
2946
2947@defun read-char &optional prompt inherit-input-method seconds
2948This function reads and returns a character input event.  If the
2949user generates an event which is not a character (i.e., a mouse click or
2950function key event), @code{read-char} signals an error.  The arguments
2951work as in @code{read-event}.
2952
2953If the event has modifiers, Emacs attempts to resolve them and return
2954the code of the corresponding character.  For example, if the user
2955types @kbd{C-a}, the function returns 1, which is the @acronym{ASCII}
2956code of the @samp{C-a} character.  If some of the modifiers cannot be
2957reflected in the character code, @code{read-char} leaves the
2958unresolved modifier bits set in the returned event.  For example, if
2959the user types @kbd{C-M-a}, the function returns 134217729, 8000001 in
2960hex, i.e.@: @samp{C-a} with the Meta modifier bit set.  This value is
2961not a valid character code: it fails the @code{characterp} test
2962(@pxref{Character Codes}).  Use @code{event-basic-type}
2963(@pxref{Classifying Events}) to recover the character code with the
2964modifier bits removed; use @code{event-modifiers} to test for
2965modifiers in the character event returned by @code{read-char}.
2966
2967In the first example below, the user types the character @kbd{1}
2968(@acronym{ASCII} code 49).  The second example shows a keyboard macro
2969definition that calls @code{read-char} from the minibuffer using
2970@code{eval-expression}.  @code{read-char} reads the keyboard macro's
2971very next character, which is @kbd{1}.  Then @code{eval-expression}
2972displays its return value in the echo area.
2973
2974@example
2975@group
2976(read-char)
2977     @result{} 49
2978@end group
2979
2980@group
2981;; @r{We assume here you use @kbd{M-:} to evaluate this.}
2982(symbol-function 'foo)
2983     @result{} "^[:(read-char)^M1"
2984@end group
2985@group
2986(execute-kbd-macro 'foo)
2987     @print{} 49
2988     @result{} nil
2989@end group
2990@end example
2991@end defun
2992
2993@defun read-char-exclusive &optional prompt inherit-input-method seconds
2994This function reads and returns a character input event.  If the
2995user generates an event which is not a character event,
2996@code{read-char-exclusive} ignores it and reads another event, until it
2997gets a character.  The arguments work as in @code{read-event}.  The
2998returned value may include modifier bits, as with @code{read-char}.
2999@end defun
3000
3001  None of the above functions suppress quitting.
3002
3003@defvar num-nonmacro-input-events
3004This variable holds the total number of input events received so far
3005from the terminal---not counting those generated by keyboard macros.
3006@end defvar
3007
3008  We emphasize that, unlike @code{read-key-sequence}, the functions
3009@code{read-event}, @code{read-char}, and @code{read-char-exclusive} do
3010not perform the translations described in @ref{Translation Keymaps}.
3011If you wish to read a single key taking these translations into
3012account (for example, to read @ref{Function Keys} in a terminal or
3013@ref{Mouse Events} from @code{xterm-mouse-mode}), use the function
3014@code{read-key}:
3015
3016@defun read-key &optional prompt disable-fallbacks
3017This function reads a single key.  It is intermediate between
3018@code{read-key-sequence} and @code{read-event}.  Unlike the former, it
3019reads a single key, not a key sequence.  Unlike the latter, it does
3020not return a raw event, but decodes and translates the user input
3021according to @code{input-decode-map}, @code{local-function-key-map},
3022and @code{key-translation-map} (@pxref{Translation Keymaps}).
3023
3024The argument @var{prompt} is either a string to be displayed in the
3025echo area as a prompt, or @code{nil}, meaning not to display a prompt.
3026
3027If argument @var{disable-fallbacks} is non-@code{nil} then the usual
3028fallback logic for unbound keys in @code{read-key-sequence} is not
3029applied.  This means that mouse button-down and multi-click events
3030will not be discarded and @code{local-function-key-map} and
3031@code{key-translation-map} will not get applied.  If @code{nil} or
3032unspecified, the only fallback disabled is downcasing of the last
3033event.
3034@end defun
3035
3036@defun read-char-choice prompt chars &optional inhibit-quit
3037This function uses @code{read-key} to read and return a single
3038character.  It ignores any input that is not a member of @var{chars},
3039a list of accepted characters.  Optionally, it will also ignore
3040keyboard-quit events while it is waiting for valid input.  If you bind
3041@code{help-form} (@pxref{Help Functions}) to a non-@code{nil} value
3042while calling @code{read-char-choice}, then pressing @code{help-char}
3043causes it to evaluate @code{help-form} and display the result.  It
3044then continues to wait for a valid input character, or keyboard-quit.
3045@end defun
3046
3047@defun read-multiple-choice prompt choices &optional help-string show-help
3048Ask user a multiple choice question.  @var{prompt} should be a string
3049that will be displayed as the prompt.
3050
3051@var{choices} is an alist where the first element in each entry is a
3052character to be entered, the second element is a short name for the
3053entry to be displayed while prompting (if there's room, it might be
3054shortened), and the third, optional entry is a longer explanation that
3055will be displayed in a help buffer if the user requests more help.
3056
3057If optional argument @var{help-string} is non-@code{nil}, it should be
3058a string with a more detailed description of all choices.  It will be
3059displayed in a help buffer instead of the default auto-generated
3060description when the user types @kbd{?}.
3061
3062If optional argument @var{show-help} is non-@code{nil}, the help
3063buffer will be displayed immediately, before any user input.  If it is
3064a string, use it as the name of the help buffer.
3065
3066The return value is the matching value from @var{choices}.
3067
3068@lisp
3069(read-multiple-choice
3070 "Continue connecting?"
3071 '((?a "always" "Accept certificate for this and future sessions.")
3072   (?s "session only" "Accept certificate this session only.")
3073   (?n "no" "Refuse to use certificate, close connection.")))
3074@end lisp
3075
3076The @code{read-multiple-choice-face} face is used to highlight the
3077matching characters in the name string on graphical terminals.
3078
3079@end defun
3080
3081@node Event Mod
3082@subsection Modifying and Translating Input Events
3083@cindex modifiers of events
3084@cindex translating input events
3085@cindex event translation
3086
3087  Emacs modifies every event it reads according to
3088@code{extra-keyboard-modifiers}, then translates it through
3089@code{keyboard-translate-table} (if applicable), before returning it
3090from @code{read-event}.
3091
3092@defvar extra-keyboard-modifiers
3093This variable lets Lisp programs ``press'' the modifier keys on the
3094keyboard.  The value is a character.  Only the modifiers of the
3095character matter.  Each time the user types a keyboard key, it is
3096altered as if those modifier keys were held down.  For instance, if
3097you bind @code{extra-keyboard-modifiers} to @code{?\C-\M-a}, then all
3098keyboard input characters typed during the scope of the binding will
3099have the control and meta modifiers applied to them.  The character
3100@code{?\C-@@}, equivalent to the integer 0, does not count as a control
3101character for this purpose, but as a character with no modifiers.
3102Thus, setting @code{extra-keyboard-modifiers} to zero cancels any
3103modification.
3104
3105When using a window system, the program can press any of the
3106modifier keys in this way.  Otherwise, only the @key{CTL} and @key{META}
3107keys can be virtually pressed.
3108
3109Note that this variable applies only to events that really come from
3110the keyboard, and has no effect on mouse events or any other events.
3111@end defvar
3112
3113@defvar keyboard-translate-table
3114This terminal-local variable is the translate table for keyboard
3115characters.  It lets you reshuffle the keys on the keyboard without
3116changing any command bindings.  Its value is normally a char-table, or
3117else @code{nil}.  (It can also be a string or vector, but this is
3118considered obsolete.)
3119
3120If @code{keyboard-translate-table} is a char-table
3121(@pxref{Char-Tables}), then each character read from the keyboard is
3122looked up in this char-table.  If the value found there is
3123non-@code{nil}, then it is used instead of the actual input character.
3124
3125Note that this translation is the first thing that happens to a
3126character after it is read from the terminal.  Record-keeping features
3127such as @code{recent-keys} and dribble files record the characters after
3128translation.
3129
3130Note also that this translation is done before the characters are
3131supplied to input methods (@pxref{Input Methods}).  Use
3132@code{translation-table-for-input} (@pxref{Translation of Characters}),
3133if you want to translate characters after input methods operate.
3134@end defvar
3135
3136@defun key-translate from to
3137This function modifies @code{keyboard-translate-table} to translate
3138character code @var{from} into character code @var{to}.  It creates
3139the keyboard translate table if necessary.
3140@end defun
3141
3142  Here's an example of using the @code{keyboard-translate-table} to
3143make @kbd{C-x}, @kbd{C-c} and @kbd{C-v} perform the cut, copy and paste
3144operations:
3145
3146@example
3147(key-translate "C-x" "<control-x>")
3148(key-translate "C-c" "<control-c>")
3149(key-translate "C-v" "<control-v>")
3150(keymap-global-set "<control-x>" 'kill-region)
3151(keymap-global-set "<control-c>" 'kill-ring-save)
3152(keymap-global-set "<control-v>" 'yank)
3153@end example
3154
3155@noindent
3156On a graphical terminal that supports extended @acronym{ASCII} input,
3157you can still get the standard Emacs meanings of one of those
3158characters by typing it with the shift key.  That makes it a different
3159character as far as keyboard translation is concerned, but it has the
3160same usual meaning.
3161
3162  @xref{Translation Keymaps}, for mechanisms that translate event sequences
3163at the level of @code{read-key-sequence}.
3164
3165@node Invoking the Input Method
3166@subsection Invoking the Input Method
3167@cindex invoking input method
3168
3169  The event-reading functions invoke the current input method, if any
3170(@pxref{Input Methods}).  If the value of @code{input-method-function}
3171is non-@code{nil}, it should be a function; when @code{read-event} reads
3172a printing character (including @key{SPC}) with no modifier bits, it
3173calls that function, passing the character as an argument.
3174
3175@defvar input-method-function
3176If this is non-@code{nil}, its value specifies the current input method
3177function.
3178
3179@strong{Warning:} don't bind this variable with @code{let}.  It is often
3180buffer-local, and if you bind it around reading input (which is exactly
3181when you @emph{would} bind it), switching buffers asynchronously while
3182Emacs is waiting will cause the value to be restored in the wrong
3183buffer.
3184@end defvar
3185
3186  The input method function should return a list of events which should
3187be used as input.  (If the list is @code{nil}, that means there is no
3188input, so @code{read-event} waits for another event.)  These events are
3189processed before the events in @code{unread-command-events}
3190(@pxref{Event Input Misc}).  Events
3191returned by the input method function are not passed to the input method
3192function again, even if they are printing characters with no modifier
3193bits.
3194
3195  If the input method function calls @code{read-event} or
3196@code{read-key-sequence}, it should bind @code{input-method-function} to
3197@code{nil} first, to prevent recursion.
3198
3199  The input method function is not called when reading the second and
3200subsequent events of a key sequence.  Thus, these characters are not
3201subject to input method processing.  The input method function should
3202test the values of @code{overriding-local-map} and
3203@code{overriding-terminal-local-map}; if either of these variables is
3204non-@code{nil}, the input method should put its argument into a list and
3205return that list with no further processing.
3206
3207@node Quoted Character Input
3208@subsection Quoted Character Input
3209@cindex quoted character input
3210
3211  You can use the function @code{read-quoted-char} to ask the user to
3212specify a character, and allow the user to specify a control or meta
3213character conveniently, either literally or as an octal character code.
3214The command @code{quoted-insert} uses this function.
3215
3216@defun read-quoted-char &optional prompt
3217@cindex octal character input
3218@cindex control characters, reading
3219@cindex nonprinting characters, reading
3220This function is like @code{read-char}, except that if the first
3221character read is an octal digit (0--7), it reads any number of octal
3222digits (but stopping if a non-octal digit is found), and returns the
3223character represented by that numeric character code.  If the
3224character that terminates the sequence of octal digits is @key{RET},
3225it is discarded.  Any other terminating character is used as input
3226after this function returns.
3227
3228Quitting is suppressed when the first character is read, so that the
3229user can enter a @kbd{C-g}.  @xref{Quitting}.
3230
3231If @var{prompt} is supplied, it specifies a string for prompting the
3232user.  The prompt string is always displayed in the echo area, followed
3233by a single @samp{-}.
3234
3235In the following example, the user types in the octal number 177 (which
3236is 127 in decimal).
3237
3238@example
3239(read-quoted-char "What character")
3240
3241@group
3242---------- Echo Area ----------
3243What character @kbd{1 7 7}-
3244---------- Echo Area ----------
3245
3246     @result{} 127
3247@end group
3248@end example
3249@end defun
3250
3251@need 2000
3252@node Event Input Misc
3253@subsection Miscellaneous Event Input Features
3254
3255This section describes how to peek ahead at events without using
3256them up, how to check for pending input, and how to discard pending
3257input.  See also the function @code{read-passwd} (@pxref{Reading a
3258Password}).
3259
3260@defvar unread-command-events
3261@cindex next input
3262@cindex peeking at input
3263This variable holds a list of events waiting to be read as command
3264input.  The events are used in the order they appear in the list, and
3265removed one by one as they are used.
3266
3267The variable is needed because in some cases a function reads an event
3268and then decides not to use it.  Storing the event in this variable
3269causes it to be processed normally, by the command loop or by the
3270functions to read command input.
3271
3272@cindex prefix argument unreading
3273For example, the function that implements numeric prefix arguments reads
3274any number of digits.  When it finds a non-digit event, it must unread
3275the event so that it can be read normally by the command loop.
3276Likewise, incremental search uses this feature to unread events with no
3277special meaning in a search, because these events should exit the search
3278and then execute normally.
3279
3280The reliable and easy way to extract events from a key sequence so as
3281to put them in @code{unread-command-events} is to use
3282@code{listify-key-sequence} (see below).
3283
3284Normally you add events to the front of this list, so that the events
3285most recently unread will be reread first.
3286
3287Events read from this list are not normally added to the current
3288command's key sequence (as returned by, e.g., @code{this-command-keys}),
3289as the events will already have been added once as they were read for
3290the first time.  An element of the form @w{@code{(t . @var{event})}}
3291forces @var{event} to be added to the current command's key sequence.
3292
3293@cindex not recording input events
3294@cindex input events, prevent recording
3295Elements read from this list are normally recorded by the
3296record-keeping features (@pxref{Recording Input}) and while defining a
3297keyboard macro (@pxref{Keyboard Macros}).  However, an element of the
3298form @w{@code{(no-record . @var{event})}} causes @var{event} to be
3299processed normally without recording it.
3300@end defvar
3301
3302@defun listify-key-sequence key
3303This function converts the string or vector @var{key} to a list of
3304individual events, which you can put in @code{unread-command-events}.
3305@end defun
3306
3307@defun input-pending-p &optional check-timers
3308@cindex waiting for command key input
3309This function determines whether any command input is currently
3310available to be read.  It returns immediately, with value @code{t} if
3311there is available input, @code{nil} otherwise.  On rare occasions it
3312may return @code{t} when no input is available.
3313
3314If the optional argument @var{check-timers} is non-@code{nil}, then if
3315no input is available, Emacs runs any timers which are ready.
3316@xref{Timers}.
3317@end defun
3318
3319@defvar last-input-event
3320This variable records the last terminal input event read, whether
3321as part of a command or explicitly by a Lisp program.
3322
3323In the example below, the Lisp program reads the character @kbd{1},
3324@acronym{ASCII} code 49.  It becomes the value of @code{last-input-event},
3325while @kbd{C-e} (we assume @kbd{C-x C-e} command is used to evaluate
3326this expression) remains the value of @code{last-command-event}.
3327
3328@example
3329@group
3330(progn (print (read-char))
3331       (print last-command-event)
3332       last-input-event)
3333     @print{} 49
3334     @print{} 5
3335     @result{} 49
3336@end group
3337@end example
3338@end defvar
3339
3340@defmac while-no-input body@dots{}
3341This construct runs the @var{body} forms and returns the value of the
3342last one---but only if no input arrives.  If any input arrives during
3343the execution of the @var{body} forms, it aborts them (working much
3344like a quit).  The @code{while-no-input} form returns @code{nil} if
3345aborted by a real quit, and returns @code{t} if aborted by arrival of
3346other input.
3347
3348If a part of @var{body} binds @code{inhibit-quit} to non-@code{nil},
3349arrival of input during those parts won't cause an abort until
3350the end of that part.
3351
3352If you want to be able to distinguish all possible values computed
3353by @var{body} from both kinds of abort conditions, write the code
3354like this:
3355
3356@example
3357(while-no-input
3358  (list
3359    (progn . @var{body})))
3360@end example
3361@end defmac
3362
3363@defvar while-no-input-ignore-events
3364This variable allow setting which special events @code{while-no-input}
3365should ignore.  It is a list of event symbols (@pxref{Event Examples}).
3366
3367@end defvar
3368
3369@defun discard-input
3370@cindex flushing input
3371@cindex discarding input
3372@cindex keyboard macro, terminating
3373This function discards the contents of the terminal input buffer and
3374cancels any keyboard macro that might be in the process of definition.
3375It returns @code{nil}.
3376
3377In the following example, the user may type a number of characters right
3378after starting the evaluation of the form.  After the @code{sleep-for}
3379finishes sleeping, @code{discard-input} discards any characters typed
3380during the sleep.
3381
3382@example
3383(progn (sleep-for 2)
3384       (discard-input))
3385     @result{} nil
3386@end example
3387@end defun
3388
3389@node Special Events
3390@section Special Events
3391
3392@cindex special events
3393Certain @dfn{special events} are handled at a very low level---as soon
3394as they are read.  The @code{read-event} function processes these
3395events itself, and never returns them.  Instead, it keeps waiting for
3396the first event that is not special and returns that one.
3397
3398  Special events do not echo, they are never grouped into key
3399sequences, and they never appear in the value of
3400@code{last-command-event} or @code{(this-command-keys)}.  They do not
3401discard a numeric argument, they cannot be unread with
3402@code{unread-command-events}, they may not appear in a keyboard macro,
3403and they are not recorded in a keyboard macro while you are defining
3404one.
3405
3406  Special events do, however, appear in @code{last-input-event}
3407immediately after they are read, and this is the way for the event's
3408definition to find the actual event.
3409
3410  The events types @code{iconify-frame}, @code{make-frame-visible},
3411@code{delete-frame}, @code{drag-n-drop}, @code{language-change}, and
3412user signals like @code{sigusr1} are normally handled in this way.
3413The keymap which defines how to handle special events---and which
3414events are special---is in the variable @code{special-event-map}
3415(@pxref{Controlling Active Maps}).
3416
3417@node Waiting
3418@section Waiting for Elapsed Time or Input
3419@cindex waiting
3420
3421  The wait functions are designed to wait for a certain amount of time
3422to pass or until there is input.  For example, you may wish to pause in
3423the middle of a computation to allow the user time to view the display.
3424@code{sit-for} pauses and updates the screen, and returns immediately if
3425input comes in, while @code{sleep-for} pauses without updating the
3426screen.
3427
3428@defun sit-for seconds &optional nodisp
3429This function performs redisplay (provided there is no pending input
3430from the user), then waits @var{seconds} seconds, or until input is
3431available.  The usual purpose of @code{sit-for} is to give the user
3432time to read text that you display.  The value is @code{t} if
3433@code{sit-for} waited the full time with no input arriving
3434(@pxref{Event Input Misc}).  Otherwise, the value is @code{nil}.
3435
3436The argument @var{seconds} need not be an integer.  If it is floating
3437point, @code{sit-for} waits for a fractional number of seconds.
3438Some systems support only a whole number of seconds; on these systems,
3439@var{seconds} is rounded down.
3440
3441The expression @code{(sit-for 0)} is equivalent to @code{(redisplay)},
3442i.e., it requests a redisplay, without any delay, if there is no pending input.
3443@xref{Forcing Redisplay}.
3444
3445If @var{nodisp} is non-@code{nil}, then @code{sit-for} does not
3446redisplay, but it still returns as soon as input is available (or when
3447the timeout elapses).
3448
3449In batch mode (@pxref{Batch Mode}), @code{sit-for} cannot be
3450interrupted, even by input from the standard input descriptor.  It is
3451thus equivalent to @code{sleep-for}, which is described below.
3452
3453It is also possible to call @code{sit-for} with three arguments,
3454as @code{(sit-for @var{seconds} @var{millisec} @var{nodisp})},
3455but that is considered obsolete.
3456@end defun
3457
3458@defun sleep-for seconds &optional millisec
3459This function simply pauses for @var{seconds} seconds without updating
3460the display.  It pays no attention to available input.  It returns
3461@code{nil}.
3462
3463The argument @var{seconds} need not be an integer.  If it is floating
3464point, @code{sleep-for} waits for a fractional number of seconds.
3465Some systems support only a whole number of seconds; on these systems,
3466@var{seconds} is rounded down.
3467
3468The optional argument @var{millisec} specifies an additional waiting
3469period measured in milliseconds.  This adds to the period specified by
3470@var{seconds}.  If the system doesn't support waiting fractions of a
3471second, you get an error if you specify nonzero @var{millisec}.
3472
3473Use @code{sleep-for} when you wish to guarantee a delay.
3474@end defun
3475
3476  @xref{Time of Day}, for functions to get the current time.
3477
3478@node Quitting
3479@section Quitting
3480@cindex @kbd{C-g}
3481@cindex quitting
3482@cindex interrupt Lisp functions
3483
3484  Typing @kbd{C-g} while a Lisp function is running causes Emacs to
3485@dfn{quit} whatever it is doing.  This means that control returns to the
3486innermost active command loop.
3487
3488  Typing @kbd{C-g} while the command loop is waiting for keyboard input
3489does not cause a quit; it acts as an ordinary input character.  In the
3490simplest case, you cannot tell the difference, because @kbd{C-g}
3491normally runs the command @code{keyboard-quit}, whose effect is to quit.
3492However, when @kbd{C-g} follows a prefix key, they combine to form an
3493undefined key.  The effect is to cancel the prefix key as well as any
3494prefix argument.
3495
3496  In the minibuffer, @kbd{C-g} has a different definition: it aborts out
3497of the minibuffer.  This means, in effect, that it exits the minibuffer
3498and then quits.  (Simply quitting would return to the command loop
3499@emph{within} the minibuffer.)  The reason why @kbd{C-g} does not quit
3500directly when the command reader is reading input is so that its meaning
3501can be redefined in the minibuffer in this way.  @kbd{C-g} following a
3502prefix key is not redefined in the minibuffer, and it has its normal
3503effect of canceling the prefix key and prefix argument.  This too
3504would not be possible if @kbd{C-g} always quit directly.
3505
3506  When @kbd{C-g} does directly quit, it does so by setting the variable
3507@code{quit-flag} to @code{t}.  Emacs checks this variable at appropriate
3508times and quits if it is not @code{nil}.  Setting @code{quit-flag}
3509non-@code{nil} in any way thus causes a quit.
3510
3511  At the level of C code, quitting cannot happen just anywhere; only at the
3512special places that check @code{quit-flag}.  The reason for this is
3513that quitting at other places might leave an inconsistency in Emacs's
3514internal state.  Because quitting is delayed until a safe place, quitting
3515cannot make Emacs crash.
3516
3517  Certain functions such as @code{read-key-sequence} or
3518@code{read-quoted-char} prevent quitting entirely even though they wait
3519for input.  Instead of quitting, @kbd{C-g} serves as the requested
3520input.  In the case of @code{read-key-sequence}, this serves to bring
3521about the special behavior of @kbd{C-g} in the command loop.  In the
3522case of @code{read-quoted-char}, this is so that @kbd{C-q} can be used
3523to quote a @kbd{C-g}.
3524
3525@cindex preventing quitting
3526  You can prevent quitting for a portion of a Lisp function by binding
3527the variable @code{inhibit-quit} to a non-@code{nil} value.  Then,
3528although @kbd{C-g} still sets @code{quit-flag} to @code{t} as usual, the
3529usual result of this---a quit---is prevented.  Eventually,
3530@code{inhibit-quit} will become @code{nil} again, such as when its
3531binding is unwound at the end of a @code{let} form.  At that time, if
3532@code{quit-flag} is still non-@code{nil}, the requested quit happens
3533immediately.  This behavior is ideal when you wish to make sure that
3534quitting does not happen within a critical section of the program.
3535
3536@cindex @code{read-quoted-char} quitting
3537  In some functions (such as @code{read-quoted-char}), @kbd{C-g} is
3538handled in a special way that does not involve quitting.  This is done
3539by reading the input with @code{inhibit-quit} bound to @code{t}, and
3540setting @code{quit-flag} to @code{nil} before @code{inhibit-quit}
3541becomes @code{nil} again.  This excerpt from the definition of
3542@code{read-quoted-char} shows how this is done; it also shows that
3543normal quitting is permitted after the first character of input.
3544
3545@example
3546(defun read-quoted-char (&optional prompt)
3547  "@dots{}@var{documentation}@dots{}"
3548  (let ((message-log-max nil) done (first t) (code 0) char)
3549    (while (not done)
3550      (let ((inhibit-quit first)
3551            @dots{})
3552        (and prompt (message "%s-" prompt))
3553        (setq char (read-event))
3554        (if inhibit-quit (setq quit-flag nil)))
3555      @r{@dots{}set the variable @code{code}@dots{}})
3556    code))
3557@end example
3558
3559@defvar quit-flag
3560If this variable is non-@code{nil}, then Emacs quits immediately, unless
3561@code{inhibit-quit} is non-@code{nil}.  Typing @kbd{C-g} ordinarily sets
3562@code{quit-flag} non-@code{nil}, regardless of @code{inhibit-quit}.
3563@end defvar
3564
3565@defvar inhibit-quit
3566This variable determines whether Emacs should quit when @code{quit-flag}
3567is set to a value other than @code{nil}.  If @code{inhibit-quit} is
3568non-@code{nil}, then @code{quit-flag} has no special effect.
3569@end defvar
3570
3571@defmac with-local-quit body@dots{}
3572This macro executes @var{body} forms in sequence, but allows quitting, at
3573least locally, within @var{body} even if @code{inhibit-quit} was
3574non-@code{nil} outside this construct.  It returns the value of the
3575last form in @var{body}, unless exited by quitting, in which case
3576it returns @code{nil}.
3577
3578If @code{inhibit-quit} is @code{nil} on entry to @code{with-local-quit},
3579it only executes the @var{body}, and setting @code{quit-flag} causes
3580a normal quit.  However, if @code{inhibit-quit} is non-@code{nil} so
3581that ordinary quitting is delayed, a non-@code{nil} @code{quit-flag}
3582triggers a special kind of local quit.  This ends the execution of
3583@var{body} and exits the @code{with-local-quit} body with
3584@code{quit-flag} still non-@code{nil}, so that another (ordinary) quit
3585will happen as soon as that is allowed.  If @code{quit-flag} is
3586already non-@code{nil} at the beginning of @var{body}, the local quit
3587happens immediately and the body doesn't execute at all.
3588
3589This macro is mainly useful in functions that can be called from
3590timers, process filters, process sentinels, @code{pre-command-hook},
3591@code{post-command-hook}, and other places where @code{inhibit-quit} is
3592normally bound to @code{t}.
3593@end defmac
3594
3595@deffn Command keyboard-quit
3596This function signals the @code{quit} condition with @code{(signal 'quit
3597nil)}.  This is the same thing that quitting does.  (See @code{signal}
3598in @ref{Errors}.)
3599@end deffn
3600
3601  To quit without aborting a keyboard macro definition or execution,
3602you can signal the @code{minibuffer-quit} condition.  This has almost
3603the same effect as the @code{quit} condition except that the error
3604handling in the command loop handles it without exiting keyboard macro
3605definition or execution.
3606
3607  You can specify a character other than @kbd{C-g} to use for quitting.
3608See the function @code{set-input-mode} in @ref{Input Modes}.
3609
3610@node Prefix Command Arguments
3611@section Prefix Command Arguments
3612@cindex prefix argument
3613@cindex raw prefix argument
3614@cindex numeric prefix argument
3615
3616  Most Emacs commands can use a @dfn{prefix argument}, a number
3617specified before the command itself.  (Don't confuse prefix arguments
3618with prefix keys.)  The prefix argument is at all times represented by a
3619value, which may be @code{nil}, meaning there is currently no prefix
3620argument.  Each command may use the prefix argument or ignore it.
3621
3622  There are two representations of the prefix argument: @dfn{raw} and
3623@dfn{numeric}.  The editor command loop uses the raw representation
3624internally, and so do the Lisp variables that store the information, but
3625commands can request either representation.
3626
3627  Here are the possible values of a raw prefix argument:
3628
3629@itemize @bullet
3630@item
3631@code{nil}, meaning there is no prefix argument.  Its numeric value is
36321, but numerous commands make a distinction between @code{nil} and the
3633integer 1.
3634
3635@item
3636An integer, which stands for itself.
3637
3638@item
3639A list of one element, which is an integer.  This form of prefix
3640argument results from one or a succession of @kbd{C-u}s with no
3641digits.  The numeric value is the integer in the list, but some
3642commands make a distinction between such a list and an integer alone.
3643
3644@item
3645The symbol @code{-}.  This indicates that @kbd{M--} or @kbd{C-u -} was
3646typed, without following digits.  The equivalent numeric value is
3647@minus{}1, but some commands make a distinction between the integer
3648@minus{}1 and the symbol @code{-}.
3649@end itemize
3650
3651We illustrate these possibilities by calling the following function with
3652various prefixes:
3653
3654@example
3655@group
3656(defun display-prefix (arg)
3657  "Display the value of the raw prefix arg."
3658  (interactive "P")
3659  (message "%s" arg))
3660@end group
3661@end example
3662
3663@noindent
3664Here are the results of calling @code{display-prefix} with various
3665raw prefix arguments:
3666
3667@example
3668        M-x display-prefix  @print{} nil
3669
3670C-u     M-x display-prefix  @print{} (4)
3671
3672C-u C-u M-x display-prefix  @print{} (16)
3673
3674C-u 3   M-x display-prefix  @print{} 3
3675
3676M-3     M-x display-prefix  @print{} 3      ; @r{(Same as @code{C-u 3}.)}
3677
3678C-u -   M-x display-prefix  @print{} -
3679
3680M--     M-x display-prefix  @print{} -      ; @r{(Same as @code{C-u -}.)}
3681
3682C-u - 7 M-x display-prefix  @print{} -7
3683
3684M-- 7   M-x display-prefix  @print{} -7     ; @r{(Same as @code{C-u -7}.)}
3685@end example
3686
3687  Emacs uses two variables to store the prefix argument:
3688@code{prefix-arg} and @code{current-prefix-arg}.  Commands such as
3689@code{universal-argument} that set up prefix arguments for other
3690commands store them in @code{prefix-arg}.  In contrast,
3691@code{current-prefix-arg} conveys the prefix argument to the current
3692command, so setting it has no effect on the prefix arguments for future
3693commands.
3694
3695  Normally, commands specify which representation to use for the prefix
3696argument, either numeric or raw, in the @code{interactive} specification.
3697(@xref{Using Interactive}.)  Alternatively, functions may look at the
3698value of the prefix argument directly in the variable
3699@code{current-prefix-arg}, but this is less clean.
3700
3701@defun prefix-numeric-value arg
3702This function returns the numeric meaning of a valid raw prefix argument
3703value, @var{arg}.  The argument may be a symbol, a number, or a list.
3704If it is @code{nil}, the value 1 is returned; if it is @code{-}, the
3705value @minus{}1 is returned; if it is a number, that number is returned;
3706if it is a list, the @sc{car} of that list (which should be a number) is
3707returned.
3708@end defun
3709
3710@defvar current-prefix-arg
3711This variable holds the raw prefix argument for the @emph{current}
3712command.  Commands may examine it directly, but the usual method for
3713accessing it is with @code{(interactive "P")}.
3714@end defvar
3715
3716@defvar prefix-arg
3717The value of this variable is the raw prefix argument for the
3718@emph{next} editing command.  Commands such as @code{universal-argument}
3719that specify prefix arguments for the following command work by setting
3720this variable.
3721@end defvar
3722
3723@defvar last-prefix-arg
3724The raw prefix argument value used by the previous command.
3725@end defvar
3726
3727  The following commands exist to set up prefix arguments for the
3728following command.  Do not call them for any other reason.
3729
3730@deffn Command universal-argument
3731This command reads input and specifies a prefix argument for the
3732following command.  Don't call this command yourself unless you know
3733what you are doing.
3734@end deffn
3735
3736@deffn Command digit-argument arg
3737This command adds to the prefix argument for the following command.  The
3738argument @var{arg} is the raw prefix argument as it was before this
3739command; it is used to compute the updated prefix argument.  Don't call
3740this command yourself unless you know what you are doing.
3741@end deffn
3742
3743@deffn Command negative-argument arg
3744This command adds to the numeric argument for the next command.  The
3745argument @var{arg} is the raw prefix argument as it was before this
3746command; its value is negated to form the new prefix argument.  Don't
3747call this command yourself unless you know what you are doing.
3748@end deffn
3749
3750@node Recursive Editing
3751@section Recursive Editing
3752@cindex recursive command loop
3753@cindex recursive editing level
3754@cindex command loop, recursive
3755
3756  The Emacs command loop is entered automatically when Emacs starts up.
3757This top-level invocation of the command loop never exits; it keeps
3758running as long as Emacs does.  Lisp programs can also invoke the
3759command loop.  Since this makes more than one activation of the command
3760loop, we call it @dfn{recursive editing}.  A recursive editing level has
3761the effect of suspending whatever command invoked it and permitting the
3762user to do arbitrary editing before resuming that command.
3763
3764  The commands available during recursive editing are the same ones
3765available in the top-level editing loop and defined in the keymaps.
3766Only a few special commands exit the recursive editing level; the others
3767return to the recursive editing level when they finish.  (The special
3768commands for exiting are always available, but they do nothing when
3769recursive editing is not in progress.)
3770
3771  All command loops, including recursive ones, set up all-purpose error
3772handlers so that an error in a command run from the command loop will
3773not exit the loop.
3774
3775@cindex minibuffer input
3776  Minibuffer input is a special kind of recursive editing.  It has a few
3777special wrinkles, such as enabling display of the minibuffer and the
3778minibuffer window, but fewer than you might suppose.  Certain keys
3779behave differently in the minibuffer, but that is only because of the
3780minibuffer's local map; if you switch windows, you get the usual Emacs
3781commands.
3782
3783@cindex @code{throw} example
3784@kindex exit
3785@cindex exit recursive editing
3786@cindex aborting
3787  To invoke a recursive editing level, call the function
3788@code{recursive-edit}.  This function contains the command loop; it
3789also contains a call to @code{catch} with tag @code{exit}, which makes
3790it possible to exit the recursive editing level by throwing to
3791@code{exit} (@pxref{Catch and Throw}).  Throwing a @code{t} value
3792causes @code{recursive-edit} to quit, so that control returns to the
3793command loop one level up.  This is called @dfn{aborting}, and is done
3794by @kbd{C-]} (@code{abort-recursive-edit}).  Similarly, you can throw
3795a string value to make @code{recursive-edit} signal an error, printing
3796this string as the message.  If you throw a function,
3797@code{recursive-edit} will call it without arguments before returning.
3798Throwing any other value, will make @code{recursive-edit} return
3799normally to the function that called it.  The command @kbd{C-M-c}
3800(@code{exit-recursive-edit}) does this.
3801
3802  Most applications should not use recursive editing, except as part of
3803using the minibuffer.  Usually it is more convenient for the user if you
3804change the major mode of the current buffer temporarily to a special
3805major mode, which should have a command to go back to the previous mode.
3806(The @kbd{e} command in Rmail uses this technique.)  Or, if you wish to
3807give the user different text to edit recursively, create and select
3808a new buffer in a special mode.  In this mode, define a command to
3809complete the processing and go back to the previous buffer.  (The
3810@kbd{m} command in Rmail does this.)
3811
3812  Recursive edits are useful in debugging.  You can insert a call to
3813@code{debug} into a function definition as a sort of breakpoint, so that
3814you can look around when the function gets there.  @code{debug} invokes
3815a recursive edit but also provides the other features of the debugger.
3816
3817  Recursive editing levels are also used when you type @kbd{C-r} in
3818@code{query-replace} or use @kbd{C-x q} (@code{kbd-macro-query}).
3819
3820@deffn Command recursive-edit
3821@cindex suspend evaluation
3822This function invokes the editor command loop.  It is called
3823automatically by the initialization of Emacs, to let the user begin
3824editing.  When called from a Lisp program, it enters a recursive editing
3825level.
3826
3827If the current buffer is not the same as the selected window's buffer,
3828@code{recursive-edit} saves and restores the current buffer.  Otherwise,
3829if you switch buffers, the buffer you switched to is current after
3830@code{recursive-edit} returns.
3831
3832In the following example, the function @code{simple-rec} first
3833advances point one word, then enters a recursive edit, printing out a
3834message in the echo area.  The user can then do any editing desired, and
3835then type @kbd{C-M-c} to exit and continue executing @code{simple-rec}.
3836
3837@example
3838(defun simple-rec ()
3839  (forward-word 1)
3840  (message "Recursive edit in progress")
3841  (recursive-edit)
3842  (forward-word 1))
3843     @result{} simple-rec
3844(simple-rec)
3845     @result{} nil
3846@end example
3847@end deffn
3848
3849@deffn Command exit-recursive-edit
3850This function exits from the innermost recursive edit (including
3851minibuffer input).  Its definition is effectively @code{(throw 'exit
3852nil)}.
3853@end deffn
3854
3855@deffn Command abort-recursive-edit
3856This function aborts the command that requested the innermost recursive
3857edit (including minibuffer input), by signaling @code{quit}
3858after exiting the recursive edit.  Its definition is effectively
3859@code{(throw 'exit t)}.  @xref{Quitting}.
3860@end deffn
3861
3862@deffn Command top-level
3863This function exits all recursive editing levels; it does not return a
3864value, as it jumps completely out of any computation directly back to
3865the main command loop.
3866@end deffn
3867
3868@defun recursion-depth
3869This function returns the current depth of recursive edits.  When no
3870recursive edit is active, it returns 0.
3871@end defun
3872
3873@node Disabling Commands
3874@section Disabling Commands
3875@cindex disabled command
3876
3877  @dfn{Disabling a command} marks the command as requiring user
3878confirmation before it can be executed.  Disabling is used for commands
3879which might be confusing to beginning users, to prevent them from using
3880the commands by accident.
3881
3882@kindex disabled
3883  The low-level mechanism for disabling a command is to put a
3884non-@code{nil} @code{disabled} property on the Lisp symbol for the
3885command.  These properties are normally set up by the user's
3886init file (@pxref{Init File}) with Lisp expressions such as this:
3887
3888@example
3889(put 'upcase-region 'disabled t)
3890@end example
3891
3892@noindent
3893For a few commands, these properties are present by default (you can
3894remove them in your init file if you wish).
3895
3896  If the value of the @code{disabled} property is a string, the message
3897saying the command is disabled includes that string.  For example:
3898
3899@example
3900(put 'delete-region 'disabled
3901     "Text deleted this way cannot be yanked back!\n")
3902@end example
3903
3904  @xref{Disabling,,, emacs, The GNU Emacs Manual}, for the details on
3905what happens when a disabled command is invoked interactively.
3906Disabling a command has no effect on calling it as a function from Lisp
3907programs.
3908
3909@deffn Command enable-command command
3910Allow @var{command} (a symbol) to be executed without special
3911confirmation from now on, and alter the user's init file (@pxref{Init
3912File}) so that this will apply to future sessions.
3913@end deffn
3914
3915@deffn Command disable-command command
3916Require special confirmation to execute @var{command} from now on, and
3917alter the user's init file so that this will apply to future sessions.
3918@end deffn
3919
3920@defvar disabled-command-function
3921The value of this variable should be a function.  When the user
3922invokes a disabled command interactively, this function is called
3923instead of the disabled command.  It can use @code{this-command-keys}
3924to determine what the user typed to run the command, and thus find the
3925command itself.
3926
3927The value may also be @code{nil}.  Then all commands work normally,
3928even disabled ones.
3929
3930By default, the value is a function that asks the user whether to
3931proceed.
3932@end defvar
3933
3934@node Command History
3935@section Command History
3936@cindex command history
3937@cindex complex command
3938@cindex history of commands
3939
3940  The command loop keeps a history of the complex commands that have
3941been executed, to make it convenient to repeat these commands.  A
3942@dfn{complex command} is one for which the interactive argument reading
3943uses the minibuffer.  This includes any @kbd{M-x} command, any
3944@kbd{M-:} command, and any command whose @code{interactive}
3945specification reads an argument from the minibuffer.  Explicit use of
3946the minibuffer during the execution of the command itself does not cause
3947the command to be considered complex.
3948
3949@defvar command-history
3950This variable's value is a list of recent complex commands, each
3951represented as a form to evaluate.  It continues to accumulate all
3952complex commands for the duration of the editing session, but when it
3953reaches the maximum size (@pxref{Minibuffer History}), the oldest
3954elements are deleted as new ones are added.
3955
3956@example
3957@group
3958command-history
3959@result{} ((switch-to-buffer "chistory.texi")
3960    (describe-key "^X^[")
3961    (visit-tags-table "~/emacs/src/")
3962    (find-tag "repeat-complex-command"))
3963@end group
3964@end example
3965@end defvar
3966
3967  This history list is actually a special case of minibuffer history
3968(@pxref{Minibuffer History}), with one special twist: the elements are
3969expressions rather than strings.
3970
3971  There are a number of commands devoted to the editing and recall of
3972previous commands.  The commands @code{repeat-complex-command}, and
3973@code{list-command-history} are described in the user manual
3974(@pxref{Repetition,,, emacs, The GNU Emacs Manual}).  Within the
3975minibuffer, the usual minibuffer history commands are available.
3976
3977@node Keyboard Macros
3978@section Keyboard Macros
3979@cindex keyboard macros
3980
3981  A @dfn{keyboard macro} is a canned sequence of input events that can
3982be considered a command and made the definition of a key.  The Lisp
3983representation of a keyboard macro is a string or vector containing the
3984events.  Don't confuse keyboard macros with Lisp macros
3985(@pxref{Macros}).
3986
3987@defun execute-kbd-macro kbdmacro &optional count loopfunc
3988This function executes @var{kbdmacro} as a sequence of events.  If
3989@var{kbdmacro} is a string or vector, then the events in it are executed
3990exactly as if they had been input by the user.  The sequence is
3991@emph{not} expected to be a single key sequence; normally a keyboard
3992macro definition consists of several key sequences concatenated.
3993
3994If @var{kbdmacro} is a symbol, then its function definition is used in
3995place of @var{kbdmacro}.  If that is another symbol, this process repeats.
3996Eventually the result should be a string or vector.  If the result is
3997not a symbol, string, or vector, an error is signaled.
3998
3999The argument @var{count} is a repeat count; @var{kbdmacro} is executed that
4000many times.  If @var{count} is omitted or @code{nil}, @var{kbdmacro} is
4001executed once.  If it is 0, @var{kbdmacro} is executed over and over until it
4002encounters an error or a failing search.
4003
4004If @var{loopfunc} is non-@code{nil}, it is a function that is called,
4005without arguments, prior to each iteration of the macro.  If
4006@var{loopfunc} returns @code{nil}, then this stops execution of the macro.
4007
4008@xref{Reading One Event}, for an example of using @code{execute-kbd-macro}.
4009@end defun
4010
4011@defvar executing-kbd-macro
4012This variable contains the string or vector that defines the keyboard
4013macro that is currently executing.  It is @code{nil} if no macro is
4014currently executing.  A command can test this variable so as to behave
4015differently when run from an executing macro.  Do not set this variable
4016yourself.
4017@end defvar
4018
4019@defvar defining-kbd-macro
4020This variable is non-@code{nil} if and only if a keyboard macro is
4021being defined.  A command can test this variable so as to behave
4022differently while a macro is being defined.  The value is
4023@code{append} while appending to the definition of an existing macro.
4024The commands @code{start-kbd-macro}, @code{kmacro-start-macro} and
4025@code{end-kbd-macro} set this variable---do not set it yourself.
4026
4027The variable is always local to the current terminal and cannot be
4028buffer-local.  @xref{Multiple Terminals}.
4029@end defvar
4030
4031@defvar last-kbd-macro
4032This variable is the definition of the most recently defined keyboard
4033macro.  Its value is a string or vector, or @code{nil}.
4034
4035The variable is always local to the current terminal and cannot be
4036buffer-local.  @xref{Multiple Terminals}.
4037@end defvar
4038
4039@defvar kbd-macro-termination-hook
4040This normal hook is run when a keyboard macro terminates, regardless
4041of what caused it to terminate (reaching the macro end or an error
4042which ended the macro prematurely).
4043@end defvar
4044