How do I turn a visual selection of lines into a numbered list?
Answer
:s/^/\=line('.') - line("'<") + 1 . '. '/
Explanation
When you need to quickly number a set of lines — such as TODO items, steps, or bullet points — you can use a visual selection combined with a substitution expression. This avoids manually typing numbers or reaching for external tools.
How it works
- Visually select the lines you want to number (e.g.,
Vthenjto extend) - Type
:to enter command mode (Vim auto-fills:'<,'>) - The substitution
s/^/\=expr/replaces the start of each line with the result of an expression line('.')returns the current line number in the fileline("'<")returns the first line of the visual selection- Subtracting and adding 1 gives a 1-based index relative to the selection
. '. 'concatenates a dot and space after the number
Example
Before (lines selected with V):
Buy groceries
Clean the house
Write documentation
Review pull request
After running the command:
1. Buy groceries
2. Clean the house
3. Write documentation
4. Review pull request
Tips
- For zero-padded numbers, use
printf()in the expression:\=printf('%02d. ', line('.') - line("'<") + 1) - To number all lines in the file, use
:%sinstead of a visual selection - You can adapt the pattern to add other prefixes like
- [ ]for checklists