Pythonを書くためのEmacsの設定は常にアップデートしている.
reformatter および ruff-format をインストールする. ほか,smartchrや flymake-ruff,undo-treeも導入している.これ以外にもtempelの設定もしてある.tempelについては以下の記事にて.
ちなみにシンタックスハイライトをいい感じにするためにtree-sitterを導入している(python-ts-mode
).
M-x treesit-install-language-grammar
から "python" と入力し,あとはenter連打(デフォルト設定)でOKだと思われる.
設定はこんな感じに落ち着いた.python用のlanguage-serverはpyrightを使っている.
(setq gc-cons-threshold 16777216) (setq read-process-output-max (* 1024 1024)) (add-to-list 'major-mode-remap-alist '(python-mode . python-ts-mode)) (add-hook 'python-ts-mode-hook #'eglot-ensure) (add-hook 'python-ts-mode-hook 'ruff-format-on-save-mode) (reformatter-define ruff-sort-imports :program "ruff" :args '("check" "--fix" "--select" "I001" "-") :group 'python) (add-hook 'python-ts-mode-hook #'ruff-sort-imports-on-save-mode) (defun smartchr-keybindings-python () (local-set-key (kbd "=") (smartchr '(" = " " == " "="))) (local-set-key (kbd "+") (smartchr '(" + " "++" " += " "+"))) (local-set-key (kbd "-") (smartchr '(" - " "--" " -= " "-"))) (local-set-key (kbd "*") (smartchr '(" * " "**" " *= " "*"))) (local-set-key (kbd "/") (smartchr '(" / " " // " " /= " "/"))) (local-set-key (kbd "<") (smartchr '(" < " " <= " "<"))) (local-set-key (kbd ">") (smartchr '(" > " " >= " ">"))) (local-set-key (kbd "(") (smartchr '("(`!!')" "("))) (local-set-key (kbd "[") (smartchr '("[`!!']" "[[`!!']]" "["))) (local-set-key (kbd "\"") (smartchr '("\"`!!'\"" "\"\"\"`!!'\"\"\"" "\""))) (local-set-key (kbd "'") (smartchr '("'`!!''" "'"))) (local-set-key (kbd ",") (smartchr '(", " ","))) (local-set-key (kbd ":") (smartchr '(": " ":")))) (add-hook 'python-ts-mode-hook #'(lambda () (require 'smartchr) (smartchr-keybindings-python))) (add-hook 'python-ts-mode-hook #'(lambda () (undo-tree-mode t))) (with-eval-after-load 'undo-tree (setq undo-tree-mode-lighter " UT")) ;; for eglot (add-hook 'eglot-managed-mode-hook #'(lambda () (when (derived-mode-p 'python-mode 'python-ts-mode) (flymake-ruff-load)) (require 'eglot-booster) (eglot-booster-mode t))) (add-hook 'after-init-hook #'(lambda () (setq jsonrpc-default-request-timeout 3000) (fset #'jsonrpc--log-event #'ignore))) ;; for consult (with-eval-after-load 'consult-imenu (add-to-list 'consult-imenu-config '(python-ts-mode :toplevel "Function" :types ((?f "Function" font-lock-function-name-face) (?m "Method" font-lock-function-name-face) (?c "Class" font-lock-type-face) (?v "Variable" font-lock-variable-name-face)))))
ruff経由でソースコードの修正をしたい場合,reformatterをインストールしたうえで以下の設定を適用する.
ruff-fix-buffer
,ruff-fix-region
,あとは保存時に自動修正するマイナーモード ruff-fix-on-save-mode
が導入される.
(reformatter-define ruff-fix :program "ruff" :args '("check" "--fix" "-") :group 'python)
LSPの動作をさらに高速にするために,lsp-booster と eglot-boosterを取り入れている.