Sunday, October 14, 2007

Vim: Run the current buffer as Python code

This uses the handy preview window feature of Vim. Flagging a window as a preview window is useful because you can use pclose! to get rid of it, meaning you can reuse that vim real estate over and over for commands that produce output, and the output has to go somewhere.

fu! DoRunPyBuffer2()
pclose! " force preview window closed
setlocal ft=python

" copy the buffer into a new window, then run that buffer through python
sil %y a | below new | sil put a | sil %!python -
" indicate the output window as the current previewwindow
setlocal previewwindow ro nomodifiable nomodified

" back into the original window
winc p

command! RunPyBuffer call DoRunPyBuffer2()
map <Leader>p :RunPyBuffer<CR>

<Backslash>+p is mapped to run the current buffer through a Python interpreter. The output appears in a new window below the current one.

The code to do this with another interpreted language, such as bash, is almost identical and left as an exercise for the reader.


Anonymous said...

Thanks, exactly what I was looking for!

-daniel, Netherlands

SEAN said...

Very nice. :)