Is it safe to map a key to a custom escape sequence in iTerm


There are some keys I use in MacVim that terminal Vim doesn't recognize. For example, Ctrl-Enter, Shift-Enter, Ctrl-Space, Shift-Space, Ctrl-Backspace.

I'm using iTerm2, which lets you map keyboard shortcuts to send escape sequences. It seems like I could use this to make my desired key mappings work in the terminal. Something like,


Ctrl-Space: Send ^[[123;456ABC


set <F13>=^[[123;456ABC
map <F13> <S-Space>

noremap <S-Space> mzO<Esc>j`z

I'm not sure this will work, but I'm also wondering what I should be aware of before I start creating custom escape sequences willy-nilly. It seems like it could cause problems…

Best Answer

Between these 2 pages (below) I figured it out:

You stay "safe" by using the key codes for unused Function keys. In iTerm2, I created "keyboard shortcuts" that map the desired key-combos to the escape sequences for Function keys F13 through F16. Then, in my vimrc, I set Vim's keycodes appropriately, mapped the desired key-combos to the right Function keys, then mapped the same key-combos to whatever I want. I'm not sure I fully understand the direction things are flowing in, but it all gets linked up and works. Here's the relevant portion of my vimrc:

" use some unused function key codes to
" make special key combos work in terminal
set  <F13>=O2P
map  <F13> <C-CR>
map! <F13> <C-CR>

set  <F14>=O2Q
map  <F14> <S-CR>
map! <F14> <S-CR>

set  <F15>=O2R
map  <F15> <C-Space>
map! <F15> <C-Space>

set  <F16>=O2S
map  <F16> <S-Space>
map! <F16> <S-Space>

" open above / below current line
inoremap <S-CR> <C-O>O
inoremap <C-CR> <C-O>o

" insert above / below current line
noremap <S-Space> mzO<Esc>j`z
noremap <C-Space> mzo<Esc>k`z