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
- Initialize:
:let i = 1 - Record macro:
qa - Insert the counter:
i<C-r>=i<CR><Esc> - Increment:
:let i += 1<CR> - 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>=evaluatesiduring insert :let i += 1increments 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