How do I use a macro to generate a numbered list automatically?
Answer
qaYp<C-a>q99@a
Explanation
By recording a macro that duplicates a line and increments its number, you can generate a numbered list of any length with a single replay command. The <C-a> key increments the number under the cursor, and repeating the macro builds the sequence automatically.
How it works
qastarts recording into registeraYyanks the current lineppastes it below<C-a>increments the first number found on the lineqstops recording99@areplays the macro 99 times, generating 100 total lines
The macro will stop early if it encounters an error (like reaching a maxfuncdepth limit), but for simple numbered lists this pattern works flawlessly.
Example
Start with a single line:
1. Item
Record the macro with qaYp<C-a>q, then replay with 9@a to get:
1. Item
2. Item
3. Item
4. Item
5. Item
6. Item
7. Item
8. Item
9. Item
10. Item
11. Item
Or start with a more complex template:
test_case_1: assert_equal(expected_1, actual_1)
The macro increments every number on the line if you position <C-a> appropriately, or you can target specific numbers by adding motions before <C-a> in the recording.
Tips
- Use
<C-x>instead of<C-a>to decrement numbers — useful for countdowns - Add
0before<C-a>in the macro to always move to the start of the line first, ensuring the correct number is incremented:qa Y p 0 <C-a> q - For multiple numbers on one line, use a count or repeat
<C-a>:3<C-a>increments by 3 - Combine with visual block mode's
g<C-a>for sequential incrementing without macros at all — select a column of identical numbers andg<C-a>turns them into a sequence - If the line contains multiple numbers and you only want to increment a specific one, navigate to it with
forwbefore pressing<C-a>during recording - Undo the entire generated list with
uif the count was wrong, then replay with the correct count