0

I would not have thought that this would be hard to do, but it's not working. What I'm trying to do is enable the search highlight from script. I've tried the following:

function! g:TestFunc()
    let @/ ="testtext"
    set hlsearch
endfunction

nnoremap <space> :call g:TestFunc()<cr>

Which doesn't work. That is, hitting space in front of some text with "testtext" in it does not highlight the text. The user still has to hit 'n'.

I also tried adding exec 'normal! n' to the end of the function but that also didn't work. Even feedkeys('n') fails.

4

The function works as expected if hlsearch is unset before calling it. It appears that setting it in the function has no effect if it's already set. You can work around this by setting nohlsearch in your mapping:

nnoremap <space> :set nohlsearch\|:call g:TestFunc()<cr>

If your goal is simply to highlight certain patterns, and you don't specifically need to use the hlsearch mechanism, you may want to look into using the match command instead. It accomplishes much the same thing more cleanly.

  • that match command is exactly what I was looking for, cheers! – Steve Vermeulen Apr 5 '13 at 2:49
1

You cannot set the last used search pattern and highlighting from within a function, see :help function-search-undo. Instead, move the :set hlsearch directly into your mapping.

0
function! wordsubstitute#run()
    execute "normal! gv\"ay"
    let @/ = @a
    "set nohlsearch
    let s:search_cmd = "normal! /".@/."/\<CR>"
    execute s:search_cmd."N"
    "set hlsearch
endfunction

Instead of using normal! nN, write nN in the mapping command:

vnoremap [g/ :<c-u>call wordsubstitute#run()<CR>nN

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.