python - 在 Emacs 中更改 Python 缩进量

标签 python emacs

因为我有

(setq python-indent-offset 4)

在我的 .emacs 中,当我从

这样的代码开始时
def fn():
  foo = bar()
  if bar1 == bar2:
    if blah1 == blah2:
      return yay

和 mark-whole-buffer (C-x h) 后跟 indent-region (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 >) ,但这些及其变体都不能满足我的要求。

最佳答案

我不确定这是否是一个完美的解决方案,因此我不想将其作为补丁推送到 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))))

我更改的部分只是删除检查以查看该行是否是 block 结束器、压痕器或 block 开始并在所有这些情况下运行 (python-indent-line) .

我已经在这个示例和其他一些示例中对此进行了测试,它们似乎有效。如果它不起作用,我很想知道!

关于python - 在 Emacs 中更改 Python 缩进量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37602217/

相关文章:

python - 意外的格式字符串行为

python - 如何逐列迭代 pandas 数据框,一次返回一个项目

emacs - 如何显示两个程序之间的差异?

emacs - 如何在 Emacs 次要模式下重新绑定(bind) TAB 和 RET?

bash - 如何为 Emacs mingw32 for Windows 运行 Windows 10 的 bash?

python - 意外的 1.0000 top_k_categorical_accuracy

python - 如何添加到 python 中的奇数索引值?

emacs - swank-clojure 和 slime 不再在 emacs 中合作

python - 使用时区打印正确的时间,Python

Emacs speedbar 不显示所有类的方法