I have jk remapped to <Esc> in insert mode and for some reason my brain always want's to exit a search by typing jk. I would like to remap jk to <CR> when performing a search. I.e typing /searchjk will put me in normal mode with the cursor over the next occurrence of 'search'. Is there a special mapping mode for search?

1 Answer 1


You can use :cnoremap, which works for search / but also for Ex commands, that you enter with :. See :help :map-modes for more information on the map modes available.

(To be exact, there are a few more cases where the command-line mappings apply, such as the input() function, or entering an expression for the expression register with <C-R>= from Insert mode, etc.)

If using this mapping for both modes is acceptable to you, then the following should work:

cnoremap jk <CR>

If you want to cover only search mode, then you can use the getcmdtype() function to only expand the mapping in that case. Use an <expr> mapping to evaluate the function.

cnoremap <expr> jk getcmdtype() =~ '^[/?]$' ? '<CR>' : 'jk'

We're using a =~ regular expression match to cover both / for a forward search and a ? for a backward search.

Note that the mapping acts on all the command-line modes (including an Ex command, input() box, expression register), just it expands back to jk in the cases where it's not in a search context. In particular, this will make the j delay when typing it in a command (Vim will wait for the next character to see whether to trigger the mapping or not.) You can possibly improve on this by adding an <expr> mapping for k alone, then checking whether it's preceded by a j (use getcmdline() and getcmdpos()) and in that case producing a sequence that will erase the j (with a backspace) and produce the <CR> that will execute the search. It's doable, but quite some work...

  • 1
    Thanks! This is exactly what I wanted :) Having the mapping for k is a really neat idea. Maybe I'll try something similar for insert mode next time I'm in the mood for some tinkering. Commented Nov 17, 2020 at 19:49

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.