Get current line in visual mode from function

I have a simple vim script that takes a visual block of text and saves it as a list. The problem with the function VtoList()is that it is executed after the cursor returns to the beginning of the visual block, and not before it. Because of this, I have no way to get the line where the visual block ends.

nn <F2> :call VtoList()<CR>

func! VtoList()
    firstline = line('v')  " Gets the line where the visual block begins
    lastline = line('.')   " Gets the current line, but not the one I want.
    mylist = getline(firstline, lastline)
    echo mylist
endfunc

The problem is line('.'). It should return the current cursor line, but before calling the function, the cursor has already returned to the beginning of the visual block. This way I get only one row instead of a range of rows.

I put together a solution that sets a mark every time the user clicks Vand sets another character before calling the function.

nnoremap V mV
nnoremap <F2> mZ:call VtoList()<CR>

, line('v') line('.') line("'V") line("'Z"), , , .

, ?

+3
1

:, <expr>:

function! s:NumSort(a, b)
    return a:a>a:b ? 1 : a:a==a:b ? 0 : -1
endfunction
func! VtoList()
    let [firstline, lastline]=sort([line('v'), line('.')], 's:NumSort')
    let mylist = getline(firstline, lastline)
    echo mylist
    return ""
endfunc
vnoremap <expr> <F2> VtoList()

: let ( ), sort (, , ), vnoremap (line("v") ), return (expr , , ).

    if mode()=~#"^[vV\<C-v>]"
        let [firstline, lastline]=sort([line('v'), line('.')], 's:NumSort')
    else
        let [firstline, lastline]=sort([line("'<"), line("'>")], 's:NumSort')
    endif

, , , : , . line("v") .

: vnoremap {lhs} : , '<,'>. , range let [firstline, lastline]=sort([a:firstline, a:lastline], 's:NumSort'). :.

+4

Source: https://habr.com/ru/post/1778162/


All Articles