How do you invoke a function on a bunch of lines selected via Ctrl-v?
Question: I am selecting some text via Ctrl-v (visual mode). Then I type \s to align
those lines and sort them like so:

    
    
    "Strip trailing space
     :map <Leader>S :1,$ s/\s\+$//g<CR>
    :imap <Leader>S :1,$ s/\s\+$//g<CR>
    

How do I pass all the selected lines to Sort(). I thought the
**vim.current.range** object might do it but that didn't work out. Currently
the Sort() function reads text 1 line at a time via cr[0]. What I need to do
is store the split lines in a matrix, compute the required length/column and
print them out into the buffer.

    
    
    function! Sort()
    python << EOF
    import vim
    cr = vim.current.range
    line = cr[0]
    line = line.split()
    fmt_str = ['%8s' for word in line]
    fmt_str = ' '.join(fmt_str)
    
    line = tuple([word for word in line])
    print(fmt_str)
    cr[0]= fmt_str % line
    EOF
    endfunction
    
    "Sort and align
    :map <Leader>s :call Sort()<CR>
    


Answer: When you want a mapping to work on the visual selection, you need to use
`:vnoremap`. An Ex command (like `:call`) will then automatically have the
visual range `'<,'>` prepended. An ordinary function would then be invoked
once per line, but you can define a special kind of function (cp. `:help
function-range-example`) that handles the range itself.

Since you seem to want to use Python, I'd just drop the prepended range via
`<C-u>` and access the selection's bounds via the `<` and `>` marks, then
access and modify the lines via `vim.current.buffer[lnum]`:

    
    
    :vnoremap <Leader>s :<C-u>call Sort()<CR>
    function! Sort()
        ...
        start = vim.current.buffer.mark('<')[0]
        end = vim.current.buffer.mark('>')[0]
    

