[Emacs] eglot + rust-mode or rust-ts-mode setting
I tried to use Emacs to write Rust programs with eglot. However it didn’t work. I investigated why it didn’t work
rust-analyzer must run at project root
If we use completions or syntax errors features, then rust-analyzer must run at project root where Cargo.toml
exists. However eglot
starts lsp-server at (project-root)
directory. This function usually returns the repository root directory, e.g. a directory where .git
exists. So there are no problems when Cargo.toml
exists at the repository root. It is alright in the most cases to me, however I sometimes create Rust project at non-repository root. So I added the following the custom functions to project-find-functions
. Then completion, syntax checking or other features work well as I expected
(defun my-rust-project-root (dir)
(let ((git-root (locate-dominating-file dir ".git")))
;; check using cargo workspace first
(if (and git-root (file-exists-p (file-name-concat git-root "Cargo.toml")))
(list 'vc 'Git git-root)
(when-let* ((root (locate-dominating-file dir "Cargo.toml")))
(list 'vc 'Git root)))))
(defun my-rust-mode-hook ()
(setq-local project-find-functions (list #'my-rust-project-root)))
(add-hook 'rust-mode-hook #'my-rust-mode-hook)
(add-hook 'rust-ts-mode-hook #'my-rust-mode-hook)