Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs macro to generate a sequence?

Tags:

emacs

If you are using Emacs 23 (and maybe 22?), use kmacro-insert-counter which is bound to C-x C-k TAB by default. So for your example, you'd do:

C-x ( C-x C-k TAB . RET C-x )

So start macro, insert counter followed by '.', newline, end macro. Then C-x e e e e e e e etc. Or M-1 0 0 C-x e to get 100 of them.

EDIT:

Forgot to mention you can set the counter to an initial value also. For example to start at 1 instead of 0 do M-1 C-x C-k C-c.

And if you don't want the counter to increment at a particular point, prefix it with C-u. Of course the keystrokes are getting a bit ridiculous at this point, so I usually bind a key to insert-but-don't-increment.


Those who feel there are too many tricks to memorize might find acquiring some elisp more profitable:

M-: (dotimes (i 20) (insert (format "%2d.\n" (1+ i))))

Emacs 23 supports elisp snippets in the replacement text of replace-regexp.

I frequently define keyboard macros that follow this pattern:

  • Copy a block of text
  • Navigate to a number that I want to increment in the copied block of text with isearch
  • Activate the mark and move the point to define a region encompassing the number
  • M-x replace-regexp
  • At the "Replace regexp" prompt, enter \([0-9]+\) to capture a group of one or more digits
  • At the "Replace regexp ([0-9]+) with:" prompt, enter \,(1+ \#1), where , indicates that an elisp form to substitute follows, 1+ is an increment function, and \#1 is the first captured match text, interpreted as a number.

After taking a minute to define the keyboard macro, this allows me to have almost the convenience of cutting and pasting to generate lots of blocks of almost-identical code, such as for case statements.

Note that this technique can be easily adapted to e.g. double numbers (\,(* 2 \#1)) or whatever. You can even use it to substitute the next element in an arbitrary sequence by using a combination of 'position and 'nth, but I won't go into that now :).


Since release 24.3 of Emacs (I believe actually since release 24.0), the keystroke sequence has been simplified:

<F3> <F3> . <ENTER> <F4>

Then repeating <F4> key will repeat the macro.

The trick is that, after having started a macro with <F3>, a second <F3> key press will insert the current value of the keyboard macro's counter into the buffer, and increments the counter by 1.

Other tricks:

  • <F3> C-u 2 <F3> . <ENTER> <F4> will increment with +2 (instead of +1)
  • C-u 100 <F3> <F3> . <ENTER> C-u 50 <F4> will start at 100 and finish at 149
  • C-x C-k C-f %03d <ENTER> <F3> <F3> . <ENTER> <F4> will pad with zero like "000"

Source: Keyboard Macro Counter section in Emacs manual.


Beside scottfrazer's answer, there is another way to create a sequence of numbers with CUA mode which may help you a lot when editing existing content. See Mark Mansour's screencast on Emacs Column Editing from position 2:30.