Friday, July 30, 2010

Python in Vim

What if your favorite editor can interpret your favorite language!!! That would make writing code a piece of cake. This is what happened to me recently. I knew Vim could interpret Python. Only after I tried it out, I found how easy it is.

Simply go to normal mode and do :py print 'Vim Roxx' to see what I am trying to tell. You have to include a :py at the start of the line and it runs in Vim just as if it were running on a Python interpreter.

I know how you are feeling. I felt the same way too. Isn't there a way to specify start of python code and end. There is one.
:py << EOF
print "This is cool"
print "I'm lovin it"

does the job for you. The EOF here is only a name and any variable_name can be used. You can also specify a file to execute by using :pyfile file_name

Here is a quick snippet. I would like to run the Python code from my current buffer. I want to go over a line and press f4 and expect Vim to execute that command by adding a ":py" in the start.

Hence I first do
:py << EOF
import vim
def run_line():
cmd = ":py " + vim.curent.line
So now every time I go over a line and type :py run_line() in the normal mode, the current line is run as a line of python code. All I now have to do is bind this function to the required key and nmap <f4> :py run_line() <CR> does the job for me.

Happy Vimming with Python :) :)

No comments:

Post a Comment