For example, I have the following code

command! -range Test call TestFunc()
function! TestFunc() abort
  " if run with range
  "   get selected content
  " else
  "   get current word under the cursor
  " endif

I want to differentiate whether users run :Test or :'<,'>Test.

I've tested mode() function doesn't work here. Also <line1>,<line2> do not help because they always give me the same result(current line number) when I run it with range(select the current line) or not.

I wonder if there are any solutions for this?

  • 1
    Since you mentioned word under the cursor, consider implementing an operator that takes a motion/text object rather than a command that takes a range. The latter is limited to lines only when passed a range. See Grep Operator from "Learn Vimscript the Hard Way" for an example operator. (You might want to consider reading the whole material, it's an excellent resource if you want to master Vimscript.)
    – filbranden
    Apr 23, 2020 at 5:26
  • 2
    @filbranden Thanks, I'll read it.
    – WW00WW
    Apr 24, 2020 at 1:15

1 Answer 1


A range with commands is always about lines. It seems you want to work with line/column positions.

Whether a range was given can be checked by using <range>:

command! -range Test call TestFunc(<range>,<line1>,<line2>)
function! TestFunc(r,l1,l2) abort
    if a:r == 0
        echo "No range"
    elseif a:r == 1
        echo "Single Line given (like :22Test)"
        echo "Line range given (like 1,23Test, '<,'>Test or %Test)"

Note: You might need to set cmdheight=2 to see the echo in all cases.

  • Implementing this as presented, it works as expected. Implemented in another function, 'l1' and 'l2' get passed as expected, but 'r' comes with a code of '2'. So the func thinks it's in error, when the range is fine. What can be going on? What does code 2 mean?
    – markling
    Dec 7, 2021 at 17:06
  • 1
    0 means no Range, 1 Single line Range, 2 multiline Range. So 2 is handele by the Else Branche.
    – Ralf
    Dec 7, 2021 at 17:11
  • ah - 'h: <range>' says <range> code 0, 1, or 2 represents "the number of items in the command range". So 2 is not an error code, but an indication that the range had two values.
    – markling
    Dec 7, 2021 at 17:11
  • Are these 0,1,2 even documented in the :help? I was struggling to understand them. Thanks for your explanation anyway...! Apr 7, 2023 at 13:51

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.