vimtricks.wiki Concise Vim tricks, one at a time.

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

  1. Visually select the lines you want to number (e.g., V then j to extend)
  2. Type : to enter command mode (Vim auto-fills :'<,'>)
  3. The substitution s/^/\=expr/ replaces the start of each line with the result of an expression
  4. line('.') returns the current line number in the file
  5. line("'<") returns the first line of the visual selection
  6. Subtracting and adding 1 gives a 1-based index relative to the selection
  7. . '. ' 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 :%s instead of a visual selection
  • You can adapt the pattern to add other prefixes like - [ ] for checklists

Next

How do I ignore whitespace changes when using Vim's diff mode?