在 vscode 中把缩进设置为空格 但在 go 文件保存或格式化时会自动将空格换成 tab 很是令人抓狂。
解决办法
1. GO的格式化工具Format Tool的问题,将默认的goreturns换成goformat
image.png如果用json配置
"go.formatTool": "goformat"
2.goformat 默认还是 tab 需要修改源代码
在 ${GOROOT}/src/go/format/format.go 中做如下修改
const (
tabWidth = 8
printerMode = printer.UseSpaces | printer.TabIndent | printerNormalizeNumbers
)
//修改为
const (
tabWidth = 4
printerMode = printer.UseSpaces
)
代码是基于Go 1.15.2 版本修改,不同版本修改略有差异 不过简单看下源代码也能找到
3. 在Go项目中执行重新安装命令:
go install golang.org/x/tools/gopls
此时发现文件默认还是 tab
4.安装插件 EditorConfig for VS Code
安装之后,需要在Go项目根目录创建一个 .editorconfig 文件去配置VSCode的默认缩进选项。
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 4
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
配置完成
此时无论自动换行 自动格式化 都是空格模式
最后
在vs code 配置文件中配置
"editor.renderControlCharacters": true,
"editor.renderWhitespace": "all",
可以将隐藏符显示出来
网友评论