Math in Vim
Do you ever wish you could perform simple math while inside Vim? The short answer is you already can and here are your options.
- Use echo:
e.g. :echo 5*2.5<CR>
Then the result 12.5 is echoed in the command line.
- Use Expression Register:
e.g. (in insert mode): <C-R>=5*2.5<CR>
Then the result 12.5 is inserted into the buffer.
The above works for most people and they did for me for a while but, there are a few things about this that I thought could be better. One problem is method is when you expect a floating point result from integer division. For example when you evaluate the expression '5/2' you get a result of '2'. The result of '2' is the truncated version of what you really wanted '2.5'. Another problem is when you enter a floating point number like this '.5/2' a decimal without a leading zero produces an error when you actually wanted was '0.5/2 = 0.25'.
Due to these small gripes and a few more I discovered along the way I made the plugin Crunch.
When I first ventured out I wanted to accomplish, then along the way I solved even more problems. This short list summarizes some of the features of Crunch.
- Force all numbers to integers
- Easier access to calculator features in Vim
- Makes syntax for evaluating math looser and easier to work with
- Evaluate current line or visually selected lines
- Save values or results, into variables for use later
Crunch started as a few substitute() commands and turned into a whole lot more. Then with a little inspiration and code from Ihar Filipau Who provided wrote most of the code that made using variables possible in Crunch in his incline calculator plugin. Crunch grew from a command line only plugin to one that worked in bufferers as well.
Below you can get a look at Crunch and action and decide if its something you might be interested in.
If Crunch sounds interesting, and you want use it as well you can download it from GitHub. The GitHub page also goes into more detail about what other problems Crunch solves.
Crunch is now in Version 2.0 and the previous demos are from Version 1.0. For a short post to see what has changed look here