$ cat "

Emacs replace-regexp fu #2: Bulleted list to numbered list

"

Time for some emacs regex love again! This time the scenario is as follows:

You have a simple flat list of stuff in a typical markdown bullet list style.

* Foo
* Foo
* Foo
* Foo
* Foo
* Foo
* Foo
* Foo

That list should be transformed into a numbered (one based) list, like so:

1. Foo
2. Foo
3. Foo
4. Foo
5. Foo
6. Foo
7. Foo
8. Foo

As you can probably guess, it's that happy regex time again! Since emacs has the handy \# thingy that gives you the match index, this should go smoothly. So let's give it a go:

M-x replace-regex

and then we use the following patterns:

Match: ^\* \(.+\)$
Replace: \#. \1

This gives us the following result:

0. Foo
1. Foo
2. Foo
3. Foo
4. Foo
5. Foo
6. Foo
7. Foo

Almost there, but the match index is zero based and we wanted a one based list, so there is still some work to do. So, now we need to do some math in our regex, and hence it is lisp time!

Let's undo the replace and give it another go:

Match: ^\* \(.+\)$
Replace: \,(+ 1 \#). \1

This yields the desired result:

1. Foo
2. Foo
3. Foo
4. Foo
5. Foo
6. Foo
7. Foo
8. Foo

Now we can take a moment to bask in the glory of the lisp regex.

Written by Erik Öjebo 2012-09-20 20:35

    Comments