In the end, I solved it by writing a script called pyexec.vim and put it in my plugin directory. The script is reproduced below:
python << endpython
import vim
def pycurpos(pythonstatement):
#split the python statement at ;
pythonstatement = pythonstatement.split(';')
stringToInsert = ''
for aStatement in pythonstatement:
#try to eval() the statement. This will work if the statement is a valid expression
try:
s = str(eval(aStatement))
except SyntaxError:
#statement is not a valid expression, so try exec. This will work if the statement is a valid python statement (such as if a==b: or print 'a')
#if this doesn't work either, fail
s = None
exec aStatement
stringToInsert += s if s is not None else ''
currentPos = vim.current.window.cursor[1]
currentLine = vim.current.line
vim.current.line = currentLine[:currentPos]+stringToInsert+currentLine[currentPos:]
endpython
This works as expected for oneliners, but doesn't quite work for multiple statements following a block. So python pycurpos('a=2;if a==3:b=4;c=6')
will result in c
always being 6
, since the if
block ends with the first line following it.
But for quick and dirty python execution, which is what I wanted, the script is adequate.