How to stop Vim from automatically inserting the comment leader when Enter is pressed?
If I'm typing a comment in gVim like this
// this is 开发者_StackOverflow社区a comment
and I hit ENTER, it will automatically start the next line with //, so it looks like this:
// this is a comment
//
But usually I don't want to write more comments when using this commenting style. Can I stop gVim from automatically doing this, while still keeping the auto-completing of the /* .. */ commenting style?
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'
To permanently disable this behavior, add autocmd FileType * set formatoptions-=r
in your .vimrc
/init.vim
.
To have it disabled every time you use vim, open your .vimrc file and add the following line:
autocmd BufNewFile,BufRead * setlocal formatoptions-=r
Adding:
set fo-=ro
in ~/.vimrc
was sufficient,
to disable Return and o/O keys in normal mode from autocommenting.
fo
is a shorthand for formatoptions
, and -=
is to subtract certain keys while retaining the rest of the original value.
The value of fo
can be shown using set fo?
in command (ex
) mode.
Issue help fo
to read more about option in the vim's internal manual pages.
精彩评论