How to stop Vim from automatically inserting the comment leader when Enter is pressed?

To disable it while hitting ENTER in insert mode, do :set formatoptions-=r

To disable it while hitting o or O in normal mode, do :set formatoptions-=o

See :help 'formatoptions' and :help fo-table.

Alternatively, you can still press CTRL-U in insert mode if you want to delete characters from start of line till the cursor.


Another answer from mine since you don't want to have this triggered for /**/ comments.

Use:

inoremap <expr> <enter> getline('.') =~ '^\s*//' ? '<enter><esc>S' : '<enter>'

For o and O:

nnoremap <expr> O getline('.') =~ '^\s*//' ? 'O<esc>S' : 'O'
nnoremap <expr> o getline('.') =~ '^\s*//' ? 'o<esc>S' : 'o'

Tags:

Vim