Wednesday, February 11, 2015

Re: obtain current visual selection

On Wednesday, February 11, 2015 at 3:26:14 AM UTC-6, Enno wrote:
> Le mardi 10 février 2015 09:22:35 UTC+1, Enno a écrit :
> > Hello,
> >
> > There is a thread on StackOverflow labelled
> >
> > "How to get visually selected text in VimScript"
> >
> > The naive and stable approach would be
> >
> > let old_reg = @v
> > normal! gv"vy
> > let raw_search = @v
> > let @v = old_reg
> > return raw_search
> >
> > but that only works if `set nosecure`. If `set secure` then
> > the functions become involved. I posted my own take at
> >
> > http://stackoverflow.com/questions/1533565/how-to-get-visually-selected-text-in-vimscript/28398359#28398359
> >
> > but it handles neither block-wise selections nor multibyte columns. A function that supports both is for example given at
> >
> > https://github.com/haya14busa/vim-asterisk/blob/4fda3a4d90926512fbb10eda8b7b0491c650eb5e/autoload/asterisk.vim#L163
> >
> > Is there a simple solution at all?
> >
> > Enno
>
> Hello Ben,
>
> The function throws an error E523 that, by :help E523, appears only if &secure.
>
> To reproduce, put
>
> set secure
> fun! grep#GetVis()
> let old_reg = @v
> normal! gv"vy
> let raw_search = @v
> let @v = old_reg
> return raw_search
> endfun
>
> in ~/.vim/autoload/grep.vim
>
> and source
>
> set secure
> xnoremap <expr> * '/' . grep#GetVis() . '<CR>'
>
> Then hitting viw* throws
>
> Error detected while processing function grep#GetVis:
> line 2:
> E523: Not allowed here
>
> instead of searching for the selected text.

Actually, the problem has nothing to do with the 'secure' option. Setting nosecure gives the same result, if I correct your mapping:

xnoremap <expr> * "\<Esc>/".GetVis()."\<CR>"

The problem is not 'secure' but rather the fact that you're using :normal inside an <expr> mapping. :help :map-<expr> says:

> Be very careful about side effects! The expression is evaluated while
> obtaining characters, you may very well make the command dysfunctional.
> For this reason the following is blocked:
> - Changing the buffer text |textlock|.
> - Editing another buffer.
> - The |:normal| command.

This alternate mapping works fine (although it is admittedly not as elegant):

xnoremap * <Esc>/<C-R>=GetVis()<CR><CR>

--
--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

---
You received this message because you are subscribed to the Google Groups "vim_use" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vim_use+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments: