Skip to content

Instantly share code, notes, and snippets.

@aaossa
Created July 9, 2026 21:28
Show Gist options
  • Select an option

  • Save aaossa/4b82e33c1a99c044f369929994cf4219 to your computer and use it in GitHub Desktop.

Select an option

Save aaossa/4b82e33c1a99c044f369929994cf4219 to your computer and use it in GitHub Desktop.
Python CLI script to lookup for the key combination to type a character (`python lookup.py ~`)
import sys
import ctypes
import ctypes.util
import unicodedata # For pulling official character names and code points
# --- ANSI Escape Codes for Terminal Styling ---
CLR_RECOMMENDED = "\033[1;32m" # Bold Green
CLR_ALT = "\033[36m" # Cyan
CLR_ERROR = "\033[1;31m" # Bold Red
CLR_RESET = "\033[0m" # Reset to default
CLR_BOLD = "\033[1m" # Bold default text
CLR_INFO = "\033[1;35m" # Magenta for Unicode Data
def format_combo(modifiers, key_name, style_color=CLR_ALT):
"""Wraps keys in clean brackets and applies terminal colors dynamically."""
elements = modifiers + [key_name]
styled_elements = [f"[{style_color}{el}{CLR_RESET}]" for el in elements]
return f" {style_color}+{CLR_RESET} ".join(styled_elements)
def format_result_item(item, style_color):
"""Formats either a single shortcut or a multi-step sequence."""
if item["type"] == "single":
return format_combo(item["mods"], item["key"], style_color)
elif item["type"] == "double":
dk_str = format_combo(item["dk_mods"], item["dk_key"], style_color)
base_str = format_combo(item["base_mods"], item["base_key"], style_color)
return f"{dk_str}{CLR_BOLD} then {CLR_RESET}{base_str}"
def get_macos_key_name(layout_ptr, kbd_type, keycode, carbon):
"""Dynamically determines the localized keycap name and handles structural keys."""
special_keys = {
36: 'Return', 48: 'Tab', 49: 'Space', 51: 'Delete', 53: 'Escape',
115: 'Home', 116: 'PageUp', 119: 'End', 121: 'PageDown',
123: '← Left Arrow', 124: '→ Right Arrow', 125: '↓ Down Arrow', 126: '↑ Up Arrow',
# Explicit Numeric Keypad Mapping
65: 'Keypad .', 67: 'Keypad *', 69: 'Keypad +', 71: 'Keypad Clear',
75: 'Keypad /', 76: 'Keypad Enter', 78: 'Keypad -', 81: 'Keypad =',
82: 'Keypad 0', 83: 'Keypad 1', 84: 'Keypad 2', 85: 'Keypad 3',
86: 'Keypad 4', 87: 'Keypad 5', 88: 'Keypad 6', 89: 'Keypad 7',
91: 'Keypad 8', 92: 'Keypad 9'
}
if keycode in special_keys:
return special_keys[keycode]
dead_key_state = ctypes.c_uint32(0)
actual_len = ctypes.c_uint32(0)
buf = (ctypes.c_uint16 * 4)()
res = carbon.UCKeyTranslate(
layout_ptr, keycode, 3, 0, kbd_type, 1,
ctypes.byref(dead_key_state), 4, ctypes.byref(actual_len), buf
)
if res == 0 and actual_len.value > 0:
base_char = "".join(chr(buf[i]) for i in range(actual_len.value)).strip()
if base_char:
return base_char.upper()
return f"Key_{keycode}"
def macos_lookup(target_char):
carbon_path = ctypes.util.find_library('Carbon')
if not carbon_path: return []
carbon = ctypes.cdll.LoadLibrary(carbon_path)
carbon.TISCopyCurrentKeyboardLayoutInputSource.argtypes = []
carbon.TISCopyCurrentKeyboardLayoutInputSource.restype = ctypes.c_void_p
carbon.TISGetInputSourceProperty.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
carbon.TISGetInputSourceProperty.restype = ctypes.c_void_p
carbon.CFDataGetBytePtr.argtypes = [ctypes.c_void_p]
carbon.CFDataGetBytePtr.restype = ctypes.c_void_p
tis_source = carbon.TISCopyCurrentKeyboardLayoutInputSource()
if not tis_source: return []
layout_data_ref = carbon.TISGetInputSourceProperty(tis_source, ctypes.c_void_p.in_dll(carbon, 'kTISPropertyUnicodeKeyLayoutData'))
if not layout_data_ref: return []
layout_ptr = carbon.CFDataGetBytePtr(layout_data_ref)
carbon.LMGetKbdType.argtypes = []
carbon.LMGetKbdType.restype = ctypes.c_uint32
kbd_type = carbon.LMGetKbdType()
carbon.UCKeyTranslate.argtypes = [
ctypes.c_void_p, ctypes.c_uint16, ctypes.c_uint16, ctypes.c_uint32,
ctypes.c_uint32, ctypes.c_uint32, ctypes.POINTER(ctypes.c_uint32),
ctypes.c_uint32, ctypes.POINTER(ctypes.c_uint32), ctypes.POINTER(ctypes.c_uint16)
]
carbon.UCKeyTranslate.restype = ctypes.c_int32
modifier_combos = [(0, []), (2, ["⇧ Shift"]), (8, ["⌥ Option"]), (10, ["⌥ Option", "⇧ Shift"])]
matches = []
# PASS 1: Direct matches
for keycode in range(128):
for mod_state, mod_names in modifier_combos:
dead_key_state = ctypes.c_uint32(0)
actual_len = ctypes.c_uint32(0)
buf = (ctypes.c_uint16 * 4)()
res = carbon.UCKeyTranslate(layout_ptr, keycode, 3, mod_state, kbd_type, 1, ctypes.byref(dead_key_state), 4, ctypes.byref(actual_len), buf)
if res == 0 and actual_len.value > 0:
res_char = "".join(chr(buf[i]) for i in range(actual_len.value))
if res_char == target_char or (target_char in ['^', 'ˆ'] and res_char in ['^', 'ˆ']):
key_name = get_macos_key_name(layout_ptr, kbd_type, keycode, carbon)
item = {"type": "single", "mods": mod_names, "key": key_name}
if item not in matches: matches.append(item)
# PASS 2: Dead key sequences
active_dead_keys = []
for keycode in range(128):
for mod_state, mod_names in modifier_combos:
dead_key_state = ctypes.c_uint32(0)
actual_len = ctypes.c_uint32(0)
buf = (ctypes.c_uint16 * 4)()
carbon.UCKeyTranslate(layout_ptr, keycode, 3, mod_state, kbd_type, 0, ctypes.byref(dead_key_state), 4, ctypes.byref(actual_len), buf)
if dead_key_state.value != 0:
key_name = get_macos_key_name(layout_ptr, kbd_type, keycode, carbon)
active_dead_keys.append((mod_names, key_name, dead_key_state.value))
for dk_mods, dk_key, dk_state_val in active_dead_keys:
for keycode in range(128):
for mod_state, mod_names in modifier_combos:
trail_state = ctypes.c_uint32(dk_state_val)
actual_len = ctypes.c_uint32(0)
buf = (ctypes.c_uint16 * 4)()
res = carbon.UCKeyTranslate(layout_ptr, keycode, 3, mod_state, kbd_type, 0, ctypes.byref(trail_state), 4, ctypes.byref(actual_len), buf)
if res == 0 and actual_len.value > 0:
res_char = "".join(chr(buf[i]) for i in range(actual_len.value))
if res_char == target_char:
normal_state, normal_len, normal_buf = ctypes.c_uint32(0), ctypes.c_uint32(0), (ctypes.c_uint16 * 4)()
carbon.UCKeyTranslate(layout_ptr, keycode, 3, mod_state, kbd_type, 1, ctypes.byref(normal_state), 4, ctypes.byref(normal_len), normal_buf)
if res_char == "".join(chr(normal_buf[i]) for i in range(normal_len.value)): continue
base_key_name = get_macos_key_name(layout_ptr, kbd_type, keycode, carbon)
item = {"type": "double", "dk_mods": dk_mods, "dk_key": dk_key, "base_mods": mod_names, "base_key": base_key_name}
if item not in matches: matches.append(item)
return matches
def windows_lookup(target_char):
vk_scan = ctypes.windll.user32.VkKeyScanW(ord(target_char))
if vk_scan == -1 or vk_scan == 65535: return []
vk = vk_scan & 0xFF
shift_state = (vk_scan >> 8) & 0xFF
modifiers = []
if shift_state & 1: modifiers.append("⇧ Shift")
if shift_state & 2: modifiers.append("Ctrl")
if shift_state & 4: modifiers.append("Alt")
if "Ctrl" in modifiers and "Alt" in modifiers: modifiers = ["AltGr"]
scan_code = ctypes.windll.user32.MapVirtualKeyW(vk, 0)
lparam = scan_code << 16
buf = ctypes.create_unicode_buffer(128)
ctypes.windll.user32.GetKeyNameTextW(lparam, buf, 128)
return [{"type": "single", "mods": modifiers, "key": buf.value.capitalize() if buf.value else chr(vk)}]
def print_unicode_fallback(char):
"""Calculates code points and handles programmatic fallback suggestions."""
try:
char_name = unicodedata.name(char)
except ValueError:
char_name = "UNNAMED UNICODE CHARACTER"
code_int = ord(char)
hex_str = f"{code_int:04X}"
print(f"\n❌ {CLR_ERROR}Character '{char}' is completely absent from your active layout.{CLR_RESET}")
print(f" {CLR_BOLD}Official Name:{CLR_RESET} {CLR_INFO}{char_name}{CLR_RESET}")
print(f" {CLR_BOLD}Code Point:{CLR_RESET} {CLR_INFO}U+{hex_str}{CLR_RESET} (Decimal: {code_int})")
if sys.platform == 'darwin':
print(f"\n{CLR_BOLD}Universal Alternative Typing Paths for macOS:{CLR_RESET}")
print(f" {CLR_RECOMMENDED}Option A: Unicode Hex Input Layout{CLR_RESET}")
print(f" 1. Enable 'Unicode Hex Input' in Settings ➔ Keyboard ➔ Input Sources.")
hex_sequence = " + ".join(f"[{c}]" for c in hex_str)
print(f" 2. Hold {format_combo(['⌥ Option'], '')} and type the hex value: {hex_sequence}")
print(f"\n {CLR_ALT}Option B: System Character Palette{CLR_RESET}")
print(f" Press {format_combo(['⌘ Cmd', '⌃ Ctrl'], 'Space')} and search for: \"{char_name.lower()}\"")
print(f"\n {CLR_ALT}Option C: Text Replacement Macro{CLR_RESET}")
print(f" Create an autocomplete snippet in Settings ➔ Keyboard ➔ Text Replacements (e.g., ',inter' ➔ {char})")
else:
print(f"\n{CLR_BOLD}Universal Alternative Typing Paths for Windows:{CLR_RESET}")
print(f" {CLR_RECOMMENDED}Option A: ALT Code Sequence{CLR_RESET}")
print(f" Hold the physical [Alt] key and type [{code_int}] on your Numeric Keypad.")
print(f"\n {CLR_ALT}Option B: Advanced Hex Input Registry Hack{CLR_RESET}")
print(f" With EnableHexNumpad set in the registry, hold [Alt] and type [+] followed by [{hex_str}].")
print()
if __name__ == "__main__":
if len(sys.argv) != 2 or len(sys.argv[1]) != 1:
print(f"{CLR_ERROR}Usage: python lookup.py <single_character>{CLR_RESET}")
sys.exit(1)
target = sys.argv[1]
results = macos_lookup(target) if sys.platform == 'darwin' else windows_lookup(target)
if results:
clean_results = []
for item in results:
if any("Keypad" in item.get(k, "") for k in ["key", "dk_key", "base_key"]): continue
clean_results.append(item)
if not clean_results: clean_results = results
print(f"\n➔ {CLR_BOLD}Recommended combination for '{target}':{CLR_RESET}")
print(f" {format_result_item(clean_results[0], CLR_RECOMMENDED)}")
if len(clean_results) > 1:
print(f"\n{CLR_BOLD}Alternative paths:{CLR_RESET}")
for alt_item in clean_results[1:]:
print(f" • {format_result_item(alt_item, CLR_ALT)}")
print()
else:
print_unicode_fallback(target)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment