EmacsでのRust開発

Posted on April 3, 2021 by nobiruwa

tl;dr

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

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

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

rlsのインストール

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

$ rustup update
$ rustup component add rls rust-analysis rust-src

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

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

Emacsパッケージの設定

lsp-modeとlsp-uiの設定は過去の記事で書いた通りなので省略します。

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

(add-hook 'rust-mode-hook 'cargo-minor-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]セクションを記述するかわりに、コマンドラインから編集できるようになります。私には合っていると思い導入することにします。

$ sudo apt install libssl-dev
$ cargo install cargo-edit
$ cargo install cargo-feature

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