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

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 range
  • s/^/.../ substitutes the start of each line
  • \= tells :substitute to evaluate the replacement as a Vim expression
  • line('.') is the current line being processed
  • line("'<") is the first line of the visual selection
  • Subtracting and adding 1 gives 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 +1 with +10

Next

How do I launch a GDB session in Vim with the built-in termdebug plugin?