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 characters that translates into a command.  It does this by calling the function read-key-sequence.  Your Lisp code can also call this function (see Keyboard Input).  Lisp programs can also do input at a lower level with read-char or discard pending input with discard-input.

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

Once the command is read, it must be executed, which includes reading arguments to be given to it.  This is done 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 command's function body does not use the minibuffer; if you call this command from Lisp code as a function, you must supply the file name string as an ordinary Lisp function argument.

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

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

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

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

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

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

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

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

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

There are three possibilities for the argument ARG-DESCRIPTOR:

  * 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 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.

  * It may be a string; then its contents should consist of a code character followed by a prompt (if required for that code character).  The prompt ends either with the end of the string or with a newline.  Here is a simple example:

          (interactive "bFrobnicate buffer: ")

     The code letter b says to read the name of an existing buffer, with completion.  The buffer name will be the sole argument passed to the command.  The rest of the string is a prompt.

     If there is a newline character in the string, it terminates the prompt. If the string does not end there, then the rest of the string should contain another code character and prompt, specifying another argument. Any number of arguments may be specified in this way.

     If the first character in the string is *, then an error is signaled if the buffer is read-only.  Otherwise, the following character is the first code character.

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.

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

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.

Here are the code character descriptions for use with interactive:

a
     A function name (i.e., a symbol which is 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, 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 a number (see Point).  No I/O.

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

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

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

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

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

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

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

N
     The raw prefix argument.  If the prefix argument is nil, then a number is read as with n.  Requires a number.  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.) See Prefix Command Arguments.  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.  No I/O.

s
     Arbitrary text, read in the minibuffer and returned as a string (see Text from Minibuffer).  Terminate the input with either LFD 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.  Any whitespace character terminates the input.  (Use C-q to include whitespace in the string.)  Other characters that normally terminate a symbol (e.g., parentheses and brackets) do not do so here.  Prompt.

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

x
     A Lisp object specified in printed representation, terminated with a LFD or RET.  The object is not evaluated.  See Object from Minibuffer.  Prompt.

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

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

Here are some examples of interactive:

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

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

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

     (defun three-b (b1 b2 b3)
       "Select three existing buffers (prompting for them in
     the Minibuffer).  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

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

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

 -- Function: commandp object
     Returns t if OBJECT is suitable for calling interactively; that is, if OBJECT is a command.  Otherwise, returns nil.

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

     A symbol is commandp if its function definition is commandp.

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

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

 -- Function: call-interactively command &optional record-flag
     This function calls the interactively callable function COMMAND, reading arguments according to its interactive calling specifications. An error is signaled if COMMAND cannot be called interactively (i.e., it is not a command).  Note that strings are not accepted, even though they are considered commands.

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

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

     A string as COMMAND is executed with execute-kbd-macro.  A function is passed to call-interactively, along with the optional RECORD-FLAG.

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

 -- Command: execute-extended-command prefix-argument
     This primitive 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, the value PREFIX-ARGUMENT is supplied.  If execute-extended-command is called interactively, the current raw prefix argument is used for PREFIX-ARGUMENT, and thus passed on to whatever command is run.

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

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

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

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

     For example:

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

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

          ;; Type M-x foo.
               -| foo

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

          foobar
               => (nil t)

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

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

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

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

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

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

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

 -- Function: this-command-keys
     This function returns a string containing the key sequence that invoked the present command, plus any previous commands that generated the prefix argument for this command.

          (this-command-keys) ;; Now type C-u C-x C-e.
               => "^U^X^E"

 -- Variable: last-command-char
     This variable is set to the last character that was typed on the terminal and was 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-char ;; Now type C-u C-x C-e.
               => 5

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

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

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

Keyboard Input
==============

The editor command loop reads keyboard input using read-key-sequence, which uses read-char.  These and other functions for keyboard 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.

 -- Function: read-char
     This function reads a character from the command input (either from direct keyboard input or from an executing keyboard macro), and returns it.

     No message is displayed to indicate that keyboard input is expected.  If you want to display a message, call message first.  If cursor-in-echo-area is non-nil, then the cursor moves to the echo area, to the end of any message displayed there.  Otherwise the cursor does not move.  See The Echo Area.

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

          (read-char)
               => 49

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

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

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

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

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

          (read-quoted-char "What character")

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

               => 127

 -- Function: read-key-sequence prompt
     This function reads a key sequence and returns it as a string.  It keeps reading characters until it has accumulated a full key sequence; that is, enough characters to specify a non-prefix command using the current local and global keymaps.  read-key-sequence is used by the command loop to read command input.

     If an input character is an upper case letter and has no definition, but the lower case equivalent is defined, then the character is converted to lower case.  Note that lookup-key does not perform case conversion in this way.

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

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

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

          (read-key-sequence "?")

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

               => "^X^F"

 -- Variable: unread-command-char
     This variable holds a character waiting to be read as the next input from the command input stream, or to the integer -1 if no character is waiting.  The variable is used because in some cases an input function reads a character and then decides not to use it. Storing the character in this variable causes it to be processed normally by the command loop or when read-char is next called.

     For example, the function that governs prefix arguments reads any number of digits.  When it finds a non-digit character, it must unread the character so that it becomes input for the next command.  Likewise, incremental search uses this feature to unread a control character used to terminate the search.

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

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

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

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

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

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

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

Quitting
========

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Here are the possible values of a raw prefix argument:

  * 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-u's 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 -.

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

     (defun print-prefix (arg)
       "Print the value of the raw prefix arg at point."
       (interactive "P")
       (message "%s" arg))

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

             M-x print-prefix  -| nil

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

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

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

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

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

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

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

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

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

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

Don't call universal-argument, digit-argument, or negative-argument unless you intend to let the user enter the prefix argument for the next command.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

          (defun simple-rec ()
            (forward-word 1)
            (message "Recursive edit in progress.")
            (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 .emacs file with Lisp expressions such as this:

     (put 'upcase-region 'disabled t)

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

If the value of the disabled property is a string, that string is included in the message printed when the command is used:

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

See 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.

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

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

 -- Variable: disabled-command-hook
     The value of this variable is a function to be called instead of any command that is disabled (i.e., that has a non-nil disabled property).  By default, the value of disabled-command-hook is a function defined to ask the user whether to proceed.

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

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

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

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

There are a number of commands and even two entire modes devoted to facilitating 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)).

 -- Variable: repeat-complex-command-map
     The value of this variable is a sparse keymap used by the minibuffer inside of read-complex-command.

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

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

 -- Function: execute-kbd-macro macro &optional count
     This function executes MACRO as a string of editor commands.  If MACRO is a string, then the characters in that string are executed exactly as if they had been typed as command input.

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

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

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

 -- Variable: executing-macro
     This variable contains the string that defines the keyboard macro that is currently executing.  It is nil if no macro is currently executing.

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

The user-level commands for defining, running and editing keyboard macros include call-last-kbd-macro, insert-kbd-macro, start-kbd-macro, end-kbd-macro, kbd-macro-query, and name-last-kbd-macro.  They are described in the user's manual (see Keyboard Macros (The GNU Emacs Manual)).