如何告诉 Vim 评论结束

How to tell Vim about the end of a comment

Vim 有一个功能,如果前一个注释行太长并且被换行,它会自动在新行插入一个注释前缀。如果您按 Enter,它还会插入换行符前缀。这使得输入长评论变得容易,但是当你想结束评论时就不方便了。您必须按退格键才能删除最后一行的注释前缀。

是否可以修改 Vim 以便如果我只在最后一行按回车,它知道终止评论?

这可以通过formatoptions来控制。来自链接文档页面

'formatoptions' is a string that can contain any of the letters below.
...
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.
...

这意味着您想要 c,但不想要 r,而且可能也不想要 o.vimrc

中的简单示例行
autocmd FileType bash,csh setlocal formatoptions=c

您需要在别处设置 textwidth(例如 set textwidth=72)。

有关更多信息,请参阅链接页面的续篇。如果您已经有一串字母,那么只需从中删除 ro 即可。相关选项是 comments -- see format-comments 页。

Vim 怎么知道最后一行是什么?

我能想到的唯一解决方法是绑定到 InsertLeave 自动命令以清除该行(如果它只是一个注释字符):

autocmd InsertLeave * if getline('.') =~ '^# *$' | normal! 0D | endif

但是,它还会删除以下行中的注释字符:

# Hello, world
#
# Continuing with the next paragraph

可以进行的改进:

  • 解析 &comments 以获得注释字符 - 格式见 :help format-comments

  • 仅当下一行不以注释字符开头时才删除该行。

  • 您可以在插入模式下映射 <Cr> 来执行类似的操作,这样您就不必离开插入模式 - 但是要非常小心,因为您可能会结束删除比你想要的更多!

  • 我的建议:只需按退格键即可。