Vim: auto-comment in new line

commentsnewlinestext formattingvim

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.

Best Answer

Try this:

function! EnterEnter()
  if getline(".") =~ '^\s*\(//\|#\|"\)\s*$'
    return "\<C-u>"
  else
    return "\<CR>"
  endif
endfunction

imap <expr> <CR> EnterEnter()
Related Question