2015-11-30 20 views
4

我最近從vim轉換爲emacs(spacemacs)。 Spacemacs附帶yapf作爲python的標準代碼reformatter工具。當代碼被破壞時,我發現autopep8能更好地處理python代碼。我不知道如何使autopep8重新格式化選定的區域,而不是整個緩衝區。在vim中,這相當於在選擇或對象上運行gq函數。我們如何在emacs/spacemacs中做到這一點?autopep8重新格式化emacs/spacemacs中的一個區域

回答

0

我不知道你是如何調用autopep8,但這個特殊的包裝已經與該地區工作或標誌着當前功能:https://gist.github.com/whirm/6122031

保存要點任何你保留個人elisp的代碼,如~/elisp/autopep8.el

.emacs確保口齒不清目錄是負載路徑上,加載該文件,並覆蓋鍵綁定:在主旨默認

(add-to-list 'load-path "~/elisp") ; or wherever you saved the elisp file 
(require 'autopep8) 
(define-key evil-normal-state-map "gq" 'autopep8) 

的版本,如果沒有區域是活躍的格式化當前功能。默認爲整個緩衝區,改寫這樣的文件中的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或任何您保留自定義設置的位置。

+0

請問您可以擴展您的答案,以包括這個函數應該放在.emacs.d /下的位置,以及它應該如何替換格式區域現有的鍵綁定邪惡''gq''。 – Meitham

+0

最簡單的事情是把它放在〜/ .emacs.d/init.el(或者〜/ .emacs,如果你使用的話)。如果你想把它放在一個單獨的文件中,建議將它放在〜/ .emacs.d/lisp /或其他一些子目錄中,而不是直接放在〜/ .emacs.d /中(不要忘記將它添加到負載路徑)。至於rebinding,我不知道邪惡模式,但這看起來很有希望:http://stackoverflow.com/questions/19483278/bind-emacs-evil-window-commands-to-g-prefix。 – jpkotta