Tuesday, December 27, 2011

Vim Setup for Python

I have used a number of modern IDEs for software development.  For example, I think it is neat how one can draw up UML diagrams and generate code from them (or vice versa).  Integration with the-more-complex revision control systems is also nice.  What I dislike is vendor lock in loss of control of the development flow.  I could speak more about this, but it is a different topic than what I'd like to cover today.

I like the Vim editor because of it's point tool nature.  It does it's job and it does it well.  It is well supported by the community, it is available on virtually every Linux installation (and Windows), and it is extremely customization.

A number of blog posts have been written that describe their settings for configuring Vim to edit Python files. This will be yet another.  The default configuration for Python in Vim leaves to be desired.  Fortunately, there are a few easy steps one can take to enable a streamlined experience.

The first step is to make sure to enable the Vim filetype plugin using command filetype plugin indent on in your $HOME/.vimrc.  The following site has more information about why to use this plugin.  To summarize, it allows the user to move filetype-specific commands outside of their main configuration file, reducing clutter in the file.

For indentation, first create a Python-specific configuration file $HOME/.vim/ftplugin/python.vim containing the following lines:

setlocal tabstop=4
setlocal softtabstop=4
setlocal shiftwidth=4
setlocal textwidth=79 " to comply with PEP-8 style guide
setlocal smarttab
setlocal expandtab

Eric McSween developed a Vim plugin for smart indentation of  Python code.  The utility is available here: http://www.vim.org/scripts/script.php?script_id=974.  Installation is straightforward, simply download the latest version of the script and copy the file to $HOME/.vim/indent/python.vim.  Use of the filetype plugin, as described above, will automatically enable the utility.

Last, Dmitry Vasiliev developed a Vim plugin for Python syntax highlighting.  The utility is available here: http://www.vim.org/scripts/script.php?script_id=790.  To install the plugin, download the latest version of the script and copy the file to $HOME/.vim/syntax/python.vim.  Enable the plugin by adding command syntax on to your $HOME/vim.rc file.

I recommend the use of a static code analyzer for anyone developing new code.  Pylint is my analysis tool of choice.  It is typically available as a binary package in most Linux distros - i.e. may need to talk to your sys admin.  There is some overhead of using code analysis in the short term, but long term, you will benefit from a code base with that looks pretty and smells less.

For integration with my editor, I use the following plugin: http://www.vim.org/scripts/script.php?script_id=891.  Installation of the plugin and requires the user to copy the downloaded script to directory $HOME/.vim/compiler