Search code examples
vimvim-plugin

Function is called several times in vimscript


I want to call a function when user presses qq in visual mode, so I wrote the following code:

function! FindSelectionMeaning()
  echo "FindSelectionMeaning"
endfunction

vnoremap <silent> qq :call FindSelectionMeaning()<CR>

The function is called but I have the following questions:

  • Why does FindSelectionMeaning getting called once for each of the selected lines? I thought that it should be called only once
  • Is there any way to call script-related function via vnoremap (in this case s:FindSelectionMeaning instead of FindSelectionMeaning)?

Solution

  • Your command was called several times (in fact the number of selected lines ), because, when you press : in visual mode, vim will automatically add range '<,'>, it leads to for each selected line execute the later inputted command. If your function want to be called only once, you can change your mapping like:

    vnoremap <silent> qq :<c-u>call FindSelectionMeaning()<CR>
    

    the <c-u> is gonna remove the range info after the :

    In fact, you can get selected text in this way, I think it is easier, keep the <c-u> mapping, and change your function:

    function! FindSelectionMeaning ()
      try
        let v_save = @v
        normal! gv"vy
        return @v
      finally
        let @v = v_save
      endtry
    endfunction
    

    This function returns selected text.