DEV Community

Bhupesh Varshney ๐Ÿ‘พ
Bhupesh Varshney ๐Ÿ‘พ

Posted on • Originally published at bhupesh.me on

Debugging Go in Vim

Using make in Vim/NeoVim can be a handy utility if you want to quickly build, run & debug programs. The make command is governed by the program set in makeprg.

By default makeprg is set to the make utility, popular in C/C++ development. Letโ€™s see how to configure this for Go. Before we do that, let's create a sample Go file with some errors ๐Ÿ˜…๏ธ

package main

import (
    "fmt"
)

func main() {
    fmtPrintln("Hello")
    fmtPrintln("World")
}

Enter fullscreen mode Exit fullscreen mode

If you want to run your Go programs directly:

:set makeprg=go\ run\ %
Enter fullscreen mode Exit fullscreen mode

If you just instead want to build :

:set makeprg=go\ build\ %
Enter fullscreen mode Exit fullscreen mode

Note: the make command will automatically create a binary with the same file (buffer) name. So you donโ€™t need to specify the -o flag.

Now all you need to do is run :make, you can also set some accessible key bindings. I have these in my vimrc

nnoremap <A-m> :make<bar>cw<CR>
inoremap <A-m> <Esc>:make<bar>cw<CR>
Enter fullscreen mode Exit fullscreen mode

To take things further, you can also combine the golint tool with go run

:set makeprg=golint\ %\ &&\ go\ run\ %
Enter fullscreen mode Exit fullscreen mode

Since you are probably using multiple languages at once, you need to set the make command on each FileType. Add this auto-command in you .vimrc or init.vim

autocmd FileType go setlocal makeprg=go\ run\ %
Enter fullscreen mode Exit fullscreen mode

Make sure to use setlocal and not set

How to fix errors

Vim provides a separate window to show errors called the error-window more formally know as the quickfix window.

Combine the make command with copen to open a quickfix window

:make | copen
Enter fullscreen mode Exit fullscreen mode

This will first build the program then open a new window at the bottom, listing all the errors.

I prefer cw instead of copen since it opens the quick fix window only if there are any errors. This makes it a perfect match with the make command

:make | cw
Enter fullscreen mode Exit fullscreen mode

You can press Enter () on each error listed to directly go to the error line in the program (vim will open the file if it isnโ€™t already opened)

Use cn and cp to go to the next & previous item in quickfix list respectively. Add these mappings

map <C-j> :cn<CR>
map <C-k> :cp<CR>

\" I prefer these instead. Suit yourself!
nnoremap <kPlus> :cn<CR>
nnoremap <kMinus> :cp<CR>
Enter fullscreen mode Exit fullscreen mode

Letโ€™s see how all this setup works

go-make-demo

Resources

Read the following vim manual pages for more insights:

  1. :help makeprg
  2. :help quickfix

Top comments (0)