Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim: keep cursor position when switching mode

Tags:

vim

I'm trying to remap the F1 key to remove search highlighting. This is simple in normal mode:

nmap <F1> :noh<CR>

but in insert mode its a little more tricky. I can do

imap <F1> <ESC>:noh<CR>i

but that causes the cursor to move backward one slot. A minor annoyance, but still an annoyance. I've tried adding a <RIGHT>, but if I do that before the i it will shift to the next line if I'm at the end of the current one, and if I do it after the i it will shift to the second character if I'm at the beginning of the line.

Is there a way to make it do what I want? Really all I want is for the F1 key to remove search highlighting in all modes. Don't much care how that happens so it there's a better solution, let me know.

like image 485
ewok Avatar asked Nov 21 '25 06:11

ewok


1 Answers

Avoid to use <esc> if you don't want your cursor to move. Use <c-o> instead.

" NB: this mapping doesn't remove, but toggles search highlighting,
" which is often much more useful

" Normal Mode
nnoremap <silent> <F8> :set hlsearch!<bar>set hlsearch?<CR>
" Insert Mode
imap     <silent> <F8> <c-o><F8>
" (strict?) Visual Mode (i.e Select Mode is excluded)
xmap     <silent> <F8> <c-\><c-n><F8>gv
" Select Mode
smap     <silent> <F8> <c-\><c-n><F8>gv<c-g>
like image 76
Luc Hermitte Avatar answered Nov 24 '25 03:11

Luc Hermitte