black.vim integration with native 'formatprg' option possible?

Created on 7 Feb 2019  路  3Comments  路  Source: psf/black

Hi, I was wondering if black.vim is able to integrate with vim's 'formatprg' option (:h 'formatprg'), which is supposed to be set to an external command to run when using 'gq' operator. I'm not sure if it's possible or at-odds with how black is supposed to be run, can anyone clarify? Docs say the external program must take the input on stdin and produce output on stdout.

integrations

Most helpful comment

Best effort so far:

in my personal ~/.vim/after/ftplugin/python.vim:

setlocal formatprg=black\ --quiet\ -
augroup black-fmt
    autocmd!
    autocmd BufWritePre <buffer> normal gggqG``
augroup END

This will set a local autocommand to run black on the current buffer file each time it is about to
save, but only if :set ft? value is 'python'. 'gq' operator works with stdin and stdout, not stderr so we tell black to be --quiet (else you get messages from black pasted into your file) and we pass it the '-' argument to tell black to use stdin.

I'm sure there are improvements that can be made, open to suggestions.

All 3 comments

Best effort so far:

in my personal ~/.vim/after/ftplugin/python.vim:

setlocal formatprg=black\ --quiet\ -
augroup black-fmt
    autocmd!
    autocmd BufWritePre <buffer> normal gggqG``
augroup END

This will set a local autocommand to run black on the current buffer file each time it is about to
save, but only if :set ft? value is 'python'. 'gq' operator works with stdin and stdout, not stderr so we tell black to be --quiet (else you get messages from black pasted into your file) and we pass it the '-' argument to tell black to use stdin.

I'm sure there are improvements that can be made, open to suggestions.

Above has one disadvantage: loses cursor position (sends you to top of file).

@mooreniemi This kinda works, but since the file is changed outside of Vim it cannot track the changes to a mark (cannot remember "current" position).

    autocmd BufWritePre <buffer> keepjumps normal m'gggqG``
Was this page helpful?
0 / 5 - 0 ratings

Related issues

nottrobin picture nottrobin  路  3Comments

JelleZijlstra picture JelleZijlstra  路  3Comments

dimaqq picture dimaqq  路  3Comments

jogama picture jogama  路  3Comments

Curly-Mo picture Curly-Mo  路  3Comments