22

I'm trying to define a command that can take a range and pass it to a function. This is what I thought I should have:

function! PrintGivenRange() range
    echo "firstline ".a:firstline." lastline ".a:lastline
    " Do some more things
endfunction

command! -range PassRange call PrintGivenRange()

However, it doesn't work that way, it seems to only pass the first line.

e.g.

:1,5PassRange "outputs firstline 1 lastline 1
:1,5call PrintGivenRange() "outputs firstline 1 lastline 5
" if you select lines in visual mode, same thing for both

I've read :help command-range already but still haven't been able to figure this out. Am I supposed to pass the range in the prefix to the call? How do I fix this?

2 Answers 2

29

You need to explicitly pass the range, try with:

command! -range PassRange <line1>,<line2>call PrintGivenRange()
2
  • Perfect, thank you! (I will accept your answer as soon as I can) It's weird that the syntax is different inside and outside a function (that might be why I missed the <line1>,<line2> syntax). May 13, 2012 at 15:48
  • Looking at the help text again, I realized that I just didn't understand what "command line range" meant. May 13, 2012 at 16:02
3

If you want use the range of currently selected line in visual mode, you can use the below:

command! -range PassRange '<,'> call PrintGivenRange()
  • '<: the first line of the current selected Visual area in the current buffer.
  • '>: the last line of the current selected Visual area in the current buffer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.