EmacsでのRust開発(rust-analyzer)

Posted on December 26, 2021 by nobiruwa

tl;dr

2021年4月3日の記事ではrlsを使いましたが、rust-analyzerを使うように手順を変更しました。rlsrust-analyzerの両方が存在する環境ではrust-analyzerが優先されるようで、rust-analyzerのインストール以外は2021年4月3日の記事の内容そのままです。

rust-mode, lsp-mode, cargo.elrust-analyzerを用いることで、十分に快適な環境を得ることができました。

rust-mode + lsp-mode + cargo.el + rust-analyzer の構築手順

開発のモードとしてrust-modeとlsp-modeとcargo.elのcargo-minor-modeを用い、バックエンドにはrust-analyzerを用います。

rust-analyzerのインストール

公式の手順に従ってrust-analyzerをインストールします。

rustupを使ってrust-srcをインストールします。

$ rustup component add rust-src

次にrust-analyzerをインストールします。

$ mkdir -p ~/.local/bin
$ curl -L https://github.com/rust-analyzer/rust-analyzer/releases/latest/download/rust-analyzer-x86_64-unknown-linux-gnu.gz | gunzip -c - > ~/.local/bin/rust-analyzer
$ chmod +x ~/.local/bin/rust-analyzer

Emacsパッケージのインストール

M-x package-install
cargo
lsp-mode
lsp-ui
rust-mode

Emacsパッケージの設定

過去の記事でのlsp-mode, lsp-uiに加えて、lsp-mode, cargo-minor-mode, rust-modeのそれぞれに設定を行います。

lsp-mode

;;;;;;;;
;; lsp-mode
;;;;;;;;
[...snip...]
;; rust
(setq lsp-rust-analyzer-proc-macro-enable t)

cargo-minor-mode

;;;;;;;;
;; cargo-minor-mode
;;;;;;;;
(require 'rust-mode)

(add-hook 'rust-mode-hook 'cargo-minor-mode)

rust-mode

;;;;;;;;
;; rust-mode
;;;;;;;;
(require 'rust-mode)

(add-hook 'rust-mode-hook
          (lambda ()
            (setq indent-tabs-mode nil)
            (lsp)))

;; Formatting is bound to C-c C-f.
;; The folowing enables automatic formatting on save.
(setq rust-format-on-save t)

cargo-edit, cargo-featureのインストール

cargo-editcargo add/rm/upgrade/set-versionサブコマンドを追加します。また、cargo-featurecargo featureサブコマンドを追加します。

cargo addcargo featureを使うと、Cargo.toml[dependencies]セクションと[dev-dependencies]セクションを記述するかわりに、コマンドラインから編集できるようになります。私には合っていると思い導入することにします。

$ cargo install cargo-edit
$ cargo install cargo-feature

ちなみに、サブコマンドの実体は~/.cargo/binディレクトリにあります。cargo-add, cargo-featureといったようにサブコマンドごとの実行ファイルが追加されます。