Introduction

If you also hate having to install plugins for everything on Neovim, I will show you how I evaluate math expressions using just a simple macro and a key map.

Note: Done on Neovim v0.11.4, tho it’s been available for years…

Neovim has a built-in calculator

Open a Neovim instance, and whilst in insert mode hit <C-r>= (CTRL + r then =). You may see that, on the command line, an expression calculator will be available. You can see where we are going, right?

Evaluating math expressions

When evaluating math expressions on Neovim’s calculator, you must follow the same symbols you use on JavaScript or Python (or… all… programming languages?).

For example, if you want to evaluate how much 28 times 13.2 is, you must use the * symbol:

28 x 13,2 // Wrong
28 * 13.2 // Correct

The first example is incorrect because it uses x instead of * for the multiplication symbol and , instead of . for decimals.

Key map

You may be asking: Do I need to open the calculator every time I want to evaluate a math expression?. The answer is no. You can create a key map somewhere on your Neovim config files, like in your init.lua or keymaps module.

Mapping

The following key map is set to be available only on visual mode. What it does, is… basically run a set of commands, just like a macro does.

vim.keymap.set(
  'v',
  '<leader>g=',
  'c<C-r>=<C-r>-<cr>',
  { desc = 'Evaluate math expression (replaces selection with result)' }
)

Let’s break it down…

  • c (change): Delete text into a register and start insert.
  • <C-r>= (open calculator): Opens the calculator in the command line.
  • <C-r>- (paste): Paste into the calculator’s input, the deleted text, smaller than one line.
  • <cr> (confirm): Tells Neovim to press enter on the current command line (calculator).

That’s it! Simple, right? After that, Neovim will proceed to paste the evaluated math expression result, into the buffer. Now every time you need to evaluate a math expression, just select it, and hit <leader>g= on your keyboard whilst a math expression is visually selected.

Caveats

This key map has some caveats…

  • Works for selections under one line (since it uses the - register), multi-line needs a different approach.
  • You may prefer to use g= for less key presses, but overriding g= changes default formatting behavior.

Conclusion

To fix simple problems, why overcomplicate things and “pollute” your plugins list? 1


  1. Terry A. Davis — “An idiot admires complexity; a genius admires simplicity.” (YouTube, ~18:57) [source: https://youtu.be/gBE6glZNJuU?t=1137]. ↩︎