I’ve been working with Go for a few weeks now and thought I had vim set up to
format my code using Fmt every time I saved. I did and I didn’t.
You see, we are working on the authorization piece of Ottemo and since many
projects can benefit from the work we are doing, we wanted to submit our
OAUTH2 work to the Martini project.
And, as should be, the source code needed to be formatted according to Golang
The one liner, which will format your code is below:
" format golang upon saveautocmd FileTypego autocmd BufWritePre<buffer> Fmt
However, there is a little more to the puzzle. In most cases I prefer spaces
to tabs, but this is not a discussion on tabs vs. spaces. Somehow this formatting was
not being set upon save. No matter what I did, it still saved the file replacing
tabs with spaces and an indention of 2 spaces.
I quickly found the culprit. In my .vimrc I have my default settings for
managing tabs and spaces to default to 2 spaces and to convert tabs to
spaces when I save a file.
settabstop=2" number of spaces that a <tab> represents in a filesetshiftwidth=2" number of spaces to use for (auto)indentsetexpandtab" expand tabs to spacessetsofttabstop=2" number of spaces that a <tab> representssetsmarttab" smart handling of tabs when inserting or deleting
This meant that when I opened a Golang formatted file, as soon as I saved it,
gone were the tabs in my Golang files. I wanted to adhere to the standard, so I
needed to find a way to make an exception for Go source files. According to
the Go formatting standards they use tabs
with a tabstop of 8.
To make an exception for Go source code, I am using the setlocal identifier
to apply the exception to my global settings. Here is the result:
autocmd FileTypegosetlocalshiftwidth=8tabstop=8softtabstop=8" set tab stops to 8 for Go filesautocmd FileTypegosetlocalnoexpandtab" don't expand tabs to spaces for Go files
This fixed my problems when saving Go formatted files and saves me from running
go Fmt on my files outside of vim.