Emacs: Keyboard Macro Tutorial

Buy Xah Emacs Tutorial. Master emacs benefits for life.
, , …,

This page shows you how to use emacs keyboard macro feature, with several examples of real world use.

geek vs non geek repetitive tasks
(original bitmap drawing by Bruno Oliveira. 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 (】 (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, call one of:

Most Useful Keyboard Macro Commands

Here are the common keyboard macro commands:

Primary Keyboard Macro Commands
Command NameKey
start-kbd-macroCtrl+x (
end-kbd-macroCtrl+x )
kmacro-end-and-call-macroCtrl+x e
call-last-kbd-macro
apply-macro-to-region-lines

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, 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:

  1. Call name-last-kbd-macro and give it a name.
  2. Call insert-kbd-macro. This will insert the lisp code for a named kmacro at the cursor position.
  3. Copy & Paste the code into your emacs init file.
  4. 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. (Emacs 23's default is visual line.) To set to logical line, call set-variable, then give line-move-visual, with value “nil”. (“t” for true; “nil” for false).

When you play back macro, be sure the line-move-visual is the same as when you recorded it.

One thing you can do is to set line-move-visual at the beginning of your keyboard macro, and set it back at the end.

Here's a command to toggle it.

(defun toggle-line-move-visual ()
  "Toggle behavior of up/down arrow key, by visual line vs logical line."
  (interactive)
  (if line-move-visual
      (setq line-move-visual nil)
    (setq line-move-visual t)))

Keyboard Macro Examples

Like it?
Buy Xah Emacs Tutorial
or share
blog comments powered by Disqus