1

I use vim-commentary to comment. Hit g-c-c to toggle comments. But this will comment out the already existing comments if they start with // and it will comment out already existing comments startin with /*.

Is there a way (with / or without a pluging) to comment out lines of code while ignoring the already existing comments in the specified block?

2
  • Your question could most probably benefit from an example (or a couple.) By "ignoring" the existing comments, do you mean preserving them when commenting the block? Or nesting them inside a separate comment block (ignoring they were already commented while commenting them)?
    – filbranden
    Sep 15, 2020 at 14:36
  • 1
    It is the same for me if the existing comments will be ignored or commented out again. Important is that when I un-comment the block again they will come back as a normal comment. I think the best option is to comment them out again. Sep 16, 2020 at 7:23

2 Answers 2

1

You might want to consider using the NERD Commenter plug-in, which offers mappings with finer granularity.

See the default mappings, you have <Leader>cc to comment a block of code (not toggle) and also <Leader>cn to comment the code, but forces nesting (which makes it easier to uncomment the block and keep the pre-existing comments as such.)

You can override the default mappings by setting the global variables from the documentation in your vimrc.

1
  • 1
    Yeah, comment comments is a feature imo. Makes it easier to uncomment later.
    – D. Ben Knoble
    Sep 15, 2020 at 13:02
1

The vim-commentary plugin uses 'commentstring' to define what a comment should look like. Some languages support multiple comment formats, e.g. // & /* */. Change 'commentstring to match the format that you use

set commentstring=//%s

However, if a project uses two different formats then you can still it becomes more challenging. I would then suggest making mappings which set 'commentstring' and then rest it after the commentary command is given with the CommentaryPost autocmd:

function! s:AltCommentary()
  let s:commentary_format = &commentstring
  let &commentstring = '// %s'
  augroup alt_commentary
    autocmd!
    autocmd User CommentaryPost let &commentstring = s:commentary_format |
          \ autocmd! alt_commentary
  augroup END
endfunction

xmap <leader>gc  :<c-u>call <SID>AltCommentary()<cr>gv<Plug>Commentary
nmap <leader>gc  :<c-u>call <SID>AltCommentary()<cr><Plug>Commentary
nmap <leader>gcc :<c-u>call <SID>AltCommentary()<cr><Plug>CommentaryLine
0

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.