Formatting Go code with Vim

August 8, 2010


There are no formatting rules when writing Go code, but there is an official style. If you pipe your code through gofmt, its output is the official style. So while writing you need to occasionally execute: %!~/bin/gofmt (which I’ve wrapped in a command, so I only need to type :Fmt).

But the trouble is that executing this code resets the cursor to the first line and you then have to jump back to whatever line number you were on.

Surely vim should do better… and it does. The scripting in vim is wonderful, this small function is all you need:

function Goformat()
    let regel=line(".")
    call cursor(regel, 1)

And then together with this:

autocmd Filetype go command! Fmt call Goformat()

Put both in your .vimrc and you are set. Nice formatting with :Fmt and you’ll stay on the current line. The actual line may be slightly different due to the reformatting, but this is a far cry from being put on the first one.