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

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+3 inserts 5
  • Variables: i inserts the value of variable i
  • Functions: line('.') inserts the current line number
  • String operations: toupper('hello') inserts HELLO

Example

To create a macro that inserts the current line number at the beginning of each line:

  1. Position on the first line
  2. Record: qaI<C-r>=line('.')<CR>. <Esc>jq
  3. This inserts the line number followed by a dot and space, then moves down
  4. Run 5@a to 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.

Next

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