Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macro for making numbered lists in vim?

Tags:

vim

macros

Often times it seems I have a list of items, and I need to add numbers in front of them. For example:

Item one Item two Item three 

Which should be:

1. Item one 2. Item two 3. Item three 

In vim, I can press I in edit mode, insert "1.", hit escape. Then I go to the next line, press ., and then ^A to increment the number. This seems hugely inefficient... how would I make a macro so that I can go to the next line, and insert a number at the beginning which is one greater than the line before?

like image 880
Nik Reiman Avatar asked Nov 19 '10 11:11

Nik Reiman


People also ask

How do I create a numbered list in Vim?

In Vim 8, the first number in a selection can be incremented by pressing Ctrl-A. If the selection covers several lines, the first number in the selection on each line is incremented. Alternatively, numbers in a selection covering several lines can be converted to a sequence by typing g Ctrl-A.

How do I create a macro in Vim?

To record a macro and save it to a register, type the key q followed by a letter from a to z that represents the register to save the macro, followed by all commands you want to record, and then type the key q again to stop the recording.


2 Answers

You can easily record a macro to do it.

First insert 1. at the start of the first line (there are a couple of spaces after the 1. but you can't see them).

Go to the start of the second line and go into record mode with qa.

Press the following key sequence:

i                         # insert mode <ctrl-Y><ctrl-Y><ctrl-Y>  # copy the first few characters from the line above   <ESC>                     # back to normal mode |                         # go back to the start of the line <ctrl-A>                  # increment the number j                         # down to the next line q                         # stop recording 

Now you can play back the recording with @a (the first time; for subsequent times, you can do @@ to repeat the last-executed macro) and it will add a new incremented number to the start of each line.

like image 59
Dave Kirby Avatar answered Oct 05 '22 08:10

Dave Kirby


Select your lines in visual mode with: V, then type:

:'<,'>s/^\s*\zs/\=(line('.') - line("'<")+1).'. ' 

Which is easy to put in a command:

command! -nargs=0 -range=% Number <line1>,<line2>s/^\s*\zs/\=(line('.') - <line1>+1).'. ' 
like image 24
Luc Hermitte Avatar answered Oct 05 '22 09:10

Luc Hermitte