Fix for Vi’s broken arrow key support in iTerm

I originally posted this at isaacschlueter.com on Tuesday, April 17th, 2007. I’ve incorporated the info from the comments into the main post. Special thanks to: radius, benstiglitz, and Higgaion for helping to provide more information.

So, I got turned on to iTerm, a prettier and more user-friendly alternative to Apple’s native Terminal.app.

However, for some reason, I got the following error message whenever I tried to use arrow keys in Vi:

Usage: [[

The problem is that Vi is faithfully responding to the TERM variable that iTerm is sending. (I’m not sure why Terminal.app and PuTTY don’t suffer from this issue, but c’est la vie.) So, I thought, you should keep the terminal setting in iTerm to xterm-color, since this is great for most things, but then add this setting to your .exrc file to tame Vi:

set term=linux

I wasn’t sure why that fixed it, but it did. set term=cons25 was another fix that I found, but it seemed to break when I had line numbers turned on, because all tab characters are turned into backticks (`).

Of course, that’ll break if you use a different terminal setting on another program, so Higgaion suggested putting this into your .vimrc or .exrc instead:

if $TERM_PROGRAM == 'iTerm.app'
set term=linux
endif

However, the same problem occurs when using the more and less commands—the arrow keys are broken, but the hjkl keys worked just like they do in Vi. Since there’s no .morerc or .lessrc to set the term variable, I was dismayed.

According to benstiglitz:

The default termcap on Mac OS X specifies that applications should enter application-specific cursor mode when capturing the display. iTerm is faithfully sending the application-mode sequences, but most terminal emulators just ignore the app-mode escape sequences and send normal key sequences instead.

So, this is being determined by iTerm’s behavior, so should be fixable in iTerm’s settings. I poked around in iTerm’s menus. Under Bookmarks > Manage Profiles > Terminal Profiles > Default, you can set the default terminal type to linux. Then you can enjoy proper arrow key support in every situation under iTerm, without futzing with config files in your home directory. Incidentally, it seems that linux has the same color support as xterm-color, so nothing is lost.