2012-07-09

replace-regexp and numbering lines

I saw the Got Emacs? posting showing off the new emacs-24 rectangle-number-lines command, to number a bunch of lines in buffer, i.e..:

foo
bar
cuux

becomes:

1 foo
2 bar
3 cuux

Very cool! An alternative is to use cua-mode, mark the column for the numbers with cua-set-rectangle-mark (C-RET), and then use M-x cua-sequence-rectangle (which takes you throught the steps, and has a lot of flexibility.

But let's look at yet another way: using replace-regexp. If we select (mark) the list once more, we can do M-x replace-regexp RET ^ RET \#. RET Note that the # is a special meta-character that represents the number of replacements already made. This has the somewhat clumsy side-effect that your list be numbered, starting at 0 rather than 1, so you should add a dummy-element at the beginning. Clearly, replace-regexp is inferior for simply adding some line numbers – however, it has the flexibility to do some smarter things.

Smarter things? Yes! replace-regexp allows you to use arbitrary Lisp-expressions in the replace strings. So, let's suppose that we want to use letters instead of numbers for our lines. Easy – again, select (mark) your lines, M-x replace-regexp RET ^ RET \,(format "%c. " (+ ?a \#)) RET and we get:

a. foo
b. bar
c. cuux

Admittedly, not the most world-shattering thing, but it does show the powers hidden in something as common as replace-regexp.

4 comments:

Mathias Dahl said...

Another classic trick is to use a macro together with a counter stored in a register, and increasing that counter in the macro.

Anonymous said...

My version of emacs has rectangle-number-lines.

Is that a typo in the first line?

AArtist said...

replace with \(1+,\#) to avoid adding extra line.

djcb said...

@Anonymous: thanks, fixed.