Fandom

Vim Tips Wiki

Evaluate current line using Python

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

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.

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)
  else:
    print result
EOL
command -narg=* PyEv python EvaluateCurrentLine(<f-args>)

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

:PyEv

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:

\setlength{\textwidth}{450-63

will give:

\setlength{\textwidth}{387

CommentsEdit

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():
  eval(compile('\n'.join(vim.current.range),'<string>','exec'),globals())
EOL
map H :py EvaluateCurrentRange()<CR>

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


Also on Fandom

Random Wiki