How do I use the expression register inside a macro for dynamic values?
Answer
qa<C-r>=expression<CR>q
Explanation
How it works
The expression register (=) lets you evaluate Vimscript expressions and insert the result. When combined with macro recording, this creates powerful dynamic macros that can compute values on the fly.
During insert mode (or command-line mode), pressing Ctrl-R = opens the expression prompt. You type a Vimscript expression, press Enter, and the result is inserted at the cursor position. This entire sequence gets recorded as part of your macro.
Common expressions you can use include:
- Arithmetic:
2+3inserts5 - Variables:
iinserts the value of variablei - Functions:
line('.')inserts the current line number - String operations:
toupper('hello')insertsHELLO
Example
To create a macro that inserts the current line number at the beginning of each line:
- Position on the first line
- Record:
qaI<C-r>=line('.')<CR>. <Esc>jq - This inserts the line number followed by a dot and space, then moves down
- Run
5@ato number the next 5 lines
Given:
apple
banana
cherry
The result after running from line 1:
1. apple
2. banana
3. cherry
The expression line('.') is evaluated fresh each time the macro runs, so each line gets its correct line number. This is far more flexible than a static macro.