Select relative range, ignoring invalid line numbers

268 views Asked by At

I was wondering if there was a syntax for specifying a range of relative lines in vim/ex that does not give 'invalid range' and instead gets as many lines as it can.

2

There are 2 answers

0
Ingo Karkat On BEST ANSWER

There is no built-in way, but you can resolve the relative ranges into absolute line numbers yourself, and then limit the range to the available lines with :help min() and :help max(). So, for example, the following relative range:

:.-5,.+5 print

is equivalent to this:

:execute (line('.') - 5) . ',' . (line('.') + 5) 'print'

would be converted into this:

:execute max([1, (line('.') - 5)]) . ',' . min([line('$'), (line('.') + 5)]) 'print'
0
Ingo Karkat On

My CmdlineSpecialEdits plugin has (among many others) a CTRL-G + mapping that changes relative ranges like .-5,.+5 to absolute line numbers and vice versa. It also corrects addressing out of bounds (<= 0 and larger than the last line number) and backwards ranges.