Emacs中自动展开评论块

7 投票
2 回答
615 浏览
提问于 2025-04-16 10:06

我喜欢评论单独占一行,不喜欢把评论放在代码的同一行。在某些编程语言中,你可以写一个这样的评论块:

/**
 * I am a comment block. This comment block will be automatically expanded by the
 * IDE such that it can contain all of the text in this block.
**/

我喜欢这样。每当我在评论块中添加更多文字时,这个评论块就会自动增加行数。我喜欢的是,如果我在评论块的某个位置插入文字,后面的文字会自动下移,这样就不会有文字超出右边界。我使用的是Python,但Python没有多行块评论。我想最接近的写法可能是:

# I am a comment block.  This comment block will NOT be automatically expanded by
# the IDE, because it does not recognize these two comment lines as being joined.

我还使用emacs。我在想有没有人想出什么聪明的办法,让我可以打开一个评论块,然后直接开始输入。这样就不用担心当评论行太宽时要按回车键换行,也不用在想要在评论块中间插入文字时重新调整整个评论的格式。有没有什么好主意呢?

总结一下:我想在emacs中为Python实现一种多行连续评论的方法,而不需要手动调整评论块中的文本格式。

谢谢

2 个回答

2

这有点不寻常,但你并不只限于用字符串作为文档字符串的注释。把它放在第一行的唯一好处是,它们会被赋值给对象的 __doc__ 方法。不过,你可以在任何地方使用它们,这样做不会影响效率。

>>> import dis
>>> def test():
...     """This is a standard doc string"""
...     a = 3  # This will get compiled
...     """This is a non standard doc string and will not get compiled"""
... 
>>> dis.dis(test)
  3           0 LOAD_CONST               1 (3)
              3 STORE_FAST               0 (a)

  4           6 LOAD_CONST               2 (None)
              9 RETURN_VALUE

你可以看到生成的代码并没有提到这两个字符串。

我提到这个是因为文档字符串似乎具备你所要求的所有功能。虽然这有点不标准,但我个人觉得没什么问题。多行注释会更好。

4

auto-fill-mode 这个功能看起来正是你想要的。当一行的长度超过 fill-column 设置的值时,它会自动换行,并插入新的注释行。

不过,这个功能并不是完全自动的。如果你在中间插入了文本,你需要按一下 M-q 来重新调整格式。

[编辑:这里有个方法可以让“空格”命令更智能。每次你按 SPC 时,你的注释块都会被重新调整格式:

(defun refill-when-in-comment ()
  (interactive)
  (let ((curr-face (get-char-property (point) 'face)))
    (if (member "comment" (split-string (prin1-to-string curr-face) "-"))
        (fill-paragraph t)
      )
    )
  )

(defun smart-space (arg)
  (interactive "P")
  (refill-when-in-comment)
  (self-insert-command (prefix-numeric-value arg))
  )

(global-set-key " " 'smart-space)

这样对你有用吗?

撰写回答