0

Foreword

In case you don't know, you can evaluate math expressions in vim/neovim with this command:

While in INSERT mode, press CTRL+R, then =. Example: =2+2 inserts 4 into your buffer.


Question

Is there a way to evaluate power, root and modulo of numbers inside the expression register?

I want for example:

  • =2^16
  • =2**16
  • =10 mod 3
  • =10 % 3

I only get this Error: E15: Invalid expression: 2^16


Afterword

I know that you can do something like :echo pow(2, 16), but I want to do it in the expression register.

I have read the :help i_CTRL-R page and the :help expression page, and could not find anything about this. Maybe I missed something?



Thanks for you help :)

1 Answer 1

1

You can use functions such as pow() from the expression register.

Just enter Ctrl+R, =pow(2, 16), Enter and it will enter 65536.0 which is the result of 2 to the power 16.

Similarly, you can use fmod() for the modulus operator.

In your example, Ctrl+R, =fmod(10, 3), Enter, which will enter 1.0 which is the modulus of 10 by 3.

Note that both of these operations return floats, so you might want to use float2nr() to convert those to integers: =float2nr(pow(2, 16)) and =float2nr(fmod(10, 3)).

You can also use "method syntax" or the arrow operator -> to call these functions in a row, which is quite convenient for the conversion for float, for example =pow(2, 16)->float2nr(). Or you can even go all the way, with =2->pow(16)->float2nr().

In short, the expression register can take any kinds of expressions. Function calls are expressions like any others, so you can just use them as normal in the expressions you pass the = register.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.