gilo/editor/editor.go

100 lines
1.8 KiB
Go
Raw Normal View History

2021-03-19 16:36:02 -04:00
package editor
2021-03-19 17:03:56 -04:00
import (
2021-03-30 11:52:44 -04:00
"strings"
2021-03-24 15:52:35 -04:00
"timshome.page/gilo/fn"
2021-03-24 16:23:17 -04:00
"timshome.page/gilo/terminal"
2021-03-19 17:03:56 -04:00
)
2021-03-24 15:09:28 -04:00
// ----------------------------------------------------------------------------
// !Editor
// ----------------------------------------------------------------------------
type cursor struct {
x int
y int
}
type editor struct {
screen *terminal.Screen
cursor *cursor
2021-03-23 15:51:59 -04:00
}
func New() *editor {
screen := terminal.Size()
cursor := &cursor { 0, 0 }
return &editor{screen, cursor }
2021-03-22 09:12:39 -04:00
}
2021-03-26 16:18:03 -04:00
func (e *editor) ProcessKeypress() bool {
var runes []rune
2021-03-24 15:09:28 -04:00
2021-03-30 14:11:36 -04:00
// for ch, size := terminal.ReadKey(); size != 0; ch, size = terminal.ReadKey() {
2021-03-30 14:42:59 -04:00
for i := 0; i < 4; i++ {
2021-03-30 14:11:36 -04:00
ch, size := terminal.ReadKey()
if size == 0 {
break
}
2021-03-26 16:18:03 -04:00
if ch == fn.Ctrl('q') {
// Clean up on exit
terminal.Write(terminal.ClearScreen + terminal.ResetCursor)
2021-03-19 17:39:15 -04:00
2021-03-26 16:18:03 -04:00
return false
2021-03-24 15:52:35 -04:00
}
2021-03-26 16:18:03 -04:00
runes = append(runes, ch)
2021-03-30 14:42:59 -04:00
// Break early for arrow keys
if i == 2 && ch >= 'A' && ch <= 'D' {
break
}
2021-03-26 12:01:17 -04:00
}
2021-03-30 14:42:59 -04:00
// terminal.Write("%v", runes)
2021-03-30 11:52:44 -04:00
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 {
2021-03-30 14:42:59 -04:00
case KeyArrowUp, KeyArrowDown, KeyArrowLeft, KeyArrowRight, KeyPageUp, KeyPageDown:
2021-03-30 11:52:44 -04:00
e.moveCursor(code)
runes = runes[:0]
return true
default:
// Do something later
terminal.Write("Code: %v", str)
}
}
2021-03-26 16:18:03 -04:00
2021-03-30 11:52:44 -04:00
return true
2021-03-26 12:01:17 -04:00
}
2021-03-30 14:42:59 -04:00
func (e *editor) moveCursor (key string) {
2021-03-25 12:46:53 -04:00
switch key {
2021-03-30 14:42:59 -04:00
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
2021-03-25 12:46:53 -04:00
}
2021-03-24 15:52:35 -04:00
}