vim: execute normal search with highlight from vimrc

326 Views Asked by At

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.

0

There are 0 best solutions below