Emacs mode for the Go programming language

This is go-mode, the Emacs mode for editing Go code.

It is a complete rewrite of the go-mode that shipped with Go 1.0.3 and before, and was part of Go 1.1 until Go 1.3. Beginning with Go 1.4, editor integration will not be part of the Go distribution anymore, making this repository the canonical place for go-mode.

Features

In addition to normal features, such as fontification and indentation, and close integration with familiar Emacs functionality (for example syntax-based navigation like beginning-of-defun), go-mode comes with the following extra features to provide an improved experience:

  • Integration with gofmt by providing a command of the same name, and gofmt-before-save, which can be used in a hook to format Go buffers before saving them.

    • Setting the gofmt-command variable also allows using goimports.
    • Setting the gofmt-args variable with a list of arguments allows using e.g. gofmt -s.
  • Integration with godoc via the functions godoc and godoc-at-point.

  • Integration with the Playground

    • go-play-buffer and go-play-region to send code to the Playground
    • go-download-play to download a Playground entry into a new buffer
  • Managing imports

    • A function for jumping to the file's imports (go-goto-imports - C-c C-f i)
    • A function for adding imports, including tab completion (go-import-add, bound to C-c C-a)
    • A function for removing or commenting unused imports (go-remove-unused-imports)
    • It is recommended that you use goimports or the organize-imports feature of gopls to manage adding/removing/organizing imports automatically.
  • Integration with godef

    • godef-describe (C-c C-d) to describe expressions
    • godef-jump (C-c C-j) and godef-jump-other-window (C-x 4 C-c C-j) to jump to declarations
    • This requires you to install godef via go get github.com/rogpeppe/godef.
  • Basic support for imenu (functions and variables)

  • Built-in support for displaying code coverage as calculated by go test (go-coverage)

  • Several functions for jumping to and manipulating the individual parts of function signatures. These functions support anonymous functions, but are smart enough to skip them when required (e.g. when jumping to a method receiver or docstring.)

    • Jump to the argument list (go-goto-arguments - C-c C-f a)
    • Jump to the docstring, create it if it does not exist yet (go-goto-docstring - C-c C-f d).
    • Jump to the function keyword (go-goto-function - C-c C-f f)
    • Jump to the function name (go-goto-function-name - C-c C-f n)
    • Jump to the return values (go-goto-return-values - C-c C-f r)
    • Jump to the method receiver, adding a pair of parentheses if no method receiver exists (go-goto-method-receiver - C-c C-f m).

    All of these functions accept a prefix argument (C-u), causing them to skip anonymous functions.

  • GOPATH detection – the function go-guess-gopath will guess a suitable value for GOPATH, based on gb or wgo projects, Godeps and src folders for plain GOPATH workspaces. The command go-set-project uses the return value of go-guess-gopath to set the GOPATH environment variable.

    You can either call go-set-project manually, or integrate it with Projectile's project switching hooks, or any other means of switching projects you may employ.

Installation

MELPA

The recommended way of installing go-mode is via ELPA, the Emacs package manager, and the MELPA Stable repository, which provides an up-to-date version of go-mode.

If you're not familiar with ELPA yet, consider reading this guide.

Manual

To install go-mode manually, check out the go-mode.el repository in a directory of your choice, add it to your load path and configure Emacs to automatically load it when opening a .go file:

(add-to-list 'load-path "/place/where/you/put/it/")
(autoload 'go-mode "go-mode" nil t)
(add-to-list 'auto-mode-alist '("\\.go\\'" . go-mode))

Either evaluate the statements with C-x C-e, or restart Emacs.

Other extensions

There are several third party extensions that can enhance the Go experience in Emacs.

Gopls integration

Gopls is the official language server protocol (lsp) implementation provided by the Go team. It is intended to replace the existing third party tools for code formatting (gofmt), automatic imports (goimports), code navigation (godef/guru), type and function descriptions (godoc/godef), error checking, auto completion (gocode), variable and type renaming (rename), and more. Once gopls is stable the older tools will no longer be supported.

Gopls is a supported backend for lsp-mode. It will be used automatically by lsp-mode if gopls is found in your PATH. You can install gopls via: go get golang.org/x/tools/gopls@latest. To enable lsp-mode for go buffers:

(add-hook 'go-mode-hook 'lsp-deferred)

Syntax/error checking

There are two ways of using flymake with Go:

  1. goflymake, which internally uses go build to capture all errors that a regular compilation would also produce
  2. flymake-go for a more lightweight solution that only uses gofmt and as such is only able to catch syntax errors. Unlike goflymake, however, it does not require an additional executable.

Additionally, there is flycheck, a modern replacement for flymake, which comes with built-in support for Go. In addition to using go build or gofmt, it also has support for go vet, golint and errcheck.

Auto completion

For auto completion, take a look at gocode.

eldoc

https://github.com/syohex/emacs-go-eldoc provides eldoc functionality for go-mode.

Snippets

I maintain a set of YASnippet snippets for go-mode at https://github.com/dominikh/yasnippet-go

Integration with errcheck

https://github.com/dominikh/go-errcheck.el provides integration with errcheck.

Stability

go-mode.el has regular, tagged releases and is part of the MELPA Stable repository. These tagged releases are intended to provide a stable experience. APIs added in tagged releases will usually not be removed or changed in future releases.

Changes made on the master branch, which is tracked by the normal MELPA repository, however, are under active development. New APIs are experimental and may be changed or removed before the next release. Furthermore, there is a higher chance for bugs.

If you want a stable experience, use MELPA Stable. If you want cutting edge features, or "beta-test" future releases, use MELPA or the master branch.

Owner
Dominik Honnef
Long-time Go user, contributor, and author of many Go related tools, including staticcheck.
Dominik Honnef
Comments
  • Add goto functions for working with function signatures

    Add goto functions for working with function signatures

    Add several functions:

    • go-goto-arguments
    • go-goto-docstring
    • go-goto-function
    • go-goto-function-name
    • go-goto-return-value
    • go-goto-type-signature

    They are all about going to different parts of function signatures, with their names being self descriptive. They all operate on the current function, the definition of which is "the closest func statement above point". If no func is found above point, the functions will jump to the first func in the file. Lastly, if the point is in the docstring of a function, the goto functions will operate on that function and not the function above.go-goto-type-signature

    Additionally, some of the functions will create their targets if they are missing:

    • go-goto-docstring will create a docstring if it does not exist as well as update the docstring name for a function that has been renamed.
    • go-goto-return-value will add space for adding return values.
    • go-goto-type-signature will add spaces and a pair of parenthesis for adding a signature.

    It should also be noted that the functions have been tested with anonymous functions as well.

    Add keymap at C-c g for goto functions. Add mapping for the already existing go-goto-imports at C-c g i. Add helper function go--get-function-name, which grabs the string of the function above point.

    Update README to reflect the addition of these functions.


    I have been using these functions for about a month now. They feel stable enough that they can be shared with the upstream go-mode.

    It should be noted and is probably apparent that this is my first real contribution to a project written in elisp (or any lisp at all, actually :dancer:). As such, I am probably missing out on conventions, useful functions and other such things. I'd be very happy to change the code so that it fits well into the project! Comments on coding style and such things are extremely welcome!


    TODO

    • [x] go-goto-docstring should not update the docstring
    • [x] Keybinds should not be on the user bindable keyspace.
    • [x] Move all define-key to one single place.
    • [x] go-goto-arguments has a copy-pasted docstring
    • [x] ~~Handle going to docstrings with prepending words (A foo etc)~~
    • [x] Fix corner cases for go-goto-function
    • [x] Don't skip past the pointer in go-goto-return-value
    • [x] Use forward-list instead of searching for ).
    • [x] go-goto-type-signature has the wrong name.
    • [x] Docstring and comments for go--in-function-p are wrong
    • [x] go-goto-docstring has a bug with empty comments above a function
    • [x] Add prefix arguments and handling of special cases for anonymous functions
    • [x] Fix bug in go-goto-docstring in the empty comments case
    • [x] Remove get- from go--get-function-name
    • [x] Handle prefix arguments as booleans
    • [x] Fix logical errors in go--in-function
    • [x] Handle prefixed non-interactive calls to go-goto-docstring and go-goto-method-receiver.
    • [x] Make go--function-name return nil for anonymous functions.
  • gofmt breaks kill-ring

    gofmt breaks kill-ring

    I have no idea why this is the case, but I've found that kill-line and kill-region work as expected when I first start emacs. After running gofmt in a buffer, however, text that is killed is no longer added to the kill-ring.

    Emacs version: 24.3.1

  • Add option to not show gofmt errors in new buffer

    Add option to not show gofmt errors in new buffer

    I already use flycheck+helm to show and navigate errors, so popping up a new buffer after running gofmt-command is unnecessary and disruptive. This makes the behavior optional.

  • Fontify variable declarations

    Fontify variable declarations

    Variable names should be highlighted with font-lock-variable-name-face where the variable is declared. For example, u, v, x, y, and z should be highlighted in the following:

    var x, y = 1, 2
    x, y := 1, 2
    for x, y := range aSlice {
    func f(x, y int) (u, v bool)
    func(x int, y char) (z bool)
    func (x T) MyMethod(y int) (z int)
    

    Highlighting variable declarations is performed in Emacs Lisp mode (for "defvar") and c-mode (for function parameters and variable declarations). I miss it in go-mode.

    BTW, Thank you very much for the improved go-mode!

  • Support outline-minor-mode

    Support outline-minor-mode

    Is it possible to add support for outline-minor-mode? outline style code folding makes it much easier to work with large source code files. This is esp. useful for go-lang as one can keep the whole package source in a single file which makes code searching and navigation much easier.

    python.el https://github.com/fgallina/python.el works with outline-minor-mode for Python and can be used as a reference. It defines two regexps: outline-regexp and outline-heading-end-regexp, and one function outline-level.

    Reference for outline minor mode can be found here: http://emacswiki.org/emacs/OutlineMinorMode

  • go-mode does not correctly highlight Go types

    go-mode does not correctly highlight Go types

    Currently, Go types such as int32, float64 etc. are not recognized as part of Go's syntax:

    package main

    import "fmt"

    func main() { var testvar int32 }

    In the above piece of code, 'int32' is not highlighted, even trough it is a valid Go type. gomode

  • go-remove-unused-imports doesn't remove any imports

    go-remove-unused-imports doesn't remove any imports

    If I edit an existing Go file, and add package to the import list that isn't referenced anywhere, then invoke go-remove-unused-imports, no imports are removed, even though the compiling the file results in an unused import error.

    Using the code with go-flymake, gocode, and auto-complete enabled. I haven't tried turning them off yet.

  • Extract gofmt foundation as a separate package

    Extract gofmt foundation as a separate package

    Could you extract the gofmt foundation as a seprate package?

    There are a lot of formatting elisp packages based on gofmt of go-mode.el. I think it is reasonable to extract gofmt foundation as a separate package and make it usable for them as a library.

    Using this package, the following code defines gofmt function, gofmt-before-save function and gofmt-show-errors customizable variable.

    (define-langfmt gofmt
      "Format the current buffer according to the gofmt tool."
      :group 'go
      :modes '(go-mode)
      :format-command gofmt-command
      :format-args '("--w")
      :format-handler (lambda (exit-status)
                        (unless (zerop exit-status)
                          (message "Could not apply gofmt")))
      :diff-handler (lambda (_ no-diff-p)
                      (message (if no-diff-p
                                   "Buffer is already gofmted"
                                 "Applied gofmt")))
      :error-filter (lambda (filename tmpfile)
                      (while (search-forward-regexp
                              (concat "^\\(" (regexp-quote tmpfile) "\\):") nil t)
                        (replace-match (file-name-nondirectory filename)
                                       t t nil 1))))
    

    This is a part of my attempt for JSCS (JavaScript Code Style) fixer in jscs.el (papaeye/emacs-jscs#1).

    Please feel free to rewrite the code and/or rename the package as you like!

  • Problem with multiple workspaces (Godep)

    Problem with multiple workspaces (Godep)

    I am using spacemacs (develop branch). The go integration that comes with it mostly delegates to go-mode.el.

    I am also using godep, so my $GOPATH looks like this:

    Now, if I try to gorename from emacs, I get

    It can not find negroni package because is installed in godeps workspace.

    But if I do the same from the command line, it works:

    In emacs, evaluating (getenv "GOPATH") produces the correct path:

    So what it is wrong? Is it me? Or is it a bug? I tried to look at your code, but I am a complete emacs/lisp n00b, so didn't get far :)

    Thanks!

  • [Feature Request]add more highlight support

    [Feature Request]add more highlight support

    hi a vimer new come to emacs , vim-go provide lots of highlight group, so i want know does go-mode support it? like this pic,vim-go support the operators highlight and some others group. image

  • godef-jump & godef-describe do not work via TRAMP

    godef-jump & godef-describe do not work via TRAMP

    When I use TRAMP 'godef-jump' and 'godef-describe' do not work with message "Could not run godef binary". When I use them from locally started Emacs they work just fine.

  • When using go-mode eglot failes to properly connect with gopls

    When using go-mode eglot failes to properly connect with gopls

    Using emacs 29 on windows from https://github.com/kiennq/emacs-build/releases/tag/v29.169.20221201.4a23421

    When using go-mode eglot failes to properly connect with gopls

    The actual error message I get is

    Error in menu-bar-update-hook (imenu-update-menubar): (jsonrpc-error "request id=2 failed:" (jsonrpc-error-message . "Timed out")
    

    I already commented out imenu-integration of go-mode, that's not the problem.

    • If I uninstall go-mode and open the file, eglot correctly starts gopls
    • If I literally open a go file and start eglot afterwards, gopls correctly loads.

    The problem is rather hard to debug. In my particular project, out of 20? times gopls and eglot start to interact properly If I open a very small project (so that gopls has probably not much to analyse) go-mode, eglot and gopls always work.

    Maybe it is a problem with windows pre-maturely reporting back successful process spawning, maybe it is gopls pre-maturely returning control to the os while rpc thread is still blocked? It seems a rather interacted timing issue of which go-mode may actually not be the culprit but rather a promoter.

    Reporting here nonetheless as without go-mode eglot and gopls work.

  • The future of syntax highlighting

    The future of syntax highlighting

    As I hack on go-mode's fontification to support generics, I also am looking at other options.

    To summarize how go-mode currently fontifies, it uses a combination of regexes and structural understanding of paren/bracket pairs. We make use of more advanced font-lock facilities such as function matchers and anchored matchers. These are relatively slow, but jit font lock mode does a really good job of only fontifying parts of the file that change, so performance is fine.

    Tree-sitter is hot, but unfortunately also only has syntactic information, so does not help in ambiguous cases such as foo[bar](). It also may be more sensitive to syntax errors than go-mode's approach, but on the other hand is almost certainly faster. I think we should consider adopting tree sitter if/when it is part of core emacs, but before that the benefits don't seem that great. (It may have other benefits beyond syntax highlighting, though.)

    The other option is LSP's semantic tokens. gopls does support semantic tokens and I was able to get it working with lsp-mode after fixing some things in gopls. In general it works, and of course it has full type information so all our ambiguity problems are solved. The fortification via lsp-mode is asynchronous, so it doesn't cause any lag, although that means it doesn't pop in immediately as you type. You can configure the idle delay before it fontifies. Setting it to 100ms gives a pretty good experience (although if you are working in a package that takes longer than 100ms to type check, the semantic tokens will be slower as well). One of the main problems is syntax errors. Without proper AST and type info, semantic tokens fall apart. To address this, I think we would need better support for partial fontification where gopls and/or lsp-mode know to keep fontification around for parts of the file that can't currently be type checked. This may be easier said than done.

    My general idea is to continue to maintain basic fontification in go-mode, but support optionally augmenting it with gopls semantic tokens to fill in the holes. Once that is working well, we can consider completely offloading syntax highlighting to gopls. Thoughts?

  • Make fill-paragraph work in multi-line back-quoted strings

    Make fill-paragraph work in multi-line back-quoted strings

    It would be nice if fill-paragraph (ALT-Q on standard bindings) worked in multi-line back-quoted strings .

    I use multi-line quotes like this to provide help

    var help = `
    Lots of nice long help text.
    
    Spread out over lots of lines
    `
    

    And in editing that help for a terminal fill-paragraph would be super useful!

    My current workaround is to drop into text-mode to do the fill-paragraph then return to go-mode.

    I'll note that python-mode allows fill-paragraph in its equivalent triple quoted strings.

    PS Thanks for writing go-mode - it is a great timesaver :-)

Related tags
Eclipse IDE for the Go programming language:
Eclipse IDE for the Go programming language:

Project website: http://goclipse.github.io/ As of 2017, Goclipse is no longer actively maintained, see this blog post for more information. If you are

Dec 20, 2022
An autocompletion daemon for the Go programming language
An autocompletion daemon for the Go programming language

An autocompletion daemon for the Go programming language VERY IMPORTANT: this project is not maintained anymore, look for alternatives or forks if you

Jan 7, 2023
Delve is a debugger for the Go programming language.
Delve is a debugger for the Go programming language.

The GitHub issue tracker is for bugs only. Please use the developer mailing list for any feature proposals and discussions. About Delve Installation L

Dec 29, 2022
Web-based IDE for the Go language
Web-based IDE for the Go language

Welcome to godev! The aim of this project is to develop a premier Go language IDE hosted in a web interface. This was inspired by the way that the god

Nov 30, 2022
A Go language server.

A Go Language Server based on the Go Extension for Visual Studio Code Wraps the VSCode Go extension from Microsoft into a language server, such that i

Dec 6, 2022
Nightly binary builds of Emacs for macOS as a self-contained Emacs.app, with native-compilation.

Emacs Builds Nightly binary builds of Emacs for macOS as a self-contained Emacs.app, with native-compilation. Features Self-contained Emacs.app applic

Dec 25, 2022
gide is an IDE framework in pure Go, using the GoGi gui. It extensively adopts emacs keybindings.
gide is an IDE framework in pure Go, using the GoGi gui.  It extensively adopts emacs keybindings.

Gide Gide is a flexible IDE (integrated development environment) framework in pure Go, using the GoGi GUI (for which it serves as a continuous testing

Jan 8, 2023
Floppa programming language inspired by the brainf*ck programming language. Created just for fun and you can convert your brainf*ck code to floppa code.

Floppa Programming Language Created just for fun. But if you want to contribute, why not? Floppa p.l. inspired by the brainf*ck programming language.

Oct 20, 2022
T# Programming Language. Something like Porth, Forth but written in Go. Stack-oriented programming language.

The T# Programming Language WARNING! THIS LANGUAGE IS A WORK IN PROGRESS! ANYTHING CAN CHANGE AT ANY MOMENT WITHOUT ANY NOTICE! Something like Forth a

Jun 29, 2022
Yayx programming language is begginer friendly programming language.
Yayx programming language is begginer friendly programming language.

Yayx Yayx programming language is begginer friendly programming language. What have yayx: Easy syntax Dynamic types Can be compiled to outhers program

Dec 27, 2021
Yayx programming language is begginer friendly programming language.

Yayx Yayx programming language is begginer friendly programming language. What have yayx: Easy syntax Dynamic types Can be compiled to outhers program

May 20, 2022
Go network programming framework, supports multiplexing, synchronous and asynchronous IO mode, modular design, and provides flexible custom interfaces
Go network programming framework, supports multiplexing, synchronous and asynchronous IO mode, modular design, and provides flexible custom interfaces

Go network programming framework, supports multiplexing, synchronous and asynchronous IO mode, modular design, and provides flexible custom interfaces。The key is the transport layer, application layer protocol has nothing to do

Nov 7, 2022
Advent of Code is an Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

Advent of Code 2021 Advent of Code is an Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved

Dec 2, 2021
Jan 4, 2022
A repository for showcasing my knowledge of the Google Go (2009) programming language, and continuing to learn the language.

Learning Google Golang (programming language) Not to be confused with the Go! programming language by Francis McCabe I don't know very much about the

Nov 6, 2022
A repository for showcasing my knowledge of the Go! (2003) programming language, and continuing to learn the language.
A repository for showcasing my knowledge of the Go! (2003) programming language, and continuing to learn the language.

Learning Go! (programming language) Not to be confused with Google Golang (2009) I don't know too much about the Go! programming language, but I know

Oct 22, 2022
🚀Gev is a lightweight, fast non-blocking TCP network library based on Reactor mode. Support custom protocols to quickly and easily build high-performance servers.
🚀Gev is a lightweight, fast non-blocking TCP network library based on Reactor mode. Support custom protocols to quickly and easily build high-performance servers.

gev 中文 | English gev is a lightweight, fast non-blocking TCP network library based on Reactor mode. Support custom protocols to quickly and easily bui

Jan 6, 2023
Integrated console application library, using Go structs as commands, with menus, completions, hints, history, Vim mode, $EDITOR usage, and more ...
Integrated console application library, using Go structs as commands, with menus, completions, hints, history, Vim mode, $EDITOR usage, and more ...

Gonsole - Integrated Console Application library This package rests on a readline console library, (giving advanced completion, hint, input and histor

Nov 20, 2022
Commando - run commands against networking devices in batch mode
Commando - run commands against networking devices in batch mode

Commando is a tiny tool that enables users to collect command outputs from a single or a multiple networking devices defined in an inventory file.

Oct 30, 2022
crawlergo is a browser crawler that uses chrome headless mode for URL collection.
crawlergo is a browser crawler that uses chrome headless mode for URL collection.

A powerful browser crawler for web vulnerability scanners

Dec 29, 2022