Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing command-range to a function

Tags:

vim

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?

like image 417
Jeff Tratner Avatar asked May 13 '12 15:05

Jeff Tratner


2 Answers

You need to explicitly pass the range, try with:

command! -range PassRange <line1>,<line2>call PrintGivenRange()
like image 106
Raimondi Avatar answered Oct 22 '22 03:10

Raimondi


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.
like image 35
HanleyLee Avatar answered Oct 22 '22 04:10

HanleyLee