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 shoul
Here's an easy way, without recording a macro:
Make a blockwise, visual selection on the first character of each list item:
^<C-V>2j
Insert a 0.
at the beginning of these lines:
I0. <Esc>
Re-select the visual selection (which is now all of the 0
s) with gv
and increment them as a sequence g<C-A>
:
gvg<C-A>
The entire sequence: ^<C-V>2jI0. <Esc>gvg<C-A>
.
A recording of the process in action.
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).'. '
There are also some plugins for doing this type of work if you have to do it on occasion:
http://vim.sourceforge.net/scripts/script.php?script_id=670
You can use the 'record' feature. It is an easy way to record macros in Vim.
See :help record
In normal mode 'qa' to start recording what you type in the 'a' register Type the necessary command to insert a number at the beginning of line, copy it to next line and use CTRL-A to increase its value. 'q' to end the recording then '@a' to replay the macro stored in register 'a' ('@@' repeat the last macro).
And you can do things like '20@a' to do it twenty times in a row.
It is pretty handy to repeat text modification.
Depending of the cases, it is easier or harder to use than a regexp.
Insert a number at the start of the block of text eg.
1. Item One
Enter the vim normal mode command as follows:
qb^yW+P^<Ctrl-A>q
This means:
qb # start recording macro 'b'
^ # move to start of text on the line
yW # 'yank' or copy a word including the ending whitespace.
+ # move one line down to the start of the next line
P # place text ahead of the cursor
^ # move to start of text
<Ctrl-A> # increment text
q # Finish recording macro
What this allows you to do is replay the macro across the last line of numbered list as many times as needed.
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.