How do I define a custom Ex command that can accept a line range or count like built-in Vim commands?
Answer
:command -range {Name} ...
Explanation
Custom Ex commands defined with :command -range can be called with a line range (e.g., '<,'>MyCmd or 1,10MyCmd) just like built-in commands such as :sort or :delete. Inside the command body, <line1> and <line2> hold the first and last line of the range, and <count> holds the line count. This lets you build powerful domain-specific shortcuts that operate on ranges without plugins.
How it works
-rangeaccepts the default range of the current line (.)-range=%defaults to the whole file if no range is given-range=Nuses count N as a default<line1>,<line2>interpolate the actual range boundaries in the body- Use
<count>when you want a count rather than a range (mutually exclusive with<line1>/<line2>)
Example
Define a :Trim command that removes trailing whitespace from a range:
:command -range Trim <line1>,<line2>s/\s\+$//e
Now you can use it in multiple ways:
:Trim " trims the current line
:%Trim " trims the entire file
:'<,'>Trim " trims the visual selection
:5,20Trim " trims lines 5 to 20
Tips
- Add
-nargs=*to also accept arguments::command -range -nargs=* MyCmd ... - Use
<q-args>to pass the raw argument string,<f-args>to split on whitespace into a list - Add
!to allow overwriting an existing command::command! -range Trim ... - Put the definition in your
vimrcso it's always available