在Emacs中更改Python缩进量

时间:2016-06-02 21:13:57

标签: python emacs

因为我有

(setq python-indent-offset 4)

在我的.emacs中,当我开始使用

等代码时
def fn():
  foo = bar()
  if bar1 == bar2:
    if blah1 == blah2:
      return yay

和标记 - 整个缓冲区(C-x h)后跟缩进区域(C-M- \),我期望得到:

def fn():
    foo = bar()
    if bar1 == bar2:
        if blah1 == blah2:
            return yay

但我改为:

def fn():
    foo = bar()
  if bar1 == bar2:
    if blah1 == blah2:
      return yay

然而,使用花括号分隔语言,缩进区域可以正常工作。有没有办法让它与基于缩进的语言(如Python?)一起使用?

请注意:

  1. 我是awareReindent,但我想留在Emacs内。
  2. 我很熟悉string-rectangle (C-x r t) and python-indent-shift-right/left (C-c >),但这些和他们的变体都不能满足我的要求。

2 个答案:

答案 0 :(得分:1)

我不确定这是否是一个完美的解决方案,因此我不想将其作为emacs-devel的补丁推送,但因为问题出在python-indent-region(我留下了一个关于这是一个评论)。我们可以尝试重新定义该功能:

(defun python-indent-region (start end)
  "Indent a Python region automagically.

Called from a program, START and END specify the region to indent."
  (let ((deactivate-mark nil))
    (save-excursion
      (goto-char end)
      (setq end (point-marker))
      (goto-char start)
      (or (bolp) (forward-line 1))
      (while (< (point) end)
        (or (and (bolp) (eolp))
            (when (and
                   ;; Skip if previous line is empty or a comment.
                   (save-excursion
                     (let ((line-is-comment-p
                            (python-info-current-line-comment-p)))
                       (forward-line -1)
                       (not
                        (or (and (python-info-current-line-comment-p)
                                 ;; Unless this line is a comment too.
                                 (not line-is-comment-p))
                            (python-info-current-line-empty-p)))))
                   ;; Don't mess with strings, unless it's the
                   ;; enclosing set of quotes or a docstring.
                   (or (not (python-syntax-context 'string))
                       (eq
                        (syntax-after
                         (+ (1- (point))
                            (current-indentation)
                            (python-syntax-count-quotes (char-after) (point))))
                        (string-to-syntax "|"))
                       (python-info-docstring-p)))
              (python-indent-line)))
        (forward-line 1))
      (move-marker end nil))))

我更改的部分只是删除了检查以查看该行是否为块ender,denter或block-start并在所有这些情况下运行(python-indent-line)

我已经在这个例子以及其他一些例子上对此进行了测试,但它们似乎有效。如果它不起作用,我很乐意知道!

答案 1 :(得分:0)

或者你可以在emacs中调用python包并让它替换缓冲区。

(defun my-py-reindent ()
         "Reindent the current file with pypi's reindent."
         (interactive)
           (shell-command-to-string (format "reindent %s" (buffer-file-name)))
           (revert-buffer t t t))

非常简单! (doc使用:http://wikemacs.org/wiki/Emacs_Lisp_Cheat_Sheet#File