Emacs: Keyboard Macro

By Xah Lee. Date: . Last updated: .

Emacs keyboard key macro (kmacro) feature lets you record and playback keystrokes. The key strokes can include calling any emacs commands.

Record a Key Macro

  1. To start recording, press Ctrl+x ( (kmacro-start-macro).
  2. Type your keystrokes.
  3. To stop recording, press Ctrl+x ) (kmacro-end-macro).

If you made a mistake, you can cancel Ctrl+g (keyboard-quit) and start over.

Run Keyboard Macro

To run the keystrokes you've just recorded, use one of:

another useful command to run key macro is

Save Keyboard Macro

Key macro can be saved for future use.

To save the macro:

  1. Alt+x name-last-kbd-macro and give it a name.
  2. Alt+x insert-kbd-macro. This will insert the lisp code for a named kmacro at the cursor position.
  3. Copy and Paste the code into your Emacs Init File.
  4. In future emacs session, you can call your kmacro by name. e.g. Alt+x name.

You can now also give it a keyboard shortcut, such as F8. [see Emacs: How to Define Keybinding]

emacs macros 2018-06-19 8a530
example of saved emacs macros

Emacs Keyboard Macro video tutorial

Xah Talk Show 2022-09-15 Emacs Key Macro

Turn Off line-move-visual

When you record keystrokes, you might want the arrow up/down keys move the cursor by a logical line, as opposed to visual line. For how to change that, see: Emacs: line-move-visual.

Reference

(info "(emacs) Keyboard Macros")

Emacs Keyboard Macro


Emacs Tutorial

Quick Start

Font

Split Window

File

Buffer

Copy/Paste

Find Replace

Unicode

Whitespace

Rectangle Edit

Line Wrap

Shell

View Special File

Editing Brackets

Org Mode

HTML

Emacs Efficiency

Misc