Command Loop
************

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

Command Loop Overview
=====================

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

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

Prior to executing the command, Emacs runs undo-boundary to create an undo boundary.  See Maintaining Undo.

To execute a command, Emacs first reads its arguments by calling command-execute (see Interactive Call).  For commands written in Lisp, the interactive specification says how to read the arguments.  This may use the prefix argument (see Prefix Command Arguments) or may read with prompting in the minibuffer (see Minibuffers).  For example, the command find-file has an interactive specification which says to read a file name using the minibuffer.  The function body of find-file does not use the minibuffer, so if you call find-file as a function from Lisp code, you must supply the file name string as an ordinary Lisp function argument.

If the command is a keyboard macro (i.e., a string or vector), Emacs executes it using execute-kbd-macro (see Keyboard Macros).

 -- Variable: pre-command-hook
     This normal hook is run by the editor command loop before it executes each command.  At that time, this-command contains the command that is about to run, and last-command describes the previous command.  See Command Loop Info.

 -- Variable: post-command-hook
     This normal hook is run by the editor command loop after it executes each command (including commands terminated prematurely by quitting or by errors).  At that time, this-command refers to the command that just ran, and last-command refers to the command before that.

     This hook is also run when Emacs first enters the command loop (at which point this-command and last-command are both nil).

Quitting is suppressed while running pre-command-hook and post-command-hook.  If an error happens while executing one of these hooks, it does not terminate execution of the hook; instead the error is silenced and the function in which the error occurred is removed from the hook.

A request coming into the Emacs server (see Emacs Server (The GNU Emacs Manual)) runs these two hooks just as a keyboard command does.

Note that, when the buffer text includes very long lines, these two hooks are called as if they were in a with-restriction form (see Narrowing), with a long-line-optimizations-in-command-hooks label and with the buffer narrowed to a portion around point.

Defining Commands
=================

The special form interactive turns a Lisp function into a command.  The interactive form must be located at top-level in the function body, usually as the first form in the body; this applies to both lambda expressions (see Lambda Expressions) and defun forms (see Defining Functions).  This form does nothing during the actual execution of the function; its presence serves as a flag, telling the Emacs command loop that the function can be called interactively.  The argument of the interactive form specifies how the arguments for an interactive call should be read.

Alternatively, an interactive form may be specified in a function symbol's interactive-form property.  A non-nil value for this property takes precedence over any interactive form in the function body itself.  This feature is seldom used.

Sometimes, a function is only intended to be called interactively, never directly from Lisp.  In that case, give the function a non-nil interactive-only property, either directly or via declare (see Declare Form).  This causes the byte compiler to warn if the command is called from Lisp.  The output of describe-function will include similar information. The value of the property can be: a string, which the byte-compiler will use directly in its warning (it should end with a period, and not start with a capital, e.g., "use (system-name) instead."); t; any other symbol, which should be an alternative function to use in Lisp code.

Generic functions (see Generic Functions) cannot be turned into commands by adding the interactive form to them.

Using interactive
-----------------

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

 -- Special Form: interactive &optional arg-descriptor &rest modes
     This special form declares that a function is a command, and that it may therefore be called interactively (via M-x or by entering a key sequence bound to it).  The argument ARG-DESCRIPTOR declares how to compute the arguments to the command when the command is called interactively.

     A command may be called from Lisp programs like any other function, but then the caller supplies the arguments and ARG-DESCRIPTOR has no effect.

     The interactive form must be located at top-level in the function body, or in the function symbol's interactive-form property (see Symbol Properties).  It has its effect because the command loop looks for it before calling the function (see Interactive Call).  Once the function is called, all its body forms are executed; at this time, if the interactive form occurs within the body, the form simply returns nil without even evaluating its argument.

     The MODES list allows specifying which modes the command is meant to be used in.  See Command Modes for more details about the effect of specifying MODES, and when to use it.

     By convention, you should put the interactive form in the function body, as the first top-level form.  If there is an interactive form in both the interactive-form symbol property and the function body, the former takes precedence.  The interactive-form symbol property can be used to add an interactive form to an existing function, or change how its arguments are processed interactively, without redefining the function.

There are three possibilities for the argument ARG-DESCRIPTOR:

  * It may be omitted or nil; then the command is called with no arguments.  This leads quickly to an error if the command requires one or more arguments.

  * It may be a string; its contents are a sequence of elements separated by newlines, one for each argument (Some elements actually supply two arguments.).  Each element consists of a code character (see Interactive Codes) optionally followed by a prompt (which some code characters use and some ignore).  Here is an example:

          (interactive "P\nbFrobnicate buffer: ")

     The code letter P sets the command's first argument to the raw command prefix (see Prefix Command Arguments).  bFrobnicate buffer:  prompts the user with Frobnicate buffer:  to enter the name of an existing buffer, which becomes the second and final argument.

     The prompt string can use % to include previous argument values (starting with the first argument) in the prompt.  This is done using format-message (see Formatting Strings).  For example, here is how you could read the name of an existing buffer followed by a new name to give to that buffer:

          (interactive "bBuffer to rename: \nsRename buffer %s to: ")

     If * appears at the beginning of the string, then an error is signaled if the buffer is read-only.

     If @ appears at the beginning of the string, and if the key sequence used to invoke the command includes any mouse events, then the window associated with the first of those events is selected before the command is run.

     If ^ appears at the beginning of the string, and if the command was invoked through shift-translation, set the mark and activate the region temporarily, or extend an already active region, before the command is run.  If the command was invoked without shift-translation, and the region is temporarily active, deactivate the region before the command is run.  Shift-translation is controlled on the user level by shift-select-mode; see Shift Selection (The GNU Emacs Manual).

     You can use *, @, and ^ together; the order does not matter.  Actual reading of arguments is controlled by the rest of the prompt string (starting with the first character that is not *, @, or ^).

  * It may be a Lisp expression that is not a string; then it should be a form that is evaluated to get a list of arguments to pass to the command.  Usually this form will call various functions to read input from the user, most often through the minibuffer (see Minibuffers) or directly from the keyboard (see Reading Input).

     Providing point or the mark as an argument value is also common, but if you do this and read input (whether using the minibuffer or not), be sure to get the integer values of point or the mark after reading.  The current buffer may be receiving subprocess output; if subprocess output arrives while the command is waiting for input, it could relocate point and the mark.

     Here's an example of what not to do:

          (interactive
           (list (region-beginning) (region-end)
                 (read-string "Foo: " nil 'my-history)))

     Here's how to avoid the problem, by examining point and the mark after reading the keyboard input:

          (interactive
           (let ((string (read-string "Foo: " nil 'my-history)))
             (list (region-beginning) (region-end) string)))

     Warning: the argument values should not include any data types that can't be printed and then read.  Some facilities save command-history in a file to be read in the subsequent sessions; if a command's arguments contain a data type that prints using #<...> syntax, those facilities won't work.

     There are, however, a few exceptions: it is ok to use a limited set of expressions such as (point), (mark), (region-beginning), and (region-end), because Emacs recognizes them specially and puts the expression (rather than its value) into the command history.  To see whether the expression you wrote is one of these exceptions, run the command, then examine (car command-history).

 -- Function: interactive-form function
     This function returns the interactive form of FUNCTION. If FUNCTION is an interactively callable function (see Interactive Call), the value is the command's interactive form (interactive SPEC), which specifies how to compute its arguments.  Otherwise, the value is nil.  If FUNCTION is a symbol, its function definition is used. When called on an OClosure, the work is delegated to the generic function oclosure-interactive-form.

 -- Function: oclosure-interactive-form function
     Just like interactive-form, this function takes a command and returns its interactive form.  The difference is that it is a generic function and it is only called when FUNCTION is an OClosure (see OClosures).  The purpose is to make it possible for some OClosure types to compute their interactive forms dynamically instead of carrying it in one of their slots.

     This is used for example for kmacro functions in order to reduce their memory size, since they all share the same interactive form.  It is also used for advice functions, where the interactive form is computed from the interactive forms of its components, so as to make this computation more lazily and to correctly adjust the interactive form when one of its component's is redefined.

Code Characters for interactive
-------------------------------

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

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

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

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

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

     Even though the code letter doesn't use a prompt string, you must follow it with a newline if it is not the last code character in the string.

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

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

Here are the code character descriptions for use with interactive:

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

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

^
     If the command was invoked through shift-translation, set the mark and activate the region temporarily, or extend an already active region, before the command is run.  If the command was invoked without shift-translation, and the region is temporarily active, deactivate the region before the command is run.  Special.

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

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

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

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

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

d
     The position of point, as an integer (see Point).  No I/O.

D
     A directory.  The default is the current default directory of the current buffer, default-directory (see File Name Expansion). Existing, Completion, Default, Prompt.

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

     You use e for mouse events and for special system events (see Misc Events).  The event list that the command receives depends on the event.  See Input Events, which describes the forms of the list for each event in the corresponding subsections.

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

f
     A file name of an existing file (see File Names).  See Reading File Names, for details about default values.  Existing, Completion, Default, Prompt.

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

G
     A file name.  The file need not exist.  If the user enters just a directory name, then the value is just that directory name, with no file name within the directory added.  Completion, Default, Prompt.

i
     An irrelevant argument.  This code always supplies nil as the argument's value.  No I/O.

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

     If k reads a key sequence that ends with a down-event, it also reads and discards the following up-event.  You can get access to that up-event with the U code character.

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

K
     A key sequence on a form that can be used as input to functions like keymap-set.  This works like k, except that it suppresses, for the last input event in the key sequence, the conversions that are normally used (when necessary) to convert an undefined key into a defined one (see Key Sequence Input), so this form is usually used when prompting for a new key sequence that is to be bound to a command.

m
     The position of the mark, as an integer.  No I/O.

M
     Arbitrary text, read in the minibuffer using the current buffer's input method, and returned as a string (see Input Methods (The GNU Emacs Manual)).  Prompt.

n
     A number, read with the minibuffer.  If the input is not a number, the user has to try again.  n never uses the prefix argument. Prompt.

N
     The numeric prefix argument; but if there is no prefix argument, read a number as with n.  The value is always a number.  See Prefix Command Arguments.  Prompt.

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

P
     The raw prefix argument.  (Note that this P is upper case.)  No I/O.

r
     Point and the mark, as two numeric arguments, smallest first.  This is the only code letter that specifies two successive arguments rather than one.  This will signal an error if the mark is not set in the buffer which is current when the command is invoked.  If Transient Mark mode is turned on (see The Mark) --- as it is by default --- and user option mark-even-if-inactive is nil, Emacs will signal an error even if the mark is set, but is inactive.  No I/O.

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

S
     An interned symbol whose name is read in the minibuffer.  Terminate the input with either C-j or RET.  Other characters that normally terminate a symbol (e.g., whitespace, parentheses and brackets) do not do so here.  Prompt.

U
     A key sequence or nil.  Can be used after a k or K argument to get the up-event that was discarded (if any) after k or K read a down-event.  If no up-event has been discarded, U provides nil as the argument.  No I/O.

v
     A variable declared to be a user option (i.e., satisfying the predicate custom-variable-p).  This reads the variable using read-variable.  See Definition of read-variable.  Existing, Completion, Prompt.

x
     A Lisp object, specified with its read syntax, terminated with a C-j or RET.  The object is not evaluated.  See Object from Minibuffer.  Prompt.

X
     A Lisp form's value.  X reads as x does, then evaluates the form so that its value becomes the argument for the command. Prompt.

z
     A coding system name (a symbol).  If the user enters null input, the argument value is nil.  See Coding Systems.  Completion, Existing, Prompt.

Z
     A coding system name (a symbol)---but only if this command has a prefix argument.  With no prefix argument, Z provides nil as the argument value.  Completion, Existing, Prompt.

Examples of Using interactive
-----------------------------

Here are some examples of interactive:

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

     (defun foo2 (n)             ; foo2 takes one argument,
         (interactive "^p")      ;   which is the numeric prefix.
                                 ; under shift-select-mode,
                                 ;   will activate or extend region.
         (forward-word (* 2 n)))
          => foo2

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

     (defun three-b (b1 b2 b3)
       "Select three existing buffers.
     Put them into three windows, selecting the last one."

         (interactive "bBuffer1:\nbBuffer2:\nbBuffer3:")
         (delete-other-windows)
         (split-window (selected-window) 8)
         (switch-to-buffer b1)
         (other-window 1)
         (split-window (selected-window) 8)
         (switch-to-buffer b2)
         (other-window 1)
         (switch-to-buffer b3))
          => three-b

     (three-b "*scratch*" "declarations.texi" "*mail*")
          => nil

Specifying Modes For Commands
-----------------------------

Many commands in Emacs are general, and not tied to any specific mode. For instance, M-x kill-region can be used in pretty much any mode that has editable text, and commands that display information (like M-x list-buffers) can be used in pretty much any context.

Many other commands, however, are specifically tied to a mode, and make no sense outside of that context.  For instance, M-x dired-diff will just signal an error if used outside of a Dired buffer.

Emacs therefore has a mechanism for specifying what mode (or modes) a command ``belongs'' to:

     (defun dired-diff (...)
       ...
       (interactive "p" dired-mode)
       ...)

This will mark the command as applicable to dired-mode only (or any modes that are derived from dired-mode).  Any number of modes can be added to the interactive form.

Specifying modes affects command completion in M-S-x (execute-extended-command-for-buffer, see Interactive Call).  It may also affect completion in M-x, depending on the value of read-extended-command-predicate.

For instance, when using the command-completion-default-include-p predicate as the value of read-extended-command-predicate, M-x won't list commands that have been marked as being applicable to a specific mode (unless you are in a buffer that uses that mode, of course).  This goes for both major and minor modes.  (By contrast, M-S-x always omits inapplicable commands from the completion candidates.)

By default, read-extended-command-predicate is nil, and completion in M-x lists all the commands that match what the user has typed, whether those commands are or aren't marked as applicable to the current buffer's mode.

Marking commands to be applicable to a mode will also make C-h m list these commands (if they aren't bound to any keys).

If using this extended interactive form isn't convenient (because the code is supposed to work in older versions of Emacs that don't support the extended interactive form), the following equivalent declaration (see Declare Form) can be used instead:

     (declare (modes dired-mode))

Which commands to tag with modes is to some degree a matter of taste, but commands that clearly do not work outside of the mode should be tagged.  This includes commands that will signal an error if called from somewhere else, but also commands that are destructive when called from an unexpected mode.  (This usually includes most of the commands that are written for special (i.e., non-editing) modes.)

Some commands may be harmless, and ``work'' when called from other modes, but should still be tagged with a mode if they don't actually make much sense to use elsewhere.  For instance, many special modes have commands to exit the buffer bound to q, and may not do anything but issue a message like "Goodbye from this mode" and then call kill-buffer.  This command will ``work'' from any mode, but it is highly unlikely that anybody would actually want to use the command outside the context of this special mode.

Many modes have a set of different commands that start the mode in different ways (e.g., eww-open-in-new-buffer and eww-open-file).  Commands like that should never be tagged as mode-specific, as they can be issued by the user from pretty much any context.

Select among Command Alternatives
---------------------------------

The macro define-alternatives can be used to define generic commands.  These are interactive functions whose implementation can be selected from several alternatives, as a matter of user preference.

 -- Macro: define-alternatives command &rest customizations
     Define the new command COMMAND, a symbol.

     When a user runs M-x COMMAND RET for the first time, Emacs prompts for which real form of the command to use, and records the selection by way of a custom variable.  Using a prefix argument repeats this process of choosing an alternative.

     The variable COMMAND-alternatives should contain an alist with alternative implementations of COMMAND. Until this variable is set, define-alternatives has no effect.

     If CUSTOMIZATIONS is non-nil, it should consist of alternating defcustom keywords (typically :group and :version) and values to add to the declaration of COMMAND-alternatives.

Interactive Call
================

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

Note that the term ``command'', in this context, refers to an interactively callable function (or function-like object), or a keyboard macro.  It does not refer to the key sequence used to invoke a command (see Keymaps).

 -- Function: commandp object &optional for-call-interactively
     This function returns t if OBJECT is a command. Otherwise, it returns nil.

     Commands include strings and vectors (which are treated as keyboard macros), lambda expressions that contain a top-level interactive form (see Using Interactive), byte-code function objects made from such lambda expressions, autoload objects that are declared as interactive (non-nil fourth argument to autoload), and some primitive functions.  Also, a symbol is considered a command if it has a non-nil interactive-form property, or if its function definition satisfies commandp.

     If FOR-CALL-INTERACTIVELY is non-nil, then commandp returns t only for objects that call-interactively could call---thus, not for keyboard macros.

     See documentation in Accessing Documentation, for a realistic example of using commandp.

 -- Function: call-interactively command &optional record-flag keys
     This function calls the interactively callable function COMMAND, providing arguments according to its interactive calling specifications. It returns whatever COMMAND returns.

     If, for instance, you have a function with the following signature:

          (defun foo (begin end)
            (interactive "r")
            ...)

     then saying

          (call-interactively 'foo)

     will call foo with the region (point and mark) as the arguments.

     An error is signaled if COMMAND is not a function or if it cannot be called interactively (i.e., is not a command).  Note that keyboard macros (strings and vectors) are not accepted, even though they are considered commands, because they are not functions.  If COMMAND is a symbol, then call-interactively uses its function definition.

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

     The argument KEYS, if given, should be a vector which specifies the sequence of events to supply if the command inquires which events were used to invoke it.  If KEYS is omitted or nil, the default is the return value of this-command-keys-vector. See Definition of this-command-keys-vector.

 -- Function: funcall-interactively function &rest arguments
     This function works like funcall (see Calling Functions), but it makes the call look like an interactive invocation: a call to called-interactively-p inside FUNCTION will return t.  If FUNCTION is not a command, it is called without signaling an error.

 -- Function: command-execute command &optional record-flag keys special
     This function executes COMMAND.  The argument COMMAND must satisfy the commandp predicate; i.e., it must be an interactively callable function or a keyboard macro.

     A string or vector as COMMAND is executed with execute-kbd-macro.  A function is passed to call-interactively (see above), along with the RECORD-FLAG and KEYS arguments.

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

     The argument SPECIAL, if given, means to ignore the prefix argument and not clear it.  This is used for executing special events (see Special Events).

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

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

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

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

     This command heeds the read-extended-command-predicate variable, which can filter out commands that are not applicable to the current major mode (or enabled minor modes).  By default, the value of this variable is nil, and no commands are filtered out. However, customizing it to invoke the function command-completion-default-include-p will perform mode-dependent filtering.  read-extended-command-predicate can be any predicate function; it will be called with two parameters: the command's symbol and the current buffer.  If should return non-nil if the command is to be included when completing in that buffer.

 -- Command: execute-extended-command-for-buffer prefix-argument
     This is like execute-extended-command, but limits the commands offered for completion to those commands that are of particular relevance to the current major mode (and enabled minor modes).  This includes commands that are tagged with the modes (see Using Interactive), and also commands that are bound to locally active keymaps.  This command is the normal definition of M-S-x (that's ``meta shift x'').

Both these commands prompt for a command name, but with different completion rules.  You can toggle between these two modes by using the M-S-x command while being prompted.

Distinguish Interactive Calls
=============================

Sometimes a command should display additional visual feedback (such as an informative message in the echo area) for interactive calls only.  There are three ways to do this.  The recommended way to test whether the function was called using call-interactively is to give it an optional argument print-message and use the interactive spec to make it non-nil in interactive calls.  Here's an example:

     (defun foo (&optional print-message)
       (interactive "p")
       (when print-message
         (message "foo")))

We use "p" because the numeric prefix argument is never nil.  Defined in this way, the function does display the message when called from a keyboard macro.

The above method with the additional argument is usually best, because it allows callers to say ``treat this call as interactive''. But you can also do the job by testing called-interactively-p.

 -- Function: called-interactively-p kind
     This function returns t when the calling function was called using call-interactively.

     The argument KIND should be either the symbol interactive or the symbol any.  If it is interactive, then called-interactively-p returns t only if the call was made directly by the user---e.g., if the user typed a key sequence bound to the calling function, but not if the user ran a keyboard macro that called the function (see Keyboard Macros).  If KIND is any, called-interactively-p returns t for any kind of interactive call, including keyboard macros.

     If in doubt, use any; the only known proper use of interactive is if you need to decide whether to display a helpful message while a function is running.

     A function is never considered to be called interactively if it was called via Lisp evaluation (or with apply or funcall).

Here is an example of using called-interactively-p:

     (defun foo ()
       (interactive)
       (when (called-interactively-p 'any)
         (message "Interactive!")
         'foo-called-interactively))

     ;; Type M-x foo.
          -| Interactive!

     (foo)
          => nil

Here is another example that contrasts direct and indirect calls to called-interactively-p.

     (defun bar ()
       (interactive)
       (message "%s" (list (foo) (called-interactively-p 'any))))

     ;; Type M-x bar.
          -| (nil t)

Information from the Command Loop
=================================

The editor command loop sets several Lisp variables to keep status records for itself and for commands that are run.  With the exception of this-command and last-command it's generally a bad idea to change any of these variables in a Lisp program.

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

     The value is copied from this-command when a command returns to the command loop, except when the command has specified a prefix argument for the following command.

     This variable is always local to the current terminal and cannot be buffer-local.  See Multiple Terminals.

 -- Variable: real-last-command
     This variable is set up by Emacs just like last-command, but never altered by Lisp programs.

 -- Variable: last-repeatable-command
     This variable stores the most recently executed command that was not part of an input event.  This is the command repeat will try to repeat, see Repeating (The GNU Emacs Manual).

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

     The command loop sets this variable just before running a command, and copies its value into last-command when the command finishes (unless the command specified a prefix argument for the following command).

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

If you do not want a particular command to be recognized as the previous command in the case where it got an error, you must code that command to prevent this.  One way is to set this-command to t at the beginning of the command, and set this-command back to its proper value at the end, like this:

     (defun foo (args...)
       (interactive ...)
       (let ((old-this-command this-command))
         (setq this-command t)
         ...do the work...
         (setq this-command old-this-command)))

We do not bind this-command with let because that would restore the old value in case of error---a feature of let which in this case does precisely what we want to avoid.

 -- Variable: this-original-command
     This has the same value as this-command except when command remapping occurs (see Remapping Commands).  In that case, this-command gives the command actually run (the result of remapping), and this-original-command gives the command that was specified to run but remapped into another command.

 -- Variable: current-minibuffer-command
     This has the same value as this-command, but is bound recursively when entering a minibuffer.  This variable can be used from minibuffer hooks and the like to determine what command opened the current minibuffer session.

 -- Function: this-command-keys
     This function returns a string or vector containing the key sequence that invoked the present command.  Any events read by the command using read-event without a timeout get tacked on to the end.

     However, if the command has called read-key-sequence, it returns the last read key sequence.  See Key Sequence Input.  The value is a string if all events in the sequence were characters that fit in a string.  See Input Events.

          (this-command-keys)
          ;; Now use C-u C-x C-e to evaluate that.
               => "^X^E"

 -- Function: this-command-keys-vector
     Like this-command-keys, except that it always returns the events in a vector, so you don't need to deal with the complexities of storing input events in a string (see Strings of Events).

 -- Function: clear-this-command-keys &optional keep-record
     This function empties out the table of events for this-command-keys to return.  Unless KEEP-RECORD is non-nil, it also empties the records that the function recent-keys (see Recording Input) will subsequently return. This is useful after reading a password, to prevent the password from echoing inadvertently as part of the next command in certain cases.

 -- Variable: last-nonmenu-event
     This 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 x-popup-menu where to pop up a menu.  It is also used internally by y-or-n-p (see Yes-or-No Queries).

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

          last-command-event
          ;; Now use C-u C-x C-e to evaluate that.
               => 5

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

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

     If the last event came from a keyboard macro, the value is macro.

Input events must come from somewhere; sometimes, that is a keyboard macro, a signal, or `unread-command-events', but it is usually a physical input device connected to a computer that is controlled by the user.  Those devices are referred to as input devices, and Emacs associates each input event with the input device from which it originated.  They are identified by a name that is unique to each input device.

The ability to determine the precise input device used depends on the details of each system.  When that information is unavailable, Emacs reports keyboard events as originating from the "Virtual core keyboard", and other events as originating from the "Virtual core pointer".  (These values are used on every platform because the X server reports them when detailed device information is not known.)

 -- Variable: last-event-device
     This variable records the name of the input device from which the last input event read was generated.  It is nil if no such device exists, i.e., the last input event was read from unread-command-events, or it came from a keyboard macro.

     When the X Input Extension is being used on X Windows, the device name is a string that is unique to each physical keyboard, pointing device and touchscreen attached to the X server.  Otherwise, it is either the string "Virtual core pointer" or "Virtual core keyboard", depending on whether the event was generated by a pointing device (such as a mouse) or a keyboard.

 -- Function: device-class frame name
     There are various different types of devices, which can be determined from their names.  This function can be used to determined the correct type of the device NAME for an event originating from FRAME.

     The return value is one of the following symbols (``device classes''):

     core-keyboard
          The core keyboard; this is means the device is a keyboard-like device, but no other characteristics are unknown.

     core-pointer
          The core pointer; this means the device is a pointing device, but no other characteristics are known.

     mouse
          A computer mouse.

     trackpoint
          A trackpoint or joystick (or other similar control.)

     eraser
          The other end of a stylus on a graphics tablet, or a standalone eraser.

     pen
          The pointed end of a pen on a graphics tablet, a stylus, or some other similar device.

     puck
          A device that looks like a computer mouse, but reports absolute coordinates relative to some other surface.

     power-button
          A power button or volume button (or other similar control.)

     keyboard
          A computer keyboard.

     touchscreen
          A computer touchpad.

     pad
          A collection of sensitive buttons, rings, and strips commonly found around a drawing tablet.

     touchpad
          An indirect touch device such as a touchpad.

     piano
          A musical instrument such as an electronic keyboard.

     test
          A device used by the XTEST extension to report input.

Adjusting Point After Commands
==============================

Emacs cannot display the cursor when point is in the middle of a sequence of text that has the display or composition property, or is invisible.  Therefore, after a command finishes and returns to the command loop, if point is within such a sequence, the command loop normally moves point to the edge of the sequence, making this sequence effectively intangible.

A command can inhibit this feature by setting the variable disable-point-adjustment:

 -- Variable: disable-point-adjustment
     If this variable is non-nil when a command returns to the command loop, then the command loop does not check for those text properties, and does not move point out of sequences that have them.

     The command loop sets this variable to nil before each command, so if a command sets it, the effect applies only to that command.

 -- Variable: global-disable-point-adjustment
     If you set this variable to a non-nil value, the feature of moving point out of these sequences is completely turned off.

Input Events
============

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

 -- Function: eventp object
     This function returns non-nil if OBJECT is an input event or event type.

     Note that any non-nil symbol might be used as an event or an event type; eventp cannot distinguish whether a symbol is intended by Lisp code to be used as an event.

Keyboard Events
---------------

There are two kinds of input you can get from the keyboard: ordinary keys, and function keys.  Ordinary keys correspond to (possibly modified) characters; the events they generate are represented in Lisp as characters.  The event type of a character event is the character itself (an integer), which might have some modifier bits set; see Classifying Events.

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

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

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

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

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

shift
     The 2**25 bit (the 26th bit) in the character event code indicates an ASCII control character 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 different character with a different basic code.  In order to keep within the ASCII character set whenever possible, Emacs avoids using the 2**25 bit for those character events.

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

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

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

alt
     The 2**22 bit in the character event code indicates a character typed with the alt key held down.  (The key labeled Alt on most keyboards is actually treated as the meta key, not this.)

It is best to avoid mentioning specific bit numbers in your program. To test the modifier bits of a character, use the function event-modifiers (see Classifying Events).  When making key bindings with keymap-set, you specify these events using strings like C-H-x instead (for ``control hyper x'') (see Changing Key Bindings).

Function Keys
-------------

Most keyboards also have function keys---keys that have names or symbols that are not characters.  Function keys are represented in Emacs Lisp as symbols; the symbol's name is the function key's label, in lower case.  For example, pressing a key labeled F1 generates an input event represented by the symbol f1.

The event type of a function key event is the event symbol itself. See Classifying Events.

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

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

     In ASCII, C-i and TAB are the same character.  If the terminal can distinguish between them, Emacs conveys the distinction to Lisp programs by representing the former as the integer 9, and the latter as the symbol tab.

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

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

left, up, right, down
     Cursor arrow keys

kp-add, kp-decimal, kp-divide, ...
     Keypad keys (to the right of the regular keyboard).

kp-0, kp-1, ...
     Keypad keys with digits.

kp-f1, kp-f2, kp-f3, kp-f4
     Keypad PF keys.

kp-home, kp-left, kp-up, kp-right, kp-down
     Keypad arrow keys.  Emacs normally translates these into the corresponding non-keypad keys home, left, ...

kp-prior, kp-next, kp-end, kp-begin, kp-insert, kp-delete
     Additional keypad duplicates of keys ordinarily found elsewhere.  Emacs normally translates these into the like-named non-keypad keys.

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

A-
     The alt modifier.

C-
     The control modifier.

H-
     The hyper modifier.

M-
     The meta modifier.

S-
     The shift modifier.

s-
     The super modifier.

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

Mouse Events
------------

Emacs supports four kinds of mouse events: click events, drag events, button-down events, and motion events.  All mouse events are represented as lists.  The CAR of the list is the event type; this says which mouse button was involved, and which modifier keys were used with it. The event type can also distinguish double or triple button presses (see Repeat Events).  The rest of the list elements give position and time information.

For key lookup, only the event type matters: two events of the same type necessarily run the same command.  The command can access the full values of these events using the e interactive code. See Interactive Codes.

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

Click Events
------------

When the user presses a mouse button and releases it at the same location, that generates a click event.  Depending on how your window-system reports mouse-wheel events, turning the mouse wheel can generate either a mouse click or a mouse-wheel event.  All mouse event share the same format:

     (EVENT-TYPE POSITION CLICK-COUNT)

EVENT-TYPE
     This is a symbol that indicates which mouse button was used.  It is one of the symbols mouse-1, mouse-2, ..., where the buttons are numbered left to right.  For mouse-wheel event, it can be wheel-up or wheel-down.

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

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

POSITION
     This is a mouse position list specifying where the mouse event occurred; see below for details.

CLICK-COUNT
     This is the number of rapid repeated presses so far of the same mouse button or the number of repeated turns of the wheel.  See Repeat Events.

To access the contents of a mouse position list in the POSITION slot of a mouse event, you should typically use the functions documented in Accessing Mouse.

The explicit format of the list depends on where the event occurred. For clicks in the text area, mode line, header line, tab line, or in the fringe or marginal areas, the mouse position list has the form

     (WINDOW POS-OR-AREA (X . Y) TIMESTAMP
      OBJECT TEXT-POS (COL . ROW)
      IMAGE (DX . DY) (WIDTH . HEIGHT))

The meanings of these list elements are as follows:

WINDOW
     The window in which the mouse event occurred.

POS-OR-AREA
     The buffer position of the character clicked on in the text area; or, if the event was outside the text area, the window area where it occurred.  It is one of the symbols mode-line, header-line, tab-line, vertical-line, left-margin, right-margin, left-fringe, or right-fringe.

     In one special case, POS-OR-AREA is a list containing a symbol (one of the symbols listed above) instead of just the symbol.  This happens after the imaginary prefix keys for the event are registered by Emacs.  See Key Sequence Input.

X, Y
     The relative pixel coordinates of the event.  For events in the text area of a window, the coordinate origin (0 . 0) is taken to be the top left corner of the text area.  See Window Sizes.  For events in a mode line, header line or tab line, the coordinate origin is the top left corner of the window itself.  For fringes, margins, and the vertical border, X does not have meaningful data. For fringes and margins, Y is relative to the bottom edge of the header line.  In all cases, the X and Y coordinates increase rightward and downward respectively.

TIMESTAMP
     The time at which the event occurred, as an integer number of milliseconds since a system-dependent initial time.

OBJECT
     Either nil, which means the event occurred on buffer text, or a cons cell of the form (STRING . STRING-POS) if there is a string from a text property or an overlay at the event position.

     STRING
          The string which was clicked on, including any properties.

     STRING-POS
          The position in the string where the click occurred.

TEXT-POS
     For clicks on a marginal area or on a fringe, this is the buffer position of the first visible character in the corresponding line in the window.  For clicks on the mode line, the header line or the tab line, this is nil.  For other events, it is the buffer position closest to the click.

COL, ROW
     These are the actual column and row coordinate numbers of the glyph under the X, Y position.  If X lies beyond the last column of actual text on its line, COL is reported by adding fictional extra columns that have the default character width. Row 0 is taken to be the header line if the window has one, or Row 1 if the window also has the tab line, or the topmost row of the text area otherwise.  Column 0 is taken to be the leftmost column of the text area for clicks on a window text area, or the leftmost mode line or header line column for clicks there.  For clicks on fringes or vertical borders, these have no meaningful data.  For clicks on margins, COL is measured from the left edge of the margin area and ROW is measured from the top of the margin area.

IMAGE
     If there is an image at the click location, this is the image object as returned by find-image (see Defining Images); otherwise this is nil.

DX, DY
     These are the pixel offsets of the click relative to the top left corner of the OBJECT's glyph that is the nearest one to the click. The relevant OBJECTs can be either a buffer, or a string, or an image, see above.  If OBJECT is nil or a string, the coordinates are relative to the top left corner of the character glyph clicked on.  Note that the offsets are always zero on text-mode frames, when OBJECT is nil, since each glyph there is considered to have exactly 1x1 pixel dimensions.

WIDTH, HEIGHT
     If the click is on a character, either from buffer text or from overlay or display string, these are the pixel width and height of that character's glyph; otherwise they are dimensions of OBJECT clicked on.

For clicks on a scroll bar, POSITION has this form:

     (WINDOW AREA (PORTION . WHOLE) TIMESTAMP PART)

WINDOW
     The window whose scroll bar was clicked on.

AREA
     This is the symbol vertical-scroll-bar.

PORTION
     The number of pixels from the top of the scroll bar to the click position.  On some toolkits, including GTK+, Emacs cannot extract this data, so the value is always 0.

WHOLE
     The total length, in pixels, of the scroll bar.  On some toolkits, including GTK+, Emacs cannot extract this data, so the value is always 0.

TIMESTAMP
     The time at which the event occurred, in milliseconds.  On some toolkits, including GTK+, Emacs cannot extract this data, so the value is always 0.

PART
     The part of the scroll bar on which the click occurred.  It is one of the symbols handle (the scroll bar handle), above-handle (the area above the handle), below-handle (the area below the handle), up (the up arrow at one end of the scroll bar), or down (the down arrow at one end of the scroll bar).

For clicks on the frame's internal border (see Frame Layout), the frame's tool bar (see Tool Bar) or tab bar, POSITION has this form:

      (FRAME PART (X . Y) TIMESTAMP)

FRAME
     The frame whose internal border or tool bar or tab bar was clicked on.

PART
     The part of the frame which was clicked on.  This can be one of the following:

     tool-bar
          The frame has a tool bar, and the event was in the tool-bar area.

     tab-bar
          The frame has a tab bar, and the event was in the tab-bar area.

     left-edge
     top-edge
     right-edge
     bottom-edge
          The click was on the corresponding border at an offset of at least one canonical character from the border's nearest corner.

     top-left-corner
     top-right-corner
     bottom-right-corner
     bottom-left-corner
          The click was on the corresponding corner of the internal border.

     nil
          The frame does not have an internal border, and the event was not on the tab bar or the tool bar.  This usually happens on text-mode frames.  This can also happen on GUI frames with internal border if the frame doesn't have its drag-internal-border parameter (see Mouse Dragging Parameters) set to a non-nil value.

Drag Events
-----------

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

     (EVENT-TYPE
      (WINDOW1 START-POSITION)
      (WINDOW2 END-POSITION))

For a drag event, the name of the symbol EVENT-TYPE contains the prefix drag-.  For example, dragging the mouse with button 2 held down generates a drag-mouse-2 event.  The second and third elements of the event give the starting and ending position of the drag, as mouse position lists (see Click Events).  You can access the second element of any mouse event in the same way.  However, the drag event may end outside the boundaries of the frame that was initially selected.  In that case, the third element's position list contains that frame in place of a window.

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

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

Button-Down Events
------------------

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

If you want to take action as soon as a button is pressed, you need to handle button-down events. (Button-down is the conservative antithesis of drag.)  These occur as soon as a button is pressed.  They are represented by lists that look exactly like click events (see Click Events), except that the EVENT-TYPE symbol name contains the prefix down-.  The down- prefix follows modifier key prefixes such as C- and M-.

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

Repeat Events
-------------

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

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

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

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

This is convenient, if the meaning of a double click somehow builds on the meaning of a single click---which is recommended user interface design practice for double clicks.

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

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

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

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

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

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

 -- User Option: double-click-fuzz
     To generate repeat events, successive mouse button presses must be at approximately the same screen position.  The value of double-click-fuzz specifies the maximum number of pixels the mouse may be moved (horizontally or vertically) between two successive clicks to make a double-click.

     This variable is also the threshold for motion of the mouse to count as a drag.

 -- User Option: double-click-time
     To generate repeat events, the number of milliseconds between successive button presses must be less than the value of double-click-time.  Setting double-click-time to nil disables multi-click detection entirely.  Setting it to t removes the time limit; Emacs then detects multi-clicks by position only.

Motion Events
-------------

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

     (mouse-movement POSITION)

POSITION is a mouse position list (see Click Events), specifying the current position of the mouse cursor.  As with the end-position of a drag event, this position list may represent a location outside the boundaries of the initially selected frame, in which case the list contains that frame in place of a window.

The track-mouse macro enables generation of motion events within its body.  Outside of track-mouse body, Emacs does not generate events for mere motion of the mouse, and these events do not appear.  See Mouse Tracking.

 -- Variable: mouse-fine-grained-tracking
     When non-nil, mouse motion events are generated even for very small movements.  Otherwise, motion events are not generated as long as the mouse cursor remains pointing to the same glyph in the text. Note that non-nil mouse-prefer-closest-glyph changes that to the left/right half of the glyph under the mouse cursor instead.

Touchscreen Events
------------------

Some window systems provide support for input devices that react to the user's touching the screen and moving fingers while touching the screen.  These input devices are known as touchscreens, and Emacs reports the events they generate as touchscreen events.

Most individual events generated by a touchscreen only have meaning as part of a larger sequence of other events: for instance, the simple operation of tapping the touchscreen involves the user placing and raising a finger on the touchscreen, and swiping the display to scroll it involves placing a finger, moving it many times upwards or downwards, and then raising the finger.

While a simplistic model consisting of one finger is adequate for taps and scrolling, more complicated gestures require support for keeping track of multiple fingers, where the position of each finger is represented by a touch point.  For example, a ``pinch to zoom'' gesture might consist of the user placing two fingers and moving them individually in opposite directions, where the distance between the positions of their individual points determine the amount by which to zoom the display, and the center of an imaginary line between those positions determines where to pan the display after zooming.

The low-level touchscreen events described below can be used to implement all the touch sequences described above.  In those events, each point is represented by a cons of an arbitrary number identifying the point and a mouse position list (see Click Events) specifying the position of the finger when the event occurred.

(touchscreen-begin POINT)
     This event is sent when POINT is created by the user pressing a finger against the touchscreen.

(touchscreen-update POINTS)
     This event is sent when a point on the touchscreen has changed position.  POINTS is a list of touch points containing the up-to-date positions of each touch point currently on the touchscreen.

(touchscreen-end POINT)
     This event is sent when POINT is no longer present on the display, because another program took the grab, or because the user raised the finger from the touchscreen.

Focus Events
------------

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

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

     (switch-frame NEW-FRAME)

where NEW-FRAME is the frame switched to.

Some X window managers are set up so that just moving the mouse into a window is enough to set the focus there.  Usually, there is no need for a Lisp program to know about the focus change until some other kind of input arrives.  Emacs generates a focus event only when the user actually types a keyboard key or presses a mouse button in the new frame; just moving the mouse between frames does not generate a focus event.

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

Xwidget events
--------------

Xwidgets (see Xwidgets) can send events to update Lisp programs on their status.  These events are dubbed xwidget-events, and contain various data describing the nature of the change.

(xwidget-event KIND XWIDGET ARG)
     This event is sent whenever some kind of update occurs in XWIDGET.  There are several types of updates, identified by their KIND.

     It is a special event (see Special Events), which should be handled by adding a callback to an xwidget that is called whenever an xwidget event for XWIDGET is received.

     You can add a callback by setting the callback of an xwidget's property list, which should be a function that accepts XWIDGET and KIND as arguments.

     load-changed
          This xwidget event indicates that the XWIDGET has reached a particular point of the page-loading process.  When these events are sent, ARG will contain a string that further describes the status of the widget:

          load-started
               This means the widget has begun a page-loading operation.

          load-finished
               This means the XWIDGET has finished processing whatever page-loading operation that it was previously performing.

          load-redirected
               This means the XWIDGET has encountered and followed a redirect during the page-loading operation.

          load-committed
               This means the XWIDGET has committed to a given URL during the page-loading operation, i.e. the URL is the final URL that will be rendered by XWIDGET during the current page-loading operation.

     download-callback
          This event indicates that a download of some kind has been completed.

     In the above events, there can be arguments after ARG, which itself indicates the URL from which the download file was retrieved: the first argument after ARG indicates the MIME type of the download, as a string, while the second argument contains the full file name of the downloaded file.

     download-started
          This event indicates that a download has been started.  In these events, ARG contains the URL of the file that is currently being downloaded.

     javascript-callback
          This event contains JavaScript callback data.  These events are used internally by xwidget-webkit-execute-script.

(xwidget-display-event XWIDGET SOURCE)
     This event is sent whenever an xwidget requests that another xwidget be displayed.  XWIDGET is the xwidget that should be displayed, and SOURCE is the xwidget that asked to display XWIDGET.

     It is also a special event which should be handled through callbacks. You can add such a callback by setting the display-callback of SOURCE's property list, which should be a function that accepts XWIDGET and SOURCE as arguments.

     XWIDGET's buffer will be set to a temporary buffer.  When displaying the widget, care should be taken to replace the buffer with the buffer in which the xwidget will be displayed, using set-xwidget-buffer  (see Xwidgets).

Miscellaneous System Events
---------------------------

A few other event types represent occurrences within the system.

(delete-frame (FRAME))
     This kind of event indicates that the user gave the window manager a command to delete a particular window, which happens to be an Emacs frame.

     The standard definition of the delete-frame event is to delete FRAME.

(iconify-frame (FRAME))
     This kind of event indicates that the user iconified FRAME using the window manager.  Its standard definition is ignore; since the frame has already been iconified, Emacs has no work to do.  The purpose of this event type is so that you can keep track of such events if you want to.

(make-frame-visible (FRAME))
     This kind of event indicates that the user deiconified FRAME using the window manager.  Its standard definition is ignore; since the frame has already been made visible, Emacs has no work to do.

(touch-end (POSITION))
     This kind of event indicates that the user's finger moved off the mouse wheel or the touchpad.  The POSITION element is a mouse position list (see Click Events), specifying the position of the mouse cursor when the finger moved off the mouse wheel.

(wheel-up POSITION CLICKS LINES PIXEL-DELTA)
(wheel-down POSITION CLICKS LINES PIXEL-DELTA)
     These kinds of event are generated by moving a mouse wheel.  The POSITION element is a mouse position list (see Click Events), specifying the position of the mouse cursor when the event occurred.

     CLICKS, if present, is the number of times that the wheel was moved in quick succession.  See Repeat Events.  LINES, if present and not nil, is the number of screen lines that should be scrolled.  PIXEL-DELTA, if present, is a cons cell of the form (X . Y), where X and Y are the numbers of pixels by which to scroll in each axis, a.k.a. pixelwise deltas.

     You can use these X and Y pixelwise deltas to determine how much the mouse wheel has actually moved at pixel resolution.  For example, the pixelwise deltas could be used to scroll the display at pixel resolution, exactly according to the user's turning the mouse wheel.

     This kind of event is generated only on some kinds of systems.  On some systems, mouse-4 and mouse-5 are used instead.  For portable code, use the variables mouse-wheel-up-event, mouse-wheel-up-alternate-event, mouse-wheel-down-event and mouse-wheel-down-alternate-event defined in mwheel.el to determine what event types to expect for the mouse wheel.

     Similarly, some mice can generate mouse-wheel-left-event and mouse-wheel-right-event and can be used to scroll if mouse-wheel-tilt-scroll is non-nil.  However, some mice also generate other events at the same time as they're generating these scroll events which may get in the way.  The way to fix this is generally to unbind these events (for instance, mouse-6 or mouse-7, but this is very hardware and operating system dependent).

(pinch POSITION DX DY SCALE ANGLE)
     This kind of event is generated by the user performing a ``pinch'' gesture by placing two fingers on a touchpad and moving them towards or away from each other.  POSITION is a mouse position list (see Click Events) that provides the position of the mouse pointer when the event occurred, DX is the change in the horizontal distance between the fingers since the last event in the same sequence, DY is the vertical movement of the fingers since the last event in the same sequence, SCALE is the ratio of the current distance between the fingers to that distance at the start of the sequence, and ANGLE is the angular difference in degrees between the direction of the line connecting the fingers in this event and the direction of that line in the last event of the same sequence.

     As pinch events are only sent at the beginning or during a pinch sequence, they do not report gestures where the user moves two fingers on a touchpad in a rotating fashion without pinching the fingers.

     All arguments after POSITION are floating point numbers.

     This event is usually sent as part of a sequence, which begins with the user placing two fingers on the touchpad, and ends with the user removing those fingers.  DX, DY, and ANGLE will be 0.0 in the first event of a sequence; subsequent events will report non-zero values for these members of the event structure.

     DX and DY are reported in imaginary relative units, in which 1.0 is the width and height of the touchpad respectively.  They are usually interpreted as being relative to the size of the object beneath the gesture: image, window, etc.

(preedit-text ARG)
     This event is sent when a system input method tells Emacs to display some text to indicate to the user what will be inserted.  The contents of ARG are dependent on the window system being used.

     On X, ARG is a string describing some text to place behind the cursor.  It can be nil, which means to remove any text previously displayed.

     On PGTK frames (see Frames), ARG is a list of strings with information about their color and underline attributes.  It has the following form:

             ((STRING1
               (ul . UNDERLINE-COLOR)
               (bg . BACKGROUND-COLOR)
               (fg . FOREGROUND-COLOR))
              (STRING2
               (ul . UNDERLINE-COLOR)
               (bg . BACKGROUND-COLOR)
               (fg . FOREGROUND-COLOR))
              ...
             )

     Color information can be omitted, leaving just the text of the strings.  UNDERLINE-COLOR can be t, meaning underlined text with default underline color, or it can be a string, the name of the color to draw the underline.

     This is a special event (see Special Events), which normally should not be bound by the user to any command.  Emacs will typically display the text contained in the event in an overlay behind point when it is received.

(drag-n-drop POSITION FILES)
     This kind of event is generated when a group of files is selected in an application outside of Emacs, and then dragged and dropped onto an Emacs frame.

     The element POSITION is a list describing the position of the event, in the same format as used in a mouse-click event (see Click Events), and 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 of systems.

help-echo
     This kind of event is generated when a mouse pointer moves onto a portion of buffer text which has a help-echo text property. The generated event has this form:

          (help-echo FRAME HELP WINDOW OBJECT POS)

     The precise meaning of the event parameters and the way these parameters are used to display the help-echo text are described in Text help-echo.

sigusr1
sigusr2
     These events are generated when the Emacs process receives the signals SIGUSR1 and SIGUSR2.  They contain no additional data because signals do not carry additional information. They can be useful for debugging (see Error Debugging).

     To catch a user signal, bind the corresponding event to an interactive command in the special-event-map (see Controlling Active Maps). The command is called with no arguments, and the specific signal event is available in last-input-event (see Event Input Misc.  For example:

          (defun sigusr-handler ()
            (interactive)
            (message "Caught signal %S" last-input-event))

          (keymap-set special-event-map "<sigusr1>" 'sigusr-handler)

     To test the signal handler, you can make Emacs send a signal to itself:

          (signal-process (emacs-pid) 'sigusr1)

language-change
     This kind of event is generated on MS-Windows when the input language has changed.  This typically means that the keyboard keys will send to Emacs characters from a different language.  The generated event has this form:

          (language-change FRAME CODEPAGE LANGUAGE-ID)

     Here FRAME is the frame which was current when the input language changed; CODEPAGE is the new codepage number; and LANGUAGE-ID is the numerical ID of the new input language.  The coding-system (see Coding Systems) that corresponds to CODEPAGE is cpCODEPAGE or windows-CODEPAGE.  To convert LANGUAGE-ID to a string (e.g., to use it for various language-dependent features, such as set-language-environment), use the w32-get-locale-info function, like this:

          ;; Get the abbreviated language name, such as "ENU" for English
          (w32-get-locale-info language-id)
          ;; Get the full English name of the language,
          ;; such as "English (United States)"
          (w32-get-locale-info language-id 4097)
          ;; Get the full localized name of the language
          (w32-get-locale-info language-id t)

end-session
     This event is generated on MS-Windows when the operating system informs Emacs that the user terminated the interactive session, or that the system is shutting down.  The standard definition of this event is to invoke the kill-emacs command (see Killing Emacs) so as to shut down Emacs in an orderly fashion; if there are unsaved changes, this will produce auto-save files (see Auto-Saving) that the user can use after restarting the session to restore the unsaved edits.

If one of these events arrives in the middle of a key sequence---that is, after a prefix key---then Emacs reorders the events so that this event comes either before or after the multi-event key sequence, not within it.

Some of these special events, such as delete-frame, invoke Emacs commands by default; others are not bound.  If you want to arrange for a special event to invoke a command, you can do that via special-event-map.  The command you bind to a function key in that map can then examine the full event which invoked it in last-input-event.  See Special Events.

Event Examples
--------------

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

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

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

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

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

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

The frame with input focus might not take up the entire screen, and the user might move the mouse outside the scope of the frame.  Inside the track-mouse macro, that produces an event like this:

     (mouse-movement (#<frame *ielm* 0x102849a30> nil (563 . 205) 532301936))

To handle a SIGUSR1 signal, define an interactive function, and bind it to the signal usr1 event sequence:

     (defun usr1-handler ()
       (interactive)
       (message "Got USR1 signal"))
     (keymap-global-set "<signal> <usr1>" 'usr1-handler)

Classifying Events
------------------

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

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

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

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

 -- Function: event-modifiers event
     This function returns a list of the modifiers that EVENT has.  The modifiers are symbols; they include shift, control, meta, alt, hyper and super.  In addition, the modifiers list of a mouse event symbol always contains one of click, drag, and down.  For double or triple events, it also contains double or triple.

     The argument EVENT may be an entire event object, or just an event type.  If EVENT is a symbol that has never been used in an event that has been read as input in the current Emacs session, then event-modifiers can return nil, even when EVENT actually has modifiers.

     Here are some examples:

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

     The modifiers list for a click event explicitly contains click, but the event symbol name itself does not contain click. Similarly, the modifiers list for an ASCII control character, such as C-a, contains control, even though reading such an event via read-char will return the value 1 with the control modifier bit removed.

 -- Function: event-basic-type event
     This function returns the key or mouse button that EVENT describes, with all modifiers removed.  The EVENT argument is as in event-modifiers.  For example:

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

 -- Function: mouse-movement-p object
     This function returns non-nil if OBJECT is a mouse movement event.  See Motion Events.

Accessing Mouse Events
----------------------

This section describes convenient functions for accessing the data in a mouse button or motion event.  Keyboard event data can be accessed using the same functions, but data elements that aren't applicable to keyboard events are zero or nil.

The following two functions return a mouse position list (see Click Events), specifying the position of a mouse event.

 -- Function: event-start event
     This returns the starting position of EVENT.

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

 -- Function: event-end event
     This returns the ending position of EVENT.

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

 -- Function: posnp object
     This function returns non-nil if OBJECT is a mouse position list, in the format documented in Click Events); and nil otherwise.

These functions take a mouse position list as argument, and return various parts of it:

 -- Function: posn-window position
     Return the window that POSITION is in.  If POSITION represents a location outside the frame where the event was initiated, return that frame instead.

 -- Function: posn-area position
     Return the window area recorded in POSITION.  It returns nil when the event occurred in the text area of the window; otherwise, it is a symbol identifying the area in which the event occurred.

 -- Function: posn-point position
     Return the buffer position in POSITION.  When the event occurred in the text area of the window, in a marginal area, or on a fringe, this is an integer specifying a buffer position.  Otherwise, the value is undefined.

 -- Function: posn-x-y position
     Return the pixel-based x and y coordinates in POSITION, as a cons cell (X . Y).  These coordinates are relative to the window given by posn-window.

     This example shows how to convert the window-relative coordinates in the text area of a window into frame-relative coordinates:

          (defun frame-relative-coordinates (position)
            "Return frame-relative coordinates from POSITION.
          POSITION is assumed to lie in a window text area."
            (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)))))

 -- Function: posn-col-row position &optional use-window
     This function returns a cons cell (COL .  ROW), containing the estimated column and row corresponding to buffer position described by POSITION.  The return value is given in units of the frame's default character width and default line height (including spacing), as computed from the X and Y values corresponding to POSITION.  (So, if the actual characters have non-default sizes, the actual row and column may differ from these computed values.)  If the optional WINDOW argument is non-nil, use the default character width in the window indicated by POSITION instead of the frame.  (This makes a difference if that window is showing a buffer with a non-default zooming level, for instance.)

     Note that ROW is counted from the top of the text area.  If the window given by POSITION possesses a header line (see Header Lines) or a tab line, they are not included in the ROW count.

 -- Function: posn-actual-col-row position
     Return the actual row and column in POSITION, as a cons cell (COL . ROW).  The values are the actual row and column numbers in the window given by POSITION.  See Click Events, for details.  The function returns nil if POSITION does not include actual position values; in that case posn-col-row can be used to get approximate values.

     Note that this function doesn't account for the visual width of characters on display, like the number of visual columns taken by a tab character or an image.  If you need the coordinates in canonical character units, use posn-col-row instead.

 -- Function: posn-string position
     Return the string object described by POSITION, either nil (which means POSITION describes buffer text), or a cons cell (STRING . STRING-POS).

 -- Function: posn-image position
     Return the image object in POSITION, either nil (if there's no image at POSITION), or an image spec (image ...).

 -- Function: posn-object position
     Return the image or string object described by POSITION, either nil (which means POSITION describes buffer text), an image (image ...), or a cons cell (STRING . STRING-POS).

 -- Function: posn-object-x-y position
     Return the pixel-based x and y coordinates relative to the upper left corner of the object described by POSITION, as a cons cell (DX . DY).  If the POSITION describes buffer text, return the relative coordinates of the buffer-text character closest to that position.

 -- Function: posn-object-width-height position
     Return the pixel width and height of the object described by POSITION, as a cons cell (WIDTH . HEIGHT). If the POSITION describes a buffer position, return the size of the character at that position.

 -- Function: posn-timestamp position
     Return the timestamp in POSITION.  This is the time at which the event occurred, in milliseconds.  Such a timestamp is reported relative to an arbitrary starting time that varies according to the window system in use.  On the X Window System, for example, it is the number of milliseconds since the X server was started.

These functions compute a position list given particular buffer position or screen position.  You can access the data in this position list with the functions described above.

 -- Function: posn-at-point &optional pos window
     This function returns a position list for position POS in WINDOW.  POS defaults to point in WINDOW; WINDOW defaults to the selected window.

     posn-at-point returns nil if POS is not visible in WINDOW.

 -- Function: posn-at-x-y x y &optional frame-or-window whole
     This function returns position information corresponding to pixel coordinates X and Y in a specified frame or window, FRAME-OR-WINDOW, which defaults to the selected window. The coordinates X and Y are relative to the text area of the selected window. If WHOLE is non-nil, the X coordinate is relative to the entire window area including scroll bars, margins and fringes.

 -- Variable: mouse-prefer-closest-glyph
     If you set this variable to non-nil, whenever you click or drag the mouse, instead of the point being always set in front of the clicked glyph, the point horizontally closest to the mouse position will be used. So if you click in the left half of a glyph, point is set in front of it, but if you click in the right half, point is set after it.

Accessing Scroll Bar Events
---------------------------

These functions are useful for decoding scroll bar events.

 -- Function: scroll-bar-event-ratio event
     This function returns the fractional vertical position of a scroll bar event within the scroll bar.  The value is a cons cell (PORTION . WHOLE) containing two integers whose ratio is the fractional position.

 -- Function: scroll-bar-scale ratio total
     This function multiplies (in effect) RATIO by TOTAL, rounding the result to an integer.  The argument RATIO is not a number, but rather a pair (NUM . DENOM)---typically a value returned by scroll-bar-event-ratio.

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

          (+ (point-min)
             (scroll-bar-scale
                (posn-x-y (event-start event))
                (- (point-max) (point-min))))

     Recall that scroll bar events have two integers forming a ratio, in place of a pair of x and y coordinates.

Putting Keyboard Events in Strings
----------------------------------

In most of the places where strings are used, we conceptualize the string as containing text characters---the same kind of characters found in buffers or files.  Occasionally Lisp programs use strings that conceptually contain keyboard characters; for example, they may be key sequences or keyboard macro definitions.  However, storing keyboard characters in a string is a complex matter, for reasons of historical compatibility, and it is not always possible.

We recommend that new programs avoid dealing with these complexities by not storing keyboard events in strings containing control characters or the like, but instead store them in the common Emacs format as understood by key-valid-p.

If you read a key sequence with read-key-sequence-vector (or read-key-sequence), or access a key sequence with this-command-keys-vector (or this-command-keys), you can transform this to the recommended format by using key-description.

The complexities stem from the modifier bits that keyboard input characters can include.  Aside from the Meta modifier, none of these modifier bits can be included in a string, and the Meta modifier is allowed only in special cases.

The earliest GNU Emacs versions represented meta characters as codes in the range of 128 to 255.  At that time, the basic character codes ranged from 0 to 127, so all keyboard character codes did fit in a string.  Many Lisp programs used \M- in string constants to stand for meta characters, especially in arguments to define-key and similar functions, and key sequences and sequences of events were always represented as strings.

When we added support for larger basic character codes beyond 127, and additional modifier bits, we had to change the representation of meta characters.  Now the flag that represents the Meta modifier in a character is 2**27 and such numbers cannot be included in a string.

To support programs with \M- in string constants, there are special rules for including certain meta characters in a string. Here are the rules for interpreting a string as a sequence of input characters:

  * If the keyboard character value is in the range of 0 to 127, it can go in the string unchanged.

  * The meta variants of those characters, with codes in the range of 2**27 to 2**27+127, can also go in the string, but you must change their numeric values.  You must set the 2**7 bit instead of the 2**27 bit, resulting in a value between 128 and 255.  Only a unibyte string can include these codes.

  * Non-ASCII characters above 256 can be included in a multibyte string.

  * Other keyboard character events cannot fit in a string.  This includes keyboard events in the range of 128 to 255.

Functions such as read-key-sequence that construct strings of keyboard input characters follow these rules: they construct vectors instead of strings, when the events won't fit in a string.

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

However, most programs would do well to avoid these issues by following the recommendations at the beginning of this section.

Reading Input
=============

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

For higher-level input facilities, see Minibuffers.

Key Sequence Input
------------------

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

 -- Function: read-key-sequence prompt &optional continue-echo dont-downcase-last switch-frame-ok command-loop
     This function reads a key sequence and returns it as a string or vector.  It keeps reading events until it has accumulated a complete key sequence; that is, enough to specify a non-prefix command using the currently active keymaps.  (Remember that a key sequence that starts with a mouse event is read using the keymaps of the buffer in the window that the mouse was in, not the current buffer.)

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

     Reading a key sequence includes translating the events in various ways.  See Translation Keymaps.

     The argument PROMPT is either a string to be displayed in the echo area as a prompt, or nil, meaning not to display a prompt. The argument CONTINUE-ECHO, if non-nil, means to echo this key as a continuation of the previous key.

     Normally any upper case event is converted to lower case if the original event is undefined and the lower case equivalent is defined. The argument DONT-DOWNCASE-LAST, if non-nil, means do not convert the last event to lower case.  This is appropriate for reading a key sequence to be defined.

     The argument SWITCH-FRAME-OK, if non-nil, means that this function should process a switch-frame event if the user switches frames before typing anything.  If the user switches frames in the middle of a key sequence, or at the start of the sequence but SWITCH-FRAME-OK is nil, then the event will be put off until after the current key sequence.

     The argument COMMAND-LOOP, if non-nil, means that this key sequence is being read by something that will read commands one after another.  It should be nil if the caller will read just one key sequence.

     In the following example, Emacs displays the prompt ? in the echo area, and then the user types C-x C-f.

          (read-key-sequence "?")

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

               => "^X^F"

     The function read-key-sequence suppresses quitting: C-g typed while reading with this function works like any other character, and does not set quit-flag.  See Quitting.

 -- Function: read-key-sequence-vector prompt &optional continue-echo dont-downcase-last switch-frame-ok command-loop
     This is like read-key-sequence except that it always returns the key sequence as a vector, never as a string. See Strings of Events.

If an input character is upper-case (or has the shift modifier) and has no key binding, but its lower-case equivalent has one, then read-key-sequence converts the character to lower case.  (This behavior can be disabled by setting the translate-upper-case-key-bindings user option to nil.) Note that lookup-key does not perform case conversion in this way.

When reading input results in such a shift-translation, Emacs sets the variable this-command-keys-shift-translated to a non-nil value.  Lisp programs can examine this variable if they need to modify their behavior when invoked by shift-translated keys. For example, the function handle-shift-selection examines the value of this variable to determine how to activate or deactivate the region (see handle-shift-selection).

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

When mouse events occur in special parts of a window or frame, such as a mode line or a scroll bar, the event type shows nothing special---it is the same symbol that would normally represent that combination of mouse button and modifier keys.  The information about the window part is kept elsewhere in the event---in the coordinates.  But read-key-sequence translates this information into imaginary prefix keys, all of which are symbols: tab-line, header-line, horizontal-scroll-bar, menu-bar, tab-bar, mode-line, vertical-line, vertical-scroll-bar, left-margin, right-margin, left-fringe, right-fringe, right-divider, and bottom-divider.  You can define meanings for mouse clicks in special window parts by defining key sequences using these imaginary prefix keys.

For example, if you call read-key-sequence and then click the mouse on the window's mode line, you get two events, like this:

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

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

Reading One Event
-----------------

The lowest level functions for command input are read-event, read-char, and read-char-exclusive.

If you need a function to read a character using the minibuffer, use read-char-from-minibuffer (see Multiple Queries).

 -- Function: read-event &optional prompt inherit-input-method seconds
     This function reads and returns the next event of command input, waiting if necessary until an event is available.

     The returned event may come directly from the user, or from a keyboard macro.  It is not decoded by the keyboard's input coding system (see Terminal I/O Encoding).

     If the optional argument PROMPT is non-nil, it should be a string to display in the echo area as a prompt.  If PROMPT is nil or the string "", read-event does not display any message to indicate it is waiting for input; instead, it prompts by echoing: it displays descriptions of the events that led to or were read by the current command.  See The Echo Area.

     If INHERIT-INPUT-METHOD is non-nil, then the current input method (if any) is employed to make it possible to enter a non-ASCII character.  Otherwise, input method handling is disabled for reading this event.

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

     If SECONDS is non-nil, it should be a number specifying the maximum time to wait for input, in seconds.  If no input arrives within that time, read-event stops waiting and returns nil.  A floating point SECONDS means to wait for a fractional number of seconds.  Some systems support only a whole number of seconds; on these systems, SECONDS is rounded down. If SECONDS is nil, read-event waits as long as necessary for input to arrive.

     If SECONDS is nil, Emacs is considered idle while waiting for user input to arrive.  Idle timers---those created with run-with-idle-timer (see Idle Timers)---can run during this period.  However, if SECONDS is non-nil, the state of idleness remains unchanged.  If Emacs is non-idle when read-event is called, it remains non-idle throughout the operation of read-event; if Emacs is idle (which can happen if the call happens inside an idle timer), it remains idle.

     If read-event gets an event that is defined as a help character, then in some cases read-event processes the event directly without returning.  See Help Functions.  Certain other events, called special events, are also processed directly within read-event (see Special Events).

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

          (read-event)
               => right

 -- Function: read-char &optional prompt inherit-input-method seconds
     This function reads and returns a character input event.  If the user generates an event which is not a character (i.e., a mouse click or function key event), read-char signals an error.  The arguments work as in read-event.

     If the event has modifiers, Emacs attempts to resolve them and return the code of the corresponding character.  For example, if the user types C-a, the function returns 1, which is the ASCII code of the C-a character.  If some of the modifiers cannot be reflected in the character code, read-char leaves the unresolved modifier bits set in the returned event.  For example, if the user types C-M-a, the function returns 134217729, 8000001 in hex, i.e. C-a with the Meta modifier bit set.  This value is not a valid character code: it fails the characterp test (see Character Codes).  Use event-basic-type (see Classifying Events) to recover the character code with the modifier bits removed; use event-modifiers to test for modifiers in the character event returned by read-char.

     In the first example below, the user types the character 1 (ASCII code 49).  The second example shows a keyboard macro definition that calls read-char from the minibuffer using eval-expression.  read-char reads the keyboard macro's very next character, which is 1.  Then eval-expression displays its return value in the echo area.

          (read-char)
               => 49

          ;; We assume here you use M-: to evaluate this.
          (symbol-function 'foo)
               => "^[:(read-char)^M1"

          (execute-kbd-macro 'foo)
               -| 49
               => nil

 -- Function: read-char-exclusive &optional prompt inherit-input-method seconds
     This function reads and returns a character input event.  If the user generates an event which is not a character event, read-char-exclusive ignores it and reads another event, until it gets a character.  The arguments work as in read-event.  The returned value may include modifier bits, as with read-char.

None of the above functions suppress quitting.

 -- Variable: num-nonmacro-input-events
     This variable holds the total number of input events received so far from the terminal---not counting those generated by keyboard macros.

We emphasize that, unlike read-key-sequence, the functions read-event, read-char, and read-char-exclusive do not perform the translations described in Translation Keymaps. If you wish to read a single key taking these translations into account (for example, to read Function Keys in a terminal or Mouse Events from xterm-mouse-mode), use the function read-key:

 -- Function: read-key &optional prompt disable-fallbacks
     This function reads a single key.  It is intermediate between read-key-sequence and read-event.  Unlike the former, it reads a single key, not a key sequence.  Unlike the latter, it does not return a raw event, but decodes and translates the user input according to input-decode-map, local-function-key-map, and key-translation-map (see Translation Keymaps).

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

     If argument DISABLE-FALLBACKS is non-nil then the usual fallback logic for unbound keys in read-key-sequence is not applied.  This means that mouse button-down and multi-click events will not be discarded and local-function-key-map and key-translation-map will not get applied.  If nil or unspecified, the only fallback disabled is downcasing of the last event.

 -- Function: read-char-choice prompt chars &optional inhibit-quit
     This function uses read-from-minibuffer to read and return a single character that is a member of CHARS, which should be a list of single characters.  It discards any input characters that are not members of CHARS, and shows a message to that effect.

     The optional argument INHIBIT-QUIT is by default ignored, but if the variable read-char-choice-use-read-key is non-nil, this function uses read-key instead of read-from-minibuffer, and in that case INHIBIT-QUIT non-nil means ignore keyboard-quit events while waiting for valid input.  In addition, if read-char-choice-use-read-key is non-nil, binding help-form (see Help Functions) to a non-nil value while calling this function causes it to evaluate help-form and display the result when the user presses help-char; it then continues to wait for a valid input character, or for keyboard-quit.

 -- Function: read-multiple-choice prompt choices &optional help-string show-help long-form
     Ask user a multiple choice question.  PROMPT should be a string that will be displayed as the prompt.

     CHOICES is an alist where the first element in each entry is a character to be entered, the second element is a short name for the entry to be displayed while prompting (if there's room, it might be shortened), and the third, optional entry is a longer explanation that will be displayed in a help buffer if the user requests more help.

     If optional argument HELP-STRING is non-nil, it should be a string with a more detailed description of all choices.  It will be displayed in a help buffer instead of the default auto-generated description when the user types ?.

     If optional argument SHOW-HELP is non-nil, the help buffer will be displayed immediately, before any user input.  If it is a string, use it as the name of the help buffer.

     If optional argument LONG-FORM is non-nil, the user will have to type in long-form answers (using completing-read) instead of hitting a single key.  The answers must be among the second elements of the values in the CHOICES list.

     The return value is the matching value from CHOICES.

          (read-multiple-choice
           "Continue connecting?"
           '((?a "always" "Accept certificate for this and future sessions.")
             (?s "session only" "Accept certificate this session only.")
             (?n "no" "Refuse to use certificate, close connection.")))

     The read-multiple-choice-face face is used to highlight the matching characters in the name string on graphical terminals.

Modifying and Translating Input Events
--------------------------------------

Emacs modifies every event it reads according to extra-keyboard-modifiers, then translates it through keyboard-translate-table (if applicable), before returning it from read-event.

 -- Variable: extra-keyboard-modifiers
     This variable lets Lisp programs ``press'' the modifier keys on the keyboard.  The value is a character.  Only the modifiers of the character matter.  Each time the user types a keyboard key, it is altered as if those modifier keys were held down.  For instance, if you bind extra-keyboard-modifiers to ?\C-\M-a, then all keyboard input characters typed during the scope of the binding will have the control and meta modifiers applied to them.  The character ?\C-@, equivalent to the integer 0, does not count as a control character for this purpose, but as a character with no modifiers. Thus, setting extra-keyboard-modifiers to zero cancels any modification.

     When using a window system, the program can press any of the modifier keys in this way.  Otherwise, only the CTL and META keys can be virtually pressed.

     Note that this variable applies only to events that really come from the keyboard, and has no effect on mouse events or any other events.

 -- Variable: keyboard-translate-table
     This terminal-local variable is the translate table for keyboard characters.  It lets you reshuffle the keys on the keyboard without changing any command bindings.  Its value is normally a char-table, or else nil.  (It can also be a string or vector, but this is considered obsolete.)

     If keyboard-translate-table is a char-table (see Char-Tables), then each character read from the keyboard is looked up in this char-table.  If the value found there is non-nil, then it is used instead of the actual input character.

     Note that this translation is the first thing that happens to a character after it is read from the terminal.  Record-keeping features such as recent-keys and dribble files record the characters after translation.

     Note also that this translation is done before the characters are supplied to input methods (see Input Methods).  Use translation-table-for-input (see Translation of Characters), if you want to translate characters after input methods operate.

 -- Function: key-translate from to
     This function modifies keyboard-translate-table to translate character code FROM into character code TO.  It creates the keyboard translate table if necessary.

Here's an example of using the keyboard-translate-table to make C-x, C-c and C-v perform the cut, copy and paste operations:

     (key-translate "C-x" "<control-x>")
     (key-translate "C-c" "<control-c>")
     (key-translate "C-v" "<control-v>")
     (keymap-global-set "<control-x>" 'kill-region)
     (keymap-global-set "<control-c>" 'kill-ring-save)
     (keymap-global-set "<control-v>" 'yank)

On a graphical terminal that supports extended ASCII input, you can still get the standard Emacs meanings of one of those characters by typing it with the shift key.  That makes it a different character as far as keyboard translation is concerned, but it has the same usual meaning.

See Translation Keymaps, for mechanisms that translate event sequences at the level of read-key-sequence.

Invoking the Input Method
-------------------------

The event-reading functions invoke the current input method, if any (see Input Methods).  If the value of input-method-function is non-nil, it should be a function; when read-event reads a printing character (including SPC) with no modifier bits, it calls that function, passing the character as an argument.

 -- Variable: input-method-function
     If this is non-nil, its value specifies the current input method function.

     Warning: don't bind this variable with let.  It is often buffer-local, and if you bind it around reading input (which is exactly when you would bind it), switching buffers asynchronously while Emacs is waiting will cause the value to be restored in the wrong buffer.

The input method function should return a list of events which should be used as input.  (If the list is nil, that means there is no input, so read-event waits for another event.)  These events are processed before the events in unread-command-events (see Event Input Misc).  Events returned by the input method function are not passed to the input method function again, even if they are printing characters with no modifier bits.

If the input method function calls read-event or read-key-sequence, it should bind input-method-function to nil first, to prevent recursion.

The input method function is not called when reading the second and subsequent events of a key sequence.  Thus, these characters are not subject to input method processing.  The input method function should test the values of overriding-local-map and overriding-terminal-local-map; if either of these variables is non-nil, the input method should put its argument into a list and return that list with no further processing.

Quoted Character Input
----------------------

You can use the function read-quoted-char to ask the user to specify a character, and allow the user to specify a control or meta character conveniently, either literally or as an octal character code. The command quoted-insert uses this function.

 -- Function: read-quoted-char &optional prompt
     This function is like read-char, except that if the first character read is an octal digit (0--7), it reads any number of octal digits (but stopping if a non-octal digit is found), and returns the character represented by that numeric character code.  If the character that terminates the sequence of octal digits is RET, it is discarded.  Any other terminating character is used as input after this function returns.

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

     If PROMPT is supplied, it specifies a string for prompting the user.  The prompt string is always displayed in the echo area, followed by a single -.

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

          (read-quoted-char "What character")

          ---------- Echo Area ----------
          What character 1 7 7-
          ---------- Echo Area ----------

               => 127

Miscellaneous Event Input Features
----------------------------------

This section describes how to peek ahead at events without using them up, how to check for pending input, and how to discard pending input.  See also the function read-passwd (see Reading a Password).

 -- Variable: unread-command-events
     This variable holds a list of events waiting to be read as command input.  The events are used in the order they appear in the list, and removed one by one as they are used.

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

     For example, the function that implements numeric prefix arguments reads any number of digits.  When it finds a non-digit event, it must unread the event so that it can be read normally by the command loop. Likewise, incremental search uses this feature to unread events with no special meaning in a search, because these events should exit the search and then execute normally.

     The reliable and easy way to extract events from a key sequence so as to put them in unread-command-events is to use listify-key-sequence (see below).

     Normally you add events to the front of this list, so that the events most recently unread will be reread first.

     Events read from this list are not normally added to the current command's key sequence (as returned by, e.g., this-command-keys), as the events will already have been added once as they were read for the first time.  An element of the form (t . EVENT) forces EVENT to be added to the current command's key sequence.

     Elements read from this list are normally recorded by the record-keeping features (see Recording Input) and while defining a keyboard macro (see Keyboard Macros).  However, an element of the form (no-record . EVENT) causes EVENT to be processed normally without recording it.

 -- Function: listify-key-sequence key
     This function converts the string or vector KEY to a list of individual events, which you can put in unread-command-events.

 -- Function: input-pending-p &optional check-timers
     This function determines whether any command input is currently available to be read.  It returns immediately, with value t if there is available input, nil otherwise.  On rare occasions it may return t when no input is available.

     If the optional argument CHECK-TIMERS is non-nil, then if no input is available, Emacs runs any timers which are ready. See Timers.

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

     In the example below, the Lisp program reads the character 1, ASCII code 49.  It becomes the value of last-input-event, while C-e (we assume C-x C-e command is used to evaluate this expression) remains the value of last-command-event.

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

 -- Macro: while-no-input body...
     This construct runs the BODY forms and returns the value of the last one---but only if no input arrives.  If any input arrives during the execution of the BODY forms, it aborts them (working much like a quit).  The while-no-input form returns nil if aborted by a real quit, and returns t if aborted by arrival of other input.

     If a part of BODY binds inhibit-quit to non-nil, arrival of input during those parts won't cause an abort until the end of that part.

     If you want to be able to distinguish all possible values computed by BODY from both kinds of abort conditions, write the code like this:

          (while-no-input
            (list
              (progn . BODY)))

 -- Variable: while-no-input-ignore-events
     This variable allow setting which special events while-no-input should ignore.  It is a list of event symbols (see Event Examples).

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

     In the following example, the user may type a number of characters right after starting the evaluation of the form.  After the sleep-for finishes sleeping, discard-input discards any characters typed during the sleep.

          (progn (sleep-for 2)
                 (discard-input))
               => nil

Special Events
==============

Certain special events are handled at a very low level---as soon as they are read.  The read-event function processes these events itself, and never returns them.  Instead, it keeps waiting for the first event that is not special and returns that one.

Special events do not echo, they are never grouped into key sequences, and they never appear in the value of last-command-event or (this-command-keys).  They do not discard a numeric argument, they cannot be unread with unread-command-events, they may not appear in a keyboard macro, and they are not recorded in a keyboard macro while you are defining one.

Special events do, however, appear in last-input-event immediately after they are read, and this is the way for the event's definition to find the actual event.

The events types iconify-frame, make-frame-visible, delete-frame, drag-n-drop, language-change, and user signals like sigusr1 are normally handled in this way. The keymap which defines how to handle special events---and which events are special---is in the variable special-event-map (see Controlling Active Maps).

Waiting for Elapsed Time or Input
=================================

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

 -- Function: sit-for seconds &optional nodisp
     This function performs redisplay (provided there is no pending input from the user), then waits SECONDS seconds, or until input is available.  The usual purpose of sit-for is to give the user time to read text that you display.  The value is t if sit-for waited the full time with no input arriving (see Event Input Misc).  Otherwise, the value is nil.

     The argument SECONDS need not be an integer.  If it is floating point, sit-for waits for a fractional number of seconds. Some systems support only a whole number of seconds; on these systems, SECONDS is rounded down.

     The expression (sit-for 0) is equivalent to (redisplay), i.e., it requests a redisplay, without any delay, if there is no pending input. See Forcing Redisplay.

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

     In batch mode (see Batch Mode), sit-for cannot be interrupted, even by input from the standard input descriptor.  It is thus equivalent to sleep-for, which is described below.

     It is also possible to call sit-for with three arguments, as (sit-for SECONDS MILLISEC NODISP), but that is considered obsolete.

 -- Function: sleep-for seconds &optional millisec
     This function simply pauses for SECONDS seconds without updating the display.  It pays no attention to available input.  It returns nil.

     The argument SECONDS need not be an integer.  If it is floating point, sleep-for waits for a fractional number of seconds. Some systems support only a whole number of seconds; on these systems, SECONDS is rounded down.

     The optional argument MILLISEC specifies an additional waiting period measured in milliseconds.  This adds to the period specified by SECONDS.  If the system doesn't support waiting fractions of a second, you get an error if you specify nonzero MILLISEC.

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

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

Quitting
========

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

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

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

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

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

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

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

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

     (defun read-quoted-char (&optional prompt)
       "...DOCUMENTATION..."
       (let ((message-log-max nil) done (first t) (code 0) char)
         (while (not done)
           (let ((inhibit-quit first)
                 ...)
             (and prompt (message "%s-" prompt))
             (setq char (read-event))
             (if inhibit-quit (setq quit-flag nil)))
           ...set the variable code...)
         code))

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

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

 -- Macro: with-local-quit body...
     This macro executes BODY forms in sequence, but allows quitting, at least locally, within BODY even if inhibit-quit was non-nil outside this construct.  It returns the value of the last form in BODY, unless exited by quitting, in which case it returns nil.

     If inhibit-quit is nil on entry to with-local-quit, it only executes the BODY, and setting quit-flag causes a normal quit.  However, if inhibit-quit is non-nil so that ordinary quitting is delayed, a non-nil quit-flag triggers a special kind of local quit.  This ends the execution of BODY and exits the with-local-quit body with quit-flag still non-nil, so that another (ordinary) quit will happen as soon as that is allowed.  If quit-flag is already non-nil at the beginning of BODY, the local quit happens immediately and the body doesn't execute at all.

     This macro is mainly useful in functions that can be called from timers, process filters, process sentinels, pre-command-hook, post-command-hook, and other places where inhibit-quit is normally bound to t.

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

To quit without aborting a keyboard macro definition or execution, you can signal the minibuffer-quit condition.  This has almost the same effect as the quit condition except that the error handling in the command loop handles it without exiting keyboard macro definition or execution.

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

Prefix Command Arguments
========================

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

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

Here are the possible values of a raw prefix argument:

  * nil, meaning there is no prefix argument.  Its numeric value is 1, but numerous commands make a distinction between nil and the integer 1.

  * An integer, which stands for itself.

  * A list of one element, which is an integer.  This form of prefix argument results from one or a succession of C-us with no digits.  The numeric value is the integer in the list, but some commands make a distinction between such a list and an integer alone.

  * The symbol -.  This indicates that M-- or C-u - was typed, without following digits.  The equivalent numeric value is -1, but some commands make a distinction between the integer -1 and the symbol -.

We illustrate these possibilities by calling the following function with various prefixes:

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

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

             M-x display-prefix  -| nil

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

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

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

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

     C-u -   M-x display-prefix  -| -

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

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

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

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

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

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

 -- Variable: current-prefix-arg
     This variable holds the raw prefix argument for the current command.  Commands may examine it directly, but the usual method for accessing it is with (interactive "P").

 -- Variable: prefix-arg
     The value of this variable is the raw prefix argument for the next editing command.  Commands such as universal-argument that specify prefix arguments for the following command work by setting this variable.

 -- Variable: last-prefix-arg
     The raw prefix argument value used by the previous command.

The following commands exist to set up prefix arguments for the following command.  Do not call them for any other reason.

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

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

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

Recursive Editing
=================

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

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

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

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

To invoke a recursive editing level, call the function recursive-edit.  This function contains the command loop; it also contains a call to catch with tag exit, which makes it possible to exit the recursive editing level by throwing to exit (see Catch and Throw).  Throwing a t value causes recursive-edit to quit, so that control returns to the command loop one level up.  This is called aborting, and is done by C-] (abort-recursive-edit).  Similarly, you can throw a string value to make recursive-edit signal an error, printing this string as the message.  If you throw a function, recursive-edit will call it without arguments before returning. Throwing any other value, will make recursive-edit return normally to the function that called it.  The command C-M-c (exit-recursive-edit) does this.

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

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

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

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

     If the current buffer is not the same as the selected window's buffer, recursive-edit saves and restores the current buffer.  Otherwise, if you switch buffers, the buffer you switched to is current after recursive-edit returns.

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

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

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

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

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

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

Disabling Commands
==================

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

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

     (put 'upcase-region 'disabled t)

For a few commands, these properties are present by default (you can remove them in your init file if you wish).

If the value of the disabled property is a string, the message saying the command is disabled includes that string.  For example:

     (put 'delete-region 'disabled
          "Text deleted this way cannot be yanked back!\n")

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

The value of the disabled property can also be a list where the first element is the symbol query.  In that case, the user will be queried whether to execute the command.  The second element in the list should be nil or non-nil to say whether to use y-or-n-p or yes-or-no-p, respectively, and the third element is the question to use.  The command-query convenience function should be used to enable querying for a command.

 -- Command: enable-command command
     Allow COMMAND (a symbol) to be executed without special confirmation from now on, and alter the user's init file (see Init File) so that this will apply to future sessions.

 -- Command: disable-command command
     Require special confirmation to execute COMMAND from now on, and alter the user's init file so that this will apply to future sessions.

 -- Variable: disabled-command-function
     The value of this variable should be a function.  When the user invokes a disabled command interactively, this function is called instead of the disabled command.  It can use this-command-keys to determine what the user typed to run the command, and thus find the command itself.

     The value may also be nil.  Then all commands work normally, even disabled ones.

     By default, the value is a function that asks the user whether to proceed.

Command History
===============

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

 -- Variable: command-history
     This variable's value is a list of recent complex commands, each represented as a form to evaluate.  It continues to accumulate all complex commands for the duration of the editing session, but when it reaches the maximum size (see Minibuffer History), the oldest elements are deleted as new ones are added.

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

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

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

Keyboard Macros
===============

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

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

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

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

     If LOOPFUNC is non-nil, it is a function that is called, without arguments, prior to each iteration of the macro.  If LOOPFUNC returns nil, then this stops execution of the macro.

     See Reading One Event, for an example of using execute-kbd-macro.

 -- Variable: executing-kbd-macro
     This variable contains the string or vector that defines the keyboard macro that is currently executing.  It is nil if no macro is currently executing.  A command can test this variable so as to behave differently when run from an executing macro.  Do not set this variable yourself.

 -- Variable: defining-kbd-macro
     This variable is non-nil if and only if a keyboard macro is being defined.  A command can test this variable so as to behave differently while a macro is being defined.  The value is append while appending to the definition of an existing macro. The commands start-kbd-macro, kmacro-start-macro and end-kbd-macro set this variable---do not set it yourself.

     The variable is always local to the current terminal and cannot be buffer-local.  See Multiple Terminals.

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

     The variable is always local to the current terminal and cannot be buffer-local.  See Multiple Terminals.

 -- Variable: kbd-macro-termination-hook
     This normal hook is run when a keyboard macro terminates, regardless of what caused it to terminate (reaching the macro end or an error which ended the macro prematurely).