Cursor Keys in Vim: You Mac’ing Me Crazy!

Kevin McFadden, Former Viget

Article Category: #Code

Posted on

Switch from PHP to Ruby on Rails? Check!

Switch from Windows to OS X? Check!

Switch from Vim to TextMate? Check! Well, most of the time.

Vim is useful in many situations, particularly for quick edits (especially as root), and editing files on a remote server. One annoyance I've had during my nine months with a Mac Book Pro is cursor keys in Vim ringing the bell in both insert or command mode instead of changing lines. Upgrading to version 7 via MacPorts yielded the same results. The cursor keys worked after switching my TERM to VT220 from rxvt! The downside was syntax highlighting stopped working.

Luckily, adding VT220 to my Google search parameters turned up a reference to vt100-cursor-keys in the Vim documentation. Add the following code to your .vimrc file to fix the problem:

:set notimeout          " don't timeout on mappings
:set ttimeout           " do timeout on terminal key codes
:set timeoutlen=100     " timeout after 100 msec

But, this only works on your computer since the settings do not propagate when you ssh to another server. A better solution is to change the default value for TERM to either linux or dtterm since the TERM value will be picked up on the remote server. In this day and age, I would bet most servers support both these terminal types.

The easiest way to set this value across all terminal instances is to update /etc/bashrc and restart the terminal session. OS X already has the framework for you to support this change, just add the export line as listed below.

case "$TERM" in
xterm*|rxvt*)
    export TERM=linux # ADD THIS LINE!
    PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD/$HOME/~}\007"'
    ;;
*)
    ;;
esac

This will cause terminal instances reporting itself as rxvt or xterm to use linux instead.

Let me know if you find instances where this does not work or know why Apple decided to default to a TERM that restricts normal functionality.

Related Articles