Wire up key event handling

This commit is contained in:
Kovid Goyal
2022-10-06 21:41:40 +05:30
parent eff239a195
commit 48f1690913
3 changed files with 65 additions and 0 deletions

View File

@@ -258,3 +258,25 @@ func (self *Readline) erase_chars_after_cursor(amt uint, traverse_line_breaks bo
self.erase_between(pos, self.cursor)
return num
}
func (self *Readline) perform_action(ac Action, repeat_count uint) bool {
switch ac {
case ActionBackspace:
return self.erase_chars_before_cursor(repeat_count, true) > 0
case ActionDelete:
return self.erase_chars_after_cursor(repeat_count, true) > 0
case ActionMoveToStartOfLine:
return self.move_to_start_of_line()
case ActionMoveToEndOfLine:
return self.move_to_end_of_line()
case ActionMoveToStartOfDocument:
return self.move_to_start()
case ActionMoveToEndOfDocument:
return self.move_to_end()
case ActionCursorLeft:
return self.move_cursor_left(repeat_count, true) > 0
case ActionCursorRight:
return self.move_cursor_right(repeat_count, true) > 0
}
return false
}

View File

@@ -30,6 +30,20 @@ func (self Position) Less(other Position) bool {
return self.Y < other.Y || (self.Y == other.Y && self.X < other.X)
}
type Action uint
const (
ActionNil Action = iota
ActionBackspace
ActionDelete
ActionMoveToStartOfLine
ActionMoveToEndOfLine
ActionMoveToStartOfDocument
ActionMoveToEndOfDocument
ActionCursorLeft
ActionCursorRight
)
type Readline struct {
prompt string
prompt_len int
@@ -97,3 +111,7 @@ func (self *Readline) OnText(text string, from_key_event bool, in_bracketed_past
self.add_text(text)
return nil
}
func (self *Readline) PerformAction(ac Action, repeat_count uint) bool {
return self.perform_action(ac, repeat_count)
}

View File

@@ -10,9 +10,34 @@ import (
var _ = fmt.Print
var default_shortcuts = map[string]Action{
"backspace": ActionBackspace,
"delete": ActionDelete,
"home": ActionMoveToStartOfLine,
"end": ActionMoveToEndOfLine,
"ctrl+home": ActionMoveToStartOfDocument,
"ctrl+end": ActionMoveToEndOfDocument,
"left": ActionCursorLeft,
"right": ActionCursorRight,
}
func action_for_key_event(event *loop.KeyEvent, shortcuts map[string]Action) Action {
for sc, ac := range shortcuts {
if event.MatchesPressOrRepeat(sc) {
return ac
}
}
return ActionNil
}
func (self *Readline) handle_key_event(event *loop.KeyEvent) error {
if event.Text != "" {
return nil
}
ac := action_for_key_event(event, default_shortcuts)
if ac != ActionNil {
event.Handled = true
self.perform_action(ac, 1)
}
return nil
}