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?
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.
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.
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.
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).'. '
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With