Sunday, October 14, 2012

Auto-completion in VIM for Python

(This is article has been written based on fedora-16 , vim-ver 7.3)

As we all know that now vim also supports auto-completion for many languages which includes Python too. And if you use vim as a python ide then most probably you will also want the relative functions to pop out as soon you type dot "." so that you don't have to remember them ;) .

So here is quick guide on how to set up your vim for autocompletion of your python codes in case it is not already enabled.

First try this :
a=[1,2,3]
a.

After typing the above lines press "ctrl+x" then "ctrl+o" , if this pops up a menu showing the methods which can be used then you dont need to read further and just enjoy your coding :) .

In case you dont find anything happening then go through the following steps:
1> Type:
vim --version | grep "system"

It should show you something like this:

[root@Rogue codes]# vim --version | grep "system"
system vimrc file: "/etc/vimrc"

So your vim configuration file is in /etc/

2.> Now open it for editing.
It will be better if you make a backup of this file before editing it.
Now type:
vim /etc/vimrc

3.> In the file opened add the following lines in top of the file:

autocmd FileType python set completefunc=pythoncomplete#Complete



Now save it.
Open a python file and try to do the previous thing again that is:
a=[1,2,3]
a.



Now press "ctrl+x" then "ctrl+o" , if this opens the autocompletion window then you are in the right track.


Now for something extra:
It is quite a waste of keyboard strokes to type ctrl+x then ctrl+o, so lets map it to the most easiest thing, i.e. to "." itself.


Again open the vimrc file and add the following line to it:

autocmd FileType python imap . .<C-x><C-o>

after imap there is a space then a "." then a space then again a "." and <C-x><C-o>
Here we are saying that as soon as you press a dot then first type a dot and then press ctrl+x then ctrl+o.
The reason for putting a dot before <C-x><C-o> is that the dot now becomes a map to the sequence of key-strokes, so when you press a dot it is not taken as an input but is rather placed with the given sequence.

Now you just need to press "." and the auto-completion will pop out.

Have fun.

No comments:

Post a Comment