Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I apply black code formatting on save?

I would like to apply black whenever I save a Python file in Sublime Text 3. How can I do that?

(Bonus points if there is a quick way to disable it)

like image 877
Martin Thoma Avatar asked Jul 31 '19 10:07

Martin Thoma


2 Answers

The answer above is really nice. In case you do not want to write your own package or plugin and you do not like the Formatter package, there is also the sublack package, which I think supports quick enabling/disabling of running black on save.

You install sublack the usual way via package control (Ctrl-Shift-P (Mac: Cmd-Shift-P) Package Controll: Install package). Afterwards you can format the current file either manually:

Run Black on current file: Press Ctrl-Alt-B to format the entire file. You can also Ctrl-Shift-P (Mac: Cmd-Shift-P) and select Sublack: Format file.

or you can:

Toggle Black on save for current view : Press Ctrl-Shift-P (Mac: Cmd-Shift-P) and select Sublack: Toggle black on save for current view.

Alternatively, you can also enable to run black on save permanently, by creating a user setting (Preferences -> Package Settings -> sublack -> settings) similar to the following:

{
    "black_on_save": true,
    "black_line_length": 80,
}
like image 90
HelgeCPH Avatar answered Oct 21 '22 06:10

HelgeCPH


  1. python 3.6
  2. pip install black
  3. cmd + shift + p then Click Package Control: Install Package
  4. sublack
  5. On terminal, which python
  6. Preferences/Package Settings/sublack/Settings On right panel

    {
        "black_on_save": true,
        "black_command": WHICH_PYTHON_RESULT
    }
    
like image 40
smartworld-dm Avatar answered Oct 21 '22 06:10

smartworld-dm