keys: properly support the alt modifier

This commit is contained in:
Raphael 'kena' Poss 2022-08-29 11:52:25 +02:00 committed by Christian Muehlhaeuser
parent f905b97756
commit 134a930f2d
2 changed files with 24 additions and 5 deletions

11
key.go
View File

@ -543,28 +543,29 @@ func readInputs(input io.Reader) ([]Msg, error) {
// Is the alt key pressed? If so, the buffer will be prefixed with an // Is the alt key pressed? If so, the buffer will be prefixed with an
// escape. // escape.
alt := false
if len(runes) > 1 && runes[0] == 0x1b { if len(runes) > 1 && runes[0] == 0x1b {
msgs = append(msgs, KeyMsg(Key{Alt: true, Type: KeyRunes, Runes: runes[1:]})) alt = true
continue runes = runes[1:]
} }
for _, v := range runes { for _, v := range runes {
// Is the first rune a control character? // Is the first rune a control character?
r := KeyType(v) r := KeyType(v)
if r <= keyUS || r == keyDEL { if r <= keyUS || r == keyDEL {
msgs = append(msgs, KeyMsg(Key{Type: r})) msgs = append(msgs, KeyMsg(Key{Type: r, Alt: alt}))
continue continue
} }
// If it's a space, override the type with KeySpace (but still include // If it's a space, override the type with KeySpace (but still include
// the rune). // the rune).
if r == ' ' { if r == ' ' {
msgs = append(msgs, KeyMsg(Key{Type: KeySpace, Runes: []rune{v}})) msgs = append(msgs, KeyMsg(Key{Type: KeySpace, Runes: []rune{v}, Alt: alt}))
continue continue
} }
// Welp, just regular, ol' runes. // Welp, just regular, ol' runes.
msgs = append(msgs, KeyMsg(Key{Type: KeyRunes, Runes: []rune{v}})) msgs = append(msgs, KeyMsg(Key{Type: KeyRunes, Runes: []rune{v}, Alt: alt}))
} }
} }

View File

@ -134,6 +134,24 @@ func TestReadInput(t *testing.T) {
}, },
}, },
}, },
"alt+enter": {
[]byte{'\x1b', '\r'},
[]Msg{
KeyMsg{
Type: KeyEnter,
Alt: true,
},
},
},
"alt+ctrl+a": {
[]byte{'\x1b', byte(keySOH)},
[]Msg{
KeyMsg{
Type: KeyCtrlA,
Alt: true,
},
},
},
} { } {
t.Run(out, func(t *testing.T) { t.Run(out, func(t *testing.T) {
msgs, err := readInputs(bytes.NewReader(td.in)) msgs, err := readInputs(bytes.NewReader(td.in))