1

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.

  • Press Ctrl-U to clear the whole line? – Christian Brabandt Mar 5 '18 at 21:15
  • Thanks, I didn’t know about that one. This might definitively be an option as well. – Michael Jung Mar 5 '18 at 21:39
0

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. – Michael Jung Mar 5 '18 at 21:37
  • Okay I just tried it with a blank .vimrc and it works. So something else seems to be interfering with this :/ – Michael Jung Mar 5 '18 at 21:43
  • Looks like jiangmiao/auto-pairs is the culprit: github.com/jiangmiao/auto-pairs/blob/… – Michael Jung Mar 5 '18 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/… – Michael Jung Mar 5 '18 at 22:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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