Question

In vim, we can do quick calculations in either insert or command mode by typing <C-r>= followed by an expression such as 1.1+2.2, to get the result into the buffer.

If I have an existing expression in the current buffer, such as 25.22 + 14.55, is there a way to have vim evaluate this expression, and replace it with the result?

I am primarily interested in solutions that do not use external tools, such as bc.

Update: To be more explicit, here is what I want on the line in the buffer before and after evaluation.

Sample Input:

25.22 + 14.55 

Sample Output:

39.77
Was it helpful?

Solution

According to the documentation you use eval() to evaluate an expression.

register                                                expr-register @r
--------        
...
When using the '=' register you get the expression itself, not what it
evaluates to.  Use eval() to evaluate it.

To pass the current line to eval() you can use the following.

:s/.*/\=eval(submatch(0))

which replaces the expression with the result of running eval on it.

Take a look at :h sub-replace-expression

OTHER TIPS

<C-r>" :paste the contents of the default register into the command line.

You can use a named register to paste the content from:

<C-r>=<C-r><register><CR>

You can create a macro like the example below and run it with @r on required line to replace the line with the evaluated expression:

:let @r='"ay$C^R=^Ra^M^['

where

  • "ay$ : Yank till end of line to register a

  • C : Delete the line and enter into insert mode.

  • ^R=^Ra^M : Evaluate the content of a register a and insert at current cursor position.

  • ^[ : Change to command mode

Make sure you insert Cnrl character literally using Ctrl-v. For example to insert Ctrl-r, press Ctrl-V then Ctrl-r.

Demo:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top