dtwr2012 2012-06-10 14:12
浏览 345
已采纳

vim-保存时自动格式化golang源代码

I'm using vim with the vim-golang plugin. This plugin comes with a function called :Fmt that "reformats" the source code using gofmt, a command-line executable.

I want to invoke the :Fmt function each time that I save the file, so it is continuously re-formatted. I think this should be done with a autocmd directive. But I have two doubts:

  1. I could not find a way to execute the function. I tried writting Fmt and :Fmt at the end of the autocmd line, but it didn't seem to work. I think I miss something, like "call".
  2. I want this to happen only when saving a file of filetype 'go'. I don't know how to combine those two conditions - I can activate variables depending on the file type, and I can do small stuff, like removing trailing spaces, whenever a file is saved, but separatedly.

So this is what I have so far:

" 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
  • 写回答

2条回答 默认 最新

  • dongtuan1594 2012-06-10 14:38
    关注

    The FileType event doesn't fire on buffer writes; BufWritePre is the correct one, but you need to provide a file pattern, e.g. *.go:

    autocmd BufWritePre *.go Fmt
    

    The only downside is that this duplicates the detection of the go filetype. You could delegate this by hooking into the FileType event, and then define the formatting autocmd for each Go buffer by using the special <buffer> pattern:

    autocmd FileType go autocmd BufWritePre <buffer> Fmt
    

    This has the downside that if the filetype ever gets set multiple times, you'll run the formatting multiple times, too. That could be solved via a custom :augroup, but now it becomes really complex. Or, if you're really sure that this is the only BufWritePre autocmd for Go buffers, you could use :autocmd! BufWritePre ... (with a !).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办