Vim: auto-comment in new line

Posted by padde on Super User See other posts from Super User or by padde
Published on 2013-11-01T16:08:20Z Indexed on 2013/11/01 21:58 UTC
Read the original article Hit count: 191

Filed under:
|
|
|

Vim automatically inserts a comment when I start a new line from a commented out line, because I have set formatoptions=tcroql. For example (cursor is *):

// this is a comment*

and after hitting <Enter> (insert mode) or o (normal mode) i am left with:

// this is a comment
// *

This feature is very handy when writing long multi-line comments, but often I just want a single line comment. Now if I want to end the comment series I have several options:

  • hit <Esc>S
  • hit <BS> three times

Both of these afford three keystrokes, taken together with the <Enter> this means four keystrokes for a new line, which I think is too much. Ideally, I would like to just hit <Enter> a second time to be left with:

// this is a comment
*

It is important that the solution will also work with different indentation levels, i.e.

int main(void) {
    // this is a comment*
}

hit <Enter>

int main(void) {
    // this is a comment
    // *
}

hit <Enter>

int main(void) {
    // this is a comment
    *
}

I think I have seen this feature in some text editor a few years ago but I do not recall which one it was. Is anyone aware of a solution that will do this for me in Vim? Pointers in the right direction on how to roll my own solution are also very welcome.

© Super User or respective owner

Related posts about vim

Related posts about text-formatting