initial commit [141.14.140.180,mike]
This commit is contained in:
commit
156bb18c91
50 files changed
+13466
No files matched your search
@@ -0,0 +1,288 @@
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package keybind
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSplit(t *testing.T) {
|
||||
cases := map[string][2]string{
|
||||
"ctrl+a=new_tab": {"ctrl+a", "new_tab"},
|
||||
"==text:=": {"=", "text:="},
|
||||
"ctrl+==text:=hello": {"ctrl+=", "text:=hello"},
|
||||
"=+ctrl=text:=hello": {"=+ctrl", "text:=hello"},
|
||||
"super+shift+,=reload": {"super+shift+,", "reload"},
|
||||
"ctrl+a>n=new_window": {"ctrl+a>n", "new_window"},
|
||||
"§=goto_split:next": {"§", "goto_split:next"},
|
||||
"super++=increase": {"super++", "increase"},
|
||||
}
|
||||
for in, want := range cases {
|
||||
tr, ac := Split(in)
|
||||
if tr != want[0] || ac != want[1] {
|
||||
t.Errorf("Split(%q) = %q, %q", in, tr, ac)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalize(t *testing.T) {
|
||||
same := [][]string{
|
||||
{"cmd+shift+t", "shift+super+T", "command+shift+t", "global:super+shift+t"},
|
||||
{"ctrl+up", "control+arrow_up", "ctrl+ArrowUp"},
|
||||
{"super++", "super+plus"},
|
||||
{"opt+grave_accent", "alt+backquote"},
|
||||
{"ctrl+a>n", "control+a>N"},
|
||||
{"super+=", "cmd+="},
|
||||
}
|
||||
for _, group := range same {
|
||||
want, err := Normalize(group[0])
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", group[0], err)
|
||||
}
|
||||
for _, g := range group[1:] {
|
||||
got, err := Normalize(g)
|
||||
if err != nil || got != want {
|
||||
t.Errorf("Normalize(%q) = %q, %v; want %q", g, got, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"ctrl+ctrl+a", "ctrl+", "ctrl+a+b", "ctrl+bogus"} {
|
||||
if _, err := Normalize(bad); err == nil && bad != "ctrl+" {
|
||||
t.Errorf("Normalize(%q) should fail", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var defaults = []string{
|
||||
"super+t=new_tab",
|
||||
"super+w=close_surface",
|
||||
"super+d=new_split:right",
|
||||
"super+arrow_right=text:\\x05",
|
||||
}
|
||||
|
||||
func values(s *Set) string { return strings.Join(s.Values(), " | ") }
|
||||
|
||||
func find(t *testing.T, s *Set, trigger string) Binding {
|
||||
t.Helper()
|
||||
n, _ := Normalize(trigger)
|
||||
for _, b := range s.Bindings() {
|
||||
if b.Norm == n {
|
||||
return b
|
||||
}
|
||||
}
|
||||
t.Fatalf("no binding for %s", trigger)
|
||||
return Binding{}
|
||||
}
|
||||
|
||||
func TestEffective(t *testing.T) {
|
||||
s := NewSet(defaults, []string{
|
||||
"super+w=unbind",
|
||||
"cmd+t=new_window",
|
||||
"ctrl+a>n=new_tab",
|
||||
"chain=toggle_fullscreen",
|
||||
})
|
||||
if b := find(t, s, "super+t"); b.Source != Changed || b.Action != "new_window" || b.Default != "new_tab" {
|
||||
t.Errorf("super+t = %+v", b)
|
||||
}
|
||||
if b := find(t, s, "super+w"); b.Source != Unbound {
|
||||
t.Errorf("super+w = %+v", b)
|
||||
}
|
||||
if b := find(t, s, "ctrl+a>n"); b.Source != Custom || len(b.Chain) != 1 || b.Chain[0] != "toggle_fullscreen" {
|
||||
t.Errorf("ctrl+a>n = %+v", b)
|
||||
}
|
||||
if b := find(t, s, "super+d"); b.Source != Default || b.InConfig {
|
||||
t.Errorf("super+d = %+v", b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClear(t *testing.T) {
|
||||
s := NewSet(defaults, []string{"clear", "super+t=new_tab"})
|
||||
if b := find(t, s, "super+t"); b.Source != Default || !b.InConfig {
|
||||
t.Errorf("super+t = %+v", b)
|
||||
}
|
||||
if b := find(t, s, "super+d"); b.Source != Unbound {
|
||||
t.Errorf("super+d should be unbound after clear: %+v", b)
|
||||
}
|
||||
s.Restore(find(t, s, "super+d"))
|
||||
if got := values(s); got != "clear | super+t=new_tab | super+d=new_split:right" {
|
||||
t.Errorf("restore after clear: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangeDefaultAction(t *testing.T) {
|
||||
s := NewSet(defaults, nil)
|
||||
b := find(t, s, "super+d")
|
||||
if err := s.Change(&b, "super+d=new_split:down"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := values(s); got != "super+d=new_split:down" {
|
||||
t.Errorf("got %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveDefaultBinding(t *testing.T) {
|
||||
s := NewSet(defaults, nil)
|
||||
b := find(t, s, "super+d")
|
||||
if err := s.Change(&b, "super+shift+d=new_split:right"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := values(s); got != "super+d=unbind | super+shift+d=new_split:right" {
|
||||
t.Errorf("got %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveUserBindingRevertsToDefault(t *testing.T) {
|
||||
s := NewSet(defaults, []string{"super+arrow_right=goto_window:next"})
|
||||
b := find(t, s, "super+arrow_right")
|
||||
if err := s.Change(&b, "super+alt+arrow_right=goto_window:next"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := values(s); got != "super+alt+arrow_right=goto_window:next" {
|
||||
t.Errorf("got %s", got)
|
||||
}
|
||||
if b := find(t, s, "super+arrow_right"); b.Source != Default {
|
||||
t.Errorf("old trigger should fall back to the default: %+v", b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveUserBindingKeepsPosition(t *testing.T) {
|
||||
s := NewSet(defaults, []string{"a=new_tab", "super+arrow_right=goto_window:next", "b=new_window"})
|
||||
b := find(t, s, "super+arrow_right")
|
||||
if err := s.Change(&b, "super+shift+k=goto_window:next"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := values(s); got != "a=new_tab | super+shift+k=goto_window:next | b=new_window" {
|
||||
t.Errorf("got %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangeReplacesConflictInPlace(t *testing.T) {
|
||||
s := NewSet(defaults, []string{"ctrl+x=copy_to_clipboard", "ctrl+y=paste_from_clipboard"})
|
||||
b := find(t, s, "ctrl+y")
|
||||
if err := s.Change(&b, "ctrl+x=paste_from_clipboard"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := values(s); got != "ctrl+x=paste_from_clipboard" {
|
||||
t.Errorf("got %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangeBackToDefaultRemovesEntry(t *testing.T) {
|
||||
s := NewSet(defaults, []string{"# not a keybind", "super+t=new_window"})
|
||||
b := find(t, s, "super+t")
|
||||
if err := s.Change(&b, "super+t=new_tab"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := values(s); got != "# not a keybind" {
|
||||
t.Errorf("got %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnbindAndRestore(t *testing.T) {
|
||||
s := NewSet(defaults, []string{"super+t=new_window", "ctrl+q=quit"})
|
||||
s.Unbind(find(t, s, "super+t"))
|
||||
s.Unbind(find(t, s, "ctrl+q"))
|
||||
if got := values(s); got != "super+t=unbind" {
|
||||
t.Errorf("after unbind: %s", got)
|
||||
}
|
||||
s.Restore(find(t, s, "super+t"))
|
||||
if got := values(s); got != "" {
|
||||
t.Errorf("after restore: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChainMovesWithBinding(t *testing.T) {
|
||||
s := NewSet(nil, []string{"ctrl+a=new_tab", "chain=toggle_fullscreen"})
|
||||
b := find(t, s, "ctrl+a")
|
||||
if err := s.Change(&b, "ctrl+b=new_tab"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := values(s); got != "ctrl+b=new_tab | chain=toggle_fullscreen" {
|
||||
t.Errorf("got %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeCSI(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"\x1b[116;9u": "super+t",
|
||||
"\x1b[116;10u": "super+shift+t",
|
||||
"\x1b[44;10u": "super+shift+,",
|
||||
"\x1b[97;5u": "ctrl+a",
|
||||
"\x1b[167;9u": "super+§",
|
||||
"\x1b[1;9C": "super+arrow_right",
|
||||
"\x1b[5;3~": "alt+page_up",
|
||||
"\x1b[13;2u": "shift+enter",
|
||||
"\x1b[57399;5u": "ctrl+numpad_0",
|
||||
"\x1b[57376u": "f13",
|
||||
"\x1b[97:65;2u": "shift+a",
|
||||
}
|
||||
for seq, want := range cases {
|
||||
c, ok := DecodeCSI([]byte(seq))
|
||||
if !ok || c.String() != want {
|
||||
t.Errorf("DecodeCSI(%q) = %q, %v; want %q", seq, c.String(), ok, want)
|
||||
}
|
||||
}
|
||||
if c, ok := DecodeCSI([]byte("\x1b[57441;2u")); !ok || !c.Modifier {
|
||||
t.Error("left shift should be reported as a modifier key")
|
||||
}
|
||||
if _, ok := DecodeCSI([]byte("\x1b[?9u")); ok {
|
||||
t.Error("kitty reply is not a key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeKeyName(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"ctrl+a": "ctrl+a",
|
||||
"alt+shift+up": "alt+shift+arrow_up",
|
||||
"ctrl+shift+up": "ctrl+shift+arrow_up",
|
||||
"f5": "f5",
|
||||
"A": "shift+a",
|
||||
"pgdown": "page_down",
|
||||
"shift+tab": "shift+tab",
|
||||
"alt+x": "alt+x",
|
||||
"+": "+",
|
||||
}
|
||||
for in, want := range cases {
|
||||
c, ok := DecodeKeyName(in)
|
||||
if !ok || c.String() != want {
|
||||
t.Errorf("DecodeKeyName(%q) = %q, %v; want %q", in, c.String(), ok, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package keybind
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Key recording.
|
||||
//
|
||||
// While recording, the editor asks the terminal for the kitty keyboard
|
||||
// protocol (flags 1|8: disambiguate escape codes, report all keys as escape
|
||||
// codes). Ghostty then reports every key press, including ones with the
|
||||
// super/cmd modifier, as "CSI code ; modifiers u" (or the legacy
|
||||
// "CSI 1 ; modifiers A" forms for arrows and function keys). Terminals
|
||||
// without the protocol send classic sequences, which are decoded from the
|
||||
// key names Bubble Tea produces.
|
||||
|
||||
// PushKitty and PopKitty enable and restore the kitty keyboard protocol.
|
||||
// QueryKitty asks the terminal for the current flags; a terminal that
|
||||
// supports the protocol answers with "CSI ? flags u".
|
||||
const (
|
||||
PushKitty = "\x1b[>9u"
|
||||
PopKitty = "\x1b[<u"
|
||||
QueryKitty = "\x1b[?u"
|
||||
)
|
||||
|
||||
// Combo is one recorded key combination.
|
||||
type Combo struct {
|
||||
Mods map[string]bool
|
||||
Key string
|
||||
Modifier bool // a lone modifier key press (ignored by the recorder)
|
||||
}
|
||||
|
||||
func (c Combo) String() string {
|
||||
return strings.Join(append(FormatMods(c.Mods), c.Key), "+")
|
||||
}
|
||||
|
||||
// Plain reports whether the combination has no modifiers.
|
||||
func (c Combo) Plain() bool {
|
||||
for _, on := range c.Mods {
|
||||
if on {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// IsKittyReply reports whether seq is the answer to QueryKitty.
|
||||
func IsKittyReply(seq []byte) bool {
|
||||
s := string(seq)
|
||||
return strings.HasPrefix(s, "\x1b[?") && strings.HasSuffix(s, "u")
|
||||
}
|
||||
|
||||
var kittyFunctional = map[int]string{
|
||||
9: "tab", 13: "enter", 27: "escape", 32: "space", 127: "backspace",
|
||||
57358: "caps_lock", 57359: "scroll_lock", 57360: "num_lock", 57361: "print_screen",
|
||||
57362: "pause", 57363: "context_menu",
|
||||
57409: "numpad_decimal", 57410: "numpad_divide", 57411: "numpad_multiply",
|
||||
57412: "numpad_subtract", 57413: "numpad_add", 57414: "numpad_enter", 57415: "numpad_equal",
|
||||
57416: "numpad_separator", 57417: "numpad_left", 57418: "numpad_right", 57419: "numpad_up",
|
||||
57420: "numpad_down", 57421: "numpad_page_up", 57422: "numpad_page_down",
|
||||
57423: "numpad_home", 57424: "numpad_end", 57425: "numpad_insert", 57426: "numpad_delete",
|
||||
57427: "numpad_begin",
|
||||
57430: "media_play_pause", 57432: "media_stop", 57435: "media_track_next",
|
||||
57436: "media_track_previous", 57438: "audio_volume_down", 57439: "audio_volume_up",
|
||||
57440: "audio_volume_mute",
|
||||
}
|
||||
|
||||
var legacyFinal = map[byte]string{
|
||||
'A': "arrow_up", 'B': "arrow_down", 'C': "arrow_right", 'D': "arrow_left",
|
||||
'H': "home", 'F': "end", 'E': "numpad_begin", 'P': "f1", 'Q': "f2", 'R': "f3", 'S': "f4",
|
||||
}
|
||||
|
||||
var tildeKeys = map[int]string{
|
||||
2: "insert", 3: "delete", 5: "page_up", 6: "page_down", 7: "home", 8: "end",
|
||||
11: "f1", 12: "f2", 13: "f3", 14: "f4", 15: "f5", 17: "f6", 18: "f7", 19: "f8",
|
||||
20: "f9", 21: "f10", 23: "f11", 24: "f12", 29: "context_menu", 57427: "numpad_begin",
|
||||
}
|
||||
|
||||
func init() {
|
||||
for i := 0; i <= 9; i++ {
|
||||
kittyFunctional[57399+i] = "numpad_" + strconv.Itoa(i)
|
||||
}
|
||||
for i := 13; i <= 25; i++ {
|
||||
kittyFunctional[57376+i-13] = "f" + strconv.Itoa(i)
|
||||
}
|
||||
}
|
||||
|
||||
func decodeMods(field string) map[string]bool {
|
||||
mods := map[string]bool{}
|
||||
v, _, _ := strings.Cut(field, ":") // drop the event type
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n < 1 {
|
||||
return mods
|
||||
}
|
||||
n--
|
||||
mods["shift"] = n&1 != 0
|
||||
mods["alt"] = n&2 != 0
|
||||
mods["ctrl"] = n&4 != 0
|
||||
mods["super"] = n&8 != 0
|
||||
return mods
|
||||
}
|
||||
|
||||
// DecodeCSI decodes a key event escape sequence ("\x1b[...u", "\x1b[1;9A",
|
||||
// "\x1b[5;3~", …). ok is false for anything that is not a key event.
|
||||
func DecodeCSI(seq []byte) (Combo, bool) {
|
||||
s := string(seq)
|
||||
if !strings.HasPrefix(s, "\x1b[") || len(s) < 3 || IsKittyReply(seq) {
|
||||
return Combo{}, false
|
||||
}
|
||||
final := s[len(s)-1]
|
||||
params := strings.Split(s[2:len(s)-1], ";")
|
||||
modField := ""
|
||||
if len(params) > 1 {
|
||||
modField = params[1]
|
||||
}
|
||||
c := Combo{Mods: decodeMods(modField)}
|
||||
|
||||
switch {
|
||||
case final == 'u':
|
||||
codeStr, _, _ := strings.Cut(params[0], ":") // drop shifted/base-layout keys
|
||||
code, err := strconv.Atoi(codeStr)
|
||||
if err != nil {
|
||||
return Combo{}, false
|
||||
}
|
||||
if code >= 57441 && code <= 57452 {
|
||||
c.Modifier = true // shift, ctrl, alt, super, hyper, meta, … keys
|
||||
return c, true
|
||||
}
|
||||
if name, ok := kittyFunctional[code]; ok {
|
||||
c.Key = name
|
||||
if code == 57358 || code == 57360 {
|
||||
c.Modifier = true // lock keys
|
||||
}
|
||||
return c, true
|
||||
}
|
||||
if code < 32 || !utf8.ValidRune(rune(code)) {
|
||||
return Combo{}, false
|
||||
}
|
||||
c.Key = string(rune(code))
|
||||
return c, true
|
||||
case final == '~':
|
||||
code, err := strconv.Atoi(params[0])
|
||||
if err != nil {
|
||||
return Combo{}, false
|
||||
}
|
||||
name, ok := tildeKeys[code]
|
||||
if !ok {
|
||||
return Combo{}, false
|
||||
}
|
||||
c.Key = name
|
||||
return c, true
|
||||
default:
|
||||
name, ok := legacyFinal[final]
|
||||
if !ok {
|
||||
return Combo{}, false
|
||||
}
|
||||
c.Key = name
|
||||
return c, true
|
||||
}
|
||||
}
|
||||
|
||||
var legacyNames = map[string]string{
|
||||
"up": "arrow_up", "down": "arrow_down", "left": "arrow_left", "right": "arrow_right",
|
||||
"pgup": "page_up", "pgdown": "page_down", "home": "home", "end": "end",
|
||||
"insert": "insert", "delete": "delete", "tab": "tab", "enter": "enter",
|
||||
"esc": "escape", "backspace": "backspace", " ": "space", "space": "space",
|
||||
}
|
||||
|
||||
// DecodeKeyName converts a Bubble Tea key name ("ctrl+a", "alt+shift+up",
|
||||
// "f5", "A") into a combination. Classic terminal input cannot represent
|
||||
// super/cmd, and shifted symbols arrive as the symbol itself.
|
||||
func DecodeKeyName(name string) (Combo, bool) {
|
||||
c := Combo{Mods: map[string]bool{}}
|
||||
if name == "" {
|
||||
return c, false
|
||||
}
|
||||
switch name {
|
||||
case "shift+tab":
|
||||
c.Mods["shift"] = true
|
||||
c.Key = "tab"
|
||||
return c, true
|
||||
case "ctrl+@", "ctrl+ ":
|
||||
c.Mods["ctrl"] = true
|
||||
c.Key = "space"
|
||||
return c, true
|
||||
}
|
||||
rest := name
|
||||
for {
|
||||
found := false
|
||||
for _, m := range []string{"ctrl+", "alt+", "shift+"} {
|
||||
if strings.HasPrefix(rest, m) && len(rest) > len(m) {
|
||||
c.Mods[strings.TrimSuffix(m, "+")] = true
|
||||
rest = rest[len(m):]
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
break
|
||||
}
|
||||
}
|
||||
if k, ok := legacyNames[rest]; ok {
|
||||
c.Key = k
|
||||
return c, true
|
||||
}
|
||||
if len(rest) >= 2 && rest[0] == 'f' {
|
||||
if n, err := strconv.Atoi(rest[1:]); err == nil && n >= 1 && n <= 25 {
|
||||
c.Key = rest
|
||||
return c, true
|
||||
}
|
||||
}
|
||||
if utf8.RuneCountInString(rest) == 1 {
|
||||
r, _ := utf8.DecodeRuneInString(rest)
|
||||
if r >= 'A' && r <= 'Z' {
|
||||
c.Mods["shift"] = true
|
||||
r += 'a' - 'A'
|
||||
}
|
||||
c.Key = string(r)
|
||||
return c, true
|
||||
}
|
||||
return c, false
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
package keybind
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Source tells where an effective binding comes from.
|
||||
type Source int
|
||||
|
||||
const (
|
||||
Default Source = iota // Ghostty's built-in binding
|
||||
Changed // a built-in trigger the user bound to another action
|
||||
Custom // a user binding on a trigger without built-in binding
|
||||
Unbound // a built-in binding the user removed
|
||||
)
|
||||
|
||||
func (s Source) String() string {
|
||||
switch s {
|
||||
case Changed:
|
||||
return "changed"
|
||||
case Custom:
|
||||
return "custom"
|
||||
case Unbound:
|
||||
return "unbound"
|
||||
}
|
||||
return "default"
|
||||
}
|
||||
|
||||
// Entry is one parsed `keybind` value.
|
||||
type Entry struct {
|
||||
Value string
|
||||
Flags string // e.g. "global:"
|
||||
Trigger string // without flags, as written
|
||||
Norm string // canonical identity of the trigger
|
||||
Action string
|
||||
Clear bool // "keybind = clear"
|
||||
Chain bool // "keybind = chain=ACTION"
|
||||
}
|
||||
|
||||
// ParseEntry parses a raw `keybind` config value.
|
||||
func ParseEntry(v string) Entry {
|
||||
v = strings.TrimSpace(v)
|
||||
if len(v) >= 2 && v[0] == '"' && v[len(v)-1] == '"' {
|
||||
v = v[1 : len(v)-1]
|
||||
}
|
||||
e := Entry{Value: v}
|
||||
if v == "clear" {
|
||||
e.Clear = true
|
||||
return e
|
||||
}
|
||||
t, a := Split(v)
|
||||
e.Action = a
|
||||
if t == "chain" {
|
||||
e.Chain = true
|
||||
return e
|
||||
}
|
||||
e.Flags, e.Trigger = StripFlags(t)
|
||||
e.Norm = NormalizeLoose(t)
|
||||
return e
|
||||
}
|
||||
|
||||
// Binding is one row of the effective key binding table.
|
||||
type Binding struct {
|
||||
Norm string
|
||||
Trigger string // as written, including flag prefixes
|
||||
Action string
|
||||
Chain []string // actions chained with "chain="
|
||||
Source Source
|
||||
Default string // Ghostty's built-in action for this trigger, if any
|
||||
InConfig bool // the user's config has an entry for this trigger
|
||||
}
|
||||
|
||||
// group is a binding entry together with the "chain=" entries after it.
|
||||
type group struct {
|
||||
entries []string
|
||||
e Entry
|
||||
}
|
||||
|
||||
func (g group) chain() []string { return g.entries[1:] }
|
||||
|
||||
// Set is the user's keybind entries on top of Ghostty's defaults.
|
||||
type Set struct {
|
||||
defaults []Entry
|
||||
defByNorm map[string]Entry
|
||||
groups []group
|
||||
}
|
||||
|
||||
// NewSet builds a set from Ghostty's default values and the user's values.
|
||||
func NewSet(defaults, user []string) *Set {
|
||||
s := &Set{defByNorm: map[string]Entry{}}
|
||||
for _, d := range defaults {
|
||||
e := ParseEntry(d)
|
||||
if e.Norm == "" || e.Action == "" {
|
||||
continue
|
||||
}
|
||||
if _, dup := s.defByNorm[e.Norm]; !dup {
|
||||
s.defaults = append(s.defaults, e)
|
||||
}
|
||||
s.defByNorm[e.Norm] = e
|
||||
}
|
||||
for _, v := range user {
|
||||
e := ParseEntry(v)
|
||||
if e.Chain && len(s.groups) > 0 && !s.groups[len(s.groups)-1].e.Clear {
|
||||
last := &s.groups[len(s.groups)-1]
|
||||
last.entries = append(last.entries, v)
|
||||
continue
|
||||
}
|
||||
s.groups = append(s.groups, group{entries: []string{v}, e: e})
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Values returns the user's keybind entries.
|
||||
func (s *Set) Values() []string {
|
||||
var out []string
|
||||
for _, g := range s.groups {
|
||||
out = append(out, g.entries...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// HasClear reports whether the user's entries contain "clear".
|
||||
func (s *Set) HasClear() bool {
|
||||
for _, g := range s.groups {
|
||||
if g.e.Clear {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// effective computes the active bindings in insertion order.
|
||||
func (s *Set) effective() (map[string]*Binding, []string) {
|
||||
m := map[string]*Binding{}
|
||||
var order []string
|
||||
put := func(b *Binding) {
|
||||
if _, ok := m[b.Norm]; !ok {
|
||||
order = append(order, b.Norm)
|
||||
}
|
||||
m[b.Norm] = b
|
||||
}
|
||||
for _, d := range s.defaults {
|
||||
put(&Binding{Norm: d.Norm, Trigger: d.Flags + d.Trigger, Action: d.Action, Source: Default, Default: d.Action})
|
||||
}
|
||||
for _, g := range s.groups {
|
||||
e := g.e
|
||||
switch {
|
||||
case e.Clear:
|
||||
m, order = map[string]*Binding{}, nil
|
||||
case e.Chain || e.Norm == "":
|
||||
case e.Action == "unbind":
|
||||
delete(m, e.Norm)
|
||||
default:
|
||||
b := &Binding{Norm: e.Norm, Trigger: e.Flags + e.Trigger, Action: e.Action, InConfig: true, Source: Custom}
|
||||
for _, c := range g.chain() {
|
||||
_, a := Split(c)
|
||||
b.Chain = append(b.Chain, a)
|
||||
}
|
||||
if d, ok := s.defByNorm[e.Norm]; ok {
|
||||
b.Default = d.Action
|
||||
b.Source = Changed
|
||||
if d.Action == e.Action && d.Flags == e.Flags && len(b.Chain) == 0 {
|
||||
b.Source = Default
|
||||
}
|
||||
}
|
||||
put(b)
|
||||
}
|
||||
}
|
||||
return m, order
|
||||
}
|
||||
|
||||
// Bindings returns every effective binding plus the built-in bindings that
|
||||
// were removed (as Unbound).
|
||||
func (s *Set) Bindings() []Binding {
|
||||
m, order := s.effective()
|
||||
var out []Binding
|
||||
for _, n := range order {
|
||||
if b, ok := m[n]; ok {
|
||||
out = append(out, *b)
|
||||
}
|
||||
}
|
||||
for _, d := range s.defaults {
|
||||
if _, ok := m[d.Norm]; ok {
|
||||
continue
|
||||
}
|
||||
out = append(out, Binding{
|
||||
Norm: d.Norm, Trigger: d.Flags + d.Trigger, Action: d.Action, Source: Unbound,
|
||||
Default: d.Action, InConfig: s.lastGroup(d.Norm) >= 0,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Lookup returns the effective binding for a trigger identity.
|
||||
func (s *Set) Lookup(norm string) (Binding, bool) {
|
||||
m, _ := s.effective()
|
||||
if b, ok := m[norm]; ok {
|
||||
return *b, true
|
||||
}
|
||||
return Binding{}, false
|
||||
}
|
||||
|
||||
// lastGroup returns the index of the last user group for norm, or -1.
|
||||
func (s *Set) lastGroup(norm string) int {
|
||||
for i := len(s.groups) - 1; i >= 0; i-- {
|
||||
if s.groups[i].e.Norm == norm && !s.groups[i].e.Chain && !s.groups[i].e.Clear {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// drop removes all user groups for norm except the one at keep (-1 for
|
||||
// none) and returns the new index of the kept group.
|
||||
func (s *Set) drop(norm string, keep int) int {
|
||||
var out []group
|
||||
newKeep := -1
|
||||
for i, g := range s.groups {
|
||||
if g.e.Norm == norm && !g.e.Clear && !g.e.Chain && i != keep {
|
||||
continue
|
||||
}
|
||||
if i == keep {
|
||||
newKeep = len(out)
|
||||
}
|
||||
out = append(out, g)
|
||||
}
|
||||
s.groups = out
|
||||
return newKeep
|
||||
}
|
||||
|
||||
func (s *Set) active(norm string) (Binding, bool) { return s.Lookup(norm) }
|
||||
|
||||
func (s *Set) appendValue(v string) {
|
||||
s.groups = append(s.groups, group{entries: []string{v}, e: ParseEntry(v)})
|
||||
}
|
||||
|
||||
// Change binds value ("trigger=action"). When old is given, that binding is
|
||||
// being edited: if its trigger changes, a built-in binding is unbound from
|
||||
// its old trigger, while a user binding simply moves (the old trigger falls
|
||||
// back to Ghostty's default, if it has one). Any other binding of the new
|
||||
// trigger is replaced.
|
||||
func (s *Set) Change(old *Binding, value string) error {
|
||||
ne := ParseEntry(value)
|
||||
if ne.Clear || ne.Chain || ne.Norm == "" || ne.Action == "" {
|
||||
return fmt.Errorf("expected trigger=action")
|
||||
}
|
||||
if _, err := Normalize(ne.Flags + ne.Trigger); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// The user's own entry for the edited binding, if any.
|
||||
oldIdx := -1
|
||||
if old != nil && old.Source != Unbound {
|
||||
if i := s.lastGroup(old.Norm); i >= 0 && s.groups[i].e.Action != "unbind" {
|
||||
oldIdx = i
|
||||
}
|
||||
}
|
||||
var chain []string
|
||||
if oldIdx >= 0 {
|
||||
chain = s.groups[oldIdx].chain()
|
||||
}
|
||||
g := group{entries: append([]string{ne.Value}, chain...), e: ne}
|
||||
|
||||
var idx int
|
||||
switch {
|
||||
case oldIdx >= 0 && old.Source != Default:
|
||||
// Rewrite the user's entry in place, then remove other entries for
|
||||
// the old and the new trigger. If the trigger changed, the old one
|
||||
// falls back to Ghostty's default (if it has one).
|
||||
s.groups[oldIdx] = g
|
||||
idx = s.drop(old.Norm, oldIdx)
|
||||
idx = s.drop(ne.Norm, idx)
|
||||
default:
|
||||
if old != nil && old.Norm != ne.Norm && old.Source == Default {
|
||||
// Moving a built-in binding: the old trigger must stop doing it.
|
||||
s.drop(old.Norm, -1)
|
||||
if _, still := s.active(old.Norm); still {
|
||||
_, trigger := StripFlags(old.Trigger)
|
||||
s.appendValue(trigger + "=unbind")
|
||||
}
|
||||
}
|
||||
idx = s.drop(ne.Norm, s.lastGroup(ne.Norm))
|
||||
if idx >= 0 {
|
||||
s.groups[idx] = g
|
||||
} else {
|
||||
s.groups = append(s.groups, g)
|
||||
idx = len(s.groups) - 1
|
||||
}
|
||||
}
|
||||
|
||||
// A binding identical to Ghostty's default needs no config entry.
|
||||
if d, ok := s.defByNorm[ne.Norm]; ok && d.Action == ne.Action && d.Flags == ne.Flags && len(chain) == 0 {
|
||||
saved := append([]group(nil), s.groups...)
|
||||
s.groups = append(s.groups[:idx:idx], s.groups[idx+1:]...)
|
||||
if b, ok := s.active(ne.Norm); !ok || b.Action != ne.Action {
|
||||
s.groups = saved // needed after all (e.g. after "clear")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Unbind removes the binding of b's trigger.
|
||||
func (s *Set) Unbind(b Binding) {
|
||||
if b.Source == Unbound {
|
||||
return
|
||||
}
|
||||
s.drop(b.Norm, -1)
|
||||
if _, still := s.active(b.Norm); still {
|
||||
_, trigger := StripFlags(b.Trigger)
|
||||
s.appendValue(trigger + "=unbind")
|
||||
}
|
||||
}
|
||||
|
||||
// Restore resets b's trigger to Ghostty's built-in behavior: the built-in
|
||||
// binding if there is one, otherwise no binding.
|
||||
func (s *Set) Restore(b Binding) {
|
||||
s.drop(b.Norm, -1)
|
||||
d, ok := s.defByNorm[b.Norm]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if cur, active := s.active(b.Norm); !active || cur.Action != d.Action {
|
||||
s.appendValue(d.Value) // e.g. after "keybind = clear"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user