vim-autoformat / vim-autoformat

Provide easy code formatting in Vim by integrating existing code formatters.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Falls back on (incorrect) indentation when auto-format with black fails for Python files

iafisher opened this issue Β· comments

First of all, thanks for writing this plugin. It's very useful to me and I appreciate the work you put into it.

I've found that, with black set as the Python formatter, the autoformat command indents a bunch of lines instead of failing when the syntax is invalid. After setting let g:formatters_python = ['black'] in your .vimrc, you should be able to repro like this:

$ echo -e 'foo(1, 2, 3\n\nbar()' > /tmp/wrong.py
$ black /tmp/wrong.py
error: cannot format /tmp/wrong.py: Cannot parse: 3:0: bar()
Oh no! πŸ’₯ πŸ’” πŸ’₯
1 file failed to reformat.
$ vim /tmp/wrong.py
# And run :Autoformat. Instead of failing, it will indent the third line incorrectly.

As the above commands demonstrate, black will normally fail without changing anything if the file's syntax is not valid.

These are the verbose messages:

Messages maintainer: Bram Moolenaar <Bram@vim.org>
"/tmp/wrong.py" 3L, 19C
Trying definition from g:formatdef_black
Evaluated formatprg: black -q  -
Using python 3 code...
Formatter black has errors: b'error: cannot format -: Cannot parse: 3:0: bar()\n'
Definition in 'g:formatdef_black' was unsuccessful.
No format definitions were successful.
Removing trailing whitespace...
Retabbing...
Autoindenting...
2 lines to indent... 
3 lines indented 

It seems that vim-autoformat is falling back on auto-indentation after the auto-formatting fails. If this is considered correct behavior and not a bug, is there a way to disable it? It's undesirable to me because it often results in hundreds of lines being incorrectly indented, and the indentation itself often takes several seconds.

You can disable it. It is explained in the README.

Oops, sorry I didn't see that. I do wonder if this is still a bug though as it seems to me that auto-indenting after black fails is never the correct behavior as black will always succeed on a valid Python file.

Concretely, maybe there should be a command in https://github.com/Chiel92/vim-autoformat/blob/master/plugin/defaults.vim that checks if formatters_python includes black, and disables auto-indentation if that's the case?

That won't work, because it may just be that black isn't installed

Fair enough. Disabling auto-indentation for Python files fixes my problem anyway. Thanks!