Emacs: Keyboard Macro
This page shows you how to use emacs keyboard macro feature, with several examples of real world use.
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?
- To start recording, press 【Ctrl+x (】 (
- Type your keystrokes.
- To stop recording, press 【Ctrl+x )】 (
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, call one of:
Most Useful Keyboard Macro Commands
Here are the common keyboard macro commands:
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, call
apropos-command then type “macro”.
Save Keyboard Macro
If you want to use your keyboard macro for future use, you can save it. To save the macro:
name-last-kbd-macroand give it a name.
insert-kbd-macro. This will insert the lisp code for a named kmacro at the cursor position.
- Copy ＆ Paste the code into your emacs init file.
- In any future emacs session, you can call your kmacro by name just like any emacs command.
Once you've saved your macro with a name, you can also give it a keyboard shortcut, such as F8. 〔➤ Emacs: How to Define Keys〕
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.
Keyboard Macro Examples
- Emacs Keyboard Macro Example: Add Title of URL
- Emacs Keyboard Macro Example: Adding HTML Attribute
- Emacs Keyboard Macro Example: Modify Webfeed Entries
- Emacs Keyboard Macro Example: Insert All Unicode Bullets
- Emacs Keyboard Macro Example: Eval Emacs Lisp Repeatedly
- Emacs Edit Exercise: puthash Unicode