Skip to content

Instantly share code, notes, and snippets.

@jgarte
Forked from casouri/eglot-rust-analyzer.el
Created May 5, 2023 06:43
Show Gist options
  • Save jgarte/5ffa1c7693dbc48ce48ce73a3fa800ed to your computer and use it in GitHub Desktop.
Save jgarte/5ffa1c7693dbc48ce48ce73a3fa800ed to your computer and use it in GitHub Desktop.
Configuring eglot for rust-analyzer
;; How to translate LSP configuration examples into Eglot’s format:
;;
;; Usually LSP servers will say something like
;;
;; rust-analyzer.procMacro.attributes.enable (default: true)
;;
;; Translate that into a JSON LSP configuration, you get
;;
;; {
;; "rust-analyzer": {
;; "procMacro": {
;; "attributes": {
;; "enable": true
;; }
;; }
;; }
;; }
;;
;; In general the key at the root level must be the LSP server’s name,
;; so that one configuration can cover multiple servers. If the LSP
;; server’s documentation omitted the name part, remember to add it
;; yourself.
;;
;; Translate that into plist format that Eglot uses, you get
;;
;; (:rust-analyzer (:procMacro (:attributes (:enable t))))
;;
;; Keys translate to keywords (with the same spelling and case),
;; dictionaries translate to plists, arrays translate to vectors, true
;; translates to t, false translates to a special keyword :json-false,
;; null translates to nil, empty directory {} translates to eglot-{}.
;; Define a setup function that runs in the mode hook.
(defun setup-rust ()
"Setup for ‘rust-mode’."
;; Configuration taken from rust-analyzer’s manual:
;; https://rust-analyzer.github.io/manual.html#configuration
(setq-local eglot-workspace-configuration
;; Setting the workspace configuration for every
;; rust-mode buffer, you can also set it with dir-local
;; variables, should you want different configuration
;; per project/directory.
'(:rust-analyzer
( :procMacro ( :attributes (:enable t)
:enable t)
:cargo (:buildScripts (:enable t))
:diagnostics (:disabled ["unresolved-proc-macro"
"unresolved-macro-call"])))))
;; Run our setup function in ‘rust-mode-hook’.
(add-hook 'rust-mode-hook #'setup-rust)
;; Define a custom eglot LSP server for rust-analyzer because it
;; expects initializationOptions done a bit differently (see below).
(defclass eglot-rust-analyzer (eglot-lsp-server) ()
:documentation "A custom class for rust-analyzer.")
;; Rust-analyzer requires the workspaceConfiguration sent as
;; initializationOptions at startup time. See
;; https://github.com/joaotavora/eglot/discussions/845 and
;; rust-analyzer’s manual page.
(cl-defmethod eglot-initialization-options ((server eglot-rust-analyzer))
eglot-workspace-configuration)
;; Use our custom ‘eglot-rust-analyzer’ for ‘rust-mode’.
(add-to-list 'eglot-server-programs
'(rust-mode . (eglot-rust-analyzer "rust-analyzer")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment