Reputation: 337
I want to write a function in vimscript that echoes the selected text or, if no text is selected, the entire buffer.
How can I distinguish between these two cases?
Upvotes: 3
Views: 716
Reputation: 3064
Could use line("'<") > 0
to check whether the selection mark exists.
Upvotes: 0
Reputation: 161694
I write a function to get visually selected text
.
I hope it can help you.
function! GetSelected()
" save reg
let reg = '"'
let reg_save = getreg(reg)
let reg_type = getregtype(reg)
" yank visually selected text
silent exe 'norm! gv"'.reg.'y'
let value = getreg(reg)
" restore reg
call setreg(reg,reg_save,reg_type)
return value
endfun
" viusal map
vnoremap gs :<C-U>echo GetSelected()<CR>
" normal map
nnoremap gs :<C-U>echo join(getline(1, '$'), "\n")<CR>
Upvotes: 1
Reputation: 172590
Define two mappings, an :nmap
using the entire buffer, and a :vmap
for the selected text. Both can invoke the same function, passing an isVisual
boolean flag or a mode
argument.
Anything else (custom commands, direct function :call
) would require an explicit hint, because in order to invoke them, visual mode as already been left (for command-line mode). You also cannot use the '<,'>
marks for the detection, because they will keep the last selection even after it has been removed.
Upvotes: 4