// Package keybind understands Ghostty key bindings: it splits and // normalizes triggers the same way Ghostty's src/input/Binding.zig does, // computes the effective set of bindings from Ghostty's defaults plus the // user's `keybind` entries, and translates edits of that set back into // config entries. package keybind import ( "fmt" "strings" "unicode" "unicode/utf8" ) // Split splits "trigger=action". It mirrors Ghostty's parser: an '=' that is // directly followed by '+' or '=' belongs to the trigger, so "ctrl+==reset" // and "=+ctrl=reset" both bind the '=' key. func Split(v string) (trigger, action string) { for i := 0; i < len(v); i++ { if v[i] != '=' { continue } if i < len(v)-1 && (v[i+1] == '+' || v[i+1] == '=') { continue } return strings.TrimSpace(v[:i]), strings.TrimSpace(v[i+1:]) } return strings.TrimSpace(v), "" } // Flag prefixes that may precede a trigger, e.g. "global:ctrl+grave". var flagPrefixes = []string{"all:", "global:", "unconsumed:", "performable:"} // StripFlags separates leading flag prefixes from a trigger. func StripFlags(trigger string) (flags, rest string) { rest = trigger for { found := false for _, p := range flagPrefixes { if strings.HasPrefix(rest, p) { flags += p rest = rest[len(p):] found = true } } if !found { return flags, rest } } } // Modifier names in the order Ghostty prints them. var modOrder = []string{"super", "ctrl", "alt", "shift", "caps_lock", "num_lock"} var modAliases = map[string]string{ "super": "super", "cmd": "super", "command": "super", "ctrl": "ctrl", "control": "ctrl", "alt": "alt", "opt": "alt", "option": "alt", "shift": "shift", "caps_lock": "caps_lock", "num_lock": "num_lock", } // keyNames are Ghostty's physical key names (src/input/key.zig, 1.3). var keyNames = map[string]bool{} func init() { for _, k := range strings.Fields(`backquote backslash bracket_left bracket_right comma digit_0 digit_1 digit_2 digit_3 digit_4 digit_5 digit_6 digit_7 digit_8 digit_9 equal intl_backslash intl_ro intl_yen key_a key_b key_c key_d key_e key_f key_g key_h key_i key_j key_k key_l key_m key_n key_o key_p key_q key_r key_s key_t key_u key_v key_w key_x key_y key_z minus period quote semicolon slash alt_left alt_right backspace caps_lock context_menu control_left control_right enter meta_left meta_right shift_left shift_right space tab convert kana_mode non_convert delete end help home insert page_down page_up arrow_down arrow_left arrow_right arrow_up num_lock numpad_0 numpad_1 numpad_2 numpad_3 numpad_4 numpad_5 numpad_6 numpad_7 numpad_8 numpad_9 numpad_add numpad_backspace numpad_clear numpad_clear_entry numpad_comma numpad_decimal numpad_divide numpad_enter numpad_equal numpad_memory_add numpad_memory_clear numpad_memory_recall numpad_memory_store numpad_memory_subtract numpad_multiply numpad_paren_left numpad_paren_right numpad_subtract numpad_separator numpad_up numpad_down numpad_right numpad_left numpad_begin numpad_home numpad_end numpad_insert numpad_delete numpad_page_up numpad_page_down escape f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11 f12 f13 f14 f15 f16 f17 f18 f19 f20 f21 f22 f23 f24 f25 fn_lock print_screen scroll_lock pause browser_back browser_favorites browser_forward browser_home browser_refresh browser_search browser_stop eject launch_app_1 launch_app_2 launch_mail media_play_pause media_select media_stop media_track_next media_track_previous power sleep audio_volume_down audio_volume_mute audio_volume_up wake_up copy cut paste catch_all`) { keyNames[k] = true } } // compatKeys are the Ghostty 1.1 key names that 1.2+ still accepts. var compatKeys = map[string]string{ "zero": "0", "one": "1", "two": "2", "three": "3", "four": "4", "five": "5", "six": "6", "seven": "7", "eight": "8", "nine": "9", "plus": "+", "apostrophe": "'", "grave_accent": "backquote", "left_bracket": "bracket_left", "right_bracket": "bracket_right", "up": "arrow_up", "down": "arrow_down", "left": "arrow_left", "right": "arrow_right", "kp_add": "numpad_add", "kp_subtract": "numpad_subtract", "kp_multiply": "numpad_multiply", "kp_divide": "numpad_divide", "kp_decimal": "numpad_decimal", "kp_enter": "numpad_enter", "kp_equal": "numpad_equal", "kp_separator": "numpad_separator", "kp_left": "numpad_left", "kp_right": "numpad_right", "kp_up": "numpad_up", "kp_down": "numpad_down", "kp_page_up": "numpad_page_up", "kp_page_down": "numpad_page_down", "kp_home": "numpad_home", "kp_end": "numpad_end", "kp_insert": "numpad_insert", "kp_delete": "numpad_delete", "kp_begin": "numpad_begin", "left_shift": "shift_left", "right_shift": "shift_right", "left_control": "control_left", "right_control": "control_right", "left_alt": "alt_left", "right_alt": "alt_right", "left_super": "meta_left", "right_super": "meta_right", } func init() { for i := 0; i <= 9; i++ { compatKeys[fmt.Sprintf("kp_%d", i)] = fmt.Sprintf("numpad_%d", i) } // "physical:" variants of the compatibility names. for k, v := range map[string]string{ "zero": "digit_0", "one": "digit_1", "two": "digit_2", "three": "digit_3", "four": "digit_4", "five": "digit_5", "six": "digit_6", "seven": "digit_7", "eight": "digit_8", "nine": "digit_9", "apostrophe": "quote", "grave_accent": "backquote", "left_bracket": "bracket_left", "right_bracket": "bracket_right", "up": "arrow_up", "down": "arrow_down", "left": "arrow_left", "right": "arrow_right", } { compatKeys["physical:"+k] = v } for i := 0; i <= 9; i++ { compatKeys[fmt.Sprintf("physical:kp_%d", i)] = fmt.Sprintf("numpad_%d", i) } } // Trigger is one key combination of a (possibly multi-key) trigger. type Trigger struct { Mods []string // canonical modifier names in modOrder Key string // canonical key: a physical key name or a single character } func (t Trigger) String() string { parts := append(append([]string(nil), t.Mods...), t.Key) return strings.Join(parts, "+") } // ParseTrigger parses a single key combination such as "cmd+shift+t" the // way Ghostty does. Unknown multi-character key names are an error. func ParseTrigger(s string) (Trigger, error) { var t Trigger if s == "" { return t, fmt.Errorf("empty trigger") } mods := map[string]bool{} keySet := false // Same loop as Ghostty: an empty part is a literal '+' key. for rem := s; len(rem) > 0; { idx := strings.IndexByte(rem, '+') if idx < 0 { idx = len(rem) } part := rem[:idx] if idx >= len(rem) { rem = "" } else { rem = rem[idx+1:] } if m, ok := modAliases[part]; ok { if mods[m] { return t, fmt.Errorf("modifier %q is repeated", part) } mods[m] = true continue } if keySet { return t, fmt.Errorf("only one key per combination is allowed (use > for sequences)") } keySet = true key, err := canonicalKey(part) if err != nil { return t, err } t.Key = key } if !keySet { return t, fmt.Errorf("the trigger has modifiers but no key") } for _, m := range modOrder { if mods[m] { t.Mods = append(t.Mods, m) } } return t, nil } func canonicalKey(part string) (string, error) { if part == "" { return "+", nil // "ctrl++" binds the plus key } if keyNames[part] { return part, nil } if utf8.RuneCountInString(part) == 1 { r, _ := utf8.DecodeRuneInString(part) // Unicode keys match case-insensitively. return string(unicode.ToLower(r)), nil } if k := fromW3C(part); k != "" { return k, nil } if k, ok := compatKeys[part]; ok { return k, nil } return "", fmt.Errorf("unknown key %q", part) } // fromW3C converts W3C key codes such as "KeyA", "ArrowUp" or "Numpad0" to // Ghostty's names. func fromW3C(s string) string { if s == "" || !unicode.IsUpper(rune(s[0])) { return "" } var b strings.Builder for i, r := range s { if i > 0 && (unicode.IsUpper(r) || (unicode.IsDigit(r) && !unicode.IsDigit(rune(s[i-1])) && s[:i] != "F")) { b.WriteByte('_') } b.WriteRune(unicode.ToLower(r)) } if keyNames[b.String()] { return b.String() } return "" } // Normalize returns a canonical identity for a trigger (including flag // prefixes and sequences), so that "cmd+shift+t", "shift+super+T" and // "global:super+shift+t" compare equal. Ghostty stores bindings by trigger; // flags are attributes of a binding, not part of its identity. func Normalize(trigger string) (string, error) { _, rest := StripFlags(strings.TrimSpace(trigger)) if rest == "" { return "", fmt.Errorf("empty trigger") } var parts []string for _, p := range splitSequence(rest) { t, err := ParseTrigger(p) if err != nil { return "", err } parts = append(parts, t.String()) } return strings.Join(parts, ">"), nil } // NormalizeLoose is Normalize that falls back to the trimmed input for // triggers it cannot parse, so that unknown syntax still gets an identity. func NormalizeLoose(trigger string) string { if n, err := Normalize(trigger); err == nil { return n } _, rest := StripFlags(strings.TrimSpace(trigger)) return strings.ToLower(rest) } // splitSequence splits "ctrl+a>n" at '>' separators. A '>' that is itself // the key (e.g. "shift+>") is kept. func splitSequence(s string) []string { var parts []string start := 0 for i := 0; i < len(s); i++ { if s[i] != '>' || i == start || s[i-1] == '+' { continue } parts = append(parts, s[start:i]) start = i + 1 } return append(parts, s[start:]) } // Action names are lowercase with underscores; the parameter follows ':'. func ActionName(action string) string { name, _, _ := strings.Cut(action, ":") return strings.TrimSpace(name) } // FormatMods renders modifiers in Ghostty's order. func FormatMods(mods map[string]bool) []string { var out []string for _, m := range modOrder { if mods[m] { out = append(out, m) } } return out }