The Go distribution comes with some great tools for writing Go in Vim. I frequently use the :Import, :Drop, and :Fmt commands.

The simplest way to enable all of the Vim plugins is to add the following lines to your vimrc:

set rtp+=$GOROOT/misc/vim
filetype plugin indent on
syntax on

Here is some of the functionality you get from the plugins:

:Import

:Import is a Vim command for importing Go packages.

For example, if you have some Go source code open in Vim:

package main

import (
    "net/http"
)

and you want to import the encoding/json package, you can type this in Vim:

:Import encoding/json

and it will result in the following:

package main

import (
    "encoding/json"
    "net/http"
)

It also keeps the list of imports alphabetized, which is nice.

If you try to import a package that is already being imported, an error is displayed (for example, '"encoding/json" already being imported'), and nothing will change.

:Drop

What about removing import lines? That's what :Drop does. This is particularly useful since Go does not allow unused imports.

If you have this Go code open in Vim:

package main

import (
    "encoding/json"
    "net/http"
)

and you want to remove the encoding/json package, you can type this:

:Drop encoding/json

and it will result in the following:

package main

import (
    "net/http"
)

If you try to drop a package that is not being imported, an error is displayed (for example, '"encoding/json" not being imported'), and nothing will change.

:Fmt

Finally, :Fmt is for running gofmt on your code in Vim.

For example, if you have some Go code open in Vim that looks like this:

package main

import (
    "net/http"
    "encoding/json"
)

type Kanji struct {
    Literal         string   `json:"literal"`
    Grade       int      `json:"grade"`
}

and you want to run gofmt on it, you can type this:

:Fmt

and it will result in the following:

package main

import (
    "encoding/json"
    "net/http"
)

type Kanji struct {
    Literal string `json:"literal"`
    Grade   int    `json:"grade"`
}


blog comments powered by Disqus

Published

2012-07-27

Categories


Tags