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:
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
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 !
).
If you use folds, gofmt messes these up (it opens closed folds, closes open ones). To keep folds as they where use the following autocommand
autocmd FileType go autocmd BufWritePre <buffer> execute "normal! mz:mkview\<esc>:Fmt\<esc>:loadview\<esc>`z"
It uses the z register to mark the cursor position because :mkview and :loadview (wich save and restores the folds) move the cursor for some reason.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With