How do I do math calculations without leaving insert mode?
Answer
<C-r>=
Explanation
The expression register (<C-r>=) lets you evaluate Vimscript expressions on the fly and insert the result directly into your text. Press <C-r>= in insert mode, type any expression, and hit <CR> — the result appears at your cursor position.
How it works
- While in insert mode, press
<C-r>=to open the expression prompt at the bottom of the screen - Type any valid Vimscript expression (arithmetic, string manipulation, function calls)
- Press
<CR>to insert the evaluated result at the cursor
Example
You're writing a comment and need to calculate a value:
// Timeout is set to | milliseconds
With the cursor at | in insert mode, press <C-r>= then type 60 * 60 * 1000<CR>. The result is inserted:
// Timeout is set to 3600000 milliseconds
You can also use it for string operations:
<C-r>=toupper('hello')<CR>
Inserts HELLO at the cursor.
Tips
- Use
<C-r>=system('date')<CR>to insert the output of a shell command - Access Vim variables:
<C-r>=&shiftwidth<CR>inserts the current shiftwidth value - Use
<C-r>=line('.')<CR>to insert the current line number - In normal mode,
"=2+2<CR>puses the expression register to paste the result - Combine with
printf()for formatted output:<C-r>=printf('0x%04X', 255)<CR>inserts0x00FF - The expression register is also available in command-line mode with
<C-r>=