bbash/input_parser/escape_handler.go
2025-01-14 10:39:22 +01:00

106 lines
2.0 KiB
Go

package input_parser
import (
"bbash/environment"
"bufio"
"fmt"
"strings"
)
func Escape_handler(reader *bufio.Reader, history_index int, input string, env environment.Env, cursor int) (string, int, int) {
next_rune, _, _ := reader.ReadRune()
if next_rune == 59 {
}
if next_rune != 91 { // not "["
return "", history_index, cursor
}
next_rune, _, _ = reader.ReadRune()
switch next_rune {
case 65: //A
if history_index > 0 {
history_index--
input = env.History[history_index]
cursor = len(input)
}
case 66: //B
if history_index < len(env.History)-1 {
history_index++
input = env.History[history_index]
}
if history_index == len(env.History)-1 {
input = ""
cursor = 0
}
cursor = len(input)
case 68: //D
if cursor > 0 {
cursor--
}
case 67: //C
if prevGhostString != "" {
input = input + prevGhostString
cursor = len(input)
}
if cursor < len(input) {
cursor++
}
case 49:
cursor = ctrl(reader, input, cursor)
return input, history_index, cursor
}
return input, history_index, cursor
}
func ctrl(reader *bufio.Reader, input string, cursor int) int {
next_rune, _, err := reader.ReadRune()
if err != nil {
fmt.Println(err.Error())
return cursor
}
if next_rune != 59 {
return cursor
}
next_rune, _, err = reader.ReadRune()
if err != nil {
fmt.Println(err.Error())
return cursor
}
if next_rune != 53 {
return cursor
}
next_rune, _, err = reader.ReadRune()
if err != nil {
fmt.Println(err.Error())
return cursor
}
switch next_rune {
case 68: // ctrl left
input_at := input[:cursor]
last_index := strings.LastIndex(input_at, " ")
if last_index == -1 {
cursor = 0
} else {
input_at = input_at[:last_index]
cursor = len(input_at)
}
case 67: // ctrl right
input_next := input[cursor:]
next_trimmed := strings.TrimLeft(input_next, " ")
last_index := strings.Index(next_trimmed, " ")
if last_index == -1 {
cursor = len(input)
} else {
cursor = cursor + last_index + (len(input_next) - len(next_trimmed))
}
}
return cursor
}