Saturday, February 17, 2018

Setting up vim autocomplete for golang

The key is to know which keystrokes to use, and you should use Ctrl-X followed by Ctrl-O in insert mode to bring up completion suggestions in a pop up. If you want automatic pop ups as you type, YouCompleteMe is supposed to work. I couldn't get it to work, and it wouldn't work on some of my setups because it requires a more recent version of vim (7.4.15xx) than I have.

So what was needed? Assuming your GOROOT and GOPATH are correctly set up (if not, see below), the following is all that you need to do:
mkdir -p ~/.vim/autoload
curl -LSso ~/.vim/autoload/pathogen.vim
echo "call pathogen#infect()" | cat - /etc/vimrc > ~/
mv ~/.vimrc ~/.vimrc.old && mv ~/ ~/.vimrc
go get
mkdir -p ~/.vim/bundle
git clone ~/.vim/bundle/vim-go
cd $GOPATH/src/
Then, open a vim session and type the following vim command:
The above will install additional go command-line tools and you should be all set. Just one more thing. Open you /etc/vim/vimrc file (if you have root privileges) or your ~/.vimrc file (which you could copy from /etc/vim/vimrc) and add or uncomment the following lines:
filetype plugin on
if has("autocmd")
  filetype plugin indent on

You can see what it should look like when you edit go code and press Ctrl-X followed by Ctrl-O in insert mode.

The screenshot gif was created on Ubuntu 16.04 using peek, along with gifski.

Setting up your Golang development environment

Installing the latest golang development environment (currently go 1.9) and setting it up involves the following steps:
curl -L0 > go1.9.linux-amd64.tar.gz
tar xfz go1.9.linux-amd64.tar.gz -C /usr/local

The key is to have GOPATH set correctly. Also set up glide for better vendoring / package dependencies.
go get
You create / checkout all your projects under $GOPATH/src. If you clone a github project, it should be under $GOPATH/src/<user>/<repo>. Using go get to get go packages would also clone the repos under these paths.

Read more!