MikeTheTall
MikeTheTall

Reputation: 3583

VIM: Vimscript to get selection in "visual insert" mode (aka "selection mode")?

I'm looking to rebind a key to search for the text selected by the selection when I'm in "visual insert" mode (aka "selection mode"). I'm using this mode because that's what happens when you include the mswin.vim file.

I've found a ton of stuff which seems to almost work, such as

Search for selection in vim

but these all seem to apply to the plan visual mode, rather than the visual insert mode. As near as I can tell when one is operating in visual insert mode typing anything replaces the selection with what one just typed which I think is interfering with the vimscript snippets that I find here and there.

Upvotes: 0

Views: 417

Answers (1)

romainl
romainl

Reputation: 196586

That problem, and many others you will have, is caused by mswin.vim. Get rid of that garbage and enjoy the unadulterated power of Vim.

Anyway…

When in select mode, you can press <C-o> to temporarily switch to visual mode so it is possible to create a select mode mapping that:

  • switches to visual mode,
  • yanks the selected text,
  • performs the search.

Something like this:

:snoremap * <C-o>"zy/<C-r>z<CR>
:snoremap # <C-o>"zy?<C-r>z<CR>

which could even be expanded to put you in select mode on every match:

:snoremap * <C-o>"zy/<C-r>z<CR>gn<C-g>
:snoremap # <C-o>"zy?<C-r>z<CR>gn<C-g>

Breakdown:

snoremap     " non-recursive select mode mapping
*            " the key you want to press
<C-o>        " switch temporarily to visual mode
"zy          " yank the selection in register z (could be any other a-z register or ")
/<C-r>z<CR>  " search forward for the content of register z
gn           " visually select the match
<C-g>        " go back to select mode

Note that gn requires a recent Vim.

Upvotes: 3

Related Questions