C-Left and C-Right
Control sequences are somehow, in 2013, something that don't really quite work properly yet. C-Left
and C-Right
(control-left-arrow & control-right-arrow) are common idioms in OSX and Windows for skipping back/forward one word. In control-sequence land, C-Left
maps to ^[5D
and C-Right
to ^[5C
, which is generally programmed to Do The Right Thing.
However, on OSX, where you have an embarrassment of modifier keys and a bucking of traditional norms, the option key is used for this behavior instead. Prior to OSX 10.7, these sent ^[5D
and ^[5C
to the terminal, which, if you were using bash, unhelpfully printed a D or a C. After 10.7, these were changed to the sequences ^[b
and ^[f
, which are emacs control sequences which bash understands as meaning backward-word and forward-word.
Unfortunately, Vim doesn't quite see things the same way. Although some emacs-mode editor escapes work on most Vim configurations in insert mode (like C-w
for delete-back-word),
So, how can you get C-Left
and C-Right
to behave consistently in your OSX terminal, and in VIM, and in screen?
The best I could come up with was to first change them both to their traditional escapes; \0335D
and \0335C
(where \033
is the ESC key) for option-cursor-left and option-cursor-right in the OSX terminal keyboard escapes preferences.
From here, you can create the keymappings for those escapes necessary to work as expected in bash and Vim. For bash, I added these bindings to my ~/.bashrc:
bind '"\e[5C": forward-word'
bind '"\e[5D": backward-word'
# a commenter on the internet recommended these additional escapes
bind '"\e[1;5C": forward-word'
bind '"\e[1;5D": backward-word'
Finally, I mapped these escape sequences in Vim to the <C-Left>
and <C-Right>
functions, which work as expected, in my ~/.vimrc
map <ESC>[5D <C-Left>
map <ESC>[5C <C-Right>
map! <ESC>[5D <C-left>
map! <ESC>[5C <C-Right>
This makes option-left and option-right work across bash and vim, both in and outside of screen.
A quick note about these mappings, since it generally goes completely undiscussed, and people just paste this stuff into their vimrc without understanding it: key mapping in Vim is mode-specific; that is, you can map keys to do different things in different modes. map
uses the mapmode nvo
, which stands for normal, visual, and operator-pending modes, and map!
uses the mapmode ic
which stands for insert and command modes. For some explanations on what each of these modes correspond to, check out :help :map-modes
.
One last caveat is that, for me, Vim treats <C-Left>
and <C-Right>
differently in normal mode compared to insert mode. In normal mode, they correspond to the B and W movement keys, respectively, whereas in insert mode they seem to correspond to b and w.