Vim customization for python

Python seems to keep growing on me. By no means am I a Python master, nor am I a vim guru but I do prefer to use vim over a gui editor. Sure there are some niceties with using a gui but getting comfortable using a tool that is almost always at your disposal has something to be said for it. Adding a few things to your vim environment will make writing python much more pleasurable.

First there is the python indent plugin. At the time of this writing the current version is 0.3. There is one annoying thing about it. When commenting with hashes it un-indents. Luckily Henry Prêcheu pointed out that its an easy one line fix.

setlocal indentkeys=!^F,o,O,<:>,0),0],0},=elif,=except

should be changed to.

setlocal indentkeys=!^F,o,O,<:>,0),0],0},=elif,=except,0#

Here is the full updated version of the script. Vim Python Indent 0.4_alpha1

Syntax Highlighting

Download http://www.vim.org/scripts/script.php?script_id=790 at the time of this writing the current version is 2.6.3. and place it in your .vim /syntax/ directory (if its not there you should create it). This will add awesome highlighting to your python files. But we can make it better! We can add some simple error checking for things like missing colons. These are the additions that I have added which I found provided by sontek aka John M. Anderson. Don’t forget to add syntax on to your .vimrc.

syn match pythonError "^\s*def\s\+\w\+(.*)\s*$" display
syn match pythonError "^\s*class\s\+\w\+(.*)\s*$" display
syn match pythonError "^\s*for\s.*[^:]$" display
syn match pythonError "^\s*except\s*$" display
syn match pythonError "^\s*finally\s*$" display
syn match pythonError "^\s*try\s*$" display
syn match pythonError "^\s*else\s*$" display
syn match pythonError "^\s*else\s*[^:].*" display
syn match pythonError "^\s*if\s.*[^\:]$" display
syn match pythonError "^\s*except\s.*[^\:]$" display
syn match pythonError "[;]$" display
syn keyword pythonError         do

We can take that a step further with the following additions to your .vimrc.

" Syntax checking entire file
" Usage: :make (check file)
" :clist (view list of errors)
" :cn, :cp (move around list of errors)
autocmd BufRead *.py set makeprg=python\ -c\ \"import\ py_compile,sys;\ sys.stderr=sys.stdout;\ py_compile.compile(r'%')\"
autocmd BufRead *.py set efm=%C\ %.%#,%A\ \ File\ \"%f\"\\,\ line\ %l%.%#,%Z%[%^\ ]%\\@=%m

This will allow you to check the syntax ofyour entire file by typing :make. you can the get a list of errors with :clist and move between the errors with :cn and :cp.

Execute block of code
Sometimes you want to check or execute a block of code. Drop the python execute block vim script into your .vim/ftplugin/ directory. With it you can visually select a block of code and execute it with Ctrl+h.

Debugging
So you are finding errors in your code and want to trace them? Drop this python ipdb vim script into your .vim/ftplugin/directory. You can set break points with F7 and clear them with shift-F7. If your not familiar with ipdb you should look it up.

While we’re at it lets add an easy way to run your current script.
map <f8> :!python %<cr>
It was pointed out by fboender on reddit that there is a better way to do this.

Download the bexec plugin open it with vim using the full path to your vimball and then type :so % to source and install the vimball. Now setup some maps for it.

nmap <silent> <unique> <F8> :call Bexec()<cr>
vmap <silent> <unique> <F8> :call BexecVisual()<cr>
map <silent> <unique <F9> :call BexecCloseOut()<cr>

in your .vimrc will cause F8 to run the file you currently have open.

Tabs
Who doesn’t love tabs? You can have them in vim too ya know! Add these lines to your .vimrc

map \t :tabnew<cr>
map \n :tabnext<cr>
map \p :tabprevious<cr>
map \c :tabclose<cr>

With these additions you can open a new tab with \t move right with \n and move left with \p. To close the tab simply enter \c.

Edit File Menu
You can add a handy menu when opening files with :e. Its called the wildmenu. Add the following lines to your .vimrc. As a side note it will also give completion options for vim commands.

set wildmenu
set wildignore+=*.pyc,*.zip,*.gz,*.bz,*.tar,*.jpg,*.png,*.gif,*.avi,*.wmv,*.ogg,*.mp3,*.mov

Code Snippets
The vim snippy plugin provides textmate like code snippets. Its pretty darn cool. Installing is hard. Download the latest version from here. Be sure to download both snippy_plugin.vba and snippy_bundles.vba as the plugin and snippets are now seperated. Create a directory .vim/after/ftplugin and put both .vba files in there. I installed them by opening them with vim using the full path to the .vba files and then typing :source % to source the file. The vim ball script will install and you will be ready to go. Open a .py file and type def<tab>. You can tab through each <{}> and fill in the content to construct your function.

Extra functional goodness like block comment

Operating on blocks of code is handy. Being able to comment out an entire section with a few keystrokes saves much time. This vim script provides that functionality. I download it and save it to .vim/ftplugin/python_fn.vim.  Then you can visually select a block of code with ]v and comment it out with ]c and move its indentation level with ]< and ]> as well as a few other things.

PEP8 Goodness

Adding the following to .vim/ftplugin/python_pep8.vim will help you with tab space and other such worries with pep8.

setlocal tabstop=4
setlocal softtabstop=4
setlocal shiftwidth=4
setlocal textwidth=79
setlocal smarttab
setlocal expandtab
setlocal smartindent

One last note
Make sure indent and plugins are turned on in your .vimrc

filetype plugin indent on

7 Comments

  • Very nice, thanks. One question: Under debugging you say you can clear breakpoints with F8 – but then you immediately suggest mapping F8 to run. Was that a mistake or do you really override the former?

  • Ah thanks for pointing that out. It was an error. Clearing breakpoints is done with shift-f7

  • Followed your link here; certainly a far more comprehensive look at what you can do with Vim than my own! Cheers, I’m going to have to set this up 😀 (and then immediately regret it when I ssh to another box at work and realise I don’t have a nice vim anymore :p).

  • Every time i come here I am not dissapointed, nice post

  • I’m glad you enjoyed it.

  • lonecat Linux Unknow wrote:

    Great post. I’m not that much into python, but I’ve grown my vim to be a (Cookie) Monster :D. Have you tried NERD_snippets and NERD_tree? check this out: http://github.com/jfgomez86/vimfiles

  • Johnathan Windows Vista Firefox 3.0.10 wrote:

    The indent/python.vim file’s handling of comments is fine, actually. No need to edit it.

    It’s smartindent that is messing the comments up, because it’s meant for C-like languages and assumes ‘#’ is the beginning of a preprocesser instruction. smartindent is really only meant to be used if you don’t have a smart indentation file around, and with indent/python.vim you do!

    It really isn’t adding anything you need either, it just does some not-quite pythonic indentation around ‘{‘ and ‘}’, and indentation after C keywords like ‘switch’ or ‘do’, all of which is getting overridden by the python indent file. The only thing smartindent is still doing is messing up lines starting with ‘#’. Even after editing the indent file in the manner you suggest, I suspect smartindent will still stop you from being able to move comments to the right with ‘>>’.

    So just don’t use smartindent on python files. Change the last line of python_pep8.vim to be “setlocal nosmartindent” and your indentation should still be just as automatic and pretty much exactly the same, just without messed up comment indentation.

Leave a Reply

Your email is never shared.Required fields are marked *

To submit your comment, click the image below where it asks you to...
Clickcha - The One-Click Captcha