我正在使用vim和vim-golang插件.这个插件附带了一个名为Fmt的函数,它使用命令行可执行文件gofmt "重新格式化"源代码.
我想在每次保存文件时调用:Fmt函数,因此它会不断重新格式化.我认为这应该使用autocmd指令完成.但我有两个疑问:
所以这就是我到目前为止所做的:
" I can set variables for go like this
autocmd FileType go setlocal noexpandtab shiftwidth=4 tabstop=4 softtabstop=4 nolist
" I can clean trailing spaces(conserving cursor position) on save like this
autocmd BufWritePre * kz|:%s/\s\+$//e|'z
" None of these worked:
autocmd BufWritePre,FileType go Fmt
autocmd BufWritePre,FileType go :Fmt
Run Code Online (Sandbox Code Playgroud)
Ing*_*kat 57
FileType缓冲区写入时不会触发该事件; BufWritePre是正确的,但你需要提供一个文件模式,例如*.go:
autocmd BufWritePre *.go Fmt
Run Code Online (Sandbox Code Playgroud)
唯一的缺点是这会重复检测go文件类型.您可以通过挂钩FileType事件委托此事件,然后使用特殊<buffer>模式为每个Go缓冲区定义格式化autocmd :
autocmd FileType go autocmd BufWritePre <buffer> Fmt
Run Code Online (Sandbox Code Playgroud)
这有一个缺点,即如果多次设置文件类型,您也将多次运行格式化.这可以通过定制来解决:augroup,但现在变得非常复杂.或者,如果你真的确定这是BufWritePreGo缓冲区的唯一autocmd,你可以使用:autocmd! BufWritePre ...(带a !).