'VSCode: How do you autoformat on save?
In Visual Studio Code, how do you automatically format your source code when the file is saved?
Solution 1:[1]
Below are the steps to change the VS Code auto format on save settings:
- Use [Ctrl]+[Shift]+[p]
- Type "Preferences"
- Select "Preferences: Open User Settings"
- Search for "format"
- 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:
- Use [Ctrl]+[Shift]+[p]
- Type "Keyboard"
- Select "Preferences: Open Keyboard Shortcuts"
- Search for "format"
- Change "Format Selection" or "Format Document".
Solution 2:[2]
Go to /.vscode/settings.json file and paste below code
{
"editor.formatOnSave": true,
}
It will format your code on save.
Solution 3:[3]
settings.json:
"editor.formatOnSave": true,
"editor.formatOnSaveMode": "modifications",
"editor.formatOnType": true,
"editor.formatOnPaste": true,
"formatOnSaveMode" is important to only format modified code, as I don't want to touch legacy code. If I want to format the whole document, I'll call "Format Document" obviously.
"formatOnType" works after I enter a full stmt (e.g. for CPP, after ';')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Benjamin Ziepert |
| Solution 2 | Domovikx |
| Solution 3 |
