Search code examples
pythonvimcode-formattingvim-pluginblack-code-formatter

Vim format Python code with Black and then force tabs


I'm using the ALE plugin to format Python code with Black. Black indents the file with spaces (it's the same case with AutoPep8), but I want to keep my tabs. So I wrote this keybinding to run Black then swap spaces with tabs:

nnoremap <leader>ff :ALEFix<cr>:%retab!<cr>

When I run this, it works, but when I run it again the spaces stay there, and when I run it again it works, and so on. I works for one time, does not for the next, and so on...

I tried this as well, but got the same result:

nnoremap <leader>ff :ALEFix<cr>gg=G

What should I do so that it always runs correctly, runs Black, then always returns back my tabs?


Solution

  • What I can surmise is that you are using the auto fix on save feature of Ale. When you save the file it turns your tabs to space as black doesn't support tabs and neither does Autopep8.

    Autopep8 does seem to have some way to get tabs. See this link.

    You can check the GitHub for issue regarding spaces vs tabs in case of black and autopep8