8.11 Repeating a Command

Many simple commands, such as those invoked with a single key or with M-x command-name RET, can be repeated by invoking them with a numeric argument that serves as a repeat count (see Numeric Arguments). However, if the command you want to repeat prompts for input, or uses a numeric argument in another way, that method won’t work.

The command C-x z (repeat) provides another way to repeat an Emacs command many times. This command repeats the previous Emacs command, whatever that was. Repeating a command uses the same arguments that were used before; it does not read new arguments each time.

To repeat the command more than once, type additional z’s: each z repeats the command one more time. Repetition ends when you type a character other than z or press a mouse button.

For example, suppose you type C-u 2 0 C-d to delete 20 characters. You can repeat that command (including its argument) three additional times, to delete a total of 80 characters, by typing C-x z z z. The first C-x z repeats the command once, and each subsequent z repeats it once again.

You can also activate repeat-mode which allows repeating commands bound to sequences of two or more keys by typing a single character. For example, after typing C-x u (undo, see Undo) to undo the most recent edits, you can undo many more edits by typing u u u…. Similarly, type C-x o o o… instead of C-x o C-x o C-x o… to switch to the window several windows away. This works by entering a transient repeating mode after you type the full key sequence that invokes the command; the single-key shortcuts are shown in the echo area.

Only some commands support repetition in repeat-mode; type M-x describe-repeat-maps RET to see which ones.

The single-character shortcuts enabled by the transient repeating mode do not need to be identical: for example, after typing C-x {, either { or } or ^ or v, or any series that mixes these characters in any order, will resize the selected window in respective ways. Similarly, after M-g n or M-g p, typing any sequence of n and/or p in any mix will repeat next-error and previous-error to navigate in a *compilation* or *grep* buffer (see Compilation Mode).

Typing any key other than those defined to repeat the previous command exits the transient repeating mode, and then the key you typed is executed normally. You can also define a key which will exit the transient repeating mode without executing the key which caused the exit. To this end, customize the user option repeat-exit-key to name a key; one natural value is RET. Finally, it’s possible to break the repetition chain automatically after some amount of idle time: customize the user option repeat-exit-timeout to specify the idle time in seconds after which this transient repetition mode will be turned off automatically.