how to repeat the last or previous command in emacs editor

One of the useful features of an editor is the ability repeat commands with minimal keystrokes. Many users find it useful when having to execute arduous long commands that require some typing.

The emacs repeat command will repeat the last action that was performed while ignoring the input events like moving around in the buffer.

M-x repeat

It is bound to the C-x z keychord and to eliminate the need to press C-x multiple times, you can press the z key repeatedly after the first invocation of the command. If you know the number of times you want to execute the last command ahead of time, then you could use the universal argument to do so.

C-u 9 C-x z

The above keychord will execute the command 9 times.

This is useful for executing simple commands but doesn’t do well when wanting to execute complex chain of commands. The keyboard macro feature of emacs might be more appropriate for such tasks.

There are other options available to do complex stuff. The emacs command repeat-complex-command will allow you to browse and execute a previously executed command.

M-x repeat-complex-command

The command is mapped to C-x M-ESC shortcut (or C-x ESC ESC) and it will convert the previous commands to an equivalent elisp function call and populate the minibuffer with it. It allows you to browse the previous commands using the arrow keys or the M-n and M-p keys. You can edit the command if needed before executing it.

If you have the consult package installed, then there is friendly version of the command which is mapped to C-x M-:.

Another related command is the repeat-matching-complex-command. This will allow you to search the previous commands using regular expression. It is useful if you know what you are searching for.