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

How do I use Vim as an inline calculator with the expression register?

Answer

<C-r>=expression<CR>

Explanation

The expression register ("=) evaluates Vimscript expressions and returns the result. In insert mode, <C-r>= opens a prompt where you can type any expression — math, string operations, function calls — and the result is inserted at the cursor.

How it works

  1. Enter insert mode
  2. Press <C-r>=
  3. Type an expression at the = prompt
  4. Press <CR> — the result is inserted

Math examples

<C-r>=2+2<CR>            " Inserts: 4
<C-r>=128*1024<CR>       " Inserts: 131072
<C-r>=3.14*5*5<CR>       " Inserts: 78.5
<C-r>=0xff<CR>           " Inserts: 255
<C-r>=pow(2,10)<CR>      " Inserts: 1024.0
<C-r>=sqrt(144)<CR>      " Inserts: 12.0

String examples

<C-r>=toupper('hello')<CR>          " Inserts: HELLO
<C-r>=repeat('-', 40)<CR>           " Inserts: ----------------------------------------
<C-r>=strftime('%Y-%m-%d')<CR>      " Inserts: 2025-01-15
<C-r>=line('.')<CR>                 " Inserts: current line number
<C-r>=expand('%:t')<CR>             " Inserts: current filename (without path)

In normal mode

" Paste the result of an expression
"=42*3<CR>p    " Pastes: 126

Tips

  • The = prompt has full Vimscript access — any function, variable, or expression works
  • Use printf() for formatted output: <C-r>=printf('0x%04X', 255)<CR> inserts 0x00FF
  • Access other registers in the expression: <C-r>=@0 . ' suffix'<CR> appends text to the yank register
  • This also works in the command line (: prompt)
  • For quick math while editing, this is faster than opening a separate calculator
  • Documented under :help expression-register and :help i_CTRL-R_=

Next

How do I run the same command across all windows, buffers, or tabs?