Buffer Yard
Language setup

Emacs Go Setup: gopls, Format on Save and Go Tests

Updated

Before touching init.el, open a terminal and install the server:

go install golang.org/x/tools/gopls@latest

gopls is the official Go language server, maintained by the Go team, and almost everything a Go programmer wants from an editor (completion, jump to definition, rename, references, import management, formatting) comes from it rather than from Emacs. The editor side is thin, which is good news: Go may be the easiest language in this series to set up.

The binary lands in $(go env GOPATH)/bin, usually ~/go/bin. Make sure that directory is on the PATH Emacs sees, not only the one your terminal sees. On Linux this is rarely a problem; on macOS a GUI Emacs started from the Dock often misses it, and the exec-path-from-shell package is the standard fix.

Choosing a major mode

There are two reasonable choices and neither is wrong.

go-ts-mode is built into Emacs since 29.1, alongside go-mod-ts-mode for go.mod files. It needs the tree-sitter grammars for go and gomod, which you install once with M-x treesit-install-language-grammar. Highlighting is precise and the mode has no dependencies.

go-mode, from MELPA, is the long-lived package that most older guides assume. It brings gofmt-before-save, a godoc lookup command and a few helpers for editing imports. Since gopls now does most of that, its main advantage is that it works on Emacs builds without tree-sitter.

On Emacs 29 or newer, use go-ts-mode. The setup below assumes it, with the go-mode alternative after.

The minimal config

(defun my/go-before-save ()
  "Organize imports and format the buffer through gopls."
  (add-hook 'before-save-hook
            (lambda ()
              (ignore-errors
                (call-interactively #'eglot-code-action-organize-imports))
              (eglot-format-buffer))
            nil t))

(use-package go-ts-mode
  :mode (("\\.go\\'" . go-ts-mode)
         ("/go\\.mod\\'" . go-mod-ts-mode))
  :hook ((go-ts-mode . eglot-ensure)
         (go-ts-mode . my/go-before-save)))

(use-package eglot
  :config
  (setq-default eglot-workspace-configuration
                '(:gopls (:staticcheck t))))

eglot already knows that Go buffers talk to gopls, so there is no eglot-server-programs entry to add. The before-save-hook is buffer-local (the final t), which keeps Go’s formatting rules out of your other languages.

The organize-imports call is wrapped in ignore-errors on purpose. When a file has nothing to fix, eglot can report that no code action applies, and an error inside before-save-hook would stop the save. Formatting runs second so it tidies whatever the import change touched.

If you prefer go-mode

(use-package go-mode
  :ensure t
  :hook ((go-mode . eglot-ensure)
         (before-save . gofmt-before-save))
  :custom (gofmt-command "goimports"))

gofmt-before-save only acts in go-mode buffers, so adding it to the global hook is safe. Setting gofmt-command to goimports (install it with go install golang.org/x/tools/cmd/goimports@latest) gives you formatting and import cleanup in one external call, without asking the server. Both approaches end in the same file on disk; the eglot route simply needs one tool fewer.

What gopls gives you in practice

Once eglot connects, the mode line shows the server and the usual commands work across the project. M-. jumps to a definition, including into the standard library and the module cache, and M-, comes back. M-? lists references. eglot-rename renames an identifier everywhere it is used, which in Go is reliable because the type checker knows exactly what refers to what.

Diagnostics arrive through Flymake as you type. With staticcheck turned on in the workspace configuration above, gopls adds the staticcheck analyzers to its own, so you see unused results, deprecated calls and suspicious comparisons without a separate linter run. If your team uses gofumpt, add :gofumpt t next to it and every save produces the stricter format.

Completion candidates come through completion-at-point, so whatever popup you chose on the completion page shows them. gopls also offers unimported packages as candidates: type strings. in a file that does not import strings, accept a completion, and the import appears.

Running go test

Go’s test tooling is good enough that Emacs does not need a special package for it. C-x p c (project-compile) runs a command from the project root, and go test ./... is the whole suite. The output goes into a compilation buffer where file and line references are clickable and M-g n steps through failures.

For a single test, go test -run TestParseHeader ./internal/header narrows it down; -run takes a regular expression, so -run 'TestParse.*' runs a family. Add -v when you want the log output of passing tests too, and -count=1 when you suspect the test cache is hiding a change.

If you would rather press one key than type commands, the gotest package on MELPA adds commands for the test at point, the current file and the current package. It is optional. Many Go programmers stay with project-compile and the minibuffer history, since M-p recalls the last test command in a keystroke.

Debugging is the one area where Emacs lags. The Go debugger, dlv, works fine from a terminal, and the dape package can drive it as a debug adapter from inside Emacs, but expect an evening of setup rather than five minutes. Many Go programmers never bother, because table-driven tests plus a few t.Logf lines answer most questions faster than stepping through code.

A note on workspaces

gopls finds the module by walking up to go.mod. In a repository with several modules, eglot starts one server per project root that project.el reports, which is usually the repository root, not the module. Recent gopls releases cope with nested modules on their own, but if a package shows up without type information, a go.work file at the root (go work init ./svc-a ./svc-b) makes the set of modules explicit and usually ends the confusion.

The languages overview collects the other guides; the Rust page uses the same eglot pattern with rust-analyzer, and the package setup guide covers the MELPA side if you went with go-mode.

Questions readers ask

Do I need go-mode if I use go-ts-mode?

No. go-ts-mode is built into Emacs 29.1 and later and covers editing on its own once the Go grammar is installed. go-mode from MELPA is still worth it on older Emacs builds, or if you want its gofmt-before-save helper and the godoc commands it ships.

Why does eglot say it cannot find gopls?

Emacs looks for gopls on its own exec-path, which can differ from your shell PATH, especially on macOS when Emacs starts from the Dock. Check with M-: (executable-find "gopls"); if it returns nil, add ~/go/bin to exec-path or use the exec-path-from-shell package.

Can gopls run gofumpt or staticcheck?

Yes, both are gopls settings. Pass them through eglot-workspace-configuration, for example (:gopls (:gofumpt t :staticcheck t)), and gopls applies the stricter formatting and the extra analyzers without separate tools.