1

If I am searching for a word inside a file, if I do not hit ENTER after the search pattern, my vi loses the current match and jumps back to where it was.

I have

set hlsearch
set incsearch 

in .vimrc.

Therefore, the moment I start typing word, vi jumps to the first occurrence and highlights that. However, this tricks me into believing that it really jumped there, so almost by instinct, I hit ESC and do whatever I was supposed to do at that point.

But that cancels my search and puts me back to where I was, which I find slightly annoying.

Can I make vi to jump there right away?

I have not yet thought through if this could have other less agreeable consequences... But I am willing to find out if it's possible.

2
  • 1
    Just a note that this is "by design": / is essentially an ex-command, which requires Enter to terminate. If you turn off incsearch the behavior is perhaps more intuitive (Enter to move), though of course incsearch is quite handy, too
    – D. Ben Knoble
    Aug 12 at 13:54
  • Yeah I think I am getting used to incsearch - I just only recently enabled it. Without it, as you are suggesting, the default behavior seems rather transparent and indeed intuitive. Aug 12 at 15:01
1

One possible solution is to enable the x cpoption, which makes <Esc> execute a command (rather than cancel it) when in command-line mode.

set cpoptions+=x

See :help cpo-x and :help c_Esc for more details.

The traadeoff in this approach is that this makes <Esc> execute or confirm in any of the command-line modes, including : (for Ex command-line, for example :q<Esc> will then quit!), also input() and a few more modes.


In theory, you could add a mapping that only handles <Esc> in command-line for searches, with:

cnoremap <expr> <Esc> getcmdtype() =~ '^[/?]$' ? '<Enter>' : '<C-C>'

Unfortunately, that breaks the use of keys whose key sequence starts with an <Esc>, such as arrow keys, in command-line mode. Vim seems to run into this issue whenever you create a mapping for <Esc>, there doesn't seem to be an easy or reliable solution for this problem.

(Note also that this last mapping needs to map to <C-C> for keeping <Esc> behavior in modes other than search, since <Esc> in mappings behaves as if the x cpoption is set, as mentioned in :help c_Esc.)

1
  • 1
    It seems to work for now! I will leave the setting for a while and see how this behaves for my other workflows. Thanks! Aug 11 at 21:52

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.