microsoft / vscode-black-formatter

Formatting support for Python using the Black formatter
https://marketplace.visualstudio.com/items?itemName=ms-python.black-formatter
MIT License
144 stars 34 forks source link

Support for format on type #489

Open Schepper-1101 opened 3 months ago

Schepper-1101 commented 3 months ago

I hope this message finds you well. I am writing to express a feature request for the Python extension that I believe would significantly enhance the coding experience for users like myself.

Currently, I find myself frequently formatting my code using the Ctrl+Shift+I shortcut, which, although effective, interrupts the flow of coding and feels somewhat cumbersome. Drawing inspiration from features available in Visual Studio, I would like to propose the implementation of automatic code formatting upon pressing the Enter key.

The functionality I envision is straightforward: when a user presses Enter to move to a new line, the Python extension would automatically format the preceding line of code according to the defined style guidelines or user preferences.

karthiknadig commented 3 months ago

@Schepper-1101 Have you tried setting editor.formatOnSave and/or editor.formatOnType settings? These should trigger formatting to occur on save or as you type.

Just for note, from the extension we don't really trigger formatting, we let the editor decide when to perform formatting. This extension is a wrapper around black and allows VS Code to use black as a formatter.

karthiknadig commented 3 months ago

Your settings should look like this:

    "[python]": {
        "editor.formatOnSave": true,
        "editor.formatOnType": true,
        "editor.defaultFormatter": "ms-python.black-formatter"
    },
Schepper-1101 commented 3 months ago

Your settings should look like this:

    "[python]": {
        "editor.formatOnSave": true,
        "editor.formatOnType": true,
        "editor.defaultFormatter": "ms-python.black-formatter"
    },

I've tried this. "editor.formatOnType": true isn't working.

karthiknadig commented 3 months ago

It looks like we need to explicitly enable this. I have updated the title to reflect that.

a-sajjad72 commented 3 months ago

It looks like we need to explicitly enable this. I have updated the title to reflect that.

@karthiknadig how it would be explicitly enabled??? Is this feature still in development???

karthiknadig commented 3 months ago

@a-sajjad72 The following is the implementation for format on save: https://github.com/microsoft/vscode-black-formatter/blob/main/bundled/tool/lsp_server.py#L104-L109

You would have to implement similar support for format on type, by handling this request: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_onTypeFormatting