gilo/editor/editor.go

109 lines
1.8 KiB
Go

package editor
import (
"fmt"
"timshome.page/gilo/fn"
"timshome.page/gilo/terminal"
)
const KiloVersion = "0.0.1"
// ----------------------------------------------------------------------------
// !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) ProcessKeypress() bool {
ch, _ := terminal.ReadKey()
// Clean up on exit
if ch == fn.Ctrl('q') {
terminal.Write(terminal.ClearScreen + terminal.ResetCursor)
return false
}
switch ch {
case 'w', 'a', 's', 'd':
e.moveCursor(ch)
default:
// Do nothing!
}
return true
}
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) moveCursor (key rune) {
switch key {
case 'a':
e.cursor.x -= 1
case 'd':
e.cursor.x += 1
case 'w':
e.cursor.y -= 1
case 's':
e.cursor.y += 1
}
}