Emacs: Keyboard Macro

By Xah Lee. Date: . Last updated: .

This page shows you how to use emacs keyboard macro feature.

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

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

How to Record a Sequence of Keystrokes?

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

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

Run Keyboard Macro

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

Most Useful Keyboard Macro Commands

Note that kmacro-end-and-call-macro is just like call-last-kbd-macro, except that if a kmacro recording is still on-going, it ends it first.

Note: there are more keyboard macro commands than listed above. To list them, Alt+x apropos-command then type “macro”.

Save Keyboard Macro

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

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 Keys]

Keyboard Macro Video Demo

emacs keyboard macro demo

Emacs Keyboard Macro Topic

If you have a question, put $5 at patreon and message me on xah discord.
Or support me by Buy Xah Emacs Tutorial

Emacs Tutorial

Emacs Init

Emacs Keys

ELisp

ELisp Examples

ELisp Write Major Mode


Emacs Tutorial

Quick Start

Manage Windows

File

Buffer

Find Replace

Copy/Paste

Unicode

Whitespace

Rectangle Edit

Line Wrap

Shell

View Special File

Working with Brackets

Org Mode

HTML

Emacs Efficiency

Misc