Keyboard Macro Counters

Emacs is incredibly useful for repetitive editing chores. For example, this Xah Lee post shows how Lee performed major surgery on hundreds of pages of HTML by using a little Emacs Lisp.

Not everyone can or wants to write Emacs Lisp but even without it you can still do a lot of automation with keyboard macros. Most Emacs users are familiar with the fundamentals: use 【Ctrl+x (】 or 【F3】 to start recording your keystrokes, perform the repetitive action one time and stop the recording with 【Ctrl+x )】 or 【F4】. Then you can repeat the keystrokes with 【Ctrl+x e】. After the first repeat you can simply type 【e】 for subsequent repeats.

Here's a little trick I learned from the EmacsWiki. Suppose you want to create a list of host names where each differs from the others by a number at the end

To do that, follow these steps

  1. Ctrl+x Ctrl+k Ctrl+a1 to set the amount to increment the counter on each repetition.
  2. Ctrl+x Ctrl+k Ctrl+c1 to set the initial value of the counter.
  3. Ctrl+x (】 to start recording the macro
  4. hostCtrl+x Ctrl+k Ctrl+i】 to insert the current counter value after host.
  5. .irreal.orgReturn Ctrl+x )】 to stop recording the macro.
  6. Ctrl+x e】 to generate the next host name.
  7. e】 to generate another and so on.

You can also use 【Ctrl+x Ctrl+k Ctrl+f】 to set the format of the counter.

This entry was posted in General. Bookmark the permalink.
  • foo

    C-u 1 (initialize counter to 1 and start macro)
    host (inserts value of the counter and increase it)
    (ends macro)
    (inserts macro)