@c -*-texinfo-*-@c This is part of the GNU Emacs Lisp Reference Manual.@c Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1998, 1999, 2002, 2003,@c 2004, 2005, 2006 Free Software Foundation, Inc.@c See the file elisp.texi for copying conditions.@setfilename ../info/commands@node Command Loop, Keymaps, Minibuffers, Top@chapter Command Loop@cindex editor command loop@cindex command loop When you run Emacs, it enters the @dfn{editor command loop} almostimmediately. This loop reads key sequences, executes their definitions,and displays the results. In this chapter, we describe how these thingsare done, and the subroutines that allow Lisp programs to do them.@menu* Command Overview:: How the command loop reads commands.* Defining Commands:: Specifying how a function should read arguments.* Interactive Call:: Calling a command, so that it will read arguments.* Command Loop Info:: Variables set by the command loop for you to examine.* Adjusting Point:: Adjustment of point after a command.* Input Events:: What input looks like when you read it.* Reading Input:: How to read input events from the keyboard or mouse.* Special Events:: Events processed immediately and individually.* Waiting:: Waiting for user input or elapsed time.* Quitting:: How @kbd{C-g} works. How to catch or defer quitting.* Prefix Command Arguments:: How the commands to set prefix args work.* Recursive Editing:: Entering a recursive edit, and why you usually shouldn't.* Disabling Commands:: How the command loop handles disabled commands.* Command History:: How the command history is set up, and how accessed.* Keyboard Macros:: How keyboard macros are implemented.@end menu@node Command Overview@section Command Loop Overview The first thing the command loop must do is read a key sequence, whichis a sequence of events that translates into a command. It does this bycalling the function @code{read-key-sequence}. Your Lisp code can alsocall this function (@pxref{Key Sequence Input}). Lisp programs can alsodo input at a lower level with @code{read-event} (@pxref{Reading OneEvent}) or discard pending input with @code{discard-input}(@pxref{Event Input Misc}). The key sequence is translated into a command through the currentlyactive keymaps. @xref{Key Lookup}, for information on how this is done.The result should be a keyboard macro or an interactively callablefunction. If the key is @kbd{M-x}, then it reads the name of anothercommand, which it then calls. This is done by the command@code{execute-extended-command} (@pxref{Interactive Call}). To execute a command requires first reading the arguments for it.This is done by calling @code{command-execute} (@pxref{InteractiveCall}). For commands written in Lisp, the @code{interactive}specification says how to read the arguments. This may use the prefixargument (@pxref{Prefix Command Arguments}) or may read with promptingin the minibuffer (@pxref{Minibuffers}). For example, the command@code{find-file} has an @code{interactive} specification which says toread a file name using the minibuffer. The command's function body doesnot use the minibuffer; if you call this command from Lisp code as afunction, you must supply the file name string as an ordinary Lispfunction argument. If the command is a string or vector (i.e., a keyboard macro) then@code{execute-kbd-macro} is used to execute it. You can call thisfunction yourself (@pxref{Keyboard Macros}). To terminate the execution of a running command, type @kbd{C-g}. Thischaracter causes @dfn{quitting} (@pxref{Quitting}).@defvar pre-command-hookThe editor command loop runs this normal hook before each command. Atthat time, @code{this-command} contains the command that is about torun, and @code{last-command} describes the previous command.@xref{Command Loop Info}.@end defvar@defvar post-command-hookThe editor command loop runs this normal hook after each command(including commands terminated prematurely by quitting or by errors),and also when the command loop is first entered. At that time,@code{this-command} refers to the command that just ran, and@code{last-command} refers to the command before that.@end defvar Quitting is suppressed while running @code{pre-command-hook} and@code{post-command-hook}. If an error happens while executing one ofthese hooks, it terminates execution of the hook, and clears the hookvariable to @code{nil} so as to prevent an infinite loop of errors. A request coming into the Emacs server (@pxref{Emacs Server,,,emacs, The GNU Emacs Manual}) runs these two hooks just as a keyboardcommand does.@node Defining Commands@section Defining Commands@cindex defining commands@cindex commands, defining@cindex functions, making them interactive@cindex interactive function A Lisp function becomes a command when its body contains, at toplevel, a form that calls the special form @code{interactive}. Thisform does nothing when actually executed, but its presence serves as aflag to indicate that interactive calling is permitted. Its argumentcontrols the reading of arguments for an interactive call.@menu* Using Interactive:: General rules for @code{interactive}.* Interactive Codes:: The standard letter-codes for reading arguments in various ways.* Interactive Examples:: Examples of how to read interactive arguments.@end menu@node Using Interactive@subsection Using @code{interactive} This section describes how to write the @code{interactive} form thatmakes a Lisp function an interactively-callable command, and how toexamine a command's @code{interactive} form.@defspec interactive arg-descriptor@cindex argument descriptorsThis special form declares that the function in which it appears is acommand, and that it may therefore be called interactively (via@kbd{M-x} or by entering a key sequence bound to it). The argument@var{arg-descriptor} declares how to compute the arguments to thecommand when the command is called interactively.A command may be called from Lisp programs like any other function, butthen the caller supplies the arguments and @var{arg-descriptor} has noeffect.The @code{interactive} form has its effect because the command loop(actually, its subroutine @code{call-interactively}) scans through thefunction definition looking for it, before calling the function. Oncethe function is called, all its body forms including the@code{interactive} form are executed, but at this time@code{interactive} simply returns @code{nil} without even evaluating itsargument.@end defspecThere are three possibilities for the argument @var{arg-descriptor}:@itemize @bullet@itemIt may be omitted or @code{nil}; then the command is called with noarguments. This leads quickly to an error if the command requires oneor more arguments.@item@cindex argument promptIt may be a string; then its contents should consist of a code characterfollowed by a prompt (which some code characters use and some ignore).The prompt ends either with the end of the string or with a newline.Here is a simple example:@smallexample(interactive "bFrobnicate buffer: ")@end smallexample@noindentThe code letter @samp{b} says to read the name of an existing buffer,with completion. The buffer name is the sole argument passed to thecommand. The rest of the string is a prompt.If there is a newline character in the string, it terminates the prompt.If the string does not end there, then the rest of the string shouldcontain another code character and prompt, specifying another argument.You can specify any number of arguments in this way.@c Emacs 19 featureThe prompt string can use @samp{%} to include previous argument values(starting with the first argument) in the prompt. This is done using@code{format} (@pxref{Formatting Strings}). For example, here is howyou could read the name of an existing buffer followed by a new name togive to that buffer:@smallexample@group(interactive "bBuffer to rename: \nsRename buffer %s to: ")@end group@end smallexample@cindex @samp{*} in @code{interactive}@cindex read-only buffers in interactiveIf the first character in the string is @samp{*}, then an error issignaled if the buffer is read-only.@cindex @samp{@@} in @code{interactive}@c Emacs 19 featureIf the first character in the string is @samp{@@}, and if the keysequence used to invoke the command includes any mouse events, thenthe window associated with the first of those events is selectedbefore the command is run.You can use @samp{*} and @samp{@@} together; the order does not matter.Actual reading of arguments is controlled by the rest of the promptstring (starting with the first character that is not @samp{*} or@samp{@@}).@itemIt may be a Lisp expression that is not a string; then it should be aform that is evaluated to get a list of arguments to pass to thecommand. Usually this form will call various functions to read inputfrom the user, most often through the minibuffer (@pxref{Minibuffers})or directly from the keyboard (@pxref{Reading Input}).@cindex argument evaluation formProviding point or the mark as an argument value is also common, butif you do this @emph{and} read input (whether using the minibuffer ornot), be sure to get the integer values of point or the mark afterreading. The current buffer may be receiving subprocess output; ifsubprocess output arrives while the command is waiting for input, itcould relocate point and the mark.Here's an example of what @emph{not} to do:@smallexample(interactive (list (region-beginning) (region-end) (read-string "Foo: " nil 'my-history)))@end smallexample@noindentHere's how to avoid the problem, by examining point and the mark afterreading the keyboard input:@smallexample(interactive (let ((string (read-string "Foo: " nil 'my-history))) (list (region-beginning) (region-end) string)))@end smallexample@strong{Warning:} the argument values should not include any datatypes that can't be printed and then read. Some facilities save@code{command-history} in a file to be read in the subsequentsessions; if a command's arguments contain a data type that printsusing @samp{#<@dots{}>} syntax, those facilities won't work.There are, however, a few exceptions: it is ok to use a limited set ofexpressions such as @code{(point)}, @code{(mark)},@code{(region-beginning)}, and @code{(region-end)}, because Emacsrecognizes them specially and puts the expression (rather than itsvalue) into the command history. To see whether the expression youwrote is one of these exceptions, run the command, then examine@code{(car command-history)}.@end itemize@cindex examining the @code{interactive} form@defun interactive-form functionThis function returns the @code{interactive} form of @var{function}.If @var{function} is an interactively callable function(@pxref{Interactive Call}), the value is the command's@code{interactive} form @code{(interactive @var{spec})}, whichspecifies how to compute its arguments. Otherwise, the value is@code{nil}. If @var{function} is a symbol, its function definition isused.@end defun@node Interactive Codes@comment node-name, next, previous, up@subsection Code Characters for @code{interactive}@cindex interactive code description@cindex description for interactive codes@cindex codes, interactive, description of@cindex characters for interactive codes The code character descriptions below contain a number of key words,defined here as follows:@table @b@item Completion@cindex interactive completionProvide completion. @key{TAB}, @key{SPC}, and @key{RET} perform namecompletion because the argument is read using @code{completing-read}(@pxref{Completion}). @kbd{?} displays a list of possible completions.@item ExistingRequire the name of an existing object. An invalid name is notaccepted; the commands to exit the minibuffer do not exit if the currentinput is not valid.@item Default@cindex default argument stringA default value of some sort is used if the user enters no text in theminibuffer. The default depends on the code character.@item No I/OThis code letter computes an argument without reading any input.Therefore, it does not use a prompt string, and any prompt string yousupply is ignored.Even though the code letter doesn't use a prompt string, you must followit with a newline if it is not the last code character in the string.@item PromptA prompt immediately follows the code character. The prompt ends eitherwith the end of the string or with a newline.@item SpecialThis code character is meaningful only at the beginning of theinteractive string, and it does not look for a prompt or a newline.It is a single, isolated character.@end table@cindex reading interactive arguments Here are the code character descriptions for use with @code{interactive}:@table @samp@item *Signal an error if the current buffer is read-only. Special.@item @@Select the window mentioned in the first mouse event in the keysequence that invoked this command. Special.@item aA function name (i.e., a symbol satisfying @code{fboundp}). Existing,Completion, Prompt.@item bThe name of an existing buffer. By default, uses the name of thecurrent buffer (@pxref{Buffers}). Existing, Completion, Default,Prompt.@item BA buffer name. The buffer need not exist. By default, uses the name ofa recently used buffer other than the current buffer. Completion,Default, Prompt.@item cA character. The cursor does not move into the echo area. Prompt.@item CA command name (i.e., a symbol satisfying @code{commandp}). Existing,Completion, Prompt.@item d@cindex position argumentThe position of point, as an integer (@pxref{Point}). No I/O.@item DA directory name. The default is the current default directory of thecurrent buffer, @code{default-directory} (@pxref{File Name Expansion}).Existing, Completion, Default, Prompt.@item eThe first or next mouse event in the key sequence that invoked the command.More precisely, @samp{e} gets events that are lists, so you can look atthe data in the lists. @xref{Input Events}. No I/O.You can use @samp{e} more than once in a single command's interactivespecification. If the key sequence that invoked the command has@var{n} events that are lists, the @var{n}th @samp{e} provides the@var{n}th such event. Events that are not lists, such as function keysand @acronym{ASCII} characters, do not count where @samp{e} is concerned.@item fA file name of an existing file (@pxref{File Names}). The defaultdirectory is @code{default-directory}. Existing, Completion, Default,Prompt.@item FA file name. The file need not exist. Completion, Default, Prompt.@item GA file name. The file need not exist. If the user enters just adirectory name, then the value is just that directory name, with nofile name within the directory added. Completion, Default, Prompt.@item iAn irrelevant argument. This code always supplies @code{nil} asthe argument's value. No I/O.@item kA key sequence (@pxref{Key Sequences}). This keeps reading eventsuntil a command (or undefined command) is found in the current keymaps. The key sequence argument is represented as a string or vector.The cursor does not move into the echo area. Prompt.If @samp{k} reads a key sequence that ends with a down-event, it alsoreads and discards the following up-event. You can get access to thatup-event with the @samp{U} code character.This kind of input is used by commands such as @code{describe-key} and@code{global-set-key}.@item KA key sequence, whose definition you intend to change. This works like@samp{k}, except that it suppresses, for the last input event in the keysequence, the conversions that are normally used (when necessary) toconvert an undefined key into a defined one.@item m@cindex marker argumentThe position of the mark, as an integer. No I/O.@item MArbitrary text, read in the minibuffer using the current buffer's inputmethod, and returned as a string (@pxref{Input Methods,,, emacs, The GNUEmacs Manual}). Prompt.@item nA number, read with the minibuffer. If the input is not a number, theuser has to try again. @samp{n} never uses the prefix argument.Prompt.@item NThe numeric prefix argument; but if there is no prefix argument, reada number as with @kbd{n}. The value is always a number. @xref{PrefixCommand Arguments}. Prompt.@item p@cindex numeric prefix argument usageThe numeric prefix argument. (Note that this @samp{p} is lower case.)No I/O.@item P@cindex raw prefix argument usageThe raw prefix argument. (Note that this @samp{P} is upper case.) NoI/O.@item r@cindex region argumentPoint and the mark, as two numeric arguments, smallest first. This isthe only code letter that specifies two successive arguments rather thanone. No I/O.@item sArbitrary text, read in the minibuffer and returned as a string(@pxref{Text from Minibuffer}). Terminate the input with either@kbd{C-j} or @key{RET}. (@kbd{C-q} may be used to include either ofthese characters in the input.) Prompt.@item SAn interned symbol whose name is read in the minibuffer. Any whitespacecharacter terminates the input. (Use @kbd{C-q} to include whitespace inthe string.) Other characters that normally terminate a symbol (e.g.,parentheses and brackets) do not do so here. Prompt.@item UA key sequence or @code{nil}. Can be used after a @samp{k} or@samp{K} argument to get the up-event that was discarded (if any)after @samp{k} or @samp{K} read a down-event. If no up-event has beendiscarded, @samp{U} provides @code{nil} as the argument. No I/O.@item vA variable declared to be a user option (i.e., satisfying thepredicate @code{user-variable-p}). This reads the variable using@code{read-variable}. @xref{Definition of read-variable}. Existing,Completion, Prompt.@item xA Lisp object, specified with its read syntax, terminated with a@kbd{C-j} or @key{RET}. The object is not evaluated. @xref{Object fromMinibuffer}. Prompt.@item X@cindex evaluated expression argumentA Lisp form's value. @samp{X} reads as @samp{x} does, then evaluatesthe form so that its value becomes the argument for the command.Prompt.@item zA coding system name (a symbol). If the user enters null input, theargument value is @code{nil}. @xref{Coding Systems}. Completion,Existing, Prompt.@item ZA coding system name (a symbol)---but only if this command has a prefixargument. With no prefix argument, @samp{Z} provides @code{nil} as theargument value. Completion, Existing, Prompt.@end table@node Interactive Examples@comment node-name, next, previous, up@subsection Examples of Using @code{interactive}@cindex examples of using @code{interactive}@cindex @code{interactive}, examples of using Here are some examples of @code{interactive}:@example@group(defun foo1 () ; @r{@code{foo1} takes no arguments,} (interactive) ; @r{just moves forward two words.} (forward-word 2)) @result{} foo1@end group@group(defun foo2 (n) ; @r{@code{foo2} takes one argument,} (interactive "p") ; @r{which is the numeric prefix.} (forward-word (* 2 n))) @result{} foo2@end group@group(defun foo3 (n) ; @r{@code{foo3} takes one argument,} (interactive "nCount:") ; @r{which is read with the Minibuffer.} (forward-word (* 2 n))) @result{} foo3@end group@group(defun three-b (b1 b2 b3) "Select three existing buffers.Put them into three windows, selecting the last one."@end group (interactive "bBuffer1:\nbBuffer2:\nbBuffer3:") (delete-other-windows) (split-window (selected-window) 8) (switch-to-buffer b1) (other-window 1) (split-window (selected-window) 8) (switch-to-buffer b2) (other-window 1) (switch-to-buffer b3)) @result{} three-b@group(three-b "*scratch*" "declarations.texi" "*mail*") @result{} nil@end group@end example@node Interactive Call@section Interactive Call@cindex interactive call After the command loop has translated a key sequence into a command itinvokes that command using the function @code{command-execute}. If thecommand is a function, @code{command-execute} calls@code{call-interactively}, which reads the arguments and calls thecommand. You can also call these functions yourself.@defun commandp object &optional for-call-interactivelyReturns @code{t} if @var{object} is suitable for calling interactively;that is, if @var{object} is a command. Otherwise, returns @code{nil}.The interactively callable objects include strings and vectors (treatedas keyboard macros), lambda expressions that contain a top-level call to@code{interactive}, byte-code function objects made from such lambdaexpressions, autoload objects that are declared as interactive(non-@code{nil} fourth argument to @code{autoload}), and some of theprimitive functions.A symbol satisfies @code{commandp} if its function definitionsatisfies @code{commandp}. Keys and keymaps are not commands.Rather, they are used to look up commands (@pxref{Keymaps}).If @var{for-call-interactively} is non-@code{nil}, then@code{commandp} returns @code{t} only for objects that@code{call-interactively} could call---thus, not for keyboard macros.See @code{documentation} in @ref{Accessing Documentation}, for arealistic example of using @code{commandp}.@end defun@defun call-interactively command &optional record-flag keysThis function calls the interactively callable function @var{command},reading arguments according to its interactive calling specifications.It returns whatever @var{command} returns. An error is signaled if@var{command} is not a function or if it cannot be calledinteractively (i.e., is not a command). Note that keyboard macros(strings and vectors) are not accepted, even though they areconsidered commands, because they are not functions. If @var{command}is a symbol, then @code{call-interactively} uses its function definition.@cindex record command historyIf @var{record-flag} is non-@code{nil}, then this command and itsarguments are unconditionally added to the list @code{command-history}.Otherwise, the command is added only if it uses the minibuffer to readan argument. @xref{Command History}.The argument @var{keys}, if given, should be a vector which specifiesthe sequence of events to supply if the command inquires which eventswere used to invoke it. If @var{keys} is omitted or @code{nil}, thedefault is the return value of @code{this-command-keys-vector}.@xref{Definition of this-command-keys-vector}.@end defun@defun command-execute command &optional record-flag keys special@cindex keyboard macro executionThis function executes @var{command}. The argument @var{command} mustsatisfy the @code{commandp} predicate; i.e., it must be an interactivelycallable function or a keyboard macro.A string or vector as @var{command} is executed with@code{execute-kbd-macro}. A function is passed to@code{call-interactively}, along with the optional @var{record-flag}and @var{keys}.A symbol is handled by using its function definition in its place. Asymbol with an @code{autoload} definition counts as a command if it wasdeclared to stand for an interactively callable function. Such adefinition is handled by loading the specified library and thenrechecking the definition of the symbol.The argument @var{special}, if given, means to ignore the prefixargument and not clear it. This is used for executing special events(@pxref{Special Events}).@end defun@deffn Command execute-extended-command prefix-argument@cindex read command nameThis function reads a command name from the minibuffer using@code{completing-read} (@pxref{Completion}). Then it uses@code{command-execute} to call the specified command. Whatever thatcommand returns becomes the value of @code{execute-extended-command}.@cindex execute with prefix argumentIf the command asks for a prefix argument, it receives the value@var{prefix-argument}. If @code{execute-extended-command} is calledinteractively, the current raw prefix argument is used for@var{prefix-argument}, and thus passed on to whatever command is run.@c !!! Should this be @kindex?@cindex @kbd{M-x}@code{execute-extended-command} is the normal definition of @kbd{M-x},so it uses the string @w{@samp{M-x }} as a prompt. (It would be betterto take the prompt from the events used to invoke@code{execute-extended-command}, but that is painful to implement.) Adescription of the value of the prefix argument, if any, also becomespart of the prompt.@example@group(execute-extended-command 3)---------- Buffer: Minibuffer ----------3 M-x forward-word RET---------- Buffer: Minibuffer ---------- @result{} t@end group@end example@end deffn@defun interactive-pThis function returns @code{t} if the containing function (the onewhose code includes the call to @code{interactive-p}) was called indirect response to user input. This means that it was called with thefunction @code{call-interactively}, and that a keyboard macro isnot running, and that Emacs is not running in batch mode.If the containing function was called by Lisp evaluation (or with@code{apply} or @code{funcall}), then it was not called interactively.@end defun The most common use of @code{interactive-p} is for deciding whetherto give the user additional visual feedback (such as by printing aninformative message). For example:@example@group;; @r{Here's the usual way to use @code{interactive-p}.}(defun foo () (interactive) (when (interactive-p) (message "foo"))) @result{} foo@end group@group;; @r{This function is just to illustrate the behavior.}(defun bar () (interactive) (setq foobar (list (foo) (interactive-p)))) @result{} bar@end group@group;; @r{Type @kbd{M-x foo}.} @print{} foo@end group@group;; @r{Type @kbd{M-x bar}.};; @r{This does not display a message.}@end group@groupfoobar @result{} (nil t)@end group@end example If you want to test @emph{only} whether the function was calledusing @code{call-interactively}, add an optional argument@code{print-message} which should be non-@code{nil} in an interactivecall, and use the @code{interactive} spec to make sure it isnon-@code{nil}. Here's an example:@example(defun foo (&optional print-message) (interactive "p") (when print-message (message "foo")))@end example@noindentDefined in this way, the function does display the message when calledfrom a keyboard macro. We use @code{"p"} because the numeric prefixargument is never @code{nil}.@defun called-interactively-pThis function returns @code{t} when the calling function was calledusing @code{call-interactively}.When possible, instead of using this function, you should use themethod in the example above; that method makes it possible for acaller to ``pretend'' that the function was called interactively.@end defun@node Command Loop Info@comment node-name, next, previous, up@section Information from the Command LoopThe editor command loop sets several Lisp variables to keep statusrecords for itself and for commands that are run.@defvar last-commandThis variable records the name of the previous command executed by thecommand loop (the one before the current command). Normally the valueis a symbol with a function definition, but this is not guaranteed.The value is copied from @code{this-command} when a command returns tothe command loop, except when the command has specified a prefixargument for the following command.This variable is always local to the current terminal and cannot bebuffer-local. @xref{Multiple Displays}.@end defvar@defvar real-last-commandThis variable is set up by Emacs just like @code{last-command},but never altered by Lisp programs.@end defvar@defvar this-command@cindex current commandThis variable records the name of the command now being executed bythe editor command loop. Like @code{last-command}, it is normally a symbolwith a function definition.The command loop sets this variable just before running a command, andcopies its value into @code{last-command} when the command finishes(unless the command specified a prefix argument for the followingcommand).@cindex kill command repetitionSome commands set this variable during their execution, as a flag forwhatever command runs next. In particular, the functions for killing textset @code{this-command} to @code{kill-region} so that any kill commandsimmediately following will know to append the killed text to theprevious kill.@end defvarIf you do not want a particular command to be recognized as the previouscommand in the case where it got an error, you must code that command toprevent this. One way is to set @code{this-command} to @code{t} at thebeginning of the command, and set @code{this-command} back to its propervalue at the end, like this:@example(defun foo (args@dots{}) (interactive @dots{}) (let ((old-this-command this-command)) (setq this-command t) @r{@dots{}do the work@dots{}} (setq this-command old-this-command)))@end example@noindentWe do not bind @code{this-command} with @code{let} because that wouldrestore the old value in case of error---a feature of @code{let} whichin this case does precisely what we want to avoid.@defvar this-original-commandThis has the same value as @code{this-command} except when commandremapping occurs (@pxref{Remapping Commands}). In that case,@code{this-command} gives the command actually run (the result ofremapping), and @code{this-original-command} gives the command thatwas specified to run but remapped into another command.@end defvar@defun this-command-keysThis function returns a string or vector containing the key sequencethat invoked the present command, plus any previous commands thatgenerated the prefix argument for this command. Any events read by thecommand using @code{read-event} without a timeout get tacked on to the end.However, if the command has called @code{read-key-sequence}, itreturns the last read key sequence. @xref{Key Sequence Input}. Thevalue is a string if all events in the sequence were characters thatfit in a string. @xref{Input Events}.@example@group(this-command-keys);; @r{Now use @kbd{C-u C-x C-e} to evaluate that.} @result{} "^U^X^E"@end group@end example@end defun@defun this-command-keys-vector@anchor{Definition of this-command-keys-vector}Like @code{this-command-keys}, except that it always returns the eventsin a vector, so you don't need to deal with the complexities of storinginput events in a string (@pxref{Strings of Events}).@end defun@defun clear-this-command-keys &optional keep-recordThis function empties out the table of events for@code{this-command-keys} to return. Unless @var{keep-record} isnon-@code{nil}, it also empties the records that the function@code{recent-keys} (@pxref{Recording Input}) will subsequently return.This is useful after reading a password, to prevent the password fromechoing inadvertently as part of the next command in certain cases.@end defun@defvar last-nonmenu-eventThis variable holds the last input event read as part of a key sequence,not counting events resulting from mouse menus.One use of this variable is for telling @code{x-popup-menu} where to popup a menu. It is also used internally by @code{y-or-n-p}(@pxref{Yes-or-No Queries}).@end defvar@defvar last-command-event@defvarx last-command-charThis variable is set to the last input event that was read by thecommand loop as part of a command. The principal use of this variableis in @code{self-insert-command}, which uses it to decide whichcharacter to insert.@example@grouplast-command-event;; @r{Now use @kbd{C-u C-x C-e} to evaluate that.} @result{} 5@end group@end example@noindentThe value is 5 because that is the @acronym{ASCII} code for @kbd{C-e}.The alias @code{last-command-char} exists for compatibility withEmacs version 18.@end defvar@c Emacs 19 feature@defvar last-event-frameThis variable records which frame the last input event was directed to.Usually this is the frame that was selected when the event wasgenerated, but if that frame has redirected input focus to anotherframe, the value is the frame to which the event was redirected.@xref{Input Focus}.If the last event came from a keyboard macro, the value is @code{macro}.@end defvar@node Adjusting Point@section Adjusting Point After Commands It is not easy to display a value of point in the middle of asequence of text that has the @code{display}, @code{composition} or@code{intangible} property, or is invisible. Therefore, after acommand finishes and returns to the command loop, if point is withinsuch a sequence, the command loop normally moves point to the edge ofthe sequence. A command can inhibit this feature by setting the variable@code{disable-point-adjustment}:@defvar disable-point-adjustmentIf this variable is non-@code{nil} when a command returns to thecommand loop, then the command loop does not check for those textproperties, and does not move point out of sequences that have them.The command loop sets this variable to @code{nil} before each command,so if a command sets it, the effect applies only to that command.@end defvar@defvar global-disable-point-adjustmentIf you set this variable to a non-@code{nil} value, the feature ofmoving point out of these sequences is completely turned off.@end defvar@node Input Events@section Input Events@cindex events@cindex input eventsThe Emacs command loop reads a sequence of @dfn{input events} thatrepresent keyboard or mouse activity. The events for keyboard activityare characters or symbols; mouse events are always lists. This sectiondescribes the representation and meaning of input events in detail.@defun eventp objectThis function returns non-@code{nil} if @var{object} is an input eventor event type.Note that any symbol might be used as an event or an event type.@code{eventp} cannot distinguish whether a symbol is intended by Lispcode to be used as an event. Instead, it distinguishes whether thesymbol has actually been used in an event that has been read as input inthe current Emacs session. If a symbol has not yet been so used,@code{eventp} returns @code{nil}.@end defun@menu* Keyboard Events:: Ordinary characters--keys with symbols on them.* Function Keys:: Function keys--keys with names, not symbols.* Mouse Events:: Overview of mouse events.* Click Events:: Pushing and releasing a mouse button.* Drag Events:: Moving the mouse before releasing the button.* Button-Down Events:: A button was pushed and not yet released.* Repeat Events:: Double and triple click (or drag, or down).* Motion Events:: Just moving the mouse, not pushing a button.* Focus Events:: Moving the mouse between frames.* Misc Events:: Other events the system can generate.* Event Examples:: Examples of the lists for mouse events.* Classifying Events:: Finding the modifier keys in an event symbol. Event types.* Accessing Events:: Functions to extract info from events.* Strings of Events:: Special considerations for putting keyboard character events in a string.@end menu@node Keyboard Events@subsection Keyboard EventsThere are two kinds of input you can get from the keyboard: ordinarykeys, and function keys. Ordinary keys correspond to characters; theevents they generate are represented in Lisp as characters. The eventtype of a character event is the character itself (an integer); see@ref{Classifying Events}.@cindex modifier bits (of input character)@cindex basic code (of input character)An input character event consists of a @dfn{basic code} between 0 and524287, plus any or all of these @dfn{modifier bits}:@table @asis@item metaThe@tex@math{2^{27}}@end tex@ifnottex2**27@end ifnottexbit in the character code indicates a charactertyped with the meta key held down.@item controlThe@tex@math{2^{26}}@end tex@ifnottex2**26@end ifnottexbit in the character code indicates a non-@acronym{ASCII}control character.@sc{ascii} control characters such as @kbd{C-a} have special basiccodes of their own, so Emacs needs no special bit to indicate them.Thus, the code for @kbd{C-a} is just 1.But if you type a control combination not in @acronym{ASCII}, such as@kbd{%} with the control key, the numeric value you get is the codefor @kbd{%} plus@tex@math{2^{26}}@end tex@ifnottex2**26@end ifnottex(assuming the terminal supports non-@acronym{ASCII}control characters).@item shiftThe@tex@math{2^{25}}@end tex@ifnottex2**25@end ifnottexbit in the character code indicates an @acronym{ASCII} controlcharacter typed with the shift key held down.For letters, the basic code itself indicates upper versus lower case;for digits and punctuation, the shift key selects an entirely differentcharacter with a different basic code. In order to keep within the@acronym{ASCII} character set whenever possible, Emacs avoids using the@tex@math{2^{25}}@end tex@ifnottex2**25@end ifnottexbit for those characters.However, @acronym{ASCII} provides no way to distinguish @kbd{C-A} from@kbd{C-a}, so Emacs uses the@tex@math{2^{25}}@end tex@ifnottex2**25@end ifnottexbit in @kbd{C-A} and not in@kbd{C-a}.@item hyperThe@tex@math{2^{24}}@end tex@ifnottex2**24@end ifnottexbit in the character code indicates a charactertyped with the hyper key held down.@item superThe@tex@math{2^{23}}@end tex@ifnottex2**23@end ifnottexbit in the character code indicates a charactertyped with the super key held down.@item altThe@tex@math{2^{22}}@end tex@ifnottex2**22@end ifnottexbit in the character code indicates a character typed withthe alt key held down. (On some terminals, the key labeled @key{ALT}is actually the meta key.)@end table It is best to avoid mentioning specific bit numbers in your program.To test the modifier bits of a character, use the function@code{event-modifiers} (@pxref{Classifying Events}). When making keybindings, you can use the read syntax for characters with modifier bits(@samp{\C-}, @samp{\M-}, and so on). For making key bindings with@code{define-key}, you can use lists such as @code{(control hyper ?x)} tospecify the characters (@pxref{Changing Key Bindings}). The function@code{event-convert-list} converts such a list into an event type(@pxref{Classifying Events}).@node Function Keys@subsection Function Keys@cindex function keysMost keyboards also have @dfn{function keys}---keys that have names orsymbols that are not characters. Function keys are represented in EmacsLisp as symbols; the symbol's name is the function key's label, in lowercase. For example, pressing a key labeled @key{F1} places the symbol@code{f1} in the input stream.The event type of a function key event is the event symbol itself.@xref{Classifying Events}.Here are a few special cases in the symbol-naming convention forfunction keys:@table @asis@item @code{backspace}, @code{tab}, @code{newline}, @code{return}, @code{delete}These keys correspond to common @acronym{ASCII} control characters that havespecial keys on most keyboards.In @acronym{ASCII}, @kbd{C-i} and @key{TAB} are the same character. If theterminal can distinguish between them, Emacs conveys the distinction toLisp programs by representing the former as the integer 9, and thelatter as the symbol @code{tab}.Most of the time, it's not useful to distinguish the two. So normally@code{function-key-map} (@pxref{Translation Keymaps}) is set up to map@code{tab} into 9. Thus, a key binding for character code 9 (thecharacter @kbd{C-i}) also applies to @code{tab}. Likewise for the othersymbols in this group. The function @code{read-char} likewise convertsthese events into characters.In @acronym{ASCII}, @key{BS} is really @kbd{C-h}. But @code{backspace}converts into the character code 127 (@key{DEL}), not into code 8(@key{BS}). This is what most users prefer.@item @code{left}, @code{up}, @code{right}, @code{down}Cursor arrow keys@item @code{kp-add}, @code{kp-decimal}, @code{kp-divide}, @dots{}Keypad keys (to the right of the regular keyboard).@item @code{kp-0}, @code{kp-1}, @dots{}Keypad keys with digits.@item @code{kp-f1}, @code{kp-f2}, @code{kp-f3}, @code{kp-f4}Keypad PF keys.@item @code{kp-home}, @code{kp-left}, @code{kp-up}, @code{kp-right}, @code{kp-down}Keypad arrow keys. Emacs normally translates these into thecorresponding non-keypad keys @code{home}, @code{left}, @dots{}@item @code{kp-prior}, @code{kp-next}, @code{kp-end}, @code{kp-begin}, @code{kp-insert}, @code{kp-delete}Additional keypad duplicates of keys ordinarily found elsewhere. Emacsnormally translates these into the like-named non-keypad keys.@end tableYou can use the modifier keys @key{ALT}, @key{CTRL}, @key{HYPER},@key{META}, @key{SHIFT}, and @key{SUPER} with function keys. The way torepresent them is with prefixes in the symbol name:@table @samp@item A-The alt modifier.@item C-The control modifier.@item H-The hyper modifier.@item M-The meta modifier.@item S-The shift modifier.@item s-The super modifier.@end tableThus, the symbol for the key @key{F3} with @key{META} held down is@code{M-f3}. When you use more than one prefix, we recommend youwrite them in alphabetical order; but the order does not matter inarguments to the key-binding lookup and modification functions.@node Mouse Events@subsection Mouse EventsEmacs supports four kinds of mouse events: click events, drag events,button-down events, and motion events. All mouse events are representedas lists. The @sc{car} of the list is the event type; this says whichmouse button was involved, and which modifier keys were used with it.The event type can also distinguish double or triple button presses(@pxref{Repeat Events}). The rest of the list elements give positionand time information.For key lookup, only the event type matters: two events of the same typenecessarily run the same command. The command can access the fullvalues of these events using the @samp{e} interactive code.@xref{Interactive Codes}.A key sequence that starts with a mouse event is read using the keymapsof the buffer in the window that the mouse was in, not the currentbuffer. This does not imply that clicking in a window selects thatwindow or its buffer---that is entirely under the control of the commandbinding of the key sequence.@node Click Events@subsection Click Events@cindex click event@cindex mouse click eventWhen the user presses a mouse button and releases it at the samelocation, that generates a @dfn{click} event. All mouse click eventshare the same format:@example(@var{event-type} @var{position} @var{click-count})@end example@table @asis@item @var{event-type}This is a symbol that indicates which mouse button was used. It isone of the symbols @code{mouse-1}, @code{mouse-2}, @dots{}, where thebuttons are numbered left to right.You can also use prefixes @samp{A-}, @samp{C-}, @samp{H-}, @samp{M-},@samp{S-} and @samp{s-} for modifiers alt, control, hyper, meta, shiftand super, just as you would with function keys.This symbol also serves as the event type of the event. Key bindingsdescribe events by their types; thus, if there is a key binding for@code{mouse-1}, that binding would apply to all events whose@var{event-type} is @code{mouse-1}.@item @var{position}This is the position where the mouse click occurred. The actualformat of @var{position} depends on what part of a window was clickedon. The various formats are described below.@item @var{click-count}This is the number of rapid repeated presses so far of the same mousebutton. @xref{Repeat Events}.@end tableFor mouse click events in the text area, mode line, header line, or inthe marginal areas, @var{position} has this form:@example(@var{window} @var{pos-or-area} (@var{x} . @var{y}) @var{timestamp} @var{object} @var{text-pos} (@var{col} . @var{row}) @var{image} (@var{dx} . @var{dy}) (@var{width} . @var{height}))@end example@table @asis@item @var{window}This is the window in which the click occurred.@item @var{pos-or-area}This is the buffer position of the character clicked on in the textarea, or if clicked outside the text area, it is the window area inwhich the click occurred. It is one of the symbols @code{mode-line},@code{header-line}, @code{vertical-line}, @code{left-margin},@code{right-margin}, @code{left-fringe}, or @code{right-fringe}.@item @var{x}, @var{y}These are the pixel-denominated coordinates of the click, relative tothe top left corner of @var{window}, which is @code{(0 . 0)}.For the mode or header line, @var{y} does not have meaningful data.For the vertical line, @var{x} does not have meaningful data.@item @var{timestamp}This is the time at which the event occurred, in milliseconds.@item @var{object}This is the object on which the click occurred. It is either@code{nil} if there is no string property, or it has the form(@var{string} . @var{string-pos}) when there is a string-type textproperty at the click position.@item @var{string}This is the string on which the click occurred, including anyproperties.@item @var{string-pos}This is the position in the string on which the click occurred,relevant if properties at the click need to be looked up.@item @var{text-pos}For clicks on a marginal area or on a fringe, this is the bufferposition of the first visible character in the corresponding line inthe window. For other events, it is the current buffer position inthe window.@item @var{col}, @var{row}These are the actual coordinates of the glyph under the @var{x},@var{y} position, possibly padded with default character widthglyphs if @var{x} is beyond the last glyph on the line.@item @var{image}This is the image object on which the click occurred. It is either@code{nil} if there is no image at the position clicked on, or it isan image object as returned by @code{find-image} if click was in an image.@item @var{dx}, @var{dy}These are the pixel-denominated coordinates of the click, relative tothe top left corner of @var{object}, which is @code{(0 . 0)}. If@var{object} is @code{nil}, the coordinates are relative to the topleft corner of the character glyph clicked on.@end tableFor mouse clicks on a scroll-bar, @var{position} has this form:@example(@var{window} @var{area} (@var{portion} . @var{whole}) @var{timestamp} @var{part})@end example@table @asis@item @var{window}This is the window whose scroll-bar was clicked on.@item @var{area}This is the scroll bar where the click occurred. It is one of thesymbols @code{vertical-scroll-bar} or @code{horizontal-scroll-bar}.@item @var{portion}This is the distance of the click from the top or left end ofthe scroll bar.@item @var{whole}This is the length of the entire scroll bar.@item @var{timestamp}This is the time at which the event occurred, in milliseconds.@item @var{part}This is the part of the scroll-bar which was clicked on. It is oneof the symbols @code{above-handle}, @code{handle}, @code{below-handle},@code{up}, @code{down}, @code{top}, @code{bottom}, and @code{end-scroll}.@end tableIn one special case, @var{buffer-pos} is a list containing a symbol (oneof the symbols listed above) instead of just the symbol. This happensafter the imaginary prefix keys for the event are inserted into theinput stream. @xref{Key Sequence Input}.@node Drag Events@subsection Drag Events@cindex drag event@cindex mouse drag eventWith Emacs, you can have a drag event without even changing yourclothes. A @dfn{drag event} happens every time the user presses a mousebutton and then moves the mouse to a different character position beforereleasing the button. Like all mouse events, drag events arerepresented in Lisp as lists. The lists record both the starting mouseposition and the final position, like this:@example(@var{event-type} (@var{window1} @var{buffer-pos1} (@var{x1} . @var{y1}) @var{timestamp1}) (@var{window2} @var{buffer-pos2} (@var{x2} . @var{y2}) @var{timestamp2}) @var{click-count})@end exampleFor a drag event, the name of the symbol @var{event-type} contains theprefix @samp{drag-}. For example, dragging the mouse with button 2 helddown generates a @code{drag-mouse-2} event. The second and thirdelements of the event give the starting and ending position of the drag.Aside from that, the data have the same meanings as in a click event(@pxref{Click Events}). You can access the second element of any mouseevent in the same way, with no need to distinguish drag events fromothers.The @samp{drag-} prefix follows the modifier key prefixes such as@samp{C-} and @samp{M-}.If @code{read-key-sequence} receives a drag event that has no keybinding, and the corresponding click event does have a binding, itchanges the drag event into a click event at the drag's startingposition. This means that you don't have to distinguish between clickand drag events unless you want to.@node Button-Down Events@subsection Button-Down Events@cindex button-down eventClick and drag events happen when the user releases a mouse button.They cannot happen earlier, because there is no way to distinguish aclick from a drag until the button is released.If you want to take action as soon as a button is pressed, you need tohandle @dfn{button-down} events.@footnote{Button-down is theconservative antithesis of drag.} These occur as soon as a button ispressed. They are represented by lists that look exactly like clickevents (@pxref{Click Events}), except that the @var{event-type} symbolname contains the prefix @samp{down-}. The @samp{down-} prefix followsmodifier key prefixes such as @samp{C-} and @samp{M-}.The function @code{read-key-sequence} ignores any button-down eventsthat don't have command bindings; therefore, the Emacs command loopignores them too. This means that you need not worry about definingbutton-down events unless you want them to do something. The usualreason to define a button-down event is so that you can track mousemotion (by reading motion events) until the button is released.@xref{Motion Events}.@node Repeat Events@subsection Repeat Events@cindex repeat events@cindex double-click events@cindex triple-click events@cindex mouse events, repeatedIf you press the same mouse button more than once in quick successionwithout moving the mouse, Emacs generates special @dfn{repeat} mouseevents for the second and subsequent presses.The most common repeat events are @dfn{double-click} events. Emacsgenerates a double-click event when you click a button twice; the eventhappens when you release the button (as is normal for all clickevents).The event type of a double-click event contains the prefix@samp{double-}. Thus, a double click on the second mouse button with@key{meta} held down comes to the Lisp program as@code{M-double-mouse-2}. If a double-click event has no binding, thebinding of the corresponding ordinary click event is used to executeit. Thus, you need not pay attention to the double click featureunless you really want to.When the user performs a double click, Emacs generates first an ordinaryclick event, and then a double-click event. Therefore, you must designthe command binding of the double click event to assume that thesingle-click command has already run. It must produce the desiredresults of a double click, starting from the results of a single click.This is convenient, if the meaning of a double click somehow ``buildson'' the meaning of a single click---which is recommended user interfacedesign practice for double clicks.If you click a button, then press it down again and start moving themouse with the button held down, then you get a @dfn{double-drag} eventwhen you ultimately release the button. Its event type contains@samp{double-drag} instead of just @samp{drag}. If a double-drag eventhas no binding, Emacs looks for an alternate binding as if the eventwere an ordinary drag.Before the double-click or double-drag event, Emacs generates a@dfn{double-down} event when the user presses the button down for thesecond time. Its event type contains @samp{double-down} instead of just@samp{down}. If a double-down event has no binding, Emacs looks for analternate binding as if the event were an ordinary button-down event.If it finds no binding that way either, the double-down event isignored.To summarize, when you click a button and then press it again rightaway, Emacs generates a down event and a click event for the firstclick, a double-down event when you press the button again, and finallyeither a double-click or a double-drag event.If you click a button twice and then press it again, all in quicksuccession, Emacs generates a @dfn{triple-down} event, followed byeither a @dfn{triple-click} or a @dfn{triple-drag}. The event types ofthese events contain @samp{triple} instead of @samp{double}. If anytriple event has no binding, Emacs uses the binding that it would usefor the corresponding double event.If you click a button three or more times and then press it again, theevents for the presses beyond the third are all triple events. Emacsdoes not have separate event types for quadruple, quintuple, etc.@:events. However, you can look at the event list to find out preciselyhow many times the button was pressed.@defun event-click-count eventThis function returns the number of consecutive button presses that ledup to @var{event}. If @var{event} is a double-down, double-click ordouble-drag event, the value is 2. If @var{event} is a triple event,the value is 3 or greater. If @var{event} is an ordinary mouse event(not a repeat event), the value is 1.@end defun@defopt double-click-fuzzTo generate repeat events, successive mouse button presses must be atapproximately the same screen position. The value of@code{double-click-fuzz} specifies the maximum number of pixels themouse may be moved (horizontally or vertically) between two successiveclicks to make a double-click.This variable is also the threshold for motion of the mouse to countas a drag.@end defopt@defopt double-click-timeTo generate repeat events, the number of milliseconds betweensuccessive button presses must be less than the value of@code{double-click-time}. Setting @code{double-click-time} to@code{nil} disables multi-click detection entirely. Setting it to@code{t} removes the time limit; Emacs then detects multi-clicks byposition only.@end defopt@node Motion Events@subsection Motion Events@cindex motion event@cindex mouse motion eventsEmacs sometimes generates @dfn{mouse motion} events to describe motionof the mouse without any button activity. Mouse motion events arerepresented by lists that look like this:@example(mouse-movement (@var{window} @var{buffer-pos} (@var{x} . @var{y}) @var{timestamp}))@end exampleThe second element of the list describes the current position of themouse, just as in a click event (@pxref{Click Events}).The special form @code{track-mouse} enables generation of motion eventswithin its body. Outside of @code{track-mouse} forms, Emacs does notgenerate events for mere motion of the mouse, and these events do notappear. @xref{Mouse Tracking}.@node Focus Events@subsection Focus Events@cindex focus eventWindow systems provide general ways for the user to control which windowgets keyboard input. This choice of window is called the @dfn{focus}.When the user does something to switch between Emacs frames, thatgenerates a @dfn{focus event}. The normal definition of a focus event,in the global keymap, is to select a new frame within Emacs, as the userwould expect. @xref{Input Focus}.Focus events are represented in Lisp as lists that look like this:@example(switch-frame @var{new-frame})@end example@noindentwhere @var{new-frame} is the frame switched to.Most X window managers are set up so that just moving the mouse into awindow is enough to set the focus there. Emacs appears to do this,because it changes the cursor to solid in the new frame. However, thereis no need for the Lisp program to know about the focus change untilsome other kind of input arrives. So Emacs generates a focus event onlywhen the user actually types a keyboard key or presses a mouse button inthe new frame; just moving the mouse between frames does not generate afocus event.A focus event in the middle of a key sequence would garble thesequence. So Emacs never generates a focus event in the middle of a keysequence. If the user changes focus in the middle of a keysequence---that is, after a prefix key---then Emacs reorders the eventsso that the focus event comes either before or after the multi-event keysequence, and not within it.@node Misc Events@subsection Miscellaneous System EventsA few other event types represent occurrences within the system.@table @code@cindex @code{delete-frame} event@item (delete-frame (@var{frame}))This kind of event indicates that the user gave the window managera command to delete a particular window, which happens to be an Emacs frame.The standard definition of the @code{delete-frame} event is to delete @var{frame}.@cindex @code{iconify-frame} event@item (iconify-frame (@var{frame}))This kind of event indicates that the user iconified @var{frame} usingthe window manager. Its standard definition is @code{ignore}; since theframe has already been iconified, Emacs has no work to do. The purposeof this event type is so that you can keep track of such events if youwant to.@cindex @code{make-frame-visible} event@item (make-frame-visible (@var{frame}))This kind of event indicates that the user deiconified @var{frame} usingthe window manager. Its standard definition is @code{ignore}; since theframe has already been made visible, Emacs has no work to do.@cindex @code{wheel-up} event@cindex @code{wheel-down} event@item (wheel-up @var{position})@item (wheel-down @var{position})These kinds of event are generated by moving a mouse wheel. Theirusual meaning is a kind of scroll or zoom.The element @var{position} is a list describing the position of theevent, in the same format as used in a mouse-click event.This kind of event is generated only on some kinds of systems. On somesystems, @code{mouse-4} and @code{mouse-5} are used instead. Forportable code, use the variables @code{mouse-wheel-up-event} and@code{mouse-wheel-down-event} defined in @file{mwheel.el} to determinewhat event types to expect for the mouse wheel.@cindex @code{drag-n-drop} event@item (drag-n-drop @var{position} @var{files})This kind of event is generated when a group of files isselected in an application outside of Emacs, and then dragged anddropped onto an Emacs frame.The element @var{position} is a list describing the position of theevent, in the same format as used in a mouse-click event, and@var{files} is the list of file names that were dragged and dropped.The usual way to handle this event is by visiting these files.This kind of event is generated, at present, only on some kinds ofsystems.@cindex @code{help-echo} event@item help-echoThis kind of event is generated when a mouse pointer moves onto aportion of buffer text which has a @code{help-echo} text property.The generated event has this form:@example(help-echo @var{frame} @var{help} @var{window} @var{object} @var{pos})@end example@noindentThe precise meaning of the event parameters and the way theseparameters are used to display the help-echo text are described in@ref{Text help-echo}.@cindex @code{signal usr1} event@cindex @code{signal usr2} event@cindex user signals@item signal usr1@itemx signal usr2These event sequences are generated when the Emacs process receivesthe signals @code{SIGUSR1} and @code{SIGUSR2}. They contain noadditional data because signals do not carry additional information.@end table If one of these events arrives in the middle of a key sequence---thatis, after a prefix key---then Emacs reorders the events so that thisevent comes either before or after the multi-event key sequence, notwithin it.@node Event Examples@subsection Event ExamplesIf the user presses and releases the left mouse button over the samelocation, that generates a sequence of events like this:@smallexample(down-mouse-1 (#<window 18 on NEWS> 2613 (0 . 38) -864320))(mouse-1 (#<window 18 on NEWS> 2613 (0 . 38) -864180))@end smallexampleWhile holding the control key down, the user might hold down thesecond mouse button, and drag the mouse from one line to the next.That produces two events, as shown here:@smallexample(C-down-mouse-2 (#<window 18 on NEWS> 3440 (0 . 27) -731219))(C-drag-mouse-2 (#<window 18 on NEWS> 3440 (0 . 27) -731219) (#<window 18 on NEWS> 3510 (0 . 28) -729648))@end smallexampleWhile holding down the meta and shift keys, the user might press thesecond mouse button on the window's mode line, and then drag the mouseinto another window. That produces a pair of events like these:@smallexample(M-S-down-mouse-2 (#<window 18 on NEWS> mode-line (33 . 31) -457844))(M-S-drag-mouse-2 (#<window 18 on NEWS> mode-line (33 . 31) -457844) (#<window 20 on carlton-sanskrit.tex> 161 (33 . 3) -453816))@end smallexampleTo handle a SIGUSR1 signal, define an interactive function, andbind it to the @code{signal usr1} event sequence:@smallexample(defun usr1-handler () (interactive) (message "Got USR1 signal"))(global-set-key [signal usr1] 'usr1-handler)@end smallexample@node Classifying Events@subsection Classifying Events@cindex event type Every event has an @dfn{event type}, which classifies the event forkey binding purposes. For a keyboard event, the event type equals theevent value; thus, the event type for a character is the character, andthe event type for a function key symbol is the symbol itself. Forevents that are lists, the event type is the symbol in the @sc{car} ofthe list. Thus, the event type is always a symbol or a character. Two events of the same type are equivalent where key bindings areconcerned; thus, they always run the same command. That does notnecessarily mean they do the same things, however, as some commands lookat the whole event to decide what to do. For example, some commands usethe location of a mouse event to decide where in the buffer to act. Sometimes broader classifications of events are useful. For example,you might want to ask whether an event involved the @key{META} key,regardless of which other key or mouse button was used. The functions @code{event-modifiers} and @code{event-basic-type} areprovided to get such information conveniently.@defun event-modifiers eventThis function returns a list of the modifiers that @var{event} has. Themodifiers are symbols; they include @code{shift}, @code{control},@code{meta}, @code{alt}, @code{hyper} and @code{super}. In addition,the modifiers list of a mouse event symbol always contains one of@code{click}, @code{drag}, and @code{down}. For double or tripleevents, it also contains @code{double} or @code{triple}.The argument @var{event} may be an entire event object, or just anevent type. If @var{event} is a symbol that has never been used in anevent that has been read as input in the current Emacs session, then@code{event-modifiers} can return @code{nil}, even when @var{event}actually has modifiers.Here are some examples:@example(event-modifiers ?a) @result{} nil(event-modifiers ?A) @result{} (shift)(event-modifiers ?\C-a) @result{} (control)(event-modifiers ?\C-%) @result{} (control)(event-modifiers ?\C-\S-a) @result{} (control shift)(event-modifiers 'f5) @result{} nil(event-modifiers 's-f5) @result{} (super)(event-modifiers 'M-S-f5) @result{} (meta shift)(event-modifiers 'mouse-1) @result{} (click)(event-modifiers 'down-mouse-1) @result{} (down)@end exampleThe modifiers list for a click event explicitly contains @code{click},but the event symbol name itself does not contain @samp{click}.@end defun@defun event-basic-type eventThis function returns the key or mouse button that @var{event}describes, with all modifiers removed. The @var{event} argument is asin @code{event-modifiers}. For example:@example(event-basic-type ?a) @result{} 97(event-basic-type ?A) @result{} 97(event-basic-type ?\C-a) @result{} 97(event-basic-type ?\C-\S-a) @result{} 97(event-basic-type 'f5) @result{} f5(event-basic-type 's-f5) @result{} f5(event-basic-type 'M-S-f5) @result{} f5(event-basic-type 'down-mouse-1) @result{} mouse-1@end example@end defun@defun mouse-movement-p objectThis function returns non-@code{nil} if @var{object} is a mouse movementevent.@end defun@defun event-convert-list listThis function converts a list of modifier names and a basic event typeto an event type which specifies all of them. The basic event typemust be the last element of the list. For example,@example(event-convert-list '(control ?a)) @result{} 1(event-convert-list '(control meta ?a)) @result{} -134217727(event-convert-list '(control super f1)) @result{} C-s-f1@end example@end defun@node Accessing Events@subsection Accessing Events@cindex mouse events, accessing the data@cindex accessing data of mouse events This section describes convenient functions for accessing the data ina mouse button or motion event. These two functions return the starting or ending position of amouse-button event, as a list of this form:@example(@var{window} @var{pos-or-area} (@var{x} . @var{y}) @var{timestamp} @var{object} @var{text-pos} (@var{col} . @var{row}) @var{image} (@var{dx} . @var{dy}) (@var{width} . @var{height}))@end example@defun event-start eventThis returns the starting position of @var{event}.If @var{event} is a click or button-down event, this returns thelocation of the event. If @var{event} is a drag event, this returns thedrag's starting position.@end defun@defun event-end eventThis returns the ending position of @var{event}.If @var{event} is a drag event, this returns the position where the userreleased the mouse button. If @var{event} is a click or button-downevent, the value is actually the starting position, which is the onlyposition such events have.@end defun@cindex mouse position list, accessing These functions take a position list as described above, andreturn various parts of it.@defun posn-window positionReturn the window that @var{position} is in.@end defun@defun posn-area positionReturn the window area recorded in @var{position}. It returns @code{nil}when the event occurred in the text area of the window; otherwise, itis a symbol identifying the area in which the event occurred.@end defun@defun posn-point positionReturn the buffer position in @var{position}. When the event occurredin the text area of the window, in a marginal area, or on a fringe,this is an integer specifying a buffer position. Otherwise, the valueis undefined.@end defun@defun posn-x-y positionReturn the pixel-based x and y coordinates in @var{position}, as acons cell @code{(@var{x} . @var{y})}. These coordinates are relativeto the window given by @code{posn-window}.This example shows how to convert these window-relative coordinatesinto frame-relative coordinates:@example(defun frame-relative-coordinates (position) "Return frame-relative coordinates from POSITION." (let* ((x-y (posn-x-y position)) (window (posn-window position)) (edges (window-inside-pixel-edges window))) (cons (+ (car x-y) (car edges)) (+ (cdr x-y) (cadr edges)))))@end example@end defun@defun posn-col-row positionReturn the row and column (in units of the frame's default characterheight and width) of @var{position}, as a cons cell @code{(@var{col} .@var{row})}. These are computed from the @var{x} and @var{y} valuesactually found in @var{position}.@end defun@defun posn-actual-col-row positionReturn the actual row and column in @var{position}, as a cons cell@code{(@var{col} . @var{row})}. The values are the actual row numberin the window, and the actual character number in that row. It returns@code{nil} if @var{position} does not include actual positions values.You can use @code{posn-col-row} to get approximate values.@end defun@defun posn-string positionReturn the string object in @var{position}, either @code{nil}, or acons cell @code{(@var{string} . @var{string-pos})}.@end defun@defun posn-image positionReturn the image object in @var{position}, either @code{nil}, or animage @code{(image ...)}.@end defun@defun posn-object positionReturn the image or string object in @var{position}, either@code{nil}, an image @code{(image ...)}, or a cons cell@code{(@var{string} . @var{string-pos})}.@end defun@defun posn-object-x-y positionReturn the pixel-based x and y coordinates relative to the upper leftcorner of the object in @var{position} as a cons cell @code{(@var{dx}. @var{dy})}. If the @var{position} is a buffer position, return therelative position in the character at that position.@end defun@defun posn-object-width-height positionReturn the pixel width and height of the object in @var{position} as acons cell @code{(@var{width} . @var{height})}. If the @var{position}is a buffer position, return the size of the character at that position.@end defun@cindex mouse event, timestamp@cindex timestamp of a mouse event@defun posn-timestamp positionReturn the timestamp in @var{position}. This is the time at which theevent occurred, in milliseconds.@end defun These functions compute a position list given particular bufferposition or screen position. You can access the data in this positionlist with the functions described above.@defun posn-at-point &optional pos windowThis function returns a position list for position @var{pos} in@var{window}. @var{pos} defaults to point in @var{window};@var{window} defaults to the selected window.@code{posn-at-point} returns @code{nil} if @var{pos} is not visible in@var{window}.@end defun@defun posn-at-x-y x y &optional frame-or-window wholeThis function returns position information corresponding to pixelcoordinates @var{x} and @var{y} in a specified frame or window,@var{frame-or-window}, which defaults to the selected window.The coordinates @var{x} and @var{y} are relative to theframe or window used.If @var{whole} is @code{nil}, the coordinates are relativeto the window text area, otherwise they are relative tothe entire window area including scroll bars, margins and fringes.@end defun These functions are useful for decoding scroll bar events.@defun scroll-bar-event-ratio eventThis function returns the fractional vertical position of a scroll barevent within the scroll bar. The value is a cons cell@code{(@var{portion} . @var{whole})} containing two integers whose ratiois the fractional position.@end defun@defun scroll-bar-scale ratio totalThis function multiplies (in effect) @var{ratio} by @var{total},rounding the result to an integer. The argument @var{ratio} is not anumber, but rather a pair @code{(@var{num} . @var{denom})}---typically avalue returned by @code{scroll-bar-event-ratio}.This function is handy for scaling a position on a scroll bar into abuffer position. Here's how to do that:@example(+ (point-min) (scroll-bar-scale (posn-x-y (event-start event)) (- (point-max) (point-min))))@end exampleRecall that scroll bar events have two integers forming a ratio, in placeof a pair of x and y coordinates.@end defun@node Strings of Events@subsection Putting Keyboard Events in Strings@cindex keyboard events in strings@cindex strings with keyboard events In most of the places where strings are used, we conceptualize thestring as containing text characters---the same kind of characters foundin buffers or files. Occasionally Lisp programs use strings thatconceptually contain keyboard characters; for example, they may be keysequences or keyboard macro definitions. However, storing keyboardcharacters in a string is a complex matter, for reasons of historicalcompatibility, and it is not always possible. We recommend that new programs avoid dealing with these complexitiesby not storing keyboard events in strings. Here is how to do that:@itemize @bullet@itemUse vectors instead of strings for key sequences, when you plan to usethem for anything other than as arguments to @code{lookup-key} and@code{define-key}. For example, you can use@code{read-key-sequence-vector} instead of @code{read-key-sequence}, and@code{this-command-keys-vector} instead of @code{this-command-keys}.@itemUse vectors to write key sequence constants containing meta characters,even when passing them directly to @code{define-key}.@itemWhen you have to look at the contents of a key sequence that might be astring, use @code{listify-key-sequence} (@pxref{Event Input Misc})first, to convert it to a list.@end itemize The complexities stem from the modifier bits that keyboard inputcharacters can include. Aside from the Meta modifier, none of thesemodifier bits can be included in a string, and the Meta modifier isallowed only in special cases. The earliest GNU Emacs versions represented meta characters as codesin the range of 128 to 255. At that time, the basic character codesranged from 0 to 127, so all keyboard character codes did fit in astring. Many Lisp programs used @samp{\M-} in string constants to standfor meta characters, especially in arguments to @code{define-key} andsimilar functions, and key sequences and sequences of events were alwaysrepresented as strings. When we added support for larger basic character codes beyond 127, andadditional modifier bits, we had to change the representation of metacharacters. Now the flag that represents the Meta modifier in acharacter is@tex@math{2^{27}}@end tex@ifnottex2**27@end ifnottexand such numbers cannot be included in a string. To support programs with @samp{\M-} in string constants, there arespecial rules for including certain meta characters in a string.Here are the rules for interpreting a string as a sequence of inputcharacters:@itemize @bullet@itemIf the keyboard character value is in the range of 0 to 127, it can goin the string unchanged.@itemThe meta variants of those characters, with codes in the range of@tex@math{2^{27}}@end tex@ifnottex2**27@end ifnottexto@tex@math{2^{27} + 127},@end tex@ifnottex2**27+127,@end ifnottexcan also go in the string, but you must change theirnumeric values. You must set the@tex@math{2^{7}}@end tex@ifnottex2**7@end ifnottexbit instead of the@tex@math{2^{27}}@end tex@ifnottex2**27@end ifnottexbit, resulting in a value between 128 and 255. Only a unibyte stringcan include these codes.@itemNon-@acronym{ASCII} characters above 256 can be included in a multibyte string.@itemOther keyboard character events cannot fit in a string. This includeskeyboard events in the range of 128 to 255.@end itemize Functions such as @code{read-key-sequence} that construct strings ofkeyboard input characters follow these rules: they construct vectorsinstead of strings, when the events won't fit in a string. When you use the read syntax @samp{\M-} in a string, it produces acode in the range of 128 to 255---the same code that you get if youmodify the corresponding keyboard event to put it in the string. Thus,meta events in strings work consistently regardless of how they get intothe strings. However, most programs would do well to avoid these issues byfollowing the recommendations at the beginning of this section.@node Reading Input@section Reading Input The editor command loop reads key sequences using the function@code{read-key-sequence}, which uses @code{read-event}. These and otherfunctions for event input are also available for use in Lisp programs.See also @code{momentary-string-display} in @ref{Temporary Displays},and @code{sit-for} in @ref{Waiting}. @xref{Terminal Input}, forfunctions and variables for controlling terminal input modes anddebugging terminal input. For higher-level input facilities, see @ref{Minibuffers}.@menu* Key Sequence Input:: How to read one key sequence.* Reading One Event:: How to read just one event.* Event Mod:: How Emacs modifies events as they are read.* Invoking the Input Method:: How reading an event uses the input method.* Quoted Character Input:: Asking the user to specify a character.* Event Input Misc:: How to reread or throw away input events.@end menu@node Key Sequence Input@subsection Key Sequence Input@cindex key sequence input The command loop reads input a key sequence at a time, by calling@code{read-key-sequence}. Lisp programs can also call this function;for example, @code{describe-key} uses it to read the key to describe.@defun read-key-sequence prompt &optional continue-echo dont-downcase-last switch-frame-ok command-loop@cindex key sequenceThis function reads a key sequence and returns it as a string orvector. It keeps reading events until it has accumulated a complete keysequence; that is, enough to specify a non-prefix command using thecurrently active keymaps. (Remember that a key sequence that startswith a mouse event is read using the keymaps of the buffer in thewindow that the mouse was in, not the current buffer.)If the events are all characters and all can fit in a string, then@code{read-key-sequence} returns a string (@pxref{Strings of Events}).Otherwise, it returns a vector, since a vector can hold all kinds ofevents---characters, symbols, and lists. The elements of the string orvector are the events in the key sequence.Reading a key sequence includes translating the events in variousways. @xref{Translation Keymaps}.The argument @var{prompt} is either a string to be displayed in theecho area as a prompt, or @code{nil}, meaning not to display a prompt.The argument @var{continue-echo}, if non-@code{nil}, means to echothis key as a continuation of the previous key.Normally any upper case event is converted to lower case if theoriginal event is undefined and the lower case equivalent is defined.The argument @var{dont-downcase-last}, if non-@code{nil}, means do notconvert the last event to lower case. This is appropriate for readinga key sequence to be defined.The argument @var{switch-frame-ok}, if non-@code{nil}, means that thisfunction should process a @code{switch-frame} event if the userswitches frames before typing anything. If the user switches framesin the middle of a key sequence, or at the start of the sequence but@var{switch-frame-ok} is @code{nil}, then the event will be put offuntil after the current key sequence.The argument @var{command-loop}, if non-@code{nil}, means that thiskey sequence is being read by something that will read commands oneafter another. It should be @code{nil} if the caller will read justone key sequence.In the following example, Emacs displays the prompt @samp{?} in theecho area, and then the user types @kbd{C-x C-f}.@example(read-key-sequence "?")@group---------- Echo Area ----------?@kbd{C-x C-f}---------- Echo Area ---------- @result{} "^X^F"@end group@end exampleThe function @code{read-key-sequence} suppresses quitting: @kbd{C-g}typed while reading with this function works like any other character,and does not set @code{quit-flag}. @xref{Quitting}.@end defun@defun read-key-sequence-vector prompt &optional continue-echo dont-downcase-last switch-frame-ok command-loopThis is like @code{read-key-sequence} except that it alwaysreturns the key sequence as a vector, never as a string.@xref{Strings of Events}.@end defun@cindex upper case key sequence@cindex downcasing in @code{lookup-key}If an input character is upper-case (or has the shift modifier) andhas no key binding, but its lower-case equivalent has one, then@code{read-key-sequence} converts the character to lower case. Notethat @code{lookup-key} does not perform case conversion in this way.The function @code{read-key-sequence} also transforms some mouse events.It converts unbound drag events into click events, and discards unboundbutton-down events entirely. It also reshuffles focus events andmiscellaneous window events so that they never appear in a key sequencewith any other events.@cindex @code{header-line} prefix key@cindex @code{mode-line} prefix key@cindex @code{vertical-line} prefix key@cindex @code{horizontal-scroll-bar} prefix key@cindex @code{vertical-scroll-bar} prefix key@cindex @code{menu-bar} prefix key@cindex mouse events, in special parts of frameWhen mouse events occur in special parts of a window, such as a modeline or a scroll bar, the event type shows nothing special---it is thesame symbol that would normally represent that combination of mousebutton and modifier keys. The information about the window part is keptelsewhere in the event---in the coordinates. But@code{read-key-sequence} translates this information into imaginary``prefix keys,'' all of which are symbols: @code{header-line},@code{horizontal-scroll-bar}, @code{menu-bar}, @code{mode-line},@code{vertical-line}, and @code{vertical-scroll-bar}. You can definemeanings for mouse clicks in special window parts by defining keysequences using these imaginary prefix keys.For example, if you call @code{read-key-sequence} and then click themouse on the window's mode line, you get two events, like this:@example(read-key-sequence "Click on the mode line: ") @result{} [mode-line (mouse-1 (#<window 6 on NEWS> mode-line (40 . 63) 5959987))]@end example@defvar num-input-keys@c Emacs 19 featureThis variable's value is the number of key sequences processed so far inthis Emacs session. This includes key sequences read from the terminaland key sequences read from keyboard macros being executed.@end defvar@node Reading One Event@subsection Reading One Event@cindex reading a single event@cindex event, reading only one The lowest level functions for command input are those that read asingle event.None of the three functions below suppresses quitting.@defun read-event &optional prompt inherit-input-method secondsThis function reads and returns the next event of command input, waitingif necessary until an event is available. Events can come directly fromthe user or from a keyboard macro.If the optional argument @var{prompt} is non-@code{nil}, it should be astring to display in the echo area as a prompt. Otherwise,@code{read-event} does not display any message to indicate it is waitingfor input; instead, it prompts by echoing: it displays descriptions ofthe events that led to or were read by the current command. @xref{TheEcho Area}.If @var{inherit-input-method} is non-@code{nil}, then the current inputmethod (if any) is employed to make it possible to enter anon-@acronym{ASCII} character. Otherwise, input method handling is disabledfor reading this event.If @code{cursor-in-echo-area} is non-@code{nil}, then @code{read-event}moves the cursor temporarily to the echo area, to the end of any messagedisplayed there. Otherwise @code{read-event} does not move the cursor.If @var{seconds} is non-@code{nil}, it should be a number specifyingthe maximum time to wait for input, in seconds. If no input arriveswithin that time, @code{read-event} stops waiting and returns@code{nil}. A floating-point value for @var{seconds} means to waitfor a fractional number of seconds. Some systems support only a wholenumber of seconds; on these systems, @var{seconds} is rounded down.If @var{seconds} is @code{nil}, @code{read-event} waits as long asnecessary for input to arrive.If @var{seconds} is @code{nil}, Emacs is considered idle while waitingfor user input to arrive. Idle timers---those created with@code{run-with-idle-timer} (@pxref{Idle Timers})---can run during thisperiod. However, if @var{seconds} is non-@code{nil}, the state ofidleness remains unchanged. If Emacs is non-idle when@code{read-event} is called, it remains non-idle throughout theoperation of @code{read-event}; if Emacs is idle (which can happen ifthe call happens inside an idle timer), it remains idle.If @code{read-event} gets an event that is defined as a help character,then in some cases @code{read-event} processes the event directly withoutreturning. @xref{Help Functions}. Certain other events, called@dfn{special events}, are also processed directly within@code{read-event} (@pxref{Special Events}).Here is what happens if you call @code{read-event} and then press theright-arrow function key:@example@group(read-event) @result{} right@end group@end example@end defun@defun read-char &optional prompt inherit-input-method secondsThis function reads and returns a character of command input. If theuser generates an event which is not a character (i.e. a mouse click orfunction key event), @code{read-char} signals an error. The argumentswork as in @code{read-event}.In the first example, the user types the character @kbd{1} (@acronym{ASCII}code 49). The second example shows a keyboard macro definition thatcalls @code{read-char} from the minibuffer using @code{eval-expression}.@code{read-char} reads the keyboard macro's very next character, whichis @kbd{1}. Then @code{eval-expression} displays its return value inthe echo area.@example@group(read-char) @result{} 49@end group@group;; @r{We assume here you use @kbd{M-:} to evaluate this.}(symbol-function 'foo) @result{} "^[:(read-char)^M1"@end group@group(execute-kbd-macro 'foo) @print{} 49 @result{} nil@end group@end example@end defun@defun read-char-exclusive &optional prompt inherit-input-method secondsThis function reads and returns a character of command input. If theuser generates an event which is not a character,@code{read-char-exclusive} ignores it and reads another event, until itgets a character. The arguments work as in @code{read-event}.@end defun@defvar num-nonmacro-input-eventsThis variable holds the total number of input events received so farfrom the terminal---not counting those generated by keyboard macros.@end defvar@node Event Mod@subsection Modifying and Translating Input Events Emacs modifies every event it reads according to@code{extra-keyboard-modifiers}, then translates it through@code{keyboard-translate-table} (if applicable), before returning itfrom @code{read-event}.@c Emacs 19 feature@defvar extra-keyboard-modifiersThis variable lets Lisp programs ``press'' the modifier keys on thekeyboard. The value is a character. Only the modifiers of thecharacter matter. Each time the user types a keyboard key, it isaltered as if those modifier keys were held down. For instance, ifyou bind @code{extra-keyboard-modifiers} to @code{?\C-\M-a}, then allkeyboard input characters typed during the scope of the binding willhave the control and meta modifiers applied to them. The character@code{?\C-@@}, equivalent to the integer 0, does not count as a controlcharacter for this purpose, but as a character with no modifiers.Thus, setting @code{extra-keyboard-modifiers} to zero cancels anymodification.When using a window system, the program can ``press'' any of themodifier keys in this way. Otherwise, only the @key{CTL} and @key{META}keys can be virtually pressed.Note that this variable applies only to events that really come fromthe keyboard, and has no effect on mouse events or any other events.@end defvar@defvar keyboard-translate-tableThis variable is the translate table for keyboard characters. It letsyou reshuffle the keys on the keyboard without changing any commandbindings. Its value is normally a char-table, or else @code{nil}.(It can also be a string or vector, but this is considered obsolete.)If @code{keyboard-translate-table} is a char-table(@pxref{Char-Tables}), then each character read from the keyboard islooked up in this char-table. If the value found there isnon-@code{nil}, then it is used instead of the actual input character.Note that this translation is the first thing that happens to acharacter after it is read from the terminal. Record-keeping featuressuch as @code{recent-keys} and dribble files record the characters aftertranslation.Note also that this translation is done before the characters aresupplied to input methods (@pxref{Input Methods}). Use@code{translation-table-for-input} (@pxref{Translation of Characters}),if you want to translate characters after input methods operate.@end defvar@defun keyboard-translate from toThis function modifies @code{keyboard-translate-table} to translatecharacter code @var{from} into character code @var{to}. It createsthe keyboard translate table if necessary.@end defun Here's an example of using the @code{keyboard-translate-table} tomake @kbd{C-x}, @kbd{C-c} and @kbd{C-v} perform the cut, copy and pasteoperations:@example(keyboard-translate ?\C-x 'control-x)(keyboard-translate ?\C-c 'control-c)(keyboard-translate ?\C-v 'control-v)(global-set-key [control-x] 'kill-region)(global-set-key [control-c] 'kill-ring-save)(global-set-key [control-v] 'yank)@end example@noindentOn a graphical terminal that supports extended @acronym{ASCII} input,you can still get the standard Emacs meanings of one of thosecharacters by typing it with the shift key. That makes it a differentcharacter as far as keyboard translation is concerned, but it has thesame usual meaning. @xref{Translation Keymaps}, for mechanisms that translate event sequencesat the level of @code{read-key-sequence}.@node Invoking the Input Method@subsection Invoking the Input Method The event-reading functions invoke the current input method, if any(@pxref{Input Methods}). If the value of @code{input-method-function}is non-@code{nil}, it should be a function; when @code{read-event} readsa printing character (including @key{SPC}) with no modifier bits, itcalls that function, passing the character as an argument.@defvar input-method-functionIf this is non-@code{nil}, its value specifies the current input methodfunction.@strong{Warning:} don't bind this variable with @code{let}. It is oftenbuffer-local, and if you bind it around reading input (which is exactlywhen you @emph{would} bind it), switching buffers asynchronously whileEmacs is waiting will cause the value to be restored in the wrongbuffer.@end defvar The input method function should return a list of events which shouldbe used as input. (If the list is @code{nil}, that means there is noinput, so @code{read-event} waits for another event.) These events areprocessed before the events in @code{unread-command-events}(@pxref{Event Input Misc}). Eventsreturned by the input method function are not passed to the input methodfunction again, even if they are printing characters with no modifierbits. If the input method function calls @code{read-event} or@code{read-key-sequence}, it should bind @code{input-method-function} to@code{nil} first, to prevent recursion. The input method function is not called when reading the second andsubsequent events of a key sequence. Thus, these characters are notsubject to input method processing. The input method function shouldtest the values of @code{overriding-local-map} and@code{overriding-terminal-local-map}; if either of these variables isnon-@code{nil}, the input method should put its argument into a list andreturn that list with no further processing.@node Quoted Character Input@subsection Quoted Character Input@cindex quoted character input You can use the function @code{read-quoted-char} to ask the user tospecify a character, and allow the user to specify a control or metacharacter conveniently, either literally or as an octal character code.The command @code{quoted-insert} uses this function.@defun read-quoted-char &optional prompt@cindex octal character input@cindex control characters, reading@cindex nonprinting characters, readingThis function is like @code{read-char}, except that if the firstcharacter read is an octal digit (0-7), it reads any number of octaldigits (but stopping if a non-octal digit is found), and returns thecharacter represented by that numeric character code. If thecharacter that terminates the sequence of octal digits is @key{RET},it is discarded. Any other terminating character is used as inputafter this function returns.Quitting is suppressed when the first character is read, so that theuser can enter a @kbd{C-g}. @xref{Quitting}.If @var{prompt} is supplied, it specifies a string for prompting theuser. The prompt string is always displayed in the echo area, followedby a single @samp{-}.In the following example, the user types in the octal number 177 (whichis 127 in decimal).@example(read-quoted-char "What character")@group---------- Echo Area ----------What character @kbd{1 7 7}----------- Echo Area ---------- @result{} 127@end group@end example@end defun@need 2000@node Event Input Misc@subsection Miscellaneous Event Input FeaturesThis section describes how to ``peek ahead'' at events without usingthem up, how to check for pending input, and how to discard pendinginput. See also the function @code{read-passwd} (@pxref{Reading aPassword}).@defvar unread-command-events@cindex next input@cindex peeking at inputThis variable holds a list of events waiting to be read as commandinput. The events are used in the order they appear in the list, andremoved one by one as they are used.The variable is needed because in some cases a function reads an eventand then decides not to use it. Storing the event in this variablecauses it to be processed normally, by the command loop or by thefunctions to read command input.@cindex prefix argument unreadingFor example, the function that implements numeric prefix arguments readsany number of digits. When it finds a non-digit event, it must unreadthe event so that it can be read normally by the command loop.Likewise, incremental search uses this feature to unread events with nospecial meaning in a search, because these events should exit the searchand then execute normally.The reliable and easy way to extract events from a key sequence so as toput them in @code{unread-command-events} is to use@code{listify-key-sequence} (@pxref{Strings of Events}).Normally you add events to the front of this list, so that the eventsmost recently unread will be reread first.Events read from this list are not normally added to the currentcommand's key sequence (as returned by e.g. @code{this-command-keys}),as the events will already have been added once as they were read forthe first time. An element of the form @code{(@code{t} . @var{event})}forces @var{event} to be added to the current command's key sequence.@end defvar@defun listify-key-sequence keyThis function converts the string or vector @var{key} to a list ofindividual events, which you can put in @code{unread-command-events}.@end defun@defvar unread-command-charThis variable holds a character to be read as command input.A value of -1 means ``empty.''This variable is mostly obsolete now that you can use@code{unread-command-events} instead; it exists only to support programswritten for Emacs versions 18 and earlier.@end defvar@defun input-pending-p@cindex waiting for command key inputThis function determines whether any command input is currentlyavailable to be read. It returns immediately, with value @code{t} ifthere is available input, @code{nil} otherwise. On rare occasions itmay return @code{t} when no input is available.@end defun@defvar last-input-event@defvarx last-input-charThis variable records the last terminal input event read, whetheras part of a command or explicitly by a Lisp program.In the example below, the Lisp program reads the character @kbd{1},@acronym{ASCII} code 49. It becomes the value of @code{last-input-event},while @kbd{C-e} (we assume @kbd{C-x C-e} command is used to evaluatethis expression) remains the value of @code{last-command-event}.@example@group(progn (print (read-char)) (print last-command-event) last-input-event) @print{} 49 @print{} 5 @result{} 49@end group@end exampleThe alias @code{last-input-char} exists for compatibility withEmacs version 18.@end defvar@defmac while-no-input body@dots{}This construct runs the @var{body} forms and returns the value of thelast one---but only if no input arrives. If any input arrives duringthe execution of the @var{body} forms, it aborts them (working muchlike a quit). The @code{while-no-input} form returns @code{nil} ifaborted by a real quit, and returns @code{t} if aborted by arrival ofother input.If a part of @var{body} binds @code{inhibit-quit} to non-@code{nil},arrival of input during those parts won't cause an abort untilthe end of that part.If you want to be able to distinguish all possible values computedby @var{body} from both kinds of abort conditions, write the codelike this:@example(while-no-input (list (progn . @var{body})))@end example@end defmac@defun discard-input@cindex flush input@cindex discard input@cindex terminate keyboard macroThis function discards the contents of the terminal input buffer andcancels any keyboard macro that might be in the process of definition.It returns @code{nil}.In the following example, the user may type a number of characters rightafter starting the evaluation of the form. After the @code{sleep-for}finishes sleeping, @code{discard-input} discards any characters typedduring the sleep.@example(progn (sleep-for 2) (discard-input)) @result{} nil@end example@end defun@node Special Events@section Special Events@cindex special eventsSpecial events are handled at a very low level---as soon as they areread. The @code{read-event} function processes these events itself, andnever returns them. Instead, it keeps waiting for the first eventthat is not special and returns that one.Events that are handled in this way do not echo, they are never groupedinto key sequences, and they never appear in the value of@code{last-command-event} or @code{(this-command-keys)}. They do notdiscard a numeric argument, they cannot be unread with@code{unread-command-events}, they may not appear in a keyboard macro,and they are not recorded in a keyboard macro while you are definingone.These events do, however, appear in @code{last-input-event} immediatelyafter they are read, and this is the way for the event's definition tofind the actual event.The events types @code{iconify-frame}, @code{make-frame-visible} and@code{delete-frame} are normally handled in this way. The keymap whichdefines how to handle special events---and which events are special---isin the variable @code{special-event-map} (@pxref{Active Keymaps}).@node Waiting@section Waiting for Elapsed Time or Input@cindex pausing@cindex waiting The wait functions are designed to wait for a certain amount of timeto pass or until there is input. For example, you may wish to pause inthe middle of a computation to allow the user time to view the display.@code{sit-for} pauses and updates the screen, and returns immediately ifinput comes in, while @code{sleep-for} pauses without updating thescreen.@defun sit-for seconds &optional nodispThis function performs redisplay (provided there is no pending inputfrom the user), then waits @var{seconds} seconds, or until input isavailable. The usual purpose of @code{sit-for} is to give the usertime to read text that you display. The value is @code{t} if@code{sit-for} waited the full time with no input arriving(@pxref{Event Input Misc}). Otherwise, the value is @code{nil}.The argument @var{seconds} need not be an integer. If it is a floatingpoint number, @code{sit-for} waits for a fractional number of seconds.Some systems support only a whole number of seconds; on these systems,@var{seconds} is rounded down.The expression @code{(sit-for 0)} is equivalent to @code{(redisplay)},i.e. it requests a redisplay, without any delay, if there is no pending input.@xref{Forcing Redisplay}.If @var{nodisp} is non-@code{nil}, then @code{sit-for} does notredisplay, but it still returns as soon as input is available (or whenthe timeout elapses).In batch mode (@pxref{Batch Mode}), @code{sit-for} cannot beinterrupted, even by input from the standard input descriptor. It isthus equivalent to @code{sleep-for}, which is described below.It is also possible to call @code{sit-for} with three arguments,as @code{(sit-for @var{seconds} @var{millisec} @var{nodisp})},but that is considered obsolete.@end defun@defun sleep-for seconds &optional millisecThis function simply pauses for @var{seconds} seconds without updatingthe display. It pays no attention to available input. It returns@code{nil}.The argument @var{seconds} need not be an integer. If it is a floatingpoint number, @code{sleep-for} waits for a fractional number of seconds.Some systems support only a whole number of seconds; on these systems,@var{seconds} is rounded down.The optional argument @var{millisec} specifies an additional waitingperiod measured in milliseconds. This adds to the period specified by@var{seconds}. If the system doesn't support waiting fractions of asecond, you get an error if you specify nonzero @var{millisec}.Use @code{sleep-for} when you wish to guarantee a delay.@end defun @xref{Time of Day}, for functions to get the current time.@node Quitting@section Quitting@cindex @kbd{C-g}@cindex quitting@cindex interrupt Lisp functions Typing @kbd{C-g} while a Lisp function is running causes Emacs to@dfn{quit} whatever it is doing. This means that control returns to theinnermost active command loop. Typing @kbd{C-g} while the command loop is waiting for keyboard inputdoes not cause a quit; it acts as an ordinary input character. In thesimplest case, you cannot tell the difference, because @kbd{C-g}normally runs the command @code{keyboard-quit}, whose effect is to quit.However, when @kbd{C-g} follows a prefix key, they combine to form anundefined key. The effect is to cancel the prefix key as well as anyprefix argument. In the minibuffer, @kbd{C-g} has a different definition: it aborts outof the minibuffer. This means, in effect, that it exits the minibufferand then quits. (Simply quitting would return to the command loop@emph{within} the minibuffer.) The reason why @kbd{C-g} does not quitdirectly when the command reader is reading input is so that its meaningcan be redefined in the minibuffer in this way. @kbd{C-g} following aprefix key is not redefined in the minibuffer, and it has its normaleffect of canceling the prefix key and prefix argument. This toowould not be possible if @kbd{C-g} always quit directly. When @kbd{C-g} does directly quit, it does so by setting the variable@code{quit-flag} to @code{t}. Emacs checks this variable at appropriatetimes and quits if it is not @code{nil}. Setting @code{quit-flag}non-@code{nil} in any way thus causes a quit. At the level of C code, quitting cannot happen just anywhere; only at thespecial places that check @code{quit-flag}. The reason for this isthat quitting at other places might leave an inconsistency in Emacs'sinternal state. Because quitting is delayed until a safe place, quittingcannot make Emacs crash. Certain functions such as @code{read-key-sequence} or@code{read-quoted-char} prevent quitting entirely even though they waitfor input. Instead of quitting, @kbd{C-g} serves as the requestedinput. In the case of @code{read-key-sequence}, this serves to bringabout the special behavior of @kbd{C-g} in the command loop. In thecase of @code{read-quoted-char}, this is so that @kbd{C-q} can be usedto quote a @kbd{C-g}.@cindex prevent quitting You can prevent quitting for a portion of a Lisp function by bindingthe variable @code{inhibit-quit} to a non-@code{nil} value. Then,although @kbd{C-g} still sets @code{quit-flag} to @code{t} as usual, theusual result of this---a quit---is prevented. Eventually,@code{inhibit-quit} will become @code{nil} again, such as when itsbinding is unwound at the end of a @code{let} form. At that time, if@code{quit-flag} is still non-@code{nil}, the requested quit happensimmediately. This behavior is ideal when you wish to make sure thatquitting does not happen within a ``critical section'' of the program.@cindex @code{read-quoted-char} quitting In some functions (such as @code{read-quoted-char}), @kbd{C-g} ishandled in a special way that does not involve quitting. This is doneby reading the input with @code{inhibit-quit} bound to @code{t}, andsetting @code{quit-flag} to @code{nil} before @code{inhibit-quit}becomes @code{nil} again. This excerpt from the definition of@code{read-quoted-char} shows how this is done; it also shows thatnormal quitting is permitted after the first character of input.@example(defun read-quoted-char (&optional prompt) "@dots{}@var{documentation}@dots{}" (let ((message-log-max nil) done (first t) (code 0) char) (while (not done) (let ((inhibit-quit first) @dots{}) (and prompt (message "%s-" prompt)) (setq char (read-event)) (if inhibit-quit (setq quit-flag nil))) @r{@dots{}set the variable @code{code}@dots{}}) code))@end example@defvar quit-flagIf this variable is non-@code{nil}, then Emacs quits immediately, unless@code{inhibit-quit} is non-@code{nil}. Typing @kbd{C-g} ordinarily sets@code{quit-flag} non-@code{nil}, regardless of @code{inhibit-quit}.@end defvar@defvar inhibit-quitThis variable determines whether Emacs should quit when @code{quit-flag}is set to a value other than @code{nil}. If @code{inhibit-quit} isnon-@code{nil}, then @code{quit-flag} has no special effect.@end defvar@defmac with-local-quit body@dots{}This macro executes @var{body} forms in sequence, but allows quitting, atleast locally, within @var{body} even if @code{inhibit-quit} wasnon-@code{nil} outside this construct. It returns the value of thelast form in @var{body}, unless exited by quitting, in which caseit returns @code{nil}.If @code{inhibit-quit} is @code{nil} on entry to @code{with-local-quit},it only executes the @var{body}, and setting @code{quit-flag} causesa normal quit. However, if @code{inhibit-quit} is non-@code{nil} sothat ordinary quitting is delayed, a non-@code{nil} @code{quit-flag}triggers a special kind of local quit. This ends the execution of@var{body} and exits the @code{with-local-quit} body with@code{quit-flag} still non-@code{nil}, so that another (ordinary) quitwill happen as soon as that is allowed. If @code{quit-flag} isalready non-@code{nil} at the beginning of @var{body}, the local quithappens immediately and the body doesn't execute at all.This macro is mainly useful in functions that can be called fromtimers, process filters, process sentinels, @code{pre-command-hook},@code{post-command-hook}, and other places where @code{inhibit-quit} isnormally bound to @code{t}.@end defmac@deffn Command keyboard-quitThis function signals the @code{quit} condition with @code{(signal 'quitnil)}. This is the same thing that quitting does. (See @code{signal}in @ref{Errors}.)@end deffn You can specify a character other than @kbd{C-g} to use for quitting.See the function @code{set-input-mode} in @ref{Terminal Input}.@node Prefix Command Arguments@section Prefix Command Arguments@cindex prefix argument@cindex raw prefix argument@cindex numeric prefix argument Most Emacs commands can use a @dfn{prefix argument}, a numberspecified before the command itself. (Don't confuse prefix argumentswith prefix keys.) The prefix argument is at all times represented by avalue, which may be @code{nil}, meaning there is currently no prefixargument. Each command may use the prefix argument or ignore it. There are two representations of the prefix argument: @dfn{raw} and@dfn{numeric}. The editor command loop uses the raw representationinternally, and so do the Lisp variables that store the information, butcommands can request either representation. Here are the possible values of a raw prefix argument:@itemize @bullet@item@code{nil}, meaning there is no prefix argument. Its numeric value is1, but numerous commands make a distinction between @code{nil} and theinteger 1.@itemAn integer, which stands for itself.@itemA list of one element, which is an integer. This form of prefixargument results from one or a succession of @kbd{C-u}'s with nodigits. The numeric value is the integer in the list, but somecommands make a distinction between such a list and an integer alone.@itemThe symbol @code{-}. This indicates that @kbd{M--} or @kbd{C-u -} wastyped, without following digits. The equivalent numeric value is@minus{}1, but some commands make a distinction between the integer@minus{}1 and the symbol @code{-}.@end itemizeWe illustrate these possibilities by calling the following function withvarious prefixes:@example@group(defun display-prefix (arg) "Display the value of the raw prefix arg." (interactive "P") (message "%s" arg))@end group@end example@noindentHere are the results of calling @code{display-prefix} with variousraw prefix arguments:@example M-x display-prefix @print{} nilC-u M-x display-prefix @print{} (4)C-u C-u M-x display-prefix @print{} (16)C-u 3 M-x display-prefix @print{} 3M-3 M-x display-prefix @print{} 3 ; @r{(Same as @code{C-u 3}.)}C-u - M-x display-prefix @print{} -M-- M-x display-prefix @print{} - ; @r{(Same as @code{C-u -}.)}C-u - 7 M-x display-prefix @print{} -7M-- 7 M-x display-prefix @print{} -7 ; @r{(Same as @code{C-u -7}.)}@end example Emacs uses two variables to store the prefix argument:@code{prefix-arg} and @code{current-prefix-arg}. Commands such as@code{universal-argument} that set up prefix arguments for othercommands store them in @code{prefix-arg}. In contrast,@code{current-prefix-arg} conveys the prefix argument to the currentcommand, so setting it has no effect on the prefix arguments for futurecommands. Normally, commands specify which representation to use for the prefixargument, either numeric or raw, in the @code{interactive} specification.(@xref{Using Interactive}.) Alternatively, functions may look at thevalue of the prefix argument directly in the variable@code{current-prefix-arg}, but this is less clean.@defun prefix-numeric-value argThis function returns the numeric meaning of a valid raw prefix argumentvalue, @var{arg}. The argument may be a symbol, a number, or a list.If it is @code{nil}, the value 1 is returned; if it is @code{-}, thevalue @minus{}1 is returned; if it is a number, that number is returned;if it is a list, the @sc{car} of that list (which should be a number) isreturned.@end defun@defvar current-prefix-argThis variable holds the raw prefix argument for the @emph{current}command. Commands may examine it directly, but the usual method foraccessing it is with @code{(interactive "P")}.@end defvar@defvar prefix-argThe value of this variable is the raw prefix argument for the@emph{next} editing command. Commands such as @code{universal-argument}that specify prefix arguments for the following command work by settingthis variable.@end defvar@defvar last-prefix-argThe raw prefix argument value used by the previous command.@end defvar The following commands exist to set up prefix arguments for thefollowing command. Do not call them for any other reason.@deffn Command universal-argumentThis command reads input and specifies a prefix argument for thefollowing command. Don't call this command yourself unless you knowwhat you are doing.@end deffn@deffn Command digit-argument argThis command adds to the prefix argument for the following command. Theargument @var{arg} is the raw prefix argument as it was before thiscommand; it is used to compute the updated prefix argument. Don't callthis command yourself unless you know what you are doing.@end deffn@deffn Command negative-argument argThis command adds to the numeric argument for the next command. Theargument @var{arg} is the raw prefix argument as it was before thiscommand; its value is negated to form the new prefix argument. Don'tcall this command yourself unless you know what you are doing.@end deffn@node Recursive Editing@section Recursive Editing@cindex recursive command loop@cindex recursive editing level@cindex command loop, recursive The Emacs command loop is entered automatically when Emacs starts up.This top-level invocation of the command loop never exits; it keepsrunning as long as Emacs does. Lisp programs can also invoke thecommand loop. Since this makes more than one activation of the commandloop, we call it @dfn{recursive editing}. A recursive editing level hasthe effect of suspending whatever command invoked it and permitting theuser to do arbitrary editing before resuming that command. The commands available during recursive editing are the same onesavailable in the top-level editing loop and defined in the keymaps.Only a few special commands exit the recursive editing level; the othersreturn to the recursive editing level when they finish. (The specialcommands for exiting are always available, but they do nothing whenrecursive editing is not in progress.) All command loops, including recursive ones, set up all-purpose errorhandlers so that an error in a command run from the command loop willnot exit the loop.@cindex minibuffer input Minibuffer input is a special kind of recursive editing. It has a fewspecial wrinkles, such as enabling display of the minibuffer and theminibuffer window, but fewer than you might suppose. Certain keysbehave differently in the minibuffer, but that is only because of theminibuffer's local map; if you switch windows, you get the usual Emacscommands.@cindex @code{throw} example@kindex exit@cindex exit recursive editing@cindex aborting To invoke a recursive editing level, call the function@code{recursive-edit}. This function contains the command loop; it alsocontains a call to @code{catch} with tag @code{exit}, which makes itpossible to exit the recursive editing level by throwing to @code{exit}(@pxref{Catch and Throw}). If you throw a value other than @code{t},then @code{recursive-edit} returns normally to the function that calledit. The command @kbd{C-M-c} (@code{exit-recursive-edit}) does this.Throwing a @code{t} value causes @code{recursive-edit} to quit, so thatcontrol returns to the command loop one level up. This is called@dfn{aborting}, and is done by @kbd{C-]} (@code{abort-recursive-edit}). Most applications should not use recursive editing, except as part ofusing the minibuffer. Usually it is more convenient for the user if youchange the major mode of the current buffer temporarily to a specialmajor mode, which should have a command to go back to the previous mode.(The @kbd{e} command in Rmail uses this technique.) Or, if you wish togive the user different text to edit ``recursively,'' create and selecta new buffer in a special mode. In this mode, define a command tocomplete the processing and go back to the previous buffer. (The@kbd{m} command in Rmail does this.) Recursive edits are useful in debugging. You can insert a call to@code{debug} into a function definition as a sort of breakpoint, so thatyou can look around when the function gets there. @code{debug} invokesa recursive edit but also provides the other features of the debugger. Recursive editing levels are also used when you type @kbd{C-r} in@code{query-replace} or use @kbd{C-x q} (@code{kbd-macro-query}).@defun recursive-edit@cindex suspend evaluationThis function invokes the editor command loop. It is calledautomatically by the initialization of Emacs, to let the user beginediting. When called from a Lisp program, it enters a recursive editinglevel.If the current buffer is not the same as the selected window's buffer,@code{recursive-edit} saves and restores the current buffer. Otherwise,if you switch buffers, the buffer you switched to is current after@code{recursive-edit} returns.In the following example, the function @code{simple-rec} firstadvances point one word, then enters a recursive edit, printing out amessage in the echo area. The user can then do any editing desired, andthen type @kbd{C-M-c} to exit and continue executing @code{simple-rec}.@example(defun simple-rec () (forward-word 1) (message "Recursive edit in progress") (recursive-edit) (forward-word 1)) @result{} simple-rec(simple-rec) @result{} nil@end example@end defun@deffn Command exit-recursive-editThis function exits from the innermost recursive edit (includingminibuffer input). Its definition is effectively @code{(throw 'exitnil)}.@end deffn@deffn Command abort-recursive-editThis function aborts the command that requested the innermost recursiveedit (including minibuffer input), by signaling @code{quit}after exiting the recursive edit. Its definition is effectively@code{(throw 'exit t)}. @xref{Quitting}.@end deffn@deffn Command top-levelThis function exits all recursive editing levels; it does not return avalue, as it jumps completely out of any computation directly back tothe main command loop.@end deffn@defun recursion-depthThis function returns the current depth of recursive edits. When norecursive edit is active, it returns 0.@end defun@node Disabling Commands@section Disabling Commands@cindex disabled command @dfn{Disabling a command} marks the command as requiring userconfirmation before it can be executed. Disabling is used for commandswhich might be confusing to beginning users, to prevent them from usingthe commands by accident.@kindex disabled The low-level mechanism for disabling a command is to put anon-@code{nil} @code{disabled} property on the Lisp symbol for thecommand. These properties are normally set up by the user'sinit file (@pxref{Init File}) with Lisp expressions such as this:@example(put 'upcase-region 'disabled t)@end example@noindentFor a few commands, these properties are present by default (you canremove them in your init file if you wish). If the value of the @code{disabled} property is a string, the messagesaying the command is disabled includes that string. For example:@example(put 'delete-region 'disabled "Text deleted this way cannot be yanked back!\n")@end example @xref{Disabling,,, emacs, The GNU Emacs Manual}, for the details onwhat happens when a disabled command is invoked interactively.Disabling a command has no effect on calling it as a function from Lispprograms.@deffn Command enable-command commandAllow @var{command} (a symbol) to be executed without specialconfirmation from now on, and alter the user's init file (@pxref{InitFile}) so that this will apply to future sessions.@end deffn@deffn Command disable-command commandRequire special confirmation to execute @var{command} from now on, andalter the user's init file so that this will apply to future sessions.@end deffn@defvar disabled-command-functionThe value of this variable should be a function. When the userinvokes a disabled command interactively, this function is calledinstead of the disabled command. It can use @code{this-command-keys}to determine what the user typed to run the command, and thus find thecommand itself.The value may also be @code{nil}. Then all commands work normally,even disabled ones.By default, the value is a function that asks the user whether toproceed.@end defvar@node Command History@section Command History@cindex command history@cindex complex command@cindex history of commands The command loop keeps a history of the complex commands that havebeen executed, to make it convenient to repeat these commands. A@dfn{complex command} is one for which the interactive argument readinguses the minibuffer. This includes any @kbd{M-x} command, any@kbd{M-:} command, and any command whose @code{interactive}specification reads an argument from the minibuffer. Explicit use ofthe minibuffer during the execution of the command itself does not causethe command to be considered complex.@defvar command-historyThis variable's value is a list of recent complex commands, eachrepresented as a form to evaluate. It continues to accumulate allcomplex commands for the duration of the editing session, but when itreaches the maximum size (@pxref{Minibuffer History}), the oldestelements are deleted as new ones are added.@example@groupcommand-history@result{} ((switch-to-buffer "chistory.texi") (describe-key "^X^[") (visit-tags-table "~/emacs/src/") (find-tag "repeat-complex-command"))@end group@end example@end defvar This history list is actually a special case of minibuffer history(@pxref{Minibuffer History}), with one special twist: the elements areexpressions rather than strings. There are a number of commands devoted to the editing and recall ofprevious commands. The commands @code{repeat-complex-command}, and@code{list-command-history} are described in the user manual(@pxref{Repetition,,, emacs, The GNU Emacs Manual}). Within theminibuffer, the usual minibuffer history commands are available.@node Keyboard Macros@section Keyboard Macros@cindex keyboard macros A @dfn{keyboard macro} is a canned sequence of input events that canbe considered a command and made the definition of a key. The Lisprepresentation of a keyboard macro is a string or vector containing theevents. Don't confuse keyboard macros with Lisp macros(@pxref{Macros}).@defun execute-kbd-macro kbdmacro &optional count loopfuncThis function executes @var{kbdmacro} as a sequence of events. If@var{kbdmacro} is a string or vector, then the events in it are executedexactly as if they had been input by the user. The sequence is@emph{not} expected to be a single key sequence; normally a keyboardmacro definition consists of several key sequences concatenated.If @var{kbdmacro} is a symbol, then its function definition is used inplace of @var{kbdmacro}. If that is another symbol, this process repeats.Eventually the result should be a string or vector. If the result isnot a symbol, string, or vector, an error is signaled.The argument @var{count} is a repeat count; @var{kbdmacro} is executed thatmany times. If @var{count} is omitted or @code{nil}, @var{kbdmacro} isexecuted once. If it is 0, @var{kbdmacro} is executed over and over until itencounters an error or a failing search.If @var{loopfunc} is non-@code{nil}, it is a function that is called,without arguments, prior to each iteration of the macro. If@var{loopfunc} returns @code{nil}, then this stops execution of the macro.@xref{Reading One Event}, for an example of using @code{execute-kbd-macro}.@end defun@defvar executing-kbd-macroThis variable contains the string or vector that defines the keyboardmacro that is currently executing. It is @code{nil} if no macro iscurrently executing. A command can test this variable so as to behavedifferently when run from an executing macro. Do not set this variableyourself.@end defvar@defvar defining-kbd-macroThis variable is non-@code{nil} if and only if a keyboard macro isbeing defined. A command can test this variable so as to behavedifferently while a macro is being defined. The value is@code{append} while appending to the definition of an existing macro.The commands @code{start-kbd-macro}, @code{kmacro-start-macro} and@code{end-kbd-macro} set this variable---do not set it yourself.The variable is always local to the current terminal and cannot bebuffer-local. @xref{Multiple Displays}.@end defvar@defvar last-kbd-macroThis variable is the definition of the most recently defined keyboardmacro. Its value is a string or vector, or @code{nil}.The variable is always local to the current terminal and cannot bebuffer-local. @xref{Multiple Displays}.@end defvar@defvar kbd-macro-termination-hookThis normal hook (@pxref{Standard Hooks}) is run when a keyboardmacro terminates, regardless of what caused it to terminate (reachingthe macro end or an error which ended the macro prematurely).@end defvar@ignore arch-tag: e34944ad-7d5c-4980-be00-36a5fe54d4b1@end ignore