在Vim中修复了太长的注释行

Tom*_*tal 5 vim

我正在寻找一种方便的方法来修复Vim中行长度超过一定数量字符的注释.我很好地使用代码手动执行此操作,特别是因为它不常见,加上重构长行通常是语言,甚至代码风格依赖,但是评论这是纯粹的苦差事.

发生的事情是我经常在评论中发现一些问题,调整一两个单词,并且该行溢出,比方说,80个字符的限制.我将最后一个单词移到下一行,然后下一行溢出,依此类推.有没有人知道在Vim中自动执行此操作的方法?

小智 3

如果这是一个常见问题,我建议将以下内容放入您的 vimrc 中:

nnoremap <leader>f gqip
Run Code Online (Sandbox Code Playgroud)

这映射了前导符 f 快捷方式(f 代表“格式”)以使用 gq 格式化注释(在设置某些 formatoption 标志后被视为段落),gq 将注释格式化为当前设置textwidthtw选项的宽度。您应该在 .vimrc 中使用 来设置 textwidth textwidth=80

Formatoptions 是您应该摆弄的另一件事,特别是在您的情况下,通过添加acq带有formatoptions+=acq. 请小心删除t标志,formatoptions-=t因为它会自动包装所有代码,而不仅仅是识别的注释。完成所有这些操作后,您应该能够仅在注释内按 f 并格式化,无论注释是否被空行包围。

这是有关格式选项的相关信息,以便您可以做出自己的选择。

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.
Run Code Online (Sandbox Code Playgroud)