Macro Counters

I’ve posted about using keyboard macros to record and play back repetitive tasks. Macros include a counter which lets you insert numerical values that increment each time the macro is called.

For example, go to a new line and start a macro with C-x ( and then hit C-a to move to the start of the line, C-x C-k C-i to insert the macro counter (initially zero) and then RET to go to a new line and C-x ) to stop the recording. Run the macro a few times with C-x e and then just e to repeat the macro and you’ll get something like this:

0
1
2
3
4

The counter starts at zero every time you define a new macro. To set it to another value, use C-x C-k C-c before defining or invoking a macro.

  • Damien Cassou

    I used to use the same keybindings as you before but always forgot about the counter ones. Now, I switched to the F3 and F4 keybindings which are by default respectively bound to kmacro-start-macro-or-insert-counter and kmacro-end-or-call-macro. These two keybindings replace the 4 keybindings you discuss in your post. I have no problem remembering them anymore. I suggest anyone to try F3 and F4.

    • Thanks for the good suggestion. I don’t like using the function keys on my laptop but there is nothing stopping me from rebinding C-x ( etc to the same functions. I’ll give that a try!

    • David Ongaro

      Me too. I never could remember these other bindings and find F3, F4 much more convenient. Note that you also can set a macro counter start value by providing a prefix argument before starting to record the macro with F3.