Making shift-space send page up and other key mappings in iTerm2

A common problem when I am paging through less output is that, while the space key will go down a page, the shift-space shortcut does not go up. The underlying reason is terminals are strings of text and date back decades and many key combinations are archaic sequences.

Shift-space is is one of these cases. While the space key inserts visible text, the shift-space variant doesn’t have a unique character. This requires hoping particular app can handle the sequence CSI 32;2 u (which may look like ^[[32;2u; this is part of a proposal known as CSI u), or changing the key map in the terminal. I went for the latter.

I use iTerm2, which is stellar for many reason. Its key mapping control can do what we want here, and looks like so:

iTerm2 key mappings, mapping shift-space to sending the escape sequence.

You can figure out what escape sequence to send for a particular existing key combination using your shell by entering a key-reading mode and then the shortcut.

For fish, this looks like:

$ fish_key_reader
Press a key: <page up>
              hex:   1B  char: \c[  (or \e)
(  0.037 ms)  hex:   5B  char: [
(  0.018 ms)  hex:   35  char: 5
(  0.020 ms)  hex:   7E  char: ~
bind -k ppage 'do something'
bind \e\[5~ 'do something'

For bash or zsh, this looks like:

$ <ctrl-v><page up>
# transitions to
$ ^[[5~

Both of these tell us that the escape sequence is CSI 5 ~, so that’s the sequence we want to tell iTerm to send. This looks like ESC+[5~ in its UI.

iTerm2 also has Dynamic Profiles, which allows text-based management of its profile settings; this lets me keep changes intentional and preserves the history in git. Adding this same keymap there looks something like this (with other content elided):

{
  "Profiles": [
    {
      "Guid": "22b93c98-1383-440b-8224-d1c3f653a850",
      "Name": "Profile Name",
      "Keyboard Map": {
        "0x20-0x20000-0x31": {
          "Version": 1,
          "Action": 10,
          "Text": "[5~",
          "Label": "PageUp for Shift-Space"
        }
      }
    }
  ]
}