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
<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?
You can use
:cnoremap, which works for search
/ but also for Ex commands, that you enter with
: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>
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
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...