Remapping keys in iterm2

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.


Solution 1:

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.

Solution 2:

I'd suggest to install Key Codes ($0) by Many Tricks and find out the shortcuts for yourself.

For instance if you want to remap the default shortcut for (forward) deleting a charcter – which is Ctrl-D (⌃D) – to be as simple as pressing the forward delete key (), you would…

  1. Open the app and press Ctrl-D

    Key Codes Example

  2. Back in iTerm 2, add the Unicode shortcut in iTerm > Preferences > Keys

    iTerm Send Hex Codes

Note: Don't copy and paste it, just type out the Unicode without spaces.

Solution 3:

The best way that I found was either with sending keycodes (as described by @pattulus or using vim key bindings.

Note on key codes: Actually you cannot make it work by sending the unicode string as described above, you need to send both the modifier and the key to gether in case of Control+D you need to send this as code: 0x840101 0x4 where 0x840101 is the control key modifier and can be obtained through Key Code.

Note on sending as vim sequence: As described in iTerm2 documentation, you can send a key code in vim-bindings format such as \<C-d> for sending Control+D (note that \ is important).

I personally prefer vim key binding because it's more readable and later you will understand what you have done.