Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Vim, how can I make Esc and arrow keys work in insert mode?

Tags:

vim

tmux

Terminals send the arrow keys as sequences which begin with Esc. In Vim, there's an option 'esckeys' which lets keys which begin with Esc work in insert mode. It does this at the expense of the actual Esc key responding immediately, because Vim no longer knows if you're just pressing Esc or beginning to spell an arrow key.

Here's what I'd like to be able to do in insert mode:

  1. Press an arrow key and have the cursor go in that direction, and
  2. Press Esc and leave insert mode immediately.

I've got the beginnings of a solution. Even with :set noesckeys, I can still map a key to <Up> like so:

imap q <Up>

Of course, q is not a good key to make the cursor go up. Instead, I'd like to map my arrow keys my terminal emulator to something that doesn't start with Esc (like some random Unicode characters I'll never type) and then imap those to the directions in Vim.

The problem is this: when I leave Vim, my arrow keys will stop working. Only Vim knows what they mean now.

I'm working inside tmux inside iTerm2. Is there a way to make a binding like this live in only one tmux pane? Or make Vim inform tmux that it should use the crazy arrow key bindings while it's running? Any other ideas?

(Incidentally, I'd be happy to just not use arrow keys in insert mode at all myself, but I pair with people who expect them to work, and I want to be a courteous pair.)

like image 818
Peeja Avatar asked Dec 22 '22 03:12

Peeja


1 Answers

What is your problem exactly? Do your arrow keys work in Vim or not? Do they work in tmux or not?

I've had a problem with arrow keys displaying control characters ([A,[B…) in Vim/tmux once, I solved it by adding

nnoremap <Esc>A <up>
nnoremap <Esc>B <down>
nnoremap <Esc>C <right>
nnoremap <Esc>D <left>
inoremap <Esc>A <up>
inoremap <Esc>B <down>
inoremap <Esc>C <right>
inoremap <Esc>D <left>

to my ~/.vimrc.

like image 92
romainl Avatar answered Dec 23 '22 15:12

romainl