gilo/editor/editor.go
Timothy Warren 458f94f576 Break stuff
2021-03-26 12:01:17 -04:00

117 lines
2.1 KiB
Go

package editor
import (
"fmt"
"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) RefreshScreen() {
ab := newBuffer()
ab.append(terminal.HideCursor)
ab.append(terminal.ResetCursor)
e.drawRows(ab)
ab.append(terminal.MoveCursor(e.cursor.x, e.cursor.y))
ab.append(terminal.ShowCursor)
terminal.Write(ab.toString())
}
func (e *editor) drawRows(ab *buffer) {
for y :=0; y < e.screen.Rows; y += 1 {
if y == e.screen.Rows / 3 {
welcome := fmt.Sprintf("Gilo editor -- version %s", KiloVersion)
if len(welcome) > e.screen.Cols {
welcome = fn.TruncateString(welcome, e.screen.Cols)
}
padding := (e.screen.Cols - len(welcome)) / 2
if padding > 0 {
ab.appendRune('~')
padding--
}
for padding > 0 {
padding--
ab.appendRune(' ')
}
ab.append(welcome)
} else {
ab.appendRune('~')
}
ab.append(terminal.ClearLine)
if y < (e.screen.Rows - 1) {
ab.append("\r\n")
}
}
}
func (e *editor) ProcessKeypress() bool {
str, _ := terminal.Read()
// 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:
e.moveCursor(code)
default:
// Do something later
}
}
for _, ch := range str {
// Clean up on exit
if ch == fn.Ctrl('q') {
terminal.Write(terminal.ClearScreen + terminal.ResetCursor)
return false
}
}
return true
}
func (e *editor) moveCursor (rawKey string) {
key := keyMap[rawKey]
switch key {
case keyLeft:
e.cursor.x -= 1
case keyRight:
e.cursor.x += 1
case keyUp:
e.cursor.y -= 1
case keyDown:
e.cursor.y += 1
}
}