My problem on this gif:

vim incremental search, theme Gotham, macOS, term

I am in one place, searching for meta, I do not want to loose my current search highlighting (yes I know that I can restore it later in / menu). I found what I need - without pressing Enter. I want to stay here, without autoscrolling back to my original position.

  • what's wrong with pressing Enter after you found what you were looking for and finished your search input?
    – Lusk116
    Commented Mar 1, 2019 at 8:02
  • I do not want to loose my current search highlighting. Commented Mar 1, 2019 at 8:11

2 Answers 2


I don't think that this is possible in Vim, but I'm ready to be surprised.

The only idea I have is to create a mapping to set the last search to the next to last search. So you hit <Enter> and then use the mapping to reset your search highlighting.

nnoremap _ps :let @/=histget('/',-2)<CR>

If you want to drop the last search entirely, you could define the mapping as

nnoremap _ps :call histdel('/',-1)\|let @/=histget('/',-1)<CR>

You can use this mapping & function to do this:

function! KeepCursorEsc() abort
  let g:search_pos = getcurpos()
  return "\<C-C>:call setpos('.', g:search_pos)\<CR>"

cnoremap <expr> <silent> <Esc> KeepCursorEsc()

How it works

We can't use an regular cmap because we need to run code while the search is still active. Instead we use an expression mapping, which allows us to run a function by evaluating it as an expression.

The function first reads the cursor position with getcurpos() and then returns a string which is used as the rhs of the mapping.

This rhs cancels the search with <C-C> (<Esc> used in a cmap runs the search command instead of cancelling it) and then restores the cursor position to what it was when the mapping was invoked by calling setpos().

N.B. Note that the function will also be called when you press Esc while typing a : command. We should really avoid this by checking the type of the command-line with getcmdtype(), but for simplicity, this answer does not do so: when you're typing a : command the cursor will be in the same position anyway, so the function won't move it unexpectedly!

  • 2
    We had very similar ideas. Although I used a self clearing CmdlineLeave event to restore the position Commented Mar 1, 2019 at 18:08
  • @PeterRincker Nice! That seems like a cleaner way of doing it than what I’m doing.
    – Rich
    Commented Mar 1, 2019 at 19:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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