I need to write a function that returns current visually selected text or <cword> on mapping. Result of this function I give further to cscope find s command. Something like this:

noremap <C-\>s :call <SID>Run_cscope(<SID>get_vselect_or_cword())<CR>

func s:Run_cscope(pattern)
  exe 'cs find s ' . a:pattern

func s:get_vselect_or_cword()
  let vselect = s:get_visual_selection()
  if vselect != ''
    let pattern = vselect
    let pattern = expand("<cword>")
  return pattern

The question is how to write get_visual_selection() function? Another words how to get current visually selected text? I have found some solutions in this question but all of them are not appropriate because get_visual_selection() returns previous visually selected text if nothing selected. I need that it returns '' in this case. It seems that solution should be very easy, but I don't really experienced in vimscript and just not see it.

1 Answer 1


The main problem is that, once you're in a mapping that is :calling a function, you're no longer in visual mode, so there's no such thing as the current visual selection in that case.

A good approach here is to install separate mappings for normal (:nnoremap) and visual (:vnoremap) modes. You can still call the same function from both, just pass an argument so you know whether you're coming from normal mode (in which case you'll want to look at expand("<cword>")) or from visual mode.

When coming from visual mode, it's possible you were in characterwise, linewise or blockwise mode and the selection might need to be handled differently for each case. You can use the visualmode() function to determine which mode you were on (and possibly pass that as the argument in your :vnoremap mapping.)

If you're in characterwise visual mode, you can capture it with a command such as:

execute "normal! `<v`>y"

And then access the contents in Vimscript from register @@. (You might want to save and restore this register at the start/end of your function.)

For an excellent tutorial explaining all these concepts, see Case Study: Grep Operator from the amazing Learn Vimscript the Hard Way by Steve Losh. (Seriously, if you haven't read it yet, do so, it's really awesome!)

  • 1
    Thanks a lot for answer. It is very useful. I read Learn Vimscript the Hard Way periodically. Feb 25, 2019 at 14:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.