私は最近、vim から emacs (spacemacs) に変換しました。Spacemacs はyapf
、Python の標準コード再フォーマットツールとして付属しています。コードが壊れている場合、autopep8 は Python コードでより適切に機能することがわかりました。バッファ全体ではなく、選択した領域を autopep8 で再フォーマットする方法がわかりません。vim では、これはgq
選択範囲またはオブジェクトに対して関数を実行することと同じです。emacs/spacemacs でそれを行うにはどうすればよいでしょうか?
1 に答える
autopep8 をどのように呼び出しているのかわかりませんが、この特定のラッパーは既にリージョンで動作しているか、現在の関数をマークしています: https://gist.github.com/whirm/6122031
などの個人的な elisp コードを保持している場所に Gist を保存します~/elisp/autopep8.el
。
.emacs
Lisp ディレクトリがロード パス上にあることを確認して、ファイルをロードし、キー バインディングをオーバーライドします。
(add-to-list 'load-path "~/elisp") ; or wherever you saved the elisp file
(require 'autopep8)
(define-key evil-normal-state-map "gq" 'autopep8)
リージョンがアクティブでない場合、gist のバージョンはデフォルトで現在の関数をフォーマットします。デフォルトでバッファー全体に設定するには、ファイル内の autopep8 関数を次のように書き換えます。
(defun autopep8 (begin end)
"Beautify a region of python using autopep8"
(interactive
(if mark-active
(list (region-beginning) (region-end))
(list (point-min) (point-max))))
(save-excursion
(shell-command-on-region begin end
(concat "python "
autopep8-path
autopep8-args)
nil t))))
上記のセットアップは、Emacs で autopep8 を使用してゼロから開始することを前提としています。他のパッケージの Emacs に autopep8 が既にある場合、それをカスタマイズする方法の最終的な答えは、コードがどこから来て、どの引数と変数がサポートされているかによって異なります。入力C-h f autopep8
して、既存の関数のヘルプを表示します。
たとえば、既存の autopep8 関数がフォーマットする領域の引数を取る場合、上記のコードのインタラクティブな領域とポイント ロジックを使用して、システム上の既存の関数をラップする新しい関数を定義できます。
(define-key evil-normal-state-map "gq" 'autopep8-x)
(defun autopep8-x (begin end)
"Wraps autopep8 from ??? to format the region or the whole buffer."
(interactive
(if mark-active
(list (region-beginning) (region-end))
(list (point-min) (point-max))))
(autopep8 begin end)) ; assuming an existing autopep8 function taking
; region arguments but not defaulting to the
; whole buffer itself
そのスニペットはすべて .emacs に入れるか、カスタマイズを保持する場所に入れることができます。