2

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

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.

| improve this answer | |
  • 1
    For simple expressions like in OP, python isn’t even necessary :P – D. Ben Knoble Sep 18 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 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 at 21:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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