Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping arrow keys when running tmux

Tags:

vim

tmux

These key mappings stop working in tmux. In my .vimrc, I have:

nmap <Space> i
map <C-Down> <C-w>j
map <C-Up> <C-w>k
map <C-Left> <C-w>h
map <C-Right> <C-w>l

When I run :map, I see:

   <C-Right>     <C-W>l
   <C-Left>      <C-W>h
   <C-Up>        <C-W>k
   <C-Down>      <C-W>j

Yet when I hit control and an arrow key at the same time, it behaves as if no keybinding was set.

like image 681
Rose Perrone Avatar asked Mar 16 '13 04:03

Rose Perrone


1 Answers

Vim knows that xterm-like terminals (identified by TERM starting with xterm, or a particular response to the t_RV sequence, if it is defined) support extended sequences for certain modified keys, but it does not assume this for screen TERMs (which you should be using under tmux).

You can, however tell Vim about these sequences and enable them if TMUX is present, and TERM starts with screen (the first lines enable (better) mouse support under tmux, which you might also like):

if &term =~ '^screen' && exists('$TMUX')
    set mouse+=a
    " tmux knows the extended mouse mode
    set ttymouse=xterm2
    " tmux will send xterm-style keys when xterm-keys is on
    execute "set <xUp>=\e[1;*A"
    execute "set <xDown>=\e[1;*B"
    execute "set <xRight>=\e[1;*C"
    execute "set <xLeft>=\e[1;*D"
    execute "set <xHome>=\e[1;*H"
    execute "set <xEnd>=\e[1;*F"
    execute "set <Insert>=\e[2;*~"
    execute "set <Delete>=\e[3;*~"
    execute "set <PageUp>=\e[5;*~"
    execute "set <PageDown>=\e[6;*~"
    execute "set <xF1>=\e[1;*P"
    execute "set <xF2>=\e[1;*Q"
    execute "set <xF3>=\e[1;*R"
    execute "set <xF4>=\e[1;*S"
    execute "set <F5>=\e[15;*~"
    execute "set <F6>=\e[17;*~"
    execute "set <F7>=\e[18;*~"
    execute "set <F8>=\e[19;*~"
    execute "set <F9>=\e[20;*~"
    execute "set <F10>=\e[21;*~"
    execute "set <F11>=\e[23;*~"
    execute "set <F12>=\e[24;*~"
endif

As the comment indicates, you also need to have the window’s xterm-keys option enabled. You can do this for all your windows like this (in your ~/.tmux.conf):

set-option -gw xterm-keys on

(Remember that changes to ~/.tmux.conf are not automatically loaded. To be effective, you will need to run this command manually (in a tmux shell command, or at a Prefix : prompt), or re-load your configuration file with source ~/.tmux.conf (in a tmux shell command, or at a Prefix : prompt), or restart your server (exit all your sessions and restart tmux)).

like image 112
Chris Johnsen Avatar answered Oct 12 '22 22:10

Chris Johnsen