Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim search and highlighting control from a script

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.

like image 763
Herbert Sitz Avatar asked Sep 22 '10 01:09

Herbert Sitz


2 Answers

run:

let @/ = a:searchStr

from inside your function then run

normal n

from outside your function (inside it does nothing) eg.

command -nargs=* Hs call MySearch() | normal n

or you can use:

set hlsearch

instead of normal n if you don't want the cursor to move

(I cannot work out another way of doing this without having something outside the function.)

like image 79
pev.hall Avatar answered Sep 30 '22 16:09

pev.hall


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.

like image 38
too much php Avatar answered Sep 30 '22 16:09

too much php