Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VSCode: How do you autoformat on save?

In Visual Studio Code, how do you automatically format your source code when the file is saved?

like image 863
neves Avatar asked May 30 '18 14:05

neves


People also ask

How do you autoformat in VS Code?

The code formatting is available in Visual Studio Code (VSCode) through the following shortcuts or key combinations: On Windows Shift + Alt + F. On macOS Shift + Option + F. On Linux Ctrl + Shift + I.

How do I beautify on Save VS Code?

To do this, go to File->Preferences->Settings: Under Text Editor, select Format On Save. Now when saving a file, it will be beautified.


2 Answers

Enable "Format On Save" by setting

"editor.formatOnSave": true 

And since version 1.49.0 editor.formatOnSaveMode has the option modifications that will just format the code you modified. Great when you change someone else code.

You can also set it just for one specific language:

"[python]": {     "editor.tabSize": 4,     "editor.insertSpaces": true,     "editor.formatOnSave": true # }, 

Since version 1.6.1, Vscode supports "Format On Save". It will automatically use a relevant installed formatter extension to format the whole document.

If you are modifying other users code and your team don't standardize a formatter, a nice option also is "editor.formatOnSaveMode": "modifications",. Unfortunately, the excellent black formatter does not support this feature.

like image 199
neves Avatar answered Oct 19 '22 23:10

neves


Below are the steps to change the VS Code auto format on save settings:

  1. Use [Ctrl]+[Shift]+[p]
  2. Type "Preferences"
  3. Select "Preferences: Open User Settings"
  4. Search for "format"
  5. Change "Editor: Format On Save" or "Editor: Format On Paste".

There are also Keyboard Shortcuts for formatting in VS Code. For instance, the default to format selected code should be [Ctrl]+K [Ctrl]+F (type both hotkeys in succession).

Below are the steps to change the auto format hotkey settings:

  1. Use [Ctrl]+[Shift]+[p]
  2. Type "Keyboard"
  3. Select "Preferences: Open Keyboard Shortcuts"
  4. Search for "format"
  5. Change "Format Selection" or "Format Document".
like image 42
Benjamin Ziepert Avatar answered Oct 20 '22 01:10

Benjamin Ziepert