Vimscript: Get text for selecting visual mode when matching

So, I'm trying to have a binding that runs lvimgrep in the current selected text.

  fun! s:get_visual_selection() let l=getline("'<") let [line1,col1] = getpos("'<")[1:2] let [line2,col2] = getpos("'>")[1:2] return l[col1 - 1: col2 - 1] endfun vnoremap <expr> <script><leader>* ":lvimgrep /" . <SID>get_visual_selection() . "/j **/*." . expand("%:e") . " \|lopen" 

Function from the comment to the question: How to get visually selected text in VimScript

The fact is that it behaves very strangely: in most cases, the text returned by the function does not correspond to the visual selection, and most often it is the text of the last visual selection, and not the current one.

Tons of messages have passed around getting visual highlight text in vimscript, but can't make it work.

I have also tried https://stackoverflow.com/a/167455/16145/ ... without success (copy selection to register) - get an error message when called from my binding.

+4
source share
1 answer

The problem is that the labels '<,'> not set until after the current selection (either by executing a command on it, or via <Esc> ). Here, your conversion of the expression complicates the addition of <Esc> to initially leave the visual mode, so it’s easier to insert the expression with :help i_CTRL-R and expression case = :

 :vnoremap <script> <leader>* <Esc>:lvimgrep /<CR><CR>=<SID>get_visual_selection()<CR>/j **/*.<CR><CR>=expand("%:e")<CR>\|lopen 

If you don't mind resetting the default case, you can also simply pull out the selection:

 :vnoremap <leader>* y:lvimgrep /<CR><CR>"/j **/*.<CR><CR>=expand("%:e")<CR>\|lopen 
+4
source

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


All Articles