views:

34

answers:

2

I'm writing a script in which I want to control searches programmatically, and get them highlighted. The search() function results are not highlighted (I think), so using that function is not of use to me.

What I want to do is use the 'normal /' command to search for a variable, but that doesn't seem to be straightforward. I can script the command:

    execute 'normal /' . my_variable . '\<CR>'

(or other variations as suggested in the vim tip here: http://vim.wikia.com/wiki/Using_normal_command_in_a_script_for_searching )

but it doesn't do anything. I can see the correct search term down in the command line after execution of the script line, but focus is in the document, the search register has not been altered, and the cursor has not done any search. (It seems as though the < CR > isn't getting entered, although no error is thrown -- and yes, I have tried using the literal ^M too.)

I can at least control the search register by doing this:

execute 'let @/ ="' . a:term .'"'

and then the obvious thing seems to be to do a:

    normal n

But that 'normal n' doesn't do anything if I run it in a script. Setting the search register does work, if I manually press 'n' after the scrip terminates the search happens (and highlighting appears, since hlsearch is on). I don't even care if the cursor is positioned, I just want the register pattern to be highlighted. But various combinations of 'set hlsearch' in the script don't work either.

I know I could use 'match()', but I want to get it working with regular search highlighting, and I wonder what I'm doing wrong. It must be something simple but I'm not seeing it. Thanks for any help.

+1  A: 

If your script is using functions, then this quote from :help function-search-undo is relevant:

The last used search pattern and the redo command "." will not be changed by the function. This also implies that the effect of :nohlsearch is undone when the function returns.

Vim usually tries to reset the search pattern (and a few other things) when a function ends, often you can get around this by adding the n (next search) to the end of a mapping, or using :map <expr> and having your function return the key sequence to be executed.

too much php
A: 

On closer inspection, it seems \<CR> is not picked up inside single quotes. Try using this instead:

execute 'normal /' . my_variable . "\<CR>"
too much php
Thanks. I'm pretty sure that was first thing I tried, and it didn't work. I think you get at the problem in your other answer where you identify problem with modifying search pattern in a function. All the commands I'm having the problem with are within a function, so I'll check it out to confirm.
Herbert Sitz