Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using line numbers in user-define command [duplicate]

Tags:

vim

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??

like image 376
venkstart Avatar asked Jan 18 '26 14:01

venkstart


2 Answers

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
like image 147
jamessan Avatar answered Jan 20 '26 04:01

jamessan


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.

like image 43
Conner Avatar answered Jan 20 '26 04:01

Conner