If you wish to perform more advanced calculations than what is available via the expression register (e.g. including functions such as
sqrt, etc), you can use an external command line tool and pipe the current line to it from vim. I have found the tool calc to be useful here and it is available for several package managers (e.g
apt install calc, but you could use any tool as long as it outputs easily to stdout).
So if we have a line that reads:
3 + 4
We can place our cursor on it in normal mode and press
!!calc and hit Enter.
You will see that it inserts the correct answer together with a warning:
Unable to associate stdin with /dev/tty
To improve this solution we can
- Filter out the warning using
sed (or vim commands)
- Insert the original expression at the beginning of the line followed by an equal sign.
- Make it work on lines that already have an
= in them (i.e. updating a calculation).
- Round answers to a limited number of decimal places.
- Create custom aliases via
sed (e.g. I prefer typing "mean" instead of "avg")
- Bind this command to a shortcut.
Implementing these features could look something like this in your .vimrc:
\ :s/ = .*//e<cr>
\!!calc \| sed 's/ //'<cr>
\i = <esc>hh
Unfortunately inline comments are not supported natively in vim, but those lines do the the following:
" Remove existing equal signs and results
" Copy the expression
" Create aliases and round the result
" Calculate the expression and remove leading tab
" Remove the warning message from calc
" Insert an equal sign and move the cursor to just before it
Now you can press you mapped shortcut when the cursor is on a line and get the results at the end!
(my leader key is space in the animation)