Skip to content

Instantly share code, notes, and snippets.

@jeroenjanssens
Last active August 14, 2024 17:26
Show Gist options
  • Save jeroenjanssens/4050c1a328db89d62c6b9459b4544f68 to your computer and use it in GitHub Desktop.
Save jeroenjanssens/4050c1a328db89d62c6b9459b4544f68 to your computer and use it in GitHub Desktop.
Generate iTerm Key Mappings with Python
#!/usr/bin/env python3
import json
import string
prefix_key = "b" # My prefix key in tmux is Ctrl-B
prefix_hex = "02" # The hex code that iTerm sends (corresponds to Ctrl-B)
keys_upper = string.ascii_uppercase + r'!@#$%^&*()_+{}:"|<>?~'
keys_lower = string.ascii_lowercase + r"1234567890-=[];'\,./`"
keys_exclude = "xcvq" # Don't override cut, copy, paste, and quit shortcuts
mod = {"cmd": "100000",
"cmd+ctrl": "140000",
"option": "80000",
}
keys_all = "".join(sorted(set(keys_upper +
keys_lower).difference(keys_exclude)))
mappings = {}
# Cmd+<KEY> becomes Prefix <KEY>
# Cmd+Ctrl+<KEY> becomes Prefix Shift+<KEY>
for send_key in keys_all:
send_hex = send_key.encode("utf-8").hex()
if send_key in keys_upper:
press_key = keys_lower[keys_upper.index(send_key)]
press_mod = mod["cmd+ctrl"] # Command+Ctrl modifier
else:
press_key = send_key
press_mod = mod["cmd"] # Command modifier
press_hex = press_key.encode("utf-8").hex()
mappings[f"0x{press_hex}-0x{press_mod}"] = {
"Version": 1,
"Action": 11, # Corresponds to "Send Hex Codes" action
"Text": f"0x{prefix_hex} 0x{send_hex}", # Hex codes to send
"Label": f"C-{prefix_key} {send_key}" # Nice for debugging
}
# Option+<KEY> becomes Prefix Ctrl+<KEY>
# Generate Option+A through Option+Z
for i, send_key in enumerate(string.ascii_lowercase, start=1):
send_hex = hex(i) # returns 0x01 for a, 0x02 for b, etc.
press_mod = mod["option"] # Option modifier
press_hex = send_key.encode("utf-8").hex()
mappings[f"0x{press_hex}-0x{press_mod}"] = {
"Version": 1,
"Action": 11, # Corresponds to "Send Hex Codes" action
"Text": f"0x{prefix_hex} {send_hex}", # Hex codes to send
"Label": f"C-{prefix_key} C-{send_key}" # Nice for debugging
}
result = {"Key Mappings": mappings}
print(json.dumps(result, indent=4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment