Vim Tips Wiki

Evaluate current line using Python

1,624pages on
this wiki
Add New Page
Talk0 Share

Duplicate tip

This tip is very similar to the following:

These tips need to be merged – see the merge guidelines.

Tip 608 Printable Monobook Previous Next

created November 24, 2003 · complexity intermediate · author Eugene M. Minkovskii · version 6.0

The Python language is generally more powerful than Vim's scripting language. If you want to evaluate a fragment of Python code in Vim, you can use command:

:py print 2*2

See :help if_pyth.txt.

Below is a more elaborate example. Put the following code in your vimrc:

python << EOL
import vim
# Do not say 'from vim import *' because that
# will delete builtin function eval.

def EvaluateCurrentLine(*args):
  cur_str = vim.current.line
  action, symb = None, None
  for i in args:
    if i in ["r","p"]: action = i
    else: symb = i
  try: start = cur_str.rindex(symb)+len(symb)
  except: start = 0
  result = eval(cur_str[start:],globals())
  if action == "r":
    vim.current.line = cur_str[:start]+str(result)
    print result
command -narg=* PyEv python EvaluateCurrentLine(<f-args>)

Be careful about identation in the Python part. This code provides command:


This command evaluates expression in line under cursor and prints result in echo area.

With r argument, it will evaluate the expression and be replaced by the result of evaluation:

:PyEv r

You can give one more argument - it will mark from which char in current line it should start evaluation.

For example: Running the following command:

:PyEv r {

on the following line:


will give:



I tried to modify your script to execute a range of lines, but the :command's -range option did not seem to propagate into vim.current.range. It always just took one line instead of the range I specified. I finally ended up with:

python << EOL
import vim
def EvaluateCurrentRange():
map H :py EvaluateCurrentRange()<CR>

The command definition using the same function (command -range Pyr python EvaluateCurrentRange()) did not work.

Ad blocker interference detected!

Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.

Also on Fandom

Random Wiki