3

I'd like to be able to select a part of a line, send it to a python interpreter, and have the selection replaced by the expression result. The use case is for doing math in Markdown documents:

1. Text here and then an expression 12 * 200
   1. More text and then an expression 31 + 5

I'd like to be able to select only 12 * 200 and have it be replaced by the result of the multiplication.

How would I go about doing that?

1 Answer 1

2

If you have a Vim version with Python support (you can check that in vim --version or :version and see if you have +python3 or +python3/dyn), then you can use py3eval() to evaluate the expression inside Vim itself.

This should work:

xnoremap <Leader>p c<C-R>=py3eval(@")<CR><Esc>

(Note: This assumes Python 3. There are similar functions for Python 2 and there's also a pyxeval() that will work with either version. But I'd really recommend against using those, since Python 2 is EOL already.)

If you don't have Python support in Vim, then you can do this by using an external call to a Python interpreter. But this is more messy, since it involves escaping the arguments to the shell and you need the Python code to print() it back to you. But if that's what's available to you, then you can use this snippet to run it through an external python3 interpreter:

xnoremap <Leader>p c<C-R>=trim(system("python3 -c ".shellescape("print(".@".")")))<CR><Esc>

The solutions use <C-R> with the expression register to insert the result of an expression as the replacement. They use the default register @" to access the text that was just deleted by the c command.

4
  • 2
    For simple expressions like in OP, python isn’t even necessary :P
    – D. Ben Knoble
    Sep 18, 2020 at 0:42
  • @Ben Yes of course! But the question was about Python, so I didn't go there... But yeah using eval() to evaluate in Vimscript would have worked just as well here.
    – filbranden
    Sep 18, 2020 at 2:23
  • Oi, just realized I'm not the only using the expression register for a bit of meta-polyglot-programming :P
    – D. Ben Knoble
    Oct 17, 2020 at 21:04
  • 1
    To add to the comments above: In neovim, one may also use Lua with luaeval() if Python support is not available (I think Lua is buillt-in so it should always be there). It doesn't work with vim, though, so its less portable.
    – luator
    Jan 26 at 15:50

Your Answer

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

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