- Published on
Doing math calculation in VIM
In vim, there is a register called =
which can be used to evaluate an expression. In this post, I will show you how to select an expression and calculate the result and insert the result in VIM.
Consider you have the following expression in your VIM editor:
Q: We have 3 apples and 4 oranges, how many fruits do we have in total?
A: 3 + 4 =
^ cursor here
You can use the following steps to calculate the result and insert it after the =
:
- Make sure you are in insert mode by pressing
a
. - Press
ctrl + r
followed by=
to use the expression register. - Now type the expression
3 + 4
and pressEnter
. - The result
7
will be inserted after the=
. - Press
Esc
to exit insert mode.
After the above steps, the text will become:
Q: We have 3 apples and 4 oranges, how many fruits do we have in total?
A: 3 + 4 = 7
^ cursor here
But wait, what if you have a long expression that you want to calculate, you don't want to type the whole expression again! You can use the registers to store the expression and use it later in command mode. Consider you have the following expression:
I have a long expression, 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 =
^ cursor here
You can use the following steps to calculate the result and insert it after the =
:
- Type
F3
to go to the beginning of the expression. - Type
yt=
to yank till the=
. - Now press
A
to go to the end of the line and enter insert mode. - Press
ctrl + r
followed by=
to use the expression register. - Press
ctrl + r
followed by"
to paste the yanked text. - Press
Enter
to calculate the result and insert it at the cursor position. - Press
Esc
to exit insert mode.
After the above steps, the text will become:
I have a long expression, 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 52
^ cursor here