Skip to content

Instantly share code, notes, and snippets.

@carlosrogue
Created November 22, 2021 10:03
Show Gist options
  • Save carlosrogue/777f43b4a46400cae21aaf9ba5ca5ccc to your computer and use it in GitHub Desktop.
Save carlosrogue/777f43b4a46400cae21aaf9ba5ca5ccc to your computer and use it in GitHub Desktop.
Configuration of gopls using Eglot
;; ===============================================================
;; EGLOT
;; ===============================================================
(require 'project)
(defun project-find-go-module (dir)
(when-let ((root (locate-dominating-file dir "go.mod")))
(cons 'go-module root)))
(cl-defmethod project-root ((project (head go-module)))
(cdr project))
(add-hook 'project-find-functions #'project-find-go-module)
;; Optional: load other packages before eglot to enable eglot integrations.
(require 'company)
(require 'yasnippet)
(require 'go-mode)
(require 'eglot)
(add-hook 'go-mode-hook 'eglot-ensure)
;; Optional: install eglot-format-buffer as a save hook.
;; The depth of -10 places this before eglot's willSave notification,
;; so that that notification reports the actual contents that will be saved.
(defun eglot-format-buffer-on-save ()
(add-hook 'before-save-hook #'eglot-format-buffer -10 t))
(add-hook 'go-mode-hook #'eglot-format-buffer-on-save)
;; Workarounds
;;
;; eglot-organize-imports is hopefully a temporary stopgap until
;; https://github.com/joaotavora/eglot/issues/574 is addressed.
(defun eglot-organize-imports ()
"Offer to execute the source.organizeImports code action."
(interactive)
(unless (eglot--server-capable :codeActionProvider)
(eglot--error "Server can't execute code actions!"))
(let* ((server (eglot--current-server-or-lose))
(actions (jsonrpc-request
server
:textDocument/codeAction
(list :textDocument (eglot--TextDocumentIdentifier))))
(action (cl-find-if
(jsonrpc-lambda (&key kind &allow-other-keys)
(string-equal kind "source.organizeImports" ))
actions)))
(when action
(eglot--dcase action
(((Command) command arguments)
(eglot-execute-command server (intern command) arguments))
(((CodeAction) edit command)
(when edit (eglot--apply-workspace-edit edit))
(when command
(eglot--dbind ((Command) command arguments) command
(eglot-execute-command server (intern command) arguments))))))))
(defun eglot-organize-imports-on-save ()
(defun eglot-organize-imports-nosignal ()
"Run eglot-organize-imports, but demote errors to messages."
;; Demote errors to work around
;; https://github.com/joaotavora/eglot/issues/411#issuecomment-749305401
;; so that we do not prevent subsequent save hooks from running
;; if we encounter a spurious error.
(with-demoted-errors "Error: %s" (eglot-organize-imports)))
(add-hook 'before-save-hook #'eglot-organize-imports-on-save))
(add-hook 'go-mode-hook #'eglot-organize-imports-on-save)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment