gpt4 book ai didi

emacs - autopep8 重新格式化 emacs/spacemacs 中的区域

转载 作者:行者123 更新时间:2023-12-01 04:59:51 25 4
gpt4 key购买 nike

我最近从 vim 转换为 emacs (spacemacs)。 Spacemacs 自带 yapf作为python的标准代码重新格式化工具。当代码被破坏时,我发现 autopep8 在 python 代码上工作得更好。我不知道如何使 autopep8 重新格式化选定区域,而不是整个缓冲区。在 vim 中这相当于运行 gq对选择或对象起作用。我们如何在 emacs/spacemacs 中做到这一点?

最佳答案

我不知道你是如何调用 autopep8 的,但是这个特定的包装器已经在该区域中工作或标记了当前函数:https://gist.github.com/whirm/6122031

将要点保存在您保留个人 elisp 代码的任何位置,例如 ~/elisp/autopep8.el .

.emacs确保您的 lisp 目录位于加载路径上,加载文件并覆盖键绑定(bind):

(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 或您保留自定义项的任何位置。

关于emacs - autopep8 重新格式化 emacs/spacemacs 中的区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34002435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com