Performing calculations

4.7
(58)

Vim’s expression register is a temporary register that can be used to run snippets of Vim script. We can use this for a variety of things, anytime we want to evaluate Vim script. One helpful use case for this is to perform math calculations right inside Vim, inserting the result into our document. To use the expression register, press <ctrl-r>= from insert mode.

  • <ctrl-r>= – From insert mode, enters Vim’s expression register

Type some simple calculation like 1 + 2 and press <enter> and 3 will be inserted into your document. Think of the expression register as a little Vim command line that evaluates whatever you put into it and inserts the results into your document. Take a look at this in action:

What if you have a mathematical expression already visible in your file? We can yank that and paste it into the expression register.

  • v w w to visually select the expression
  • y to yank (copy) it
  • A to enter insert mode at the end of the line
  • <ctrl-r>= to enter the expression register
  • <ctrl-r>" to paste the yanked text from the default register
  • <enter> to perform the calculation and insert the result

There’s a short video of that method below. As is common to many languages, dividing an integer by an integer will yield a rounded integer. So if you want to get a float out, make sure your expression uses floats.

How useful was this tip?

Average rating 4.7 / 5. Vote count: 58

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

90 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts

Leave a reply

Your email address will not be published. Required fields are marked *