I want to set up simple user-defined command to be able to comment out several lines at once in VIM. I tried this
:command -range Cm :<line1>,<line2>s/^/##/
and invoked it as shown
:Cm 11,14
but get error saying Trailing Characters .Also tried the same replacing -range with -nargs=+ but still doesn't work. Can anyone help me what I'm missing here??
User-defined commands accept ranges in the same way that other Vim commands do. That is, they come at the start of the command line. You would want to execute
:11,14Cm
There are many good plugins for commenting in vim, including tComment and vim-commentary. However, if you'd like to make a custom command like this, here's a template to start from:
command! -range -nargs=* Cm <line1>,<line2>call Comment(<f-args>)
fun! Comment(...) range
if a:firstline != a:lastline
sil exe a:firstline . "," . a:lastline . "s/^/##/"
else
sil exe a:1 . "," . a:2 . "s/^/##/"
endif
endfun
This command takes either a range or arguments. It's useful to allow it to take a range since you might want to operate the command on a visual selection. It sets the default range to the current line and then says if the current line is all we're operating on, ignore the range given and instead look at the parameters given.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With