Vim: search and highlight but do not jump

The super star (*) key in Vim will search for the word under the cursor and jump forward to the next match. The user can jump to the next matches with the n key. If hlsearch is enabled, it will also highlight the matches.

I want to be able to press * and get the highlighted matches and be able to navigate the matches using the n key. However, I do not want Vim to jump to the next match when * is pressed, it should remain on the current word. Is there a way to do this?


I would map:

nnoremap * *``

Works exactly like you want, except that it adds a jump in the jump list. To prevent that you need:

nnoremap * :keepjumps normal! mi*`i<CR>

The best solution:

  1. don't add a jump to the jump list
  2. the behavior of the star key is not be changed

so, try the plugin: http://www.vim.org/scripts/script.php?script_id=4335

Much better than:

" a jump adds to the jump list
nnoremap * *``
" I got a dead loop on macvim
nnoremap * :keepjumps normal *``<cr>
" the behavior is changed
nnoremap <silent> <Leader>* :let @/='\<<C-R>=expand("<cword>")<CR>\>'<CR>:set hls<CR>

I haven't seen this one yet:

nmap <silent> * "syiw<Esc>: let @/ = @s<CR>

It's very short and does not involve jumping around which can result in blinking.

Explanation: copy the word under cursor to s register and then set the search register (/) to the content of s register. The search register is not writeable directly, that's why the let is necessary and hence the silent to keep vim's command line clean.


I found this works pretty well, there's no blink and it doesn't need an intermediate register.

nnoremap <silent> * :let @/= '\<' . expand('<cword>') . '\>' <bar> set hls <cr>

Or if you want the g* behavior:

nnoremap <silent> g* :let @/=expand('<cword>') <bar> set hls <cr>

I have the following in my .vimrc, which I think works better than the other alternatives:

" Put word under cursor into search register and highlight
nnoremap <silent> <Leader>* :let @/='\<<C-R>=expand("<cword>")<CR>\>'<CR>:set hls<CR>
vnoremap <silent> <Leader>* :<C-U>
  \let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR>
  \gvy:let @/=substitute(
  \escape(@", '/\.*$^~['), '\_s\+', '\\_s\\+', 'g')<CR>
  \gV:call setreg('"', old_reg, old_regtype)<CR>:set hls<CR>