Search code examples
vimex

Select relative range, ignoring invalid line numbers


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.


Solution

  • 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'