简体   繁体   中英

VSCode: How do you autoformat on save?

在 Visual Studio Code 中,如何在保存文件时自动格式化源代码?

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", .

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".

Go to /.vscode/settings.json file and paste below code

{
    "editor.formatOnSave": true,
}

It will format your code on save.

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 (eg for CPP, after ';')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM