Remapping keys in iterm2

iterm

I'm trying to remap some of the default key combinations in iTerm2, and would like to understand what is going on when I bind keys to "Send Hex Codes".

A previous post helped me get started with remapping the ctrl-a and ctrl-e key combos to cmd-left and cmd-right, respectively, but I would like to remap other key combos as well. (Link to previous Stackoverflow post).

I have a vague understanding that there are hex codes involved, but I am at a point where I can't figure out where to go next to understand what's going on or what to do.

Best Answer

Those hex codes are just sequences of bytes. For example mapping a key combination to 0x66 0x6f 0x6f would make it insert foo. 0xc3 0xa4 would insert ä if you use UTF-8. 0x1b 0x1b 0x5b 0x43 means escape escape [ C.

Some sequences of bytes like ANSI escape sequences and even single bytes like ASCII control characters have special meanings in terminals.

To make ⌘← and ⌘→ go to the beginning and end of line, you can assign them to 0x01 (^A in caret notation) and 0x05 (^E in caret notation):

  • ⌘←: Send Hex Codes: 0x01
  • ⌘→: Send Hex Codes: 0x05

You can make ⌥⌦ delete a word forward by assigning it to \ed:

  • ⌥⌦: Send ^[ d

Changing ⌥← and ⌥→ to \eb and \ef in iTerm's preferences would also change them in programs that don't support readline or emacs-style keybindings. Another option is to add this to ~/.inputrc:

"\e\e[D": backward-word
"\e\e[C": forward-word

You can run read and press key combinations to see what characters they insert. For example ⌥← inserts ^[^[[D by default, where ^[ is escape in caret notation.

See also http://code.google.com/p/iterm2/wiki/Keybindings.