How do I prepend ascending numbers only to the lines in my visual selection?
Answer
:'<,'>s/^/\=line('.')-line("'<")+1 . '. '/
Explanation
When you need quick numbered steps, logs, or checklist entries, this pattern adds numbers only to the lines you selected, not the whole buffer. It uses a visual range and an expression replacement, so the numbering is computed per matched line at execution time. This is especially useful for one-off formatting jobs where macros are overkill.
How it works
:'<,'>s/^/\=line('.')-line("'<")+1 . '. '/
'<,'>targets only the last visual selection ranges/^/.../substitutes the start of each line\=tells:substituteto evaluate the replacement as a Vim expressionline('.')is the current line being processedline("'<")is the first line of the visual selection- Subtracting and adding
1gives a 1-based counter . '. 'appends a period and trailing space after the number
Example
Before:
refactor parser
write migration
add regression test
Select those three lines in Visual Line mode, then run the command.
After:
1. refactor parser
2. write migration
3. add regression test
Tips
- For padded numbers, use
printf('%02d. ', line('.')-line("'<")+1)in the expression - To continue numbering from 10, replace
+1with+10