1
1
Fork 0

Adds home end delete and backspace, starts overflow solutions

This commit is contained in:
sloum 2021-04-01 20:24:07 -07:00
parent 8fa1f10d88
commit 5a837ab3fc
1 changed files with 36 additions and 11 deletions

47
main.go
View File

@ -26,16 +26,34 @@ const (
BackSpace rune = 127
)
var (
width int
)
type Buffer struct {
buf []rune
cursor int
maxWidth int
offset int
}
func (lb Buffer) String() string {
return string(lb.buf)
}
func (lb *Buffer) AddChar(c rune, echo bool) {
func (lb *Buffer) deleteChar() {
if lb.cursor == len(lb.buf) {
return
} else if lb.cursor == len(lb.buf)-1 {
lb.buf = lb.buf[:len(lb.buf)-1]
fmt.Printf("\033[0K")
} else {
lb.buf = append(lb.buf[:lb.cursor], lb.buf[lb.cursor+1:]...)
fmt.Printf("%s\033[0K\033[%dD", string(lb.buf[lb.cursor:]), len(lb.buf)-lb.cursor)
}
}
func (lb *Buffer) addChar(c rune, echo bool) {
if lb.cursor == len(lb.buf) {
lb.buf = append(lb.buf, c)
lb.cursor++
@ -55,9 +73,12 @@ func (lb *Buffer) AddChar(c rune, echo bool) {
func (lb *Buffer) controlInput(c rune) {
switch c {
case Delete:
lb.deleteChar()
case BackSpace:
lb.cursor--
fmt.Printf("%c", BackSpace)
fmt.Print("\033[1D")
lb.deleteChar()
case LeftArrow:
if lb.cursor > 0 {
lb.cursor--
@ -68,17 +89,24 @@ func (lb *Buffer) controlInput(c rune) {
lb.cursor++
fmt.Print("\033[1C")
}
case Home:
fmt.Printf("\033[%dD", lb.cursor)
lb.cursor = 0
case End:
fmt.Printf("\033[%dC", len(lb.buf)-lb.cursor)
lb.cursor = len(lb.buf)
}
}
func (lb *Buffer) seedContent(s string) {
for _, r := range s {
lb.AddChar(r, false)
lb.addChar(r, false)
}
}
func GetText(prompt string, content string, endChar rune, includeEndChar bool) string {
b := Buffer{make([]rune, 0, (len(content)+1)*2), 0}
func GetText(prompt string, content string) string {
cols, _ := termios.GetWindowSize()
b := Buffer{make([]rune, 0, (len(content)+1)*2), 0, cols-len(prompt), 0}
b.seedContent(content)
fmt.Print(prompt)
@ -93,17 +121,14 @@ func GetText(prompt string, content string, endChar rune, includeEndChar bool) s
if err != nil {
continue
}
if ch == endChar {
if includeEndChar {
b.AddChar(ch, true)
}
if ch == CarriageReturn || ch == NewLine {
break
}
if isControl(ch) {
b.controlInput(ch)
} else {
b.AddChar(ch, true)
b.addChar(ch, true)
}
}
@ -230,6 +255,6 @@ func main() {
for {
fmt.Print("\n")
str = GetText("> ", str, '\n', false)
str = GetText("> ", str)
}
}