Search code examples
pythonvimpep8

How to set correct indendation when using formatprg=autopep8?


With the following option set: setlocal formatprg=autopep8\ -aa\ -

When I select a single line in Visual Mode and press gq, the autopep8 makes its modification to the line but it also alters the indentation of the line: it defaults to an indent of 4 spaces, no matter the current indentation level of the line(s). I want it to assume that the lines are indented correctly and so to leave them alone.

Similarly, if I set the --indent-size 8 switch for autopep8 it will push the lines to an indent level of 8 spaces. Note that if the visual selection is large enough to encompass the top-level indentation (i.e. where there's no indentation), everything is indented correctly. But I tend to Visual Select smaller blocks before making commits.


Solution

  • You need to give --indent-size 0. So my .vimrc has this line:

    " Use gq to clean up code
    " Indent to 0 because otherwise it pushes selected lines to the given
    " indent-size, no matter the current indent level of the line.
    au FileType python setlocal formatprg=autopep8\ -aa\ --indent-size\ 0\ -