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

How do I create a macro that uses an incrementing counter?

Answer

Use :let i=1 with macro

Explanation

By combining a Vimscript variable with a macro, you can create sequences with incrementing numbers. The variable increments each time the macro runs.

How it works

  1. Initialize: :let i = 1
  2. Record macro: qa
  3. Insert the counter: i<C-r>=i<CR><Esc>
  4. Increment: :let i += 1<CR>
  5. Stop: q

Example

Create numbered items:

:let i = 1
qaI<C-r>=i<CR>. <Esc>:let i += 1<CR>jq

Running @a on each line produces:

1. first item
2. second item
3. third item

Tips

  • The expression register <C-r>= evaluates i during insert
  • :let i += 1 increments after each use
  • This is more flexible than g<C-a> for complex numbering
  • Can use any expression: :let i = char2nr('A') for letter sequences

Next

How do you yank a single word into a named register?