When I press return at the end of a comment line, vim will automatically insert the comment leader on the next line as well:

// My comment bla bla
// ‸

I like this feature and I would like to leave it switched on. However, quite often, I also want to write uncommented code on the next line. Is there an easy way to configure vim in such a way that pressing backspace once in this position will remove the whole comment leader? I find it at little bit annoying to always have to press backspace three times.

  • 1
    Press Ctrl-U to clear the whole line? Mar 5, 2018 at 21:15
  • Thanks, I didn’t know about that one. This might definitively be an option as well. Mar 5, 2018 at 21:39

2 Answers 2


You can accomplish this with a simple mapping;

inoremap <silent><expr> <bs> getline('.') =~# '^//\s*$' ? "<c-u>" : "<bs>"

Note that if your backspace setting includes start, this will delete the comment regardless of whether it was automatically entered or not.

Alternatively, here is a slightly different workflow. I use the following snippet; pressing <cr> will insert the comment leader, pressing shift+<cr> will not. Note that not all terminals support this key combination.

execute "set <f26>=\<esc>OM"

inoremap <silent><expr> <f26>
    \ synIDattr(synID(line('.'), col('.')-1, 1), 'name') =~? 'comment'
    \ ? "<cr><c-u>"
    \ : "<cr>"
  • Unfortunately both variants don’t work for me. I run vim in tmux and it looks like shift + <cr> won’t work with tmux. But I’m also unsure whether it would fit my workflow: I’m looking for something that works after pressing ‘o’ as well. The first one looks like what I want, but vim will just remove the space characters. Mar 5, 2018 at 21:37
  • Okay I just tried it with a blank .vimrc and it works. So something else seems to be interfering with this :/ Mar 5, 2018 at 21:43
  • Looks like jiangmiao/auto-pairs is the culprit: github.com/jiangmiao/auto-pairs/blob/… Mar 5, 2018 at 21:49
  • I managed to reconcile it with auto-pairs. If anyone is interested, you can see my solution on github.com/MichaelWJung/dev-env/blob/… Mar 5, 2018 at 22:52
set fo-=or

These options remove adding the comment leader automatically when pressing o or O in Normal mode, and when pressing in Insert mode respectively.

see fo-table in vim help :h fo-table

  • 4
    While legal, set fo-=or isn't really correct as it will not work unless o and r are adjacent in current configuration. You should run -= on one flag at a time.
    – B Layer
    Nov 20, 2019 at 23:04
  • Oh that's great to know! I always wondered why people list them out manually. I must have gotten away with it by luck
    – Michael
    Mar 26, 2020 at 7:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.