neovim with gopls, adding new deps

making gopls pick up new go dependencies in neovim without a restart

SEAN K.H. LIAO

neovim with gopls, adding new deps

making gopls pick up new go dependencies in neovim without a restart

neovim, gopls, dependencies

neovim is my editor of choice these days, and with that comes a plethora of plugin options. For completion, I use nvim-cmp along with nvim-cmp-lsp, and nvim-lspconfig to setup all the LSP settings. For Go, that means using gopls.

One thing that has been a papercut for me for a while has been adding new dependencies. gopls will suggest to import a dependency, say golang.org/x/sys/unix, adding it to the import block on the file, but then completion breaks since the dependency is not part of the module's dependencies (not listed in go.mod). What I've been doing is: save, exit neovim, run go mod tidy, open neovim. But that incurs a startup penalty every time.

Recently, I learned that it should actually work with LSP's didChangeWatchedFiles, merged over a year ago into neovim. This lets gopls tell neovim it's interested in getting notified about go.mod file updates (so new dependencies), allowing it pick up changes without a restart.

Now the flow is: save, and in a separate terminal run go mod tidy. gopls should just pick up the changes and autocomplete will start working for the new dependency.

1local capabilities = require("cmp_nvim_lsp").default_capabilities()
2capabilities.workspace = { didChangeWatchedFiles = { dynamicRegistration = true } }
3-- ... set other capabilities
4
5require("lspconfig").gopls.setup({
6  capabilities = capabilities,
7  -- other settings
8})