Nicely formatting long //comments in vim
When I am typing a long code comment in VIM, I manually judge when each comment 开发者_JAVA百科line reaches 80 characters, then manually typically press < enter >< tab >//< space > and continue on. Likewise it is awkward editing comments, adding or removing text.
// The comments I have to use
// look like this
Ideally, I'd like some kind of comment mode, where you type text, and the 80 line character limit and the // symbols are sorted out automatically. Does anything like this exist?
You can turn on formatting options with set formatoptions=tcq
(with tcq each representing an option, there are others as well). Use h formatoptions
to see what the various flags are.
In this case you probably want to use set fo+=a
.
Personally though, I prefer to just type my comments normally, then when I'm done run gqip
. gq
is the formatting command, ip
for in paragraph. Make sure the comment block is not next to code though or it will suck that up when reformatting your comment.
I use :set textwidth=80
to set the formatting width (actually, 80 is the default).
Then I move the cursor to the first line of the comment and in command mode press gq}
to format the comment. It also works for other comment types from other programming languages such as #
and /* ... */
A variant on @Alex's suggestion is to select the lines in visual mode and then press gq
. This allows you to avoid the problem of gqip
reformatting code as well.
Pressing capital V
selects an entire line, then you can just move up or down to highlight all the comments and press gq
.
精彩评论