0

I am using the following to map * to search current selection with highlight

set hlsearch
vnoremap * :call VisualSelection('f')<CR>
vnoremap # :call VisualSelection('b')<CR>
function! VisualSelection(direction) range
  let l:saved_reg = @"
  execute "normal! vgvy"
  let l:pattern = escape(@", '\\/.*$^~[]')
  let l:pattern = substitute(l:pattern, "\n$", "", "")

  if a:direction == 'b'
    execute "normal ?" . l:pattern . "\<CR>"
  elseif a:direction == 'gv'
    call CmdLine("vimgrep " . '/'. l:pattern . '/' . ' **/*.')
  elseif a:direction == 'replace'
    call CmdLine("%s" . '/'. l:pattern . '/')
  elseif a:direction == 'f'
    execute "normal /" . l:pattern . "\<CR>"
  endif

  let @/ = l:pattern
  let @" = l:saved_reg
endfunction

However, this script doesn't highlight the search result. When manually input the command in ex command mode: execute "normal /" . l:pattern . "\<CR>", however, I do get highlight.

Please let me know how to enable highlight from the vimrc script as well.

dragonxlwang
  • 462
  • 5
  • 13
  • 2
    The last used search pattern (`@/`) and `hlsearch` are reset after a function is completed (see [`:help function-search-undo`](http://vimhelp.appspot.com/eval.txt.html#function%2dsearch%2dundo)) so I suspect this is it. In fact, you're manually resetting `@/` − hlsearch highlights the current search pattern. You probably want to use `matchadd()` − my [powersearch.vim plugin](https://bitbucket.org/Carpetsmoker/powersearch.vim/src/6a42dd1e61cbdaae9c80216e8ddc0ed174c8293b/plugin/powersearch.vim?fileviewer=file-view-default#powersearch.vim-127) does that. – Martin Tournoij Mar 28 '16 at 20:24
  • Thanks! I think you are right! – dragonxlwang Mar 28 '16 at 20:33

0 Answers0