【问题标题】:How to indent code in Emacs with python-mode?如何使用 python 模式在 Emacs 中缩进代码?
【发布时间】:2014-09-13 03:23:25
【问题描述】:

我正在运行带有 python-mode.el 的 Emacs 以在 Python 中进行编码。我希望学习如何使代码区域自动缩进。

以下代码没有很好的缩进。

while match != None:

        if match.group(1):
            titles.append(match.group(1))

        if match.group(2):
            if match.group(2) != '':
                pns.append(int(match.group(2)))
            else:
                pns.append('')
        else:
            pns.append('')

        if match.group(3):
            closings.append(len(''.join(match.group(3).split())))
        else:
            closings.append(0)

    match = pat.search(match.group(4))

如果我选择地区,然后点击M-x indent-region,那就完全错误了:

while match != None:

    if match.group(1):
        titles.append(match.group(1))

        if match.group(2):
            if match.group(2) != '':
                pns.append(int(match.group(2)))
            else:
                pns.append('')
        else:
            pns.append('')

            if match.group(3):
                closings.append(len(''.join(match.group(3).split())))
            else:
                closings.append(0)

                match = pat.search(match.group(4))

理想应该是:

while match != None:

    if match.group(1):
        titles.append(match.group(1))

    if match.group(2):
        if match.group(2) != '':
            pns.append(int(match.group(2)))
        else:
            pns.append('')
    else:
        pns.append('')

    if match.group(3):
        closings.append(len(''.join(match.group(3).split())))
    else:
        closings.append(0)

    match = pat.search(match.group(4))
  1. 为什么M-x indent-region 错误理解缩进 代码行之间的关系?是不是因为我的代码不明确?
  2. 那我该怎么办?

谢谢。

【问题讨论】:

    标签: python emacs python-mode


    【解决方案1】:

    问题在于 emacs 无法知道您希望 if 块在哪里结束。您想要的代码和 indent-region 生成的代码都是有效的 python。在类 C 语言中,这不是问题,因为大括号决定了块的长度。对于 python,由于 emacs 无法确定它假设每一行代码仍然是前一个块的一部分。

    您可能想查看 python-indent-left(绑定到“C-c ”)。要修复您的示例,您需要突出显示除第一行之外的所有内容,然后运行 ​​python-indent-left。

    【讨论】:

      【解决方案2】:

      如前所述,在 Python 中,您不能可靠地自动缩进较大的部分。

      但是,有一种方法可以加快逐行执行的速度。这是在这里使用的:

      (defun indent-and-forward ()
        "Indent current line and go forward one line. "
        (interactive "*")
        (if (empty-line-p)
            (fixup-whitespace)
            (indent-according-to-mode))
        (if (eobp)
            (newline-and-indent)
          (forward-line 1))
        (back-to-indentation))
      

      顺便说一句,它也应该适用于其他模式,而不仅仅是 Python。这里的钥匙是

      (global-set-key [(super i)] 'indent-and-forward)
      

      按下此键,您可能会移动大部分区域 - 请注意它仍然可以执行您想要的操作。如果不是 - 仅在这一行使用 TAB 键并继续下一行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-04
        • 1970-01-01
        • 2012-09-25
        • 2014-04-07
        • 1970-01-01
        相关资源
        最近更新 更多