I want to format only a part of file and keep the rest unchanged using ALE. I imagine that its kinda possible by providing a fragment of code for example for black formatter and replacing the selected lines with the result retrieved from black.

Applying formatter for a large file could cause too many changes. Its way easier to track what have changed if only a part of the file is changed at once.

  • How would ALE know which part of the file to operate on? Setting formatprg is probably a better option, I think? But you need to invoke that manually. Commented Feb 26, 2021 at 4:02
  • @MartinTournoij I imagine that visual-line mode could be used to select the block for the formatting.
    – niekas
    Commented Feb 26, 2021 at 7:40
  • Yeah, you could use formatprg for that, assuming that black can operate on partial files: set formatprg=black (may need flags?), select what you want to be formatted, and then gq. Many people like to map gq to q btw, which is a bit easier to type. Commented Feb 26, 2021 at 9:24
  • @MartinTournoij i use Q, perhaps that’s what you meant? Black does have some issues when the partial file is not syntactically correct, and it’s also noisy (needs some cleanup). And i think a stdin or - flag is required
    – D. Ben Knoble
    Commented Feb 26, 2021 at 14:01

2 Answers 2


Range formatting is not supported by black because range of lines are in general not valid Python code.

You may have a look at black-macchiato.

Install black-macchiato by running the shell command:

pip install black-macchiato

To format a range of select lines run the vim command:

:'<,'>!python -m macchiato

You can also set the corresponding formatprg command.

:setlocal formatprg=python -m macchiato

This will allow you to format using the gq command.

You can also install the pluging smbl64/vim-black-macchiato: vim-black-macchiato

Remark: Black-Macchiato doesn't work out of the box on Windows but there are two forks that solve the problem on Windows, e.g., black-macchiato.


I'm doing this now with vim9script in ~/.vim/after/ftplugin/python.vim:

autocmd! BufWritePre <buffer> {
  var view = winsaveview()
  silent! execute ':%!black --quiet -'

To automatically format python filetype buffers just before saving.

To use the gq operator, you can set also do setlocal formatprg=black\ --quiet\ - but beware this will not always work, for example if you select a line like def add(a b) black can't parse that and you'll get the black error put in your buffer, however, if you select the entire function, let's say it's:

def add(a               b):
    answer       = a     + b
    return answer

and you do gqap on it, this will work, or if you did vip then gq, that works as well.

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.