9

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.

Patrick Oscity
  • 1,829
  • 1
  • 16
  • 19

3 Answers3

4

Try this:

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

imap <expr> <CR> EnterEnter()
romainl
  • 23,415
3

I extended @romainl's answer to work with arbitrary languages by generating the regex from Vim's &commentstring:

function! s:IsOnlyComment(getlineArg)
  let commentRegex='^\s*'.substitute(&commentstring,'%s','\\s*','').'$'
  return strlen(matchstr(getline(a:getlineArg), commentRegex)) > 0
endfunction

function! SmartEnter()
  if s:IsOnlyComment('.')
    return "\<Esc>S"
  else
    return "\<CR>"
  endif
endfunction

inoremap <expr> <CR> SmartEnter()

However, I can't seem to remap <CR> at all, this just won't work. For now, I use <CR><CR> until this issue is solved.

Patrick Oscity
  • 1,829
  • 1
  • 16
  • 19
2

Remove r from 'formatoptions. That's what that option does. Turning it off will mean you never get vim doing that for you which means you will need to add the leading comment markers when you do actually want them but that's the tradeoff.

Etan Reisner
  • 2,238