GithubHelp home page GithubHelp logo

ray-x / go.nvim Goto Github PK

View Code? Open in Web Editor NEW
1.9K 15.0 119.0 1.02 MB

G'day Nvimer, Joyful Gopher: Discover the Feature-Rich Go Plugin for Neovim

License: MIT License

Lua 95.88% Makefile 0.32% Go 0.81% Scheme 1.52% Vim Script 1.48%
neovim nvim go golang nvim-plugin treesitter gopls neovim-plugin null-ls nvim-dap

go.nvim's Introduction

go.nvim

A modern go neovim plugin based on treesitter, nvim-lsp and dap debugger. It is written in Lua and async as much as possible. PR & Suggestions are welcome.

The plugin covers most features required for a gopher.
  • Perproject setup. Allows you setup plugin behavior per project based on project files(launch.json, .gonvim)
  • Async jobs with libuv
  • Syntax highlight & Texobject: Native treesitter support is faster and more accurate. All you need is a theme support treesitter, try aurora, starry.nvim. Also, there are quite a few listed in awesome-neovim
  • All the GoToXxx (E.g reference, implementation, definition, goto doc, peek code/doc etc) You need lspconfig setup. There are lots of posts on how to set it up. You can also check my navigator gopls setup lspconfig.lua
  • gopls commands: e.g. fillstruct, organize imports, list modules, list packages, gc_details, generate, change signature, etc.
  • Runtime lint/vet/compile: Supported by LSP (once you set up your LSP client), GoLint with golangci-lint also supported
  • Build/Make/Test: Go.nvim provides support for these by an async job wrapper.
  • Test coverage: run test coverage and show coverage sign and function metrics
  • Dlv Debug: with nvim-dap and Dap UI. Go adapter included, zero config for your debug setup.
  • Load vscode launch configuration
  • Unit test: generate unit test framework with gotests. Run test with ginkgo/gotestsum/go test
  • Add and remove tag for struct with tag modify(gomodifytags)
  • Code format: Supports LSP format and GoFmt(with golines)
  • CodeLens : gopls codelens and codelens action support
  • Comments: Add autodocument for your package/function/struct/interface. This feature is unique and can help you suppress golint errors...
  • Go to alternative go file (between test and source)
  • Test with ginkgo, gotestsum inside floaterm (to enable floaterm, guihua.lua has to be installed)
  • Code refactor made easy: GoFixPlural, FixStruct, FixSwitch, Add comment, IfErr, ModTidy, GoGet, extract function/block with codeactions... Most of the tools are built on top of treesitter AST or go AST. Fast and accurate.
  • GoCheat get go cheatsheet from cheat.sh.
  • Smart build tag detection when debug/run tests (e.g. //go:build integration)
  • Generate mocks with mockgen
  • Inlay hints: gopls (version 0.9.x or greater) inlay hints; version 0.10.x inlay hints are enabled by default.
  • luasnip: go.nvim included a feature rich luasnips you definitally need to try.
  • Treesitter highlight injection: go.nvim included a treesitter highlight injection for SQL and JSON.
  • Treesitter also injects highlight for go template, gohtmltmpl
  • Generate return value for current function
  • Generate go file with template
  • Generate go struct from json

Installation

Use your favorite package manager to install. The dependency treesitter (and optionally, treesitter-objects) should be installed the first time you use it. Also Run TSInstall go to install the go parser if not installed yet. sed is recommended to run this plugin.

Plug 'nvim-treesitter/nvim-treesitter'
Plug 'neovim/nvim-lspconfig'
Plug 'ray-x/go.nvim'
Plug 'ray-x/guihua.lua' ; recommended if need floating window support
use 'ray-x/go.nvim'
use 'ray-x/guihua.lua' -- recommended if need floating window support
use 'neovim/nvim-lspconfig'
use 'nvim-treesitter/nvim-treesitter'
{
  "ray-x/go.nvim",
  dependencies = {  -- optional packages
    "ray-x/guihua.lua",
    "neovim/nvim-lspconfig",
    "nvim-treesitter/nvim-treesitter",
  },
  config = function()
    require("go").setup()
  end,
  event = {"CmdlineEnter"},
  ft = {"go", 'gomod'},
  build = ':lua require("go.install").update_all_sync()' -- if you need to install/update all binaries
}

The go.nvim load speed is fast and you can enable it by default image

Make sure the $GOPATH/bin path is added to your $PATH environment variable. To check this you can run

echo $PATH | grep "$GOPATH/bin"

If nothing shows up, you can add the following to your shell config file:

export PATH=$PATH:$GOPATH/bin

Add format in your vimrc.

lua <<EOF
local format_sync_grp = vim.api.nvim_create_augroup("GoFormat", {})
vim.api.nvim_create_autocmd("BufWritePre", {
  pattern = "*.go",
  callback = function()
   require('go.format').goimports()
  end,
  group = format_sync_grp,
})

EOF

To startup/setup the plugin

require('go').setup()

Screenshots

Add comments

auto comments

Add/Remove tags

auto tag

GoTest in floating term

gotest

Use:

:GoTermClose

To close the floating term.

SQL/JSON Highlight injection

image

Inlay hints

image

refactor gorename

gorename as an alternative to gopls rename as it supports rename across packages Note: use with care Command: GoRename

code format

nvim-lsp support goimports by default.

autocmd BufWritePre (InsertLeave?) <buffer> lua vim.lsp.buf.formatting_sync(nil,500)

The plugin provides code format, by default is goline + gofumpt (stricter version of gofmt)

Use following code to format go code

require("go.format").gofmt()  -- gofmt only
require("go.format").goimports()  -- goimports + gofmt

Format on save

To config format on save, add one of the following to your init.lua:

Run gofmt on save

-- Run gofmt on save

local format_sync_grp = vim.api.nvim_create_augroup("GoFormat", {})
vim.api.nvim_create_autocmd("BufWritePre", {
  pattern = "*.go",
  callback = function()
   require('go.format').gofmt()
  end,
  group = format_sync_grp,
})

Run gofmt + goimports on save

-- Run gofmt + goimports on save

local format_sync_grp = vim.api.nvim_create_augroup("goimports", {})
vim.api.nvim_create_autocmd("BufWritePre", {
  pattern = "*.go",
  callback = function()
   require('go.format').goimports()
  end,
  group = format_sync_grp,
})

Auto-fill

Note: auto-fill struct also supported by gopls lsp-action

command Description
GoFillStruct auto fill struct
GoFillSwitch fill switch
GoIfErr Add if err
GoFixPlurals change func foo(b int, a int, r int) -> func foo(b, a, r int)

GoFixPlurals Youtube video

package foo

import "io"

func Foo() (io.Reader, error) { // the cursor on this line to add if err statement
}

auto struct

Textobject

Supported by treesitter. TS provided better parse result compared to regular expression. See the example treesitter config file on how to setup textobjects. Also with treesitter-objects, you can move, swap the selected blocks of codes, which is fast and accurate. go.nvim will load textobject with treesiteter, with default keybindings, if you what to set it up yourself, you can set textobject to false.

Go binaries install and update

The following go binaries are used in go.nvim (depends on your setup):

  • gofumpt
  • golines
  • goimports
  • gorename
  • gomodifytags
  • gotests
  • iferr
  • impl
  • fillstruct
  • fillswitch
  • dlv
  • ginkgo
  • gotestsum
  • govulncheck
  • goenum

If you run GoFmt and the configured binary (e.g. golines) was not installed, the plugin will install it for you. But the first run of GoFmt may fail. Recommended to run GoInstallBinaries to install all binaries before using the plugin.

command Description
GoInstallBinary go_binary_name use go install go_binary_url@latest to install tool, if installed will skip
GoUpdateBinary go_binary_name use go install go_binary_url@latest Will force re-install/update if already installed, otherwise same as GoInstallBinary
GoInstallBinaries use go install to install all tools, skip the ones installed
GoUpdateBinaries use go install to update all tools to the latest version

Build and test

command Description
GoMake async make, use with other commands
GoBuild args go build args (-g: enable debug, %: expand to current file, %:h expand to current package)
GoGenerate
GoRun {args} -a {cmd_args} e.g. GoRun equal to go run .; or GoRun ./cmd equal to go run ./cmd, Additional args: -F run in floaterm
GoRun -a {cmd_args} specify additional arguments pass to your main(), see notes 3
GoStop {job_id} stop the job started with GoRun
GoTest go test ./...
GoTestSum {pkgname} {gotestsum arguments} run gotestsum and show result in side panel
GoTestSum -w run gotestsum in watch mode
GoTest -v go test -v current_file_path
GoTest -c go test -c current_file_path
GoTest -n test nearest, see GoTestFunc
GoTest -f test current file, see GoTestFile
GoTest -n 1 -count=1 flag
GoTest -p {pkgname} test package, see GoTestPkg, test current package if {pkgname} not specified
GoTest -parallel {number} test current package with parallel number
GoTest -b {build_flags} run go test with build flags e.g. -gcflags=.
GoTest -t yourtags go test ./... -tags=yourtags, see notes
GoTest -F ./... | awk '{$1=$1};1' | delta pipe the test output to awk and then delta/diff-so-fancy to show diff output of go test (e.g. testify)
GoTest -a your_args go test ./... -args=yourargs, see notes
GoTest package_path -t yourtags go test packagepath -tags=yourtags
GoTest package_path -t yourtags other_args go test packagepath -tags=yourtags other_args
GoLint golangci-lint
GoGet {package_url} go get package_url and restart gopls. Note1
GoVet go vet
GoWork {run use} {pkgpath}
GoCoverage go test -coverprofile
GoCoverage -p go test -coverprofile (only tests package for current buffer)
GoCoverage -f coverage_file_name load coverage file
GoCoverage {flags} -t : toggle, -r: remove signs, -R remove sings from all files, -m show metrics
GoCoverage {flags} {go test flags} e.g: GoCoverage -p -coverpkg 'yourpackagename'
GoTermClose closes the floating term

Note:

  1. if package_url not provided, will check current line is a valid package url or not, if it is valid, will fetch current url
  2. tags: if //+build tags exist it will be added automatically
  3. args: if multiple args is provided, you need toconcatenate it with '\ ', e.g. GoTest -a yourtags\ other_args
  4. % will expand to current file path, e.g. GoBuild %

Show test coverage:

GoTestCoverage

Provided wrapper for gobulild/test etc with async make Also suggest to use vim-test, which can run running tests on different granularities.

Unit test with gotests and testify

Support table based unit test auto generate, parse current function/method name using treesitter

command Description
GoTestFunc run test for current func
GoTestFunc -s select the test function you want to run
GoTestFunc -tags=yourtag run test for current func with -tags yourtag option
GoTestFile run test for current file
GoTestFile -tags=yourtag run test for current folder with -tags yourtag option
GoTestPkg run test for current package/folder
GoTestPkg -tags=yourtag run test for current folder with -tags yourtag option
GoAddTest [-parallel] Add test for current func
GoAddExpTest [-parallel] Add tests for exported funcs
GoAddAllTest [-parallel] Add tests for all funcs

GoTestXXX Arguments

arguments Description
-v verbose mode
-c compile
-C coverprofile
-n count
-t tags
-f fuzz
-bench bench test
-m metric
-s select
-p package
-F floaterm mode
-a args

Note: For GoTestXXX

You can add available arguments with long name or character flag e.g. GoTest -tags=integration ./internal/web -b=. -count=1 -

You can also add other unmapped arguments after the -a or -args flag GoTest -a mock=true

GoCheat

Show cheat.sh for api in neovim new buffer. e.g. GoCheat sort

GoDoc

Show go doc for api in neovim floating window. e.g. GoDoc fmt.Println

Godoc

If no argument provided, fallback to lsp.hover()

GoPkgOutline

A symbole outline for all symbols (var, const, func, struct, interface etc) inside a package You can still use navigator or sidebar plugins (e.g. vista, symbols-outline) to check outline within a file. But it is more useful for go to check the symbols in a package, as those symbols are visuals inside package, also the method can be defined in different source file.

Command format: GoPkgOutline {options} options: -f: show in floatwing window (default side panel, both require quihua.lua) -p package_name: the package you want to list. e.g. GoPkgOutline -p json; default package is current file's package If guihua not installed fallback to loclist

image

Modifytags

Modify struct tags by gomodifytags and treesitter

command Description
GoAddTag
GoRmTag
GoClearTag

Options: -transform/-t: transform the tag -add-options/-a: add options to the tag

GoFmt

nvim-lsp support goimports by default. The plugin provided a new formatter, goline + gofumpt (stricter version of gofmt)

command Description
GoFmt {opts} default: gofumpt
GoImports default: goimports
GoImports package_path gopls add_import package

{opts} : -a format all buffers

GoImplements

nvim-lsp/gopls support implementation by default. The plugin provides this command for people migrate from vim-go

GoImpl

generate method stubs for implementing an interface

Usage:

:GoImpl {receiver} {interface}

Also, you can put the cursor on the struct and run

:GoImpl {interface}

e.g:

:GoImpl f *File io.Reader

or simply put your cursor in a struct and do

:GoImpl io.Reader

or simply your cursor on a interface and specify a receiver type

:GoImpl MyType

Debug

command Description
GoDebug start debug session, Note 1
GoDebug -h show helps info
GoDebug -c compile only
GoDebug -t start debug session for go test file, Note 2
GoDebug -R restart debug session
GoDebug -n start debug session for nearest go test function
GoDebug -p launch package test and start debug
GoDebug -e program dap exec program
GoDebug -a attach to remote process
GoDebug -s stop debug session and unmap debug keymap
GoDebug -A args debug session with args
GoDbgKeys show debug keymaps in a floating window (guihua)
GoBreakToggle GoDebug -b
GoDbgStop Same as GoDebug -s
GoDbgContinue Continue debug session
BreakCondition conditional break

Notes:

  1. Without any argument, will check if launch.json existed or not, if existed, using launch.json and popup input. If launch.json not existed, will start debug session for current file, if current file is package main will run main(), else will start the debug package test
  2. with -t option, if the current file is not a test file, will switch to the test file and run test for current function
  3. If the cursor is inside scope of a test function, will debug the current test function, if cursor is inside a test file, will debug current test file

Switch between go and test file

command Description
GoAlt / GoAlt! open alternative go file (use ! to create if not exist)
GoAltS / GoAltS! open alternative go file in split
GoAltV / GoAltV! open alternative go file in vertical split

Go Mock

command Description
GoMockGen default: generate mocks for current file
GoMockGen -s source mode(default)
GoMockGen -i interface mode, provide interface name or put the cursor on interface -p package
GoMockGen -d destination directory, default: ./mocks

Comments and Doc

Auto doc (to suppress golang-lint warning), generate comments by treesitter parsing result

type GoLintComplaining struct{}

And run

lua.require('go.comment').gen() -- or your favorite key binding and setup placeholder "no more complaint ;P"

The code will be:

// GoLintComplaining struct no more complaint ;P
type GoLintComplaining struct{}
command Description
GoCmt Add comment

GoModTidy

command Description
GoModInit run go mod init and restart gopls
GoModTidy run go mod tidy and restart gopls
GoModVendor run go mod vendor and restart gopls

run go mod tidy and restart gopls

LSP

Nvim-lsp is good enough for a gopher. If you looking for a better GUI. You can install navigator, or lspsaga, and lsp-utils etc. The goal of go.nvim is more provide unique functions releated to gopls instead of a general lsp gui client. The lsp config in go.nvim has a none default setup and contains some improvement and I would suggest you to use.

LSP cmp support

The latest version enabled lsp snippets (and other setups) by default. In case you need flowing the setup from cmp README.md, please use flowing command:

local capabilities = require('cmp_nvim_lsp').default_capabilities(vim.lsp.protocol.make_client_capabilities())
require('go').setup({
  -- other setups ....
  lsp_cfg = {
    capabilities = capabilities,
    -- other setups
  },
})

LSP CodeLens

Gopls supports code lens. To run gopls code lens action GoCodeLenAct Note: codelens need to be enabled in gopls, check default config in

LSP CodeActions

You can use native code action provided by lspconfig. If you installed guihua, you can also use a GUI version of code action GoCodeAction

Lint

Supported by LSP, also GoLint command (by calling golangcl-lint) if you need background golangci-lint check, you can configure it with ALE

Debug with dlv

Setup(adapter) for go included. Need Dap and Dap UI plugin nvim-dap nvim-dap-ui dap GDB style key mapping is used

Keymaps

key Description
c continue
n next
s step
o stepout
S cap S: stop debug
u up
D cap D: down
C cap C: run to cursor
b toggle breakpoint
P cap P: pause
p print, hover value (also in visual mode)

Moving from vscode-go debug

Please check Vscode Launch configurations for more info go.nvim support launch debugger from vscode-go .vscode/launch.json configurations If launch.json is valid, run GoDebug will launch from the launch.json configuration.

Inlay hints

image

Command

  • GoToggleInlay

Note:

Please use jsonls/null-ls check your launch.json is valid json file. Following syntax is not supported

  • Trailing comma
  • Comment

Here is a sample launch.json

Json to Go struct

  • ["x]GoJson2Struct! Visual select the json and run GoJson2Struct youStructName -bang will put result to register a if ["x] specified, will put get json from clipboard

Load Env file

  • GoEnv {filename} By default load .env file in current directory, if you want to load other file, use {filename} option

Generate return value

  • GoGenReturn

create return value for current function e.g. if we have

func Foo() (int, error) {
  return 1, nil
}

and in your code you cursor on Foo

Foo()

will generate

i, err := Foo()
if err != nil {
  return
}

Rename modules

  • Gomvp Rename module name in under cursor e.g. Gomvp Gomvp old_mod_name Gomvp old_mod_name new_mod_name

govulncheck

  • GoVulnCheck {arguments} Run govulncheck on current project

goenum

  • Goenum {arguments} Run goenum on current project

gonew

  • GoNew {filename} Create new go file. It will use template file. e.g. GoNew ./pkg/string.go will create string.go with template file GoNew also support using gonew command to create new file with template file gonew cli, e.g GoNew hello package_name/folder is same as gonew golang.org/x/example/hello package_name/folder if package_name/folder not provided, a hello project will be created in current folder

ginkgo

  • Ginkgo {args}
Arg Description
run
watch
build
bootstrap
labels
outline

Debug Commands

Command Description
GoDebug Start debugger, to debug test, run GoDebug test, to add addition args run GoDebug arg1 arg2
GoDebugConfig Open launch.json file
GoBreakSave save all breakpoints to project file
GoBreakLoad load all breakpoints from project file
GoBreakToggle toggle break point
BreakCondition conditional break point
ReplRun dap repl run_last
ReplToggle dap repl toggle

Required DAP plugins

The plugin will setup debugger. But you need to install

  • dap

    • 'mfussenegger/nvim-dap'
  • dap ui (optional)

    • 'rcarriga/nvim-dap-ui'
    • 'nvim-neotest/nvim-nio'
  • dap virtual text (optional)

    • 'theHamsta/nvim-dap-virtual-text'

Also you can check telescope dap extension : nvim-telescope/telescope-dap.nvim

Sample vimrc for DAP

Plug 'mfussenegger/nvim-dap'
Plug 'rcarriga/nvim-dap-ui'
Plug 'nvim-neotest/nvim-nio'
Plug 'theHamsta/nvim-dap-virtual-text'
" Plug 'nvim-telescope/telescope-dap.nvim'

Commands

Check commands.lua on all the commands provided

Gopls commands

Check gopls.lua on all the gopls commands provided, some of them are not exposed to user, but you can still use it in your lua setup.

  • list_imports
  • add_import
  • list_packages
  • tidy
  • change_signature
  • ...

configuration

Configure from lua suggested, The default setup:

require('go').setup({

  disable_defaults = false, -- true|false when true set false to all boolean settings and replace all tables
  -- settings with {}; string will be set to ''. user need to setup ALL the settings
  -- It is import to set ALL values in your own config if set value to true otherwise the plugin may not work
  go='go', -- go command, can be go[default] or e.g. go1.18beta1
  goimports ='gopls', -- goimports command, can be gopls[default] or either goimports or golines if need to split long lines
  gofmt = 'gopls', -- gofmt through gopls: alternative is gofumpt, goimports, golines, gofmt, etc
  fillstruct = 'gopls',  -- set to fillstruct if gopls fails to fill struct
  max_line_len = 0, -- max line length in golines format, Target maximum line length for golines
  tag_transform = false, -- can be transform option("snakecase", "camelcase", etc) check gomodifytags for details and more options
  tag_options = 'json=omitempty', -- sets options sent to gomodifytags, i.e., json=omitempty
  gotests_template = "", -- sets gotests -template parameter (check gotests for details)
  gotests_template_dir = "", -- sets gotests -template_dir parameter (check gotests for details)
  comment_placeholder = '' ,  -- comment_placeholder your cool placeholder e.g. 󰟓       
  icons = {breakpoint = '🧘', currentpos = '🏃'},  -- setup to `false` to disable icons setup
  verbose = false,  -- output loginf in messages
  lsp_cfg = false, -- true: use non-default gopls setup specified in go/lsp.lua
                   -- false: do nothing
                   -- if lsp_cfg is a table, merge table with with non-default gopls setup in go/lsp.lua, e.g.
                   --   lsp_cfg = {settings={gopls={matcher='CaseInsensitive', ['local'] = 'your_local_module_path', gofumpt = true }}}
  lsp_gofumpt = true, -- true: set default gofmt in gopls format to gofumpt
                      -- false: do not set default gofmt in gopls format to gofumpt
  lsp_on_attach = nil, -- nil: use on_attach function defined in go/lsp.lua,
                       --      when lsp_cfg is true
                       -- if lsp_on_attach is a function: use this function as on_attach function for gopls
  lsp_keymaps = true, -- set to false to disable gopls/lsp keymap
  lsp_codelens = true, -- set to false to disable codelens, true by default, you can use a function
  -- function(bufnr)
  --    vim.api.nvim_buf_set_keymap(bufnr, "n", "<space>F", "<cmd>lua vim.lsp.buf.formatting()<CR>", {noremap=true, silent=true})
  -- end
  -- to setup a table of codelens
  diagnostic = {  -- set diagnostic to false to disable vim.diagnostic.config setup,
                  -- true: default nvim setup
    hdlr = false, -- hook lsp diag handler and send diag to quickfix
    underline = true,
    virtual_text = { spacing = 2, prefix = '' }, -- virtual text setup
    signs = {'', '', '', ''},  -- set to true to use default signs, an array of 4 to specify custom signs
    update_in_insert = false,
  },
  -- if you need to setup your ui for input and select, you can do it here
  -- go_input = require('guihua.input').input -- set to vim.ui.input to disable guihua input
  -- go_select = require('guihua.select').select -- vim.ui.select to disable guihua select
  lsp_document_formatting = true,
  -- set to true: use gopls to format
  -- false if you want to use other formatter tool(e.g. efm, nulls)
  lsp_inlay_hints = {
    enable = true,
    -- hint style, set to 'eol' for end-of-line hints, 'inlay' for inline hints
    -- inlay only available for 0.10.x
    style = 'inlay',
    -- Note: following setup only works for style = 'eol', you do not need to set it for 'inlay'
    -- Only show inlay hints for the current line
    only_current_line = false,
    -- Event which triggers a refersh of the inlay hints.
    -- You can make this "CursorMoved" or "CursorMoved,CursorMovedI" but
    -- not that this may cause higher CPU usage.
    -- This option is only respected when only_current_line and
    -- autoSetHints both are true.
    only_current_line_autocmd = "CursorHold",
    -- whether to show variable name before type hints with the inlay hints or not
    -- default: false
    show_variable_name = true,
    -- prefix for parameter hints
    parameter_hints_prefix = "󰊕 ",
    show_parameter_hints = true,
    -- prefix for all the other hints (type, chaining)
    other_hints_prefix = "=> ",
    -- whether to align to the length of the longest line in the file
    max_len_align = false,
    -- padding from the left if max_len_align is true
    max_len_align_padding = 1,
    -- whether to align to the extreme right or not
    right_align = false,
    -- padding from the right if right_align is true
    right_align_padding = 6,
    -- The color of the hints
    highlight = "Comment",
  },
  gopls_cmd = nil, -- if you need to specify gopls path and cmd, e.g {"/home/user/lsp/gopls", "-logfile","/var/log/gopls.log" }
  gopls_remote_auto = true, -- add -remote=auto to gopls
  gocoverage_sign = "",
  sign_priority = 5, -- change to a higher number to override other signs
  dap_debug = true, -- set to false to disable dap
  dap_debug_keymap = true, -- true: use keymap for debugger defined in go/dap.lua
                           -- false: do not use keymap in go/dap.lua.  you must define your own.
                           -- Windows: Use Visual Studio keymap
  dap_debug_gui = {}, -- bool|table put your dap-ui setup here set to false to disable
  dap_debug_vt = { enabled_commands = true, all_frames = true }, -- bool|table put your dap-virtual-text setup here set to false to disable

  dap_port = 38697, -- can be set to a number, if set to -1 go.nvim will pick up a random port
  dap_timeout = 15, --  see dap option initialize_timeout_sec = 15,
  dap_retries = 20, -- see dap option max_retries
  build_tags = "tag1,tag2", -- set default build tags
  textobjects = true, -- enable default text objects through treesittter-text-objects
  test_runner = 'go', -- one of {`go`,  `dlv`, `ginkgo`, `gotestsum`}
  verbose_tests = true, -- set to add verbose flag to tests deprecated, see '-v' option
  run_in_floaterm = false, -- set to true to run in a float window. :GoTermClose closes the floatterm
                           -- float term recommend if you use gotestsum ginkgo with terminal color

  floaterm = {   -- position
    posititon = 'auto', -- one of {`top`, `bottom`, `left`, `right`, `center`, `auto`}
    width = 0.45, -- width of float window if not auto
    height = 0.98, -- height of float window if not auto
    title_colors = 'nord', -- default to nord, one of {'nord', 'tokyo', 'dracula', 'rainbow', 'solarized ', 'monokai'}
                              -- can also set to a list of colors to define colors to choose from
                              -- e.g {'#D8DEE9', '#5E81AC', '#88C0D0', '#EBCB8B', '#A3BE8C', '#B48EAD'}
  },
  trouble = false, -- true: use trouble to open quickfix
  test_efm = false, -- errorfomat for quickfix, default mix mode, set to true will be efm only
  luasnip = false, -- enable included luasnip snippets. you can also disable while add lua/snips folder to luasnip load
  --  Do not enable this if you already added the path, that will duplicate the entries
  on_jobstart = function(cmd) _=cmd end, -- callback for stdout
  on_stdout = function(err, data) _, _ = err, data end, -- callback when job started
  on_stderr = function(err, data)  _, _ = err, data  end, -- callback for stderr
  on_exit = function(code, signal, output)  _, _, _ = code, signal, output  end, -- callback for jobexit, output : string
  iferr_vertical_shift = 4 -- defines where the cursor will end up vertically from the begining of if err statement
})

You will need to add keybind yourself: e.g

vim.cmd("autocmd FileType go nmap <Leader><Leader>l GoLint")
vim.cmd("autocmd FileType go nmap <Leader>gc :lua require('go.comment').gen()")

Project setup

go.nvim allow you override your setup by a project file. Put .gonvim/init.lua in your root folder. It is a small lua script and will be run durning go.setup(). The return value is used to override go.nvim setup. The sample project setup. You can check the youtube video here on how to use this feature.

-- .gonvim/init.lua project config

return {
  go = "go", -- set to go1.18beta1 if necessary
  goimports = "gopls", -- if set to 'gopls' will use gopls format, also goimports
  gofmt = "gofumpt", -- if set to gopls will use gopls format
  null_ls_document_formatting_disable = true
}

This will override your global go.nvim setup

Text object

I did not provide textobject support in the plugin. Please use treesitter textobject plugin. My treesitter config:

  require "nvim-treesitter.configs".setup {
    incremental_selection = {
      enable = enable,
      keymaps = {
        -- mappings for incremental selection (visual mappings)
        init_selection = "gnn", -- maps in normal mode to init the node/scope selection
        node_incremental = "grn", -- increment to the upper named parent
        scope_incremental = "grc", -- increment to the upper scope (as defined in locals.scm)
        node_decremental = "grm" -- decrement to the previous node
      }
    },

    textobjects = {
      -- syntax-aware textobjects
      enable = enable,
      lsp_interop = {
        enable = enable,
        peek_definition_code = {
          ["DF"] = "@function.outer",
          ["DF"] = "@class.outer"
        }
      },
      keymaps = {
        ["iL"] = {
          -- you can define your own textobjects directly here
          go = "(function_definition) @function",
        },
        -- or you use the queries from supported languages with textobjects.scm
        ["af"] = "@function.outer",
        ["if"] = "@function.inner",
        ["aC"] = "@class.outer",
        ["iC"] = "@class.inner",
        ["ac"] = "@conditional.outer",
        ["ic"] = "@conditional.inner",
        ["ae"] = "@block.outer",
        ["ie"] = "@block.inner",
        ["al"] = "@loop.outer",
        ["il"] = "@loop.inner",
        ["is"] = "@statement.inner",
        ["as"] = "@statement.outer",
        ["ad"] = "@comment.outer",
        ["am"] = "@call.outer",
        ["im"] = "@call.inner"
      },
      move = {
        enable = enable,
        set_jumps = true, -- whether to set jumps in the jumplist
        goto_next_start = {
          ["]m"] = "@function.outer",
          ["]]"] = "@class.outer"
        },
        goto_next_end = {
          ["]M"] = "@function.outer",
          ["]["] = "@class.outer"
        },
        goto_previous_start = {
          ["[m"] = "@function.outer",
          ["[["] = "@class.outer"
        },
        goto_previous_end = {
          ["[M"] = "@function.outer",
          ["[]"] = "@class.outer"
        }
      },
      select = {
        enable = enable,
        keymaps = {
          -- You can use the capture groups defined in textobjects.scm
          ["af"] = "@function.outer",
          ["if"] = "@function.inner",
          ["ac"] = "@class.outer",
          ["ic"] = "@class.inner",
          -- Or you can define your own textobjects like this
          ["iF"] = {
            python = "(function_definition) @function",
            cpp = "(function_definition) @function",
            c = "(function_definition) @function",
            java = "(method_declaration) @function",
            go = "(method_declaration) @function"
          }
        }
      },
      swap = {
        enable = enable,
        swap_next = {
          ["<leader>a"] = "@parameter.inner"
        },
        swap_previous = {
          ["<leader>A"] = "@parameter.inner"
        }
      }
    }
  }

LuaSnip supports

go.nvim provides a better snippet support for go. Please check snippets for all languages and snippets for go

For a video demo, please check this: go.nvim new features work through

If you are not familiar with luasnip, please checkout LuaSnip Tutorial and TJ's Introduction to LuaSnip

Nvim LSP setup

go.nvim provided a better non-default setup for gopls (includes debounce, staticcheck, diagnosticsDelay etc)

This gopls setup provided by go.nvim works perfectly fine for most of the cases. You can also install navigator.lua which can auto setup all lsp clients and provides a better GUI.

For diagnostic issue, you can use the default setup. There are also quite a few plugins that you can use to explore issues, e.g. navigator.lua, folke/lsp-trouble.nvim. Nvim-tree and Bufferline also introduced lsp diagnostic hooks.

Important

I will integrate more gopls functions into go.nvim, please make sure you have the latest version installed Also, enable gopls experimental features if it is configure somewhere other than go.nvim Otherwise, set lsp_cfg to true in your go.nvim setup to enable gopls setup in go.nvim

Gopls default settings in go.nvim
gopls = {
    capabilities = {
      textDocument = {
        completion = {
          completionItem = {
            commitCharactersSupport = true,
            deprecatedSupport = true,
            documentationFormat = { 'markdown', 'plaintext' },
            preselectSupport = true,
            insertReplaceSupport = true,
            labelDetailsSupport = true,
            snippetSupport = true,
            resolveSupport = {
              properties = {
                'documentation',
                'details',
                'additionalTextEdits',
              },
            },
          },
          contextSupport = true,
          dynamicRegistration = true,
        },
      },
    },
    filetypes = { 'go', 'gomod', 'gosum', 'gotmpl', 'gohtmltmpl', 'gotexttmpl' },
    message_level = vim.lsp.protocol.MessageType.Error,
    cmd = {
      'gopls', -- share the gopls instance if there is one already
      '-remote.debug=:0',
    },
    root_dir = function(fname)
      local has_lsp, lspconfig = pcall(require, 'lspconfig')
      if has_lsp then
        local util = lspconfig.util
        return util.root_pattern('go.work', 'go.mod')(fname)
          or util.root_pattern('.git')(fname)
          or util.path.dirname(fname)
      end
    end,
    flags = { allow_incremental_sync = true, debounce_text_changes = 500 },
    settings = {
      gopls = {
        -- more settings: https://github.com/golang/tools/blob/master/gopls/doc/settings.md
        -- not supported
        analyses = {
          unreachable = true,
          nilness = true,
          unusedparams = true,
          useany = true,
          unusedwrite = true,
          ST1003 = true,
          undeclaredname = true,
          fillreturns = true,
          nonewvars = true,
          fieldalignment = false,
          shadow = true,
        },
        codelenses = {
          generate = true, -- show the `go generate` lens.
          gc_details = true, -- Show a code lens toggling the display of gc's choices.
          test = true,
          tidy = true,
          vendor = true,
          regenerate_cgo = true,
          upgrade_dependency = true,
        },
        hints = {
          assignVariableTypes = true,
          compositeLiteralFields = true,
          compositeLiteralTypes = true,
          constantValues = true,
          functionTypeParameters = true,
          parameterNames = true,
          rangeVariableTypes = true,
        },
        usePlaceholders = true,
        completeUnimported = true,
        staticcheck = true,
        matcher = 'Fuzzy',
        diagnosticsDelay = '500ms',
        symbolMatcher = 'fuzzy',
        semanticTokens = true,
        noSemanticTokens = true, -- disable semantic string tokens so we can use treesitter highlight injection

        ['local'] = get_current_gomod(),
        gofumpt = _GO_NVIM_CFG.lsp_gofumpt or false, -- true|false, -- turn on for new repos, gofmpt is good but also create code turmoils
        buildFlags = { '-tags', 'integration' },
      },
    },
    -- NOTE: it is important to add handler to formatting handlers
    -- the async formatter will call these handlers when gopls responed
    -- without these handlers, the file will not be saved
    handlers = {
      [range_format] = function(...)
        vim.lsp.handlers[range_format](...)
        if vfn.getbufinfo('%')[1].changed == 1 then
          vim.cmd('noautocmd write')
        end
      end,
      [formatting] = function(...)
        vim.lsp.handlers[formatting](...)
        if vfn.getbufinfo('%')[1].changed == 1 then
          vim.cmd('noautocmd write')
        end
      end,
    },
  }

Integrate with mason-lspconfig

require("mason").setup()
require("mason-lspconfig").setup()
require('lspconfig').gopls.setup({
   -- your gopls setup
})

If you want to use gopls setup provided by go.nvim

-- setup your go.nvim
-- make sure lsp_cfg is disabled
require("mason").setup()
require("mason-lspconfig").setup()
require('go').setup{
  lsp_cfg = false
  -- other setups...
}
local cfg = require'go.lsp'.config() -- config() return the go.nvim gopls setup

require('lspconfig').gopls.setup(cfg)

Highlighting for gomod, gosum, gohtmltmpl, gotmpl, gotexttmpl

You can install treesitter parser for gomod and gosum

:TSInstall gomod gosum

As for go template, the plugin has not been merge to treeistter master yet, you need to install treesitter-go-template

local parser_config = require'nvim-treesitter.parsers'.get_parser_configs()
parser_config.gotmpl = {
  install_info = {
    url = "https://github.com/ngalaiko/tree-sitter-go-template",
    files = {"src/parser.c"}
  },
  filetype = "gotmpl",
  used_by = {"gohtmltmpl", "gotexttmpl", "gotmpl", "yaml"}
}

And run

:TSInstall gotmpl

The plugin injects the tmpl to html syntax so you should see this:

image

Integrate null-ls

The plugin provides:

  • gotest LSP diagnostic source for null-ls
  • golangci_lint A async version of golangci-lint null-ls lint
  • gotest_action LSP test code action for null-ls

Gotest allow you run go test <package> when you save your go file and add diagnostics to nvim

local null_ls = require("null-ls")
local sources = {
  null_ls.builtins.diagnostics.revive,
  null_ls.builtins.formatting.golines.with({
    extra_args = {
      "--max-len=180",
      "--base-formatter=gofumpt",
    },
  })
}
-- for go.nvim
local gotest = require("go.null_ls").gotest()
local gotest_codeaction = require("go.null_ls").gotest_action()
local golangci_lint = require("go.null_ls").golangci_lint()
table.insert(sources, gotest)
table.insert(sources, golangci_lint)
table.insert(sources, gotest_codeaction)
null_ls.setup({ sources = sources, debounce = 1000, default_timeout = 5000 })

-- alternatively
null_ls.register(gotest)

You will see the failed tests flagged null-ls go.nvim

Sample vimrc

The following vimrc will enable all features provided by go.nvim

set termguicolors
call plug#begin('~/.vim/plugged')
Plug 'neovim/nvim-lspconfig'
Plug 'nvim-treesitter/nvim-treesitter'

Plug 'mfussenegger/nvim-dap'
Plug 'rcarriga/nvim-dap-ui'
Plug 'theHamsta/nvim-dap-virtual-text'
Plug 'ray-x/guihua.lua' " float term, codeaction and codelens gui support

Plug 'ray-x/go.nvim'

call plug#end()

lua <<EOF
require 'go'.setup({
  goimports = 'gopls', -- if set to 'gopls' will use golsp format
  gofmt = 'gopls', -- if set to gopls will use golsp format
  tag_transform = false,
  test_dir = '',
  comment_placeholder = '',
  lsp_cfg = true, -- false: use your own lspconfig
  lsp_gofumpt = true, -- true: set default gofmt in gopls format to gofumpt
  lsp_on_attach = true, -- use on_attach from go.nvim
  dap_debug = true,
})

local protocol = require'vim.lsp.protocol'

EOF

This will setup gopls with non default configure provided by go.nvim (Includes lspconfig default keymaps)

Other plugins that you may like

Q & A:

Q: What is Toggle gc annotation details

A: This is a codelens message, please run codelens GoCodeLenAct and get more info

go.nvim's People

Contributors

alesbrelih avatar blob42 avatar bytedaring avatar davincible avatar ddzero2c avatar etrnal70 avatar littledarren avatar mateusz834 avatar mr-lllll avatar nanozuki avatar nikola-milovic avatar olliebun avatar partounian avatar patrickreiis avatar prurph avatar qasimwarraich avatar rafaelzasas avatar ray-x avatar ray-xu-deltatre avatar rodrigc avatar roychoo avatar sidneyw avatar snowair avatar svrana avatar taigrr avatar tiny-box avatar urandom avatar urso avatar vcraescu avatar wilriker avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go.nvim's Issues

Keymap config

Currently I put this at the end of my lsp lua config file:

-- go plugin
require('go').setup()
require("go.format").gofmt()
require("go.format").goimport()
vim.cmd("autocmd BufWritePre *.go :silent! lua require('go.format').gofmt()")
vim.cmd("autocmd BufWritePre (InsertLeave?) <buffer> lua vim.lsp.buf.formatting_sync(nil,500)")

Which results in the following error:
image

Also, is the way I have set it up here right?

GoCoverage throw error and feature request: enable -tags on GoCoverage

Hi! First of all, thanks for this amazing plugins. It really speed up coding.

I've never used this but today i used :GoCoverage and this error was thrown:

E5108: Error executing lua Vim:E730: using List as a String stack traceback: [C]: in function 'jobstart' .../nvim/site/pack/packer/start/go.nvim/lua/go/coverage.lua:268: in function 'run' [string ":lua"]:1: in main chunk

One more thing. It would be great if we can add tags on coverage like this:
:GoCoverage -tags=sqlite_fts5

But it seems like it doesn't support adding -tags on :GoCoverage now based on what i've read on the readme. Is it possible to add -tags to :GoCoverage?

Thanks.

allow arbitrary arguments to GoTest

Right now it seems like "GoTest" arguments are limited to just providing a tag.

Other go plugins like vim-go allow for any arbitrary flags to be provided at the end of the "GoTest" command.

This is useful for only testing a particular package from neovim: "GoTest ./pkg/mypackage"

Consistency of vim commands

I've noticed that a few commands, like Gfstruct only start with a G, whereas the majority of the commands start with Go. A few of the Go prefixed commands are also not camelcased: Gofmt for example. Would it be possible to normalize all of these commands, so that they all start with Go, and they are all camelcased? Also, most of the commands are quite expressive with their name, but some, like Gfstruct are rather succinct. Would it be possible to name them more expressively as well, such as GoFillStruct?

LspCodeLens highlight group collision

function M.setup()
vim.cmd('highlight! link LspCodeLens WarningMsg')
vim.cmd('highlight! link LspCodeLensText WarningMsg')
vim.cmd('highlight! link LspCodeLensTextSign LspCodeLensText')
vim.cmd('highlight! link LspCodeLensTextSeparator Boolean')

Having the highlight groups defined in this way can be problematic if they are also set elsewhere by the user (like in a colorscheme, or init.[vim/lua]). Can you make it so that it is configurable or expose a way to choose the group parameters or what they're linked to?

Need help with :GoCoverage and :GoTestFunc

First of all, thank you so much for great plugin ❤️

:GoCoverage:

Screenshot from 2022-01-13 13-18-59

In short, GoCoverage could not find the package (where current buffer is) to perform test coverage. Note that: GoTestPkg runs fine (detectable)

:GoTestFunc

Seem like GoTestFunc is performing go test ./... which search for run-able test not only in current package (where current buffer is), but also all packages inside my workspace. Thus result in bloat of Skip package, no test to run

Could you please help @ray-x

Breakpoint/stopped symbols

Hey there. Thanks for taking this on.
Is/will there be a way to assign a custom breakpoint/stopped symbol?

I tried this in my init:

vim.fn.sign_define('DapBreakpoint', {text = '', texthl = '', linehl = '', numhl = ''})
vim.fn.sign_define('DapStopped', {text = '', texthl = '', linehl = '', numhl = ''})

But it seems that go.nvim overrides this when started.

:GoLint, causes asyncmake.lua Invalid %( in format string

When I tried to run:

:GoLint

I just got this:

stack traceback:
^I[C]: in function 'setqflist'
^I...nvim/site/pack/packer/start/go.nvim/lua/go/asyncmake.lua:104: in function <...nvim/site/pack/packer/start/go.nvim/lua/go/asyncmake.
lua:77> function: builtin#18 Vim:E377: Invalid %( in format string

Any ideas what might be causing this?

Syntax highlighting

Hello!

I apologize for posting this issue because I think my issue is not related to your plugin. But I thought I would ask.

Your screen shots so great syntax highlighting for Go.

image

But I have very little syntax highlighting.

image

Do you have any ideas why I have very little syntax highlighting? I have syntax highlighting in other languages.

Thanks again

GoDebug throwing an error

E5108: Error executing lua ...share/nvim/site/pack/packer/start/go.nvim/lua/go/dap.lua:114: attempt to call field 'open' (a nil value)                                                                                                                    
stack traceback:                                                                                                             
        ...share/nvim/site/pack/packer/start/go.nvim/lua/go/dap.lua:114: in function 'run'                                   
        [string ":lua"]:1: in main chunk                     

I have in my init.lua:

use 'leoluz/nvim-dap-go'                                                                                             
use 'mfussenegger/nvim-dap'                                                                                          
use 'mfussenegger/nvim-dap-ui'                                                                                       
use 'ray-x/go.nvim'

and am doing require('dap-go').setup() and

                                                                            
require('go').setup({                                                                                                  
    goimport = 'gopls', -- if set to 'gopls' will use golsp format                                                       
    gofmt = 'gopls', -- if set to gopls will use golsp format                                                            
    max_line_len = 120,                                                                                                  
    tag_transform = false,                                                                                               
    test_dir = '',                                                                                                       
    comment_placeholder = '   ',                                                                                        
    lsp_cfg = true, -- false: use your own lspconfig                                                                     
    lsp_gofumpt = true, -- true: set default gofmt in gopls format to gofumpt                                            
    lsp_on_attach = true, -- use on_attach from go.nvim                                                                  
    dap_debug = true                                                                                                     
})

Any advice would be greatly appreciated. Thanks!

Format not working

As I mentioned in my previous comment, go format wasn't working. I managed to fix it on my machine, and there were two issues:

  1. gofmt and gofumpt is only checked for in $GOPATH/bin/, but on my system they were installed on /usr/bin/. I symlinked them to $GOPATH/bin/ and that fixed it
    2) the default format arguments --max-len and --base-formatter didn't exist in my gofumpt binary. I commented them out and replaced them with {}. nonsense

After these two fixes it now works.

Edit: I found a few issues, see my pull request#4 for a fix

Question: Should go mod tidy require an LspRestart?

I've noticed that I need to :LspRestart after running :GoModTidy to clear import errors. I was going to just write a wrapper that did this automatically, but I was wondering if maybe I just have something misconfigured. Are you seeing the same behavior?

attemp to compare string with nil

nil

-- go.nvim setup copy from https://github.com/ray-x/go.nvim#sample-vimrc

require('go').setup({
  goimport = 'gopls', -- if set to 'gopls' will use golsp format
  gofmt = 'gopls', -- if set to gopls will use golsp format
  max_line_len = 120,
  tag_transform = false,
  test_dir = '',
  comment_placeholder = '',
  lsp_cfg = false, -- false: use your own lspconfig
  lsp_gofumpt = true, -- true: set default gofmt in gopls format to gofumpt
  lsp_on_attach = true, -- use on_attach from go.nvim
  dap_debug = true,
})
-- lsp-installer setup

...

    elseif server.name == "gopls" then
      -- require'go.lsp' : attemp to compare string with nil ?????
      local go_lsp_opts = require'go.lsp'.config() -- config() return the go.nvim gopls setup
      go_lsp_opts = vim.tbl_deep_extend("force", go_lsp_opts, opts)
      server:setup(go_lsp_opts)

...
gopls version
golang.org/x/tools/gopls master
    golang.org/x/tools/[email protected] h1:8Az52YwcFXTWPvrRomns1C0N+zlgTyyPKWvRazO9GG8=

Manually specify gopls path

I'm using nvim-lspinstall to manage all my lsp installations. Is it possible to tell go.nvim where the path to this binary is?

Here's an example of what I was doing before:

DATA_PATH = vim.fn.stdpath "data"
require('lspconfig').gopls.setup{
    cmd = { DATA_PATH .. "/lspinstall/go/gopls" },
    settings = {
      gopls = {
        analyses = {
          unusedparams = true,
        },
        staticcheck = true,
      },
    },
}

lint output to location list

is it possible to add the GoLint output to a location list so hitting enter on the file will bring you to the offending line?

Real time test output

Hey there,

This is a subjective request so feel free to shoot this down.

In vim-go when you run a test a new window is opened and all the output is immedaitely present. In your plugin, there is not much indication that tests are indeed running and that nothing went wrong.

I'd like to see if you have any thoughts on providing some kinda of feedback to the user that tests are indeed running and under way. This could be a buffer with test output as its running or some kinda ui element which suggests tests are currently running.

GoRun doesn't work at nvim 0.6

Invoke :GoRun result like this

|| 
|| go run: no go files listed
|| 
||

Here is my nvim --version

NVIM v0.6.0-dev+1518-g02bf251bb
Build type: Release
LuaJIT 2.1.0-beta3
Compilation: clang -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1 -DNVIM_TS_HAS_SET_MATCH_LIMIT -O2 -DNDEBUG -Wall -Wextra -pedantic -Wno-unused-parameter -Wstrict-prototypes -std=gnu99 -Wshadow -Wconversion -Wmissing-prototypes -Wimplicit-fallthrough -Wvla -fstack-protector-strong -fno-common -fdiagnostics-color=auto -DINCLUDE_GENERATED_DECLARATIONS -D_GNU_SOURCE -DNVIM_MSGPACK_HAS_FLOAT32 -DNVIM_UNIBI_HAS_VAR_FROM -DMIN_LOG_LEVEL=3 -I/tmp/neovim-20210714-39663-lqn3eb/build/config -I/tmp/neovim-20210714-39663-lqn3eb/src -I/usr/local/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include -I/usr/local/opt/gettext/include -I/tmp/neovim-20210714-39663-lqn3eb/build/src/nvim/auto -I/tmp/neovim-20210714-39663-lqn3eb/build/include
编译者 [email protected]

Features: +acl +iconv +tui
See ":help feature-compile"

     系统 vimrc 文件: "$VIM/sysinit.vim"
         $VIM 预设值: "/usr/local/Cellar/neovim/HEAD-02bf251/share/nvim"

Run :checkhealth for more info

GoTestFunc got error

run GoTestFunc in my test function and got an error

E488: 多余的尾部字符: :Gmake -run ..

Is there some dependence I missed ?

Quickfix layout of test

Thanks you for this great plugin.

When open an outline buffer, the quickfix of test result is below outline buffer.
See image:
image

I think it shoule be this layout:
image

'golines' is not executable

When trying to run the formatter inside neovim I get this error:

installing golines
formatting... /Users/x/Documents/code/go/hello/main.go{ "--max-len=120", "--base-formatter=gofumpt", "/Users/x/Documents/code/go/he
llo/main.go" }
E5108: Error executing lua Vim:E475: Invalid value for argument cmd: 'golines' is not executable

Any idea how to fix this? Been stuck here for a couple of hours...

GoDoc on hovered input and GoDef

Can you please add this features ?
when you place cursor on a word and type GoDoc it will open a popup containing doc to it (just like vim.go)
Also GoDef which take you to the definition of what ever cursor on.

gofumports depricated

From this commit: As the v0.1.0 release notes describe, gofumports was always a bit of a hack to allow IDEs to run both gofumpt and goimports at once. Now that gopls exists and bundles both features in an efficient way, people should just use that.

It's not installing anymore with gofumpt, and therefore the goimport command does not work

Edit: I just noticed gopls has not been integrated at all yet, was that done for a reason?

`GoTestFunc`: Unable to find nodes. Is your query correct?

Hey there,
Running into this err when running GoTestFunc. I've tried with the cursor in the middle of the method name (ex: on the '2' in '256') and in the body of the method.
Screen Shot 2021-11-16 at 11 10 49 AM
Can't seem to get it to work in any of my projects, but for example it fails here

My init.lua looks like

local use = require('packer').use
require('packer').startup(function()
...
  use 'nvim-treesitter/nvim-treesitter'
  -- Additional textobjects for treesitter
  use 'nvim-treesitter/nvim-treesitter-textobjects'
...
  use {'ray-x/go.nvim', requires = { 'nvim-treesitter/nvim-treesitter' } }
...
end)
...
-------------------------------------------------
-- Golang config
-------------------------------------------------
require('go').setup()
vim.api.nvim_exec([[ autocmd BufWritePre (InsertLeave?) <buffer> lua vim.lsp.buf.formatting_sync(nil,500) ]], false)
-- Import on save
vim.api.nvim_exec([[ autocmd BufWritePre *.go :silent! lua require('go.format').goimport() ]], false)

gotests is on the path, and the gopls language server is set
Screen Shot 2021-11-16 at 11 16 35 AM
up and running.

Any idea why this is happening? Thanks

GoAddTags -line, -offset or -struct cannot be used together. pick one

When call command GoAddTags json, there is nothing happened.

Then I tried output the actual cmd which was executed, I got this

{ "gomodifytags", "-format", "json", "-file", "gameserver/msghandler/user.go", "-struct", "Error", "-w", "-add-tags", "yaml", "-line", "32" }

Then I execute the command in the terminal directly and the result is

-line, -offset or -struct cannot be used together. pick one

Gofmt/Goimport will add an extra line after go file.

  • minimal config file:
require('packer').startup(function (use)
  use 'ray-x/go.nvim'
end)
require('go').setup()
  • steps

Create a new go project, just add hello world project, use nvim to open it, and call command :Goimport or :Gofmt.
And will get:

package main

import (
        "fmt"
)

func main() {
        fmt.Println("hello, world")
}

There will be an extra line at end of the file. This is not the behavior of goimport/gofumport, and will let the linter warning.

Run test error of 'errorformat' after commit "41a5a3e08e58864f7c2fc1dd9c36ee0754518c5d"

After commit hash "41a5a3e08e58864f7c2fc1dd9c36ee0754518c5d", It's always failed when run test.
error message:
...nvim/site/pack/packer/start/go.nvim/lua/go/asyncmake.lua:80: Failed to get value for option 'errorformat' stack traceback: ^I[C]: in function 'nvim_buf_get_option' ^I...nvim/site/pack/packer/start/go.nvim/lua/go/asyncmake.lua:80: in function <...nvim/site/pack/packer/start/go.nvim/lua/go/asyncmake.lua:66>

how to close the GoTest floatterm windows

How do I close the floating floatterm after I run GoTest ?
Right now I have to run this long lua script. There has to be a faster way to switch to the terminal and exit it.

lua for _, win in ipairs(vim.api.nvim_list_wins()) do local config = vim.api.nvim_win_get_config(win); if config.relative ~= "" then vi
m.api.nvim_win_close(win, false); print('Closing window', win) end end

Can't run test in path which contains some special characters.

If the test file path contains special characters such as ' ', '-'. Can't run "GoTestFunc".
For example:
"/Users/imkerberos/tmp/This is a - special path/MyProject". Neovim will output:

E5108: Error executing lua ...re/nvim/site/pack/packer/start/go.nvim/lua/go/gotest.lua:234: Vim(setlocal):E518: Unknown option: a stack traceback: [C]: in function 'cmd' ...re/nvim/site/pack/packer/start/go.nvim/lua/go/gotest.lua:234: in function 'test_fun' [string ":lua"]:1: in main chunk

I think should escape the path when run test. But I can't fix it because I don't understand lua.

Error detected while processing BufEnter Autocommands for "<buffer=1>"

hey, the title error message flash out on screen on every *.go files

minimal_config

-- install packer
local fn = vim.fn

local install_path = '/tmp/nvim/site/pack/packer/start/packer.nvim'

vim.cmd [[set packpath=/tmp/nvim/site]]

local function load_plugins()
local use = require('packer').use
require('packer').startup {
function()
use 'wbthomason/packer.nvim'
use 'neovim/nvim-lspconfig'
use {
"hrsh7th/nvim-compe",
config = function()
vim.o.completeopt = "menuone,noselect"
require'compe'.setup {
source = {
path = true;
buffer = true;
nvim_lsp = true;
nvim_lua = true;
vsnip = true;
emoji = true;
};
}
end
}
use {
"ray-x/go.nvim",
config = function ()
require("go").setup{
cfg = {
tag_transform = true,
lsp_on_attach = false,
}
}
end
}
end,
config = { package_root = '/tmp/nvim/site/pack' },
}
end

_G.load_config = function()
local nvim_lsp = require 'lspconfig'
local name = 'gopls'
local cmd = { 'gopls' }
nvim_lsp[name].setup {
cmd = cmd,
}

end

if fn.isdirectory(install_path) == 0 then
fn.system { 'git', 'clone', 'https://github.com/wbthomason/packer.nvim', install_path }
load_plugins()
require('packer').sync()
vim.cmd 'autocmd User PackerComplete ++once lua load_config()'
else
load_plugins()
_G.load_config()
end

Invalid workig directory when debugging tests

Given a test that reads a file relative to the package folder, let's suppose the following project structure:

$ tree
├── dummy
│   ├── dummy.go
│   ├── dummy_test.go
│   └── testdata
│       └── goldenfile
└── go.mod
$ cat dummy/dummy_test.go
package dummy

import (
	"os"
	"path"
	"testing"
)

func TestDummy(t *testing.T) {
	cases, err := os.Open(path.Join("testdata", "goldenfile"))
	if err != nil {
		t.Error(err)
	}
       // ........
}
$ go test ./dummy -test.run TestDummy
ok      tt/dummy        0.001s

It fails when it's debugged, i.e.: :GoDebug test

--- FAIL: TestDummy (9.10s)
    dummy_test.go:13: open testdata/goldenfile: no such file or directory
FAIL

Changing the os.Open sentence to cases, err := os.Open(path.Join("dummy", "testdata", "goldenfile")), it works fine.

GoAddTag doesn't work with inline struct.

Here is the code I'm trying to add tag.

func test() {
  type some struct {
    Success bool   //<- where the cursor is
  }
  ...
}

Invoke :GoAddTag reports

Unable to find any nodes at pos.
struct not found

This may related to treesitter.

dap_debug_keymap option doesn't seem to have any effect

When running setup with dap_debug_keymap = false, I would expect the gdb style keymaps not to be set during debug session.
I am not sure if there's any other meaning behind this setting?

Looking through the source I can't see any behavior affected by this setting.

Need help with :GoDebug and keybindings for dlv and dap

I need some help with how to use the DAP integration for debugging.

Setup

Steps to try

  1. Opened a go fie in the editor
  2. Positioned my cursor in the main() function
  3. Ran :GoDebug
  4. DAP started and opened a bunch of windows
  5. Run :GoBreakToggle
  6. How do I use the default keybindings, n, s, c as listed here: https://github.com/ray-x/go.nvim/blob/master/lua/go/dap.lua#L25

Those didn't seem to work for me.

[Feature] Adding Dap/debug support

With treesitter+lsp and go.nvim. This plugin could be a replacement for vim-go in neovim-0.5+ world.
I think the only missing part is debug support. Alough vim-inspector is very good. I am interested in add dap support as it is lightweight.

dap-go

I can setup dap for go in my init.lua. But the learning curve ..... I still remember 4 months back I took 3 hrs to set up dap for dlv as it were not well documented at that time.

Please add comments if you find a good setup for dap-go.

GoRun - GoDebug not working on windows

Firts of all, I just intalled your plugin and already love it. It have several features and run so fast.
The thing is, when trying to do anything related to the project path like GoRun - GoRun ./cmd or GoDebug it says that it doesn't find the main module (.projectRoot/cmd/main.go - go.mod - go.sum) , which i'm running the code from. Obviously I have all my modules declared, builded and linked with each other.
Hope you can help me, it's such a great plugin!!

OS: Windows 10
Shell: Powershell
Nvim version: v0.5.1

Module 'vim.lsp.codelens' not found

Nvim is pretty unhappy about not finding this codelens module. I've followed the setup as instructed but can't figure out what's missing. Any guidance?
Screen Shot 2021-09-12 at 10 41 45 PM

Scrolling the `GoTest` floating window

First of all thanks for this great project, it's awesome!

Secondly I apologise in advance if this is raised in the incorrect place, I think it may be specific to the guihua plugin but I'm unsure.

When I run go tests, I often need to scroll back in the output and can't seem to find a way to do this - am I missing something obvious or is it not currently supported?

Neovim don't detect installed binaries

When trying to run a command it fails, so it try to pull the missing binary without success.
My attempt to solve the problem was installing all the binaries with the command GoInstallBinaries, so once installed I tried again but it didn't work either.
This is the output of checkhealth:
2022-01-30-194228_1600x900_scrot

Discard new changes on save

Hello When I write changes to a file and save them , they got discarded

hooks.add("setup_mappings", function(map)
    -- go
    vim.api.nvim_exec([[ autocmd BufWritePre *.go :silent! lua require('go.format').gofmt() ]], false)
    vim.api.nvim_exec([[ autocmd BufWritePre *.go :silent! lua require('go.format').goimport() ]], false)

when I comment those lines , it works again. the loosing is only in *.go files.
I got this error when I open vim , also it goes away when I comment lines above.

image

Discussion: adding params for TS modules

Hi, tks you for a great plugin for Gophers.

I really like your idea of using Treesitter to extract struct/interface/method/... at the current cursor position. I wish to use those exported functions in my own plugin.

However, I might need to pass bufnr as a parameter to those functions. The current implementation will not allow that.

M.get_struct_node_at_pos = function(row, col)
  local query = M.query_struct_block .. " " .. M.query_em_struct_block
  local bufn = vim.fn.bufnr("") -- will only query at the current buffer
  -- ...
end

My idea is that we can pass bufnr as the 3rd parameter for those function. This should be optional and fallback to the current implementation if missing. I suppose this will not break any current behavior.

M.get_struct_node_at_pos = function(row, col, bufnr)
  local query = M.query_struct_block .. " " .. M.query_em_struct_block
  local bufn = burnr or vim.fn.bufnr("") -- fallback if bufnr is missing
  -- ...
end

Just wondering if you are open to updating. I will gladly make a PR for this modification

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.