VSCode: 你如何在保存时自动格式化?

VSCode: How do you autoformat on save?

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

通过设置

启用“保存时格式化”
"editor.formatOnSave": true

并且由于 version 1.49.0 editor.formatOnSaveMode 具有选项 modifications,它将仅格式化代码 you 修改。当您更改其他人的代码时很棒。

您也可以只针对一种特定语言进行设置:

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

自版本 1.6.1,Vscode 支持“保存时格式化”。它将自动使用相关安装的格式化程序扩展来格式化整个文档。

如果您正在修改其他用户的代码并且您的团队没有标准化格式化程序,那么 "editor.formatOnSaveMode": "modifications", 也是一个不错的选择。不幸的是,出色的黑色格式化程序 not support this feature.

以下是在保存设置时更改 VS Code 自动格式的步骤:

  1. 使用[Ctrl]+[Shift]+[p]
  2. 键入“首选项”
  3. Select“首选项:打开用户设置”
  4. 搜索“格式”
  5. 更改“编辑器:保存时设置格式”或“编辑器:粘贴时设置格式”。

VS Code 中也有用于格式化的键盘快捷键。例如,格式化所选代码的默认设置应为 [Ctrl]+K [Ctrl]+F(连续键入两个热键)。

以下是更改自动格式热键设置的步骤:

  1. 使用[Ctrl]+[Shift]+[p]
  2. 键入“键盘”
  3. Select“首选项:打开键盘快捷键”
  4. 搜索“格式”
  5. 更改“格式化 Selection”或“格式化文档”。

转到 /.vscode/settings.json 文件并粘贴下面的代码

{
    "editor.formatOnSave": true,
}

它会在保存时格式化您的代码。

settings.json:

"editor.formatOnSave": true,
"editor.formatOnSaveMode": "modifications",
"editor.formatOnType": true,
"editor.formatOnPaste": true,

“formatOnSaveMode”仅对格式化修改后的代码很重要,因为我不想触及遗留代码。 如果我想格式化整个文档,我显然会调用“格式化文档”。

“formatOnType”在我输入完整的 stmt 后起作用(例如,对于 CPP,在“;”之后)