gilo/editor/editor.go
2021-03-30 14:42:59 -04:00

100 lines
1.8 KiB
Go

package editor
import (
"strings"
"timshome.page/gilo/fn"
"timshome.page/gilo/terminal"
)
// ----------------------------------------------------------------------------
// !Editor
// ----------------------------------------------------------------------------
type cursor struct {
x int
y int
}
type editor struct {
screen *terminal.Screen
cursor *cursor
}
func New() *editor {
screen := terminal.Size()
cursor := &cursor { 0, 0 }
return &editor{screen, cursor }
}
func (e *editor) ProcessKeypress() bool {
var runes []rune
// for ch, size := terminal.ReadKey(); size != 0; ch, size = terminal.ReadKey() {
for i := 0; i < 4; i++ {
ch, size := terminal.ReadKey()
if size == 0 {
break
}
if ch == fn.Ctrl('q') {
// Clean up on exit
terminal.Write(terminal.ClearScreen + terminal.ResetCursor)
return false
}
runes = append(runes, ch)
// Break early for arrow keys
if i == 2 && ch >= 'A' && ch <= 'D' {
break
}
}
// terminal.Write("%v", runes)
str := string(runes)
runes = runes[:0]
// Escape sequences can be less fun...
if strings.Contains(str, terminal.EscPrefix) {
code := strings.TrimPrefix(str, terminal.EscPrefix)
switch code {
case KeyArrowUp, KeyArrowDown, KeyArrowLeft, KeyArrowRight, KeyPageUp, KeyPageDown:
e.moveCursor(code)
runes = runes[:0]
return true
default:
// Do something later
terminal.Write("Code: %v", str)
}
}
return true
}
func (e *editor) moveCursor (key string) {
switch key {
case KeyArrowLeft:
if e.cursor.x != 0 {
e.cursor.x -= 1
}
case KeyArrowRight:
if e.cursor.x != e.screen.Cols-1 {
e.cursor.x += 1
}
case KeyArrowUp:
if e.cursor.y != 0 {
e.cursor.y -= 1
}
case KeyArrowDown:
if e.cursor.y != e.screen.Rows-1 {
e.cursor.y += 1
}
case KeyPageUp:
e.cursor.y = 0
case KeyPageDown:
e.cursor.y = e.screen.Rows
}
}