Vim and python

Posted on Monday, May 25th, 2009 under ,

Few months ago, at a wurbe edition, I’ve seen two great editors in action: vim and emacs. At first, I was impressed by Alex Nedelcu’s presentation of emacs and I gave it a try, but I’ve switched to vim soon after, because emacs just…”didn’t feel right”. What I liked about emacs was that could be easily extended and customised to fit the user’s needs with lisp. Alex showed us some scripts made by him to improve his productivity.

I also like to customise my tools, and that what drawn me to emacs in the first place. And when I’ve switched over to vim, I’ve tried to write some custom plugins, but with vim it’s not that simple. Vim uses a built in scripting language, which it’s really weird and badly documented and since it can’t be used anywhere outside of vim, mastering it would be a waste of time. So I’ve postponed the customisation of the editor until I had enough time to look over the vim scripting language. Until now. I’ve recently read an article presenting vim scripting in python, and I’ve decided to give it a try. And it proved to be much simpler than I’ve thought.

First of all, install vim’s python support. If you’re an Ubuntu / Debian user, simply pop this in the console:

tudor@thor:~$ sudo apt-get install vim-python

If not, compile vim from source / use your package manager to install vim with python support. After vim is up and running, create the two files in the ~/.vim/plugin/ directory: my_plugin.vim and my_plugin.py.

The my_plugin.vim should look something like this:

if !has("python")
	call confirm("You must have vim compiled with python in order for this to work", 'OK')
	finish
endif
 
if filereadable($HOME."/.vim/plugin/my_plugin.py")
	pyfile $HOME/.vim/plugin/my_plugin.py
else
	call confirm("Error: my_plugin.py cannot be found! Please reinstall the plugin", 'OK')
	finish
endif
 
"commands for invoking the functions
command! -nargs=1 MyPluginDoSomething python do_something('<args>')
command! -nargs=1 MyPluginDoSomethingElse python do_something_else('<args>')

This is all the vim script you need to know :) And now, in my_plugin.py file, write your plugin’s logic in python, knowing that each vim command will call a function from this file:

def do_something( argument ):
    print 'wassup %s' % argument
 
def do_something_else:
    pass

If you print something in python, it will be shown in vim’s error messages area, at the bottom of the window. But the vim module is available in python allows you to read and write into vim’s buffers and therefore inserting data in the opened document. Type :help python in vim for more details.

I’ve started working on a vim plugin that will aid me with my Zend Framework development. A Zend_Tool integrated with vim that actually does something useful :p

Related posts

Leave a Reply