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

How do I insert the result of a calculation directly while typing in insert mode?

Answer

<C-r>=2+2<CR>

Explanation

The expression register (<C-r>=) in insert mode lets you evaluate any Vimscript expression and insert the result inline. This turns Vim into a calculator and lets you insert dynamic values, function results, or environment variables without leaving insert mode.

How it works

  • <C-r>= — opens the expression prompt at the bottom of the screen
  • Type any Vimscript expression
  • Press <CR> — the result is inserted at the cursor
  • Works in insert mode and command-line mode

Example

In insert mode:
<C-r>=2+2<CR>         → inserts: 4
<C-r>=0xff<CR>        → inserts: 255
<C-r>=strftime('%c')<CR> → inserts: Thu Jan 15 14:30:00 2024
<C-r>=line('.')<CR>   → inserts current line number

Tips

  • Supports all Vimscript functions: strlen(), toupper(), system(), etc.
  • Use system('cmd')[:-2] to insert shell command output (trims trailing newline)
  • Float arithmetic works: <C-r>=3.14*2<CR> → 6.28
  • <C-r>=@a<CR> inserts register a contents (alternative to <C-r>a)

Next

How do I return to normal mode from absolutely any mode in Vim?