Emacs: Keyboard Macro

By Xah Lee. Date: . Last updated: .

What is Key Macro

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

geek vs non geek repetitive tasks
(original bitmap drawing by [Bruno Oliveira https://plus.google.com/102451193315916178828/posts/MGxauXypb1Y]. Used with permission)

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

If you call apply-macro-to-region-lines make sure that when you record a macro, best to start by putting cursor at beginning of a line, record the macro, and end with cursor the same line. No need to move to next line.

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

with a name, now you can give it a keyboard shortcut, such as F8. [see Emacs Keys: Define Key]

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

Moving to Next Line in Keyboard Macro

To move to the next logical line (line with a line return at the end), move to end of line first, then right cursor moves it to beginning of next line. Because if you have Emacs: Visual Line Mode on, down arrow may move to the next visual line.

Reference

Emacs Keyboard Macro