2015-11-30 56 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