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

How do I insert sequential line numbers using visual block mode?

Answer

<C-v>jjI\=printf('%02d ', line('.')-line("'<")+1)<CR><Esc>

Explanation

By combining visual block insert with Vim's expression register, you can insert dynamically computed line numbers at the start of each selected line. The expression register (=) evaluates a Vimscript expression for each line, allowing sequential numbering.

How it works

  • <C-v>jj — select lines in block mode
  • I — enter insert mode at the start of the block
  • <C-r>= — invoke the expression register
  • printf('%02d ', line('.')-line("'<")+1) — calculates the relative line number, zero-padded
  • <CR><Esc> — confirm expression and apply to all lines

Example

Before:
apple
banana
cherry

After:
01 apple
02 banana
03 cherry

Tips

  • Use g<C-a> on a visual selection of zeros for a simpler numbering approach
  • Change the printf format for different styles: '%d. ' for 1. 2. 3.
  • line("'<") gives the first line of the selection for relative numbering
  • For absolute line numbers, just use line('.') without the offset

Next

How do I return to normal mode from absolutely any mode in Vim?