How to expand a range in a list in vimscript?

I would like to automatically take a visually selected block of text, for example, 51-100and expand it on 51,52,53,...,99,100.

Is there an easy way to do this in vimscript?

+5
source share
1 answer

Let me suggest the following implementation.

vnoremap <silent> <leader># :<c-u>call ExpandRange()<cr>
function! ExpandRange()
    norm! gvy
    let n = matchlist(@", '\(\d\+\)\s*-\s*\(\d\+\)')[1:2]
    if len(n) != 2 || +n[0] > +n[1]
        return
    end
    exe 'norm! gvc' . join(range(n[0], n[1]), ',')
endfunction

If the range notation guarantees the absence of spaces around numbers, the second operator ExpandRange()can be simplified by using split(),

    let n = split(@", '-')

Note that the text denoting the range is placed in an unnamed register. If it is preferable to leave the register unaffected, change ExpandRange()it to preserve its state in advance and restore it later.

function! ExpandRange()
    let [qr, qt] = [getreg('"'), getregtype('"')]
    norm! gvy
    let n = matchlist(@", '\(\d\+\)\s*-\s*\(\d\+\)')[1:2]
    call setreg('"', qr, qt)
    if len(n) != 2 || +n[0] > +n[1]
        return
    end
    exe 'norm! gv"_c' . join(range(n[0], n[1]), ',')
endfunction
+8
source

All Articles