1

I have the official black plugin installed in vim. I have in my vimrc:

au FileType python autocmd BufWritePre <buffer> Black

This works fine, but I would like to be able to disable the autoformatting in some situations. I tried this:

au FileType python autocmd BufWritePre <buffer> if get(b:, 'black_enabled', 1) | Black | endif

That successfully disables formatting if I let b:black_enabled=0, but when black_enabled=1 (or is unset), that results in:

Error detected while processing function black#Black:
line    4:
E684: list index out of range: 1
E684: list index out of range: 1

...and then Black appears to run anyway.

What's wrong with my syntax that it's causing errors?

5
  • 1
    How is the Black command defined? Does it have the -bar attribute? If it doesn't it will see | endif as its arguments. You can check whether the -bar attribute was used by running :command Black and checking if the first column contains a |. Commented Jan 24, 2022 at 7:42
  • The function is defined here. I'm a little confused by your comment; I thought | was the vimscript command separator (like ; in the shell), so I wouldn't expect a function definition to influence how it behaves. Is that incorrect?
    – larsks
    Commented Jan 24, 2022 at 12:50
  • 1
    Not all commands see | as a separator; some see it as part of their arguments. Most notorious examples for the latter are :g and :argdo, :bufdo and :windo. Commented Jan 24, 2022 at 12:57
  • 1
    The link you provided points to the definition of the Black() function. What you need to check is the definition of the :Black command here. It does not include the -bar parameter, so :Black will see | as part of its arguments. Commented Jan 24, 2022 at 13:00
  • 1
    You might want to try if :command! -bar -nargs=* -complete=customlist,BlackComplete Black :call black#Black(<f-args>) before the au-command fixes your problem. If yes you can ask the maintainer(s) to include this change. Commented Jan 24, 2022 at 14:36

1 Answer 1

1

The solution I've come up with for now (that doesn't require any changes to the Black plugin) is to just call the underlying function directly:

au FileType python autocmd BufWritePre <buffer> if get(b:, 'black_enabled', 1) | call black#Black() | endif

This seems to work as intended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.