vim - Get the current line in visual mode from a function -


i have simple vim script takes visual block of text , stores list. problem function vtolist() executes after cursor returns start of visual block, not before it. because of this, have no way of getting line visual block ends.

nn <f2> :call vtolist()<cr>  func! vtolist()     firstline = line('v')  " gets line visual block begins     lastline = line('.')   " gets current line, not 1 want.     mylist = getline(firstline, lastline)     echo mylist endfunc 

the problem line('.'). should return current line of cursor, before function called, cursor has returned start of visual block. thus, i'm getting single line instead of range of lines.

i put solution sets mark everytime user hits v , sets mark before function called.

nnoremap v mv nnoremap <f2> mz:call vtolist()<cr> 

the function works fine if substitute line('v') , line('.') line("'v") , line("'z"), want avoid solution if can because conflict user's mappings.

is there way can current line of visual block within function before cursor has returned start of visual block?

don't use :, use <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() 

note other changes: let (you forgot it), sort (line selection starts may after line selection ends), vnoremap (line("v") works in visual mode), return (expr mappings return value executed, don't need it, need side effects). can replace second line with

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

the reason why solution not working when : occurs in mapping, exit visual mode , enter command mode. line("v") works in visual mode.

other note: vnoremap {lhs} : produce command line filled '<,'>. may have added range function definition , use let [firstline, lastline]=sort([a:firstline, a:lastline], 's:numsort'). nevertheless exit visual mode :.


Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -