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 https://tpo.pe/pathogen.vim
echo "call pathogen#infect()" | cat - /etc/vimrc > ~/.vimrc.new
mv ~/.vimrc ~/.vimrc.old && mv ~/.vimrc.new ~/.vimrc
go get github.com/nsf/gocode
mkdir -p ~/.vim/bundle
git clone https://github.com/fatih/vim-go.git ~/.vim/bundle/vim-go
cd $GOPATH/src/github.com/nsf/gocode/vim
./update.sh
Then, open a vim session and type the following vim command:
:GoInstallBinaries
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
endif

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 https://storage.googleapis.com/golang/go1.9.linux-amd64.tar.gz > go1.9.linux-amd64.tar.gz
tar xfz go1.9.linux-amd64.tar.gz -C /usr/local

GOROOT=/usr/local/go
GOPATH=~/devel/apporbit/go
PATH="$GOROOT/bin:$PATH:$GOPATH/bin"
export PATH GOROOT GOPATH
The key is to have GOPATH set correctly. Also set up glide for better vendoring / package dependencies.
go get github.com/Masterminds/glide
You create / checkout all your projects under $GOPATH/src. If you clone a github project, it should be under $GOPATH/src/github.com/<user>/<repo>. Using go get to get go packages would also clone the repos under these paths.

No comments: