Gopls:在 Sublime Text 中使用

请使用 LSP 插件。在通过 Package Control 安装该插件后,请执行以下操作:

  • 打开 命令面板
  • 找到并运行命令 LSP: Enable Language Server Globally(全局启用语言服务器)
  • 选择 gopls 条目。请注意不要错误地选择名称相似的 golsp

最后,您应该熟悉 LSP 插件的 设置快捷键。您可以在菜单项 Preferences > Package Settings > LSP(偏好设置 > 插件设置 > LSP)下找到它们。

示例

最小化的全局 LSP 设置,假设 goplsgo 出现在 Sublime Text 可见的 PATH 中。

{
    "clients": {
        "gopls": {
             "enabled": true,
         }
    }
}

全局 LSP 设置,为查找 goplsgo 提供了一个特定的 PATH,以及一些 Sublime LSP 本身的的设置。

{
    "clients": {
        "gopls": {
            "enabled": true,
            "env": {
                "PATH": "/path/to/your/go/bin",
            }
        }
    },
    // Recommended by https://agniva.me/gopls/2021/01/02/setting-up-gopls-sublime.html
    // except log_stderr mentioned there is no longer recognized.
    "show_references_in_quick_panel": true,
    "log_debug": true,
    // These two are recommended by LSP-json as replacement for deprecated only_show_lsp_completions
    "inhibit_snippet_completions": true,
    "inhibit_word_completions": true,
 }

LSP 和 gopls 的设置也可以针对每个项目进行调整,以覆盖全局设置。

{
    "folders": [
        {
            "path": "/path/to/a/folder/one"
        },
        {
            // If you happen to be working on Go itself, this can be helpful; go-dev/bin should be on PATH.
            "path": "/path/to/your/go-dev/src/cmd"
        }
     ],
    "settings": {
        "LSP": {
            "gopls": {
                // To use a specific version of gopls with Sublime Text LSP (e.g., to try new features in development)
                "command": [
                    "/path/to/your/go/bin/gopls"
                ],
                "env": {
                    "PATH": "/path/to/your/go-dev/bin:/path/to/your/go/bin",
                    "GOPATH": "",
                },
                "settings": {
                    "experimentalWorkspaceModule": true
                }
            }
        },
        // This will apply for all languages in this project that have
        // LSP servers, not just Go, however cannot enable just for Go.
        "lsp_format_on_save": true,
    }
}

通常,在保存项目文件后,这些设置的更改就会生效,但有时可能需要重新启动服务器(Tools > LSP > Restart Servers)(工具 > LSP > 重启服务器)或退出并重新启动 Sublime Text 本身。


本文档的源代码可以在 golang.org/x/tools/gopls/doc 下找到。