[英]How to indent code in Emacs with python-mode?
我使用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))
如果我选择区域,并点击Mx 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))
Mx indent-region
错误地理解了代码行之间的缩进关系? 是因为我的代码含糊不清吗? 谢谢。
问题是emacs无法知道你想要if块的结束位置。 您所需的代码和代码缩进区域生成都是有效的python。 在类C语言中,由于大括号决定了块的长度,因此这不是问题。 对于python,因为emacs无法确定它假设每行代码仍然是前一个块的一部分。
您可能希望查看python-indent-left(绑定到“Cc <”)和python-indent-right(“Cc>”)。 要修复你的例子,你要突出显示除第一行之外的所有内容,然后运行python-indent-left。
如上所述,在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键作为此行并继续下一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.