1
0
Fork 0
gilo/editor/editor.go

128 lines
2.4 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 {
// Handle simplest inputs first
ch, _ := terminal.ReadKey()
if ch == fn.Ctrl('q') {
// Clean up on exit
terminal.Write(terminal.ClearScreen + terminal.ResetCursor)
return false
} else {
// Back up so that the input can be read as a string
terminal.Write(terminal.ClearScreen + terminal.ResetCursor)
fmt.Printf("%v\r\n", keyMap)
return false
// terminal.UnReadKey()
}
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)
return true
default:
// Do something later
}
}
return true
}
//func (e *editor) processEscapeCode() bool {
//
//}
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
}
}