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

How do I perform arithmetic calculations and insert the result without leaving insert mode?

Answer

<C-r>={expr}<CR>

Explanation

The expression register ("=) lets you evaluate any Vimscript expression and insert the result directly into the buffer — all without leaving insert mode. This makes it ideal for quick calculations, line-number references, or string manipulations during typing.

How it works

  • <C-r> in insert mode pastes the contents of a register
  • = specifies the expression register, which accepts a Vimscript expression instead of stored text
  • Type your expression at the prompt and press <CR> — the evaluated result is inserted at the cursor

Example

While in insert mode, you need to insert the result of a calculation:

Press <C-r>= to open the = prompt, then type:

1024 * 1024 * 8

Press <CR> and 8388608 is inserted into your text.

Other useful expressions:

line('.')          " current line number
strftime('%Y-%m-%d') " today's date
expand('%:t')      " current filename
pi()               " 3.14159...

Tips

  • Works in command-line mode too: type <C-r>= at the : prompt to insert a computed value into an Ex command
  • Chain with printf() to format output: <C-r>=printf('%08x', 255)<CR> inserts 000000ff
  • Access other registers inside the expression: <C-r>=@a . ' suffix'<CR> appends suffix to register a content before inserting

Next

How do I refer to the matched text in a Vim substitution replacement?