Emacs填充模式在Python中不破坏引号字符串导致错误

8 投票
2 回答
842 浏览
提问于 2025-04-18 07:04

我在Emacs中写一个Python脚本,并通过输入 M-x auto-fill-mode 开启了自动换行模式。不过,我总是遇到一个问题,就是这个换行模式会把字符串分成多行,而没有做任何调整,导致运行脚本时出错。

举个例子:

print 'the quick brown fox jumped over the lazy dog and
then did something else'

这样运行时会出现 SyntaxError: EOL while scanning string literal 的错误。

请问在Emacs中有没有一种换行模式,它能识别Python的字符串,并且自动进行一些调整,比如在 Python风格的字符串换行中讨论的那种,而不是简单地把字符串分开,导致出错呢?

2 个回答

0

使用当前的 python-mode.el

它应该这样运行:

print 'the quick brown fox jumped over the lazy dog and then did something asd asdf \
asdf elssdsd e'

https://gitlab.com/python-mode-devs/python-mode

2

编辑 我自己把这个功能关掉了,因为它在处理某些文档时让Emacs消耗了很多处理器时间。我只能忍受这个糟糕的填充模式——如果能有个合适的解决方案就好了:

some_list.append("This is a very long string which I would like to "
                 "break in a sensible way")

/编辑

我为这个问题纠结了很久,终于找到了解决办法。

这个方法对我来说有效。不幸的是,我觉得这会关闭所有模式下的引号字符串填充,而不仅仅是Python模式。我相信有更懂elisp的人能想出一个修改版,只限制在python-mode,但我认为这个方案比上面提到的要好。

这个解决方案来自于一个相关的回答——如果你觉得不错,可以去给这个回答点个赞。

(defun odd-number-of-single-quotes-this-paragraph-so-far ()
  (oddp (how-many "'" (save-excursion (backward-paragraph) (point)) (point))))
(defun odd-number-of-double-quotes-this-paragraph-so-far ()
  (oddp (how-many "\"" (save-excursion (backward-paragraph) (point)) (point))))

(add-to-list 'fill-nobreak-predicate
     'odd-number-of-single-quotes-this-paragraph-so-far)
(add-to-list 'fill-nobreak-predicate
     'odd-number-of-double-quotes-this-paragraph-so-far)

'''

撰写回答