emacs開發環境配置(4)——rust開發環境

一曲廣陵散發表於2021-11-10

一、參考

emacs系列文章目錄——更新ing

emacs rust-mode

Configuring Emacs for Rust development

My Emacs Rust Language Config

二、希望實現的特性

特性描述
原始碼之間移動找到函式的原始碼為止,回到函式引用處
程式碼自動填充
程式碼語法檢查和錯誤高亮
程式碼語法規範化
cargo編譯和執行

三、通過emacs-racer實現

3.1 依賴安裝

程式安裝
rust非emacs包
cargo非emacs包
rust-modeM-x package-install rust-mode
cargoM-x package-install cargo
racer非emacs包
rustup toolchain add nightly
rustup component add rust-src
cargo +nightly install racer

3.2 更新配置

;; started from http://emacs-bootstrap.com/

;; rust-mode
;; https://github.com/rust-lang/rust-mode
(use-package rust-mode
  :bind ( :map rust-mode-map
               (("C-c C-t" . racer-describe)
                ([?\t] .  company-indent-or-complete-common)))
  :config
  (progn
    ;; add flycheck support for rust (reads in cargo stuff)
    ;; https://github.com/flycheck/flycheck-rust
    (use-package flycheck-rust)

    ;; cargo-mode for all the cargo related operations
    ;; https://github.com/kwrooijen/cargo.el
    (use-package cargo
      :hook (rust-mode . cargo-minor-mode)
      :bind
      ("C-c C-c C-n" . cargo-process-new)) ;; global binding
;;; racer-mode for getting IDE like features for rust-mode
    ;; https://github.com/racer-rust/emacs-racer
    (use-package racer
      :hook (rust-mode . racer-mode)
      :config
      (progn
        ;; package does this by default ;; set racer rust source path environment variable
        ;; (setq racer-rust-src-path (getenv "RUST_SRC_PATH"))
        (defun my-racer-mode-hook ()
          (set (make-local-variable 'company-backends)
               '((company-capf company-files)))
          (setq company-minimum-prefix-length 1)
          (setq indent-tabs-mode nil))

        (add-hook 'racer-mode-hook 'my-racer-mode-hook)

        ;; enable company and eldoc minor modes in rust-mode (racer-mode)
        (add-hook 'racer-mode-hook #'company-mode)
        (add-hook 'racer-mode-hook #'eldoc-mode)))

    (add-hook 'rust-mode-hook 'flycheck-mode)
    (add-hook 'flycheck-mode-hook 'flycheck-rust-setup)

    ;; format rust buffers on save using rustfmt
    (add-hook 'before-save-hook
              (lambda ()
                (when (eq major-mode 'rust-mode)
                  (rust-format-buffer))))))

3.3 最終配置

(use-package rust-mode
  :mode
  (("\\.rs\\'" . rust-mode))
  :hook
  (rust-mode . global-linum-mode) ;; 行顯示
  (rust-mode . hs-minor-mode) ;; 摺疊模式
  (rust-mode . eldoc-mode) ;; 程式碼追蹤
  (rust-mode . company-mode) ;; 自動填充
  (rust-mode . cargo-minor-mode)
  (rust-mode . racer-mode)
  (rust-mode . flycheck-mode)
  (flycheck-mode . flycheck-rust-setup)
  (rust-mode . (lambda () (setq indent-tabs-mode nil))) ;; 設定縮排

  :config
  (setq rust-format-on-save t) ;; 設定格式化
  )

相關文章