Skip to content

nvim-cmp source providing the names of Go packages to import

License

Notifications You must be signed in to change notification settings

Yu-Leo/cmp-go-pkgs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

cmp-go-pkgs

nvim-cmp source providing the names of Go packages to import

demo.mp4

✨ Features

  • Using gopls Language Server to get a list of packages available for import
  • Using nvim-treesitter to show suggestions only if the cursor is in the import section
  • Smart suggestions. See completion rules bellow

📦 Installation

Install the plugin with your preferred package manager:

{
  "hrsh7th/nvim-cmp",

  dependencies = {
    "Yu-Leo/cmp-go-pkgs",
  },

  config = function()
    local cmp = require("cmp")
    cmp.setup({
      sources = {
        { name = "go_pkgs" },
      },
    })
  end,
}

⚡️ Requirements

⚙️ Setup

⚠️ Attention! The plugin won't work without it ⚠️

You need to add the following code next to other autocmds in your neovim config.

vim.api.nvim_create_autocmd({ "LspAttach" }, {
  pattern = { "*.go" },
  callback = function(args)
    require("cmp_go_pkgs").init_items(args)
  end,
})

This code defines the following behavior: at each LspAttach event, the plugin will request a list of packages available for import from gopls and save them to its cache. This is more efficient than sending requests to the LSP for each completion request. However, because of this, if you change or add new packages, they will be displayed in the previously opened buffer only if you reopen it or call :LspRestart.

🚀 Usage

Like any other nvim-cmp source.

Completion rules

  • Complements only the package name. Without double quotes
  • If the current line contains /, it offers only those options that contain the incomplete line as a prefix
  • If the current line does not contain /, it offers all available options

See my neovim configuration.

🤝 Contributing

PRs and Issues are always welcome.

Author: @Yu-Leo

🫶 Alternatives

I took the code of this plugin as a basis and modified it to suit my needs.