在Vim中修复过长的注释行

5
我正在寻找一种方便的方法来解决在Vim中超出一定字符数限制的注释。我可以手动编写代码进行操作,特别是因为这种情况并不频繁,而且重构长行通常取决于语言甚至代码风格,但对于注释来说,这纯粹是苦差事。
经常发生的情况是我在注释中发现了一些问题,稍微修改一两个单词,然后行就超过了80个字符的限制。我将最后一个单词移到下一行,然后下一行也会溢出,如此循环。有没有人知道在Vim中自动完成这个任务的方法?

7
我认为只需要设置textwidth=80,然后使用gq<motion>重新格式化即可。 - Codie CodeMonkey
哦,我的天,我简直不敢相信它是那么简单,谢谢! - Tomek Kaftal
@DeepYellow 但是当你在行末写字时,它似乎只会回车,对吗?如果你在开头添加文本,它不会将超出的文本移到下一行。或者我做错了吗? - Nadir Sampaoli
我也注意到了这一点,但如果你选择一个包括下一行的动作,它应该可以工作。我发现将整个注释块进行可视化选择并运行gq对我来说效果最好。 - Tomek Kaftal
Tomek是正确的,或者使用gqj格式化下一行。我通常只是重复几次这个过程。 - Codie CodeMonkey
1
如果你想在写入任何地方时进行换行,请在formatoptions中包括a。同时,请确保它包含c以便在注释中起作用,查看:h fo-table以获取其他有用的字符。 - ZyX
1个回答

3
如果这是一个常见的问题,我建议将以下内容放入您的vimrc文件中:
```vim set nowrapscan ```
这个设置可以禁止在搜索到文件末尾时重新开始搜索。
nnoremap <leader>f gqip

这将把快捷键 f 映射到格式化评论的操作(在设置某些 formatoption 标志后,将其视为一个段落),并使用 gq 将评论格式化为当前设置的 textwidthtw 选项的宽度。您应该在 .vimrc 中使用 textwidth=80 来设置 textwidth。

formatoptions 是另一件需要调整的事情,特别是在您的案例中,通过添加 acq 标志来使用 formatoptions+=acq 进行调整。请注意使用 formatoptions-=t 移除 t 标志,因为这会自动换行所有代码,而不仅仅是被识别的注释部分。完成所有这些操作后,您应该能够按下 f 键,在评论中进行格式化,无论其是否被空行包围。

以下是有关 formatoptions 的相关信息,以便您可以做出自己的选择。

t       Auto-wrap text using textwidth

c       Auto-wrap comments using textwidth, inserting the current comment
    leader automatically.

r       Automatically insert the current comment leader after hitting
    <Enter> in Insert mode.

o       Automatically insert the current comment leader after hitting 'o' or
    'O' in Normal mode.

q       Allow formatting of comments with "gq".
    Note that formatting will not change blank lines or lines containing
    only the comment leader.  A new paragraph starts after such a line,
    or when the comment leader changes.

w       Trailing white space indicates a paragraph continues in the next line.
    A line that ends in a non-white character ends a paragraph.

a       Automatic formatting of paragraphs.  Every time text is inserted or
    deleted the paragraph will be reformatted.  See |auto-format|.
    When the 'c' flag is present this only happens for recognized
    comments.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接