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.