这将取决于语言。您需要安装/设置特定语言的格式化程序,然后启用 "editor.formatOnSave" 设置,这将在保存文件时应用格式化程序规则。
此答案适用于 Python 和 JavaScript,因为这是我通常使用的。
对于 JavaScript,我使用 Prettier 扩展名。
(它有plugins for other languages,但我主要用于JS。)
然后将这些添加到您的 settings.json:
// Set the default setting
"editor.formatOnSave": false,
// Then toggle depending on the language
"[javascript]": {
"editor.formatOnSave": true
},
默认情况下,Prettier 已经提供了一些默认的格式化规则。但是您可以指定 own configuration file 来指定您自己的(或特定于项目的)格式规则集。
.
├── ...
├── .prettierrc.js
├── test.js
...
└── <<other files>>
在 .prettierrc.js 中:
// prettier.config.js or .prettierrc.js
module.exports = {
useTabs: false,
tabWidth: 4
};
Prettier 配置指定不使用制表符并使用 4 个空格的缩进级别。现在,通过该设置,当您保存文件时,它会自动将制表符更改为空格(我理解这是您想要的)。还有other formatting options。
您会知道该扩展程序正在运行,因为它在状态栏中显示“更漂亮”:
对于 Python,VS Code currently supports 3 formatting providers):
我使用“autopep8”。
在您的环境中安装autopep8。然后在 VS Code 中,确保 select the environment 具有 autopep8。然后将其添加到您的 settings.json:
// Set the default setting
"editor.formatOnSave": false,
"[python]": {
"editor.formatOnSave": true
},
"python.formatting.provider": "autopep8",
"python.formatting.autopep8Args": [
// "--ignore=W191, E101, E111" // Uncomment to disable fixing indentation
],
在这里,autopep8 格式化代码以遵循 PEP8 style guide,它已经推荐了 spaces over tabs。所以所有需要做的就是启用它。
您可能还对与空格相关的 VS Code 设置感兴趣(这样一开始就不会将制表符放入文件中):
"editor.detectIndentation": false,
"editor.insertSpaces": true,
"editor.tabSize": 4,