Run goimports on save in Sublime Text?

时间:2016-04-21 21:49:38

标签: go sublimetext3 gofmt

In Sublime Text 3, with plugins GoSublime and GoImports installed.

I'm having trouble having goimports run on my file automatically everytime I save.

Here's what I tried :

My GoSublime settings are set to :

{
    "env": {"GOPATH": "/home/nicolas/.go", "PATH": "$GOPATH/bin:$PATH" },
    //"fmt_cmd": ["goimports"]
}

When I save with these settings, the code gets formatted but imports are not added. Nothing surprising so far.

If I hit ctrl+shift+P then GoImports, imports get added as expected.

Now my problem is, when I uncomment that previous line to have these settings :

{
    "env": {"GOPATH": "/home/nicolas/.go", "PATH": "$GOPATH/bin:$PATH" },
    "fmt_cmd": ["goimports"]
}

Not only does it not add the imports, but no other formatting gets done anymore.

Any idea where I went wrong ?

I'm using Linux (Ubuntu).

3 个答案:

答案 0 :(得分:9)

  1. 确保$ PATH中的$ GOPATH / bin(Windows:%GOPATH%\ bin) 在你的%PATH%)。
  2. 运行go -u golang.org/x/tools/cmd/goimports(你可能必须这样做 安装mercurial)。
  3. 安装Sublime Text和GoSublime(或确保你已经获得了 最新更新,如果它已经安装)。
  4. 打开gosublime用户配置/首选项文件(Mac:⌘。⌘5Windows: 按Ctrl +。 CTRL + 5)。确保按下命令按钮 整个捷径序列。
  5. 让它看起来像这样: {"fmt_cmd": ["goimports"]}
  6. Source

答案 1 :(得分:3)

所以,我错了:

我使用Package control > Install package > GoImports从Sublime内部安装了GoImports。它将它安装在Sublime Packages文件夹中,该文件夹不在我的$PATH

我应该做些什么呢?

使用命令go get -u golang.org/x/tools/cmd/goimports安装它。这将把它安装在你的$ GOPATH中(并且$ GOPATH / bin应该在你的$ PATH上)。

答案 2 :(得分:0)

ctrl+. , ctrl+x打开margo.go文件。 然后取消注释golang.GoFmt和golang.GoImports之一。重新启动崇高文字,然后重试。

// golang.GoFmt,
// or
// golang.GoImports,

我使用ubuntu + sublime text 3207 + Go-1.10 + Gosublime + Goimports-release-1.10。它在我取消注释golang.GoImports后就可以使用。