highlighting search results from within a function

19 views
Skip to first unread message

richard emberson

unread,
Jun 21, 2012, 4:59:28 PM6/21/12
to vim...@googlegroups.com
I've got a function:

function! XXXX()
execute '/this'
endfunction

and when I run it:

:call XXXX()

my cursor is positioned at the first 'this' but the text
is not highlighted (nor is the text of any of the other 'this'
highlighted).

If I go into search history, the search is there and if I
execute the historical search, the 'this's all highlight.

So, my question is: how can I do a search from within a
function and have the search results highlighted?

Thanks

Richard
--
Quis custodiet ipsos custodes

Tim Chase

unread,
Jun 21, 2012, 5:18:01 PM6/21/12
to vim...@googlegroups.com, richard emberson
On 06/21/12 15:59, richard emberson wrote:
> I've got a function:
>
> function! XXXX()
> execute '/this'
> endfunction
>
> and when I run it:
>
> :call XXXX()
>
> my cursor is positioned at the first 'this' but the text
> is not highlighted (nor is the text of any of the other 'this'
> highlighted).
>
> If I go into search history, the search is there and if I
> execute the historical search, the 'this's all highlight.
>
> So, my question is: how can I do a search from within a
> function and have the search results highlighted?

To address your immediate issue, I suspect you also need to make
sure that highlight-search is set on

function! XX()
/this
set hls
endfunction

As a side-note, as you can see in my example, you can directly issue
the search without wrapping it in an exec call.

Alternatively, you might investigate using the :match command
something like

function XX()
match Error /this/
endfunction

where "Error" is the highlighting group you want to use for
colori[zs]ation purposes.

-tim



Gary Johnson

unread,
Jun 21, 2012, 5:44:36 PM6/21/12
to vim...@googlegroups.com
On 2012-06-21, richard emberson wrote:
> I've got a function:
>
> function! XXXX()
> execute '/this'
> endfunction
>
> and when I run it:
>
> :call XXXX()
>
> my cursor is positioned at the first 'this' but the text
> is not highlighted (nor is the text of any of the other 'this'
> highlighted).

The problem is that the search register is saved before a function
call and restored after, so when your function returns the search
register no longer contains "this". See ":help
function-search-undo".

One solution would be

function! XXXX()
execute '/this'
return @/
endfunction

and to use the following instead of ":call XXXX()".

:let @/ = XXXX()

HTH,
Gary

richard emberson

unread,
Jun 21, 2012, 6:14:03 PM6/21/12
to vim...@googlegroups.com
Thanks, that did the trick.
Reply all
Reply to author
Forward
0 new messages