Vim settings for Go language

First of all, make sure you’ve got your $GOPATH/bin directory in your $PATH.

Install goimports command, which acts just like go fmt, but automatically takes care of import section:

go get -u -v code.google.com/p/go.tools/cmd/goimports

Go-related .vimrc excerpt:

" Some Linux distributions set filetype in /etc/vimrc.
" Clear filetype flags before changing runtimepath to force Vim to reload them.
filetype off
filetype plugin indent off
set runtimepath+=/usr/local/go/misc/vim
filetype plugin indent on

let g:gofmt_command ="goimports"
au FileType go au BufWritePre <buffer> Fmt
au FileType go setlocal formatoptions=cqra1 tw=80 ai nofoldenable

Please note, you have to change path to your Go distribution, if it’s not in /usr/local/go as mine.

This way you’ll have your code formatted on save, don’t have to bother about managing import manually, have nice coloring, auto-wrapping inside comments.

Syntax completion

If you like vim’s omnicompletion, you’d also like to have it for Go code. Install gocode package:

go get -u -v github.com/nsf/gocode

Then install it’s vim files:

cd $GOPATH/src/github.com/nsf/gocode && sh -x vim/update.sh

Check style with golint

If you want your code to follow accepted style of Go project and Google, you’d want to use golint:

go get -u -v github.com/golang/lint/golint

To run golint on file save operations, add the following to your .vimrc file:

set runtimepath+=$GOPATH/src/github.com/golang/lint/misc/vim
au FileType go au BufWritePost,FileWritePost <buffer> execute 'Lint' | cwindow

This would run golint after saving file and populate vim’s quickfix window with any suggestions golint had.