autopep8 with vim

pep8, python, vim

Solution

The correct way of using autopep8 is to rely on vim "formatprg" settings. So you add the line below to vimrc:

au FileType python setlocal formatprg=autopep8\ -

Now when you select lines in python and hit `gq` (the default mapping unless you remapped it). It will filter the lines through `autopep8` and writes the nicely formatted version in place.

The setting above also make it work with vim objects and vim motions, so you could rerender a paragraph (well lines of python code with no blank line between) using `gqap`.

To do the whole file you could do `gggqG`

The hyphen '-' at the end of the command is required to make autopep8 read the lines from the standard in.

Problem

Is there a way to automatically apply autopep8 to a file being edited in vim? I have the following vimrc. Thank you in advance.

Original source