gilo/editor/editor.go
2021-03-24 16:23:17 -04:00

83 lines
1.4 KiB
Go

package editor
import (
"fmt"
"timshome.page/gilo/fn"
"timshome.page/gilo/terminal"
)
const KiloVersion = "0.0.1"
// ----------------------------------------------------------------------------
// !Editor
// ----------------------------------------------------------------------------
type editor struct {
rows int
cols int
}
func New() *editor {
rows, cols := terminal.Size()
return &editor{rows, cols}
}
func (e *editor) RefreshScreen() {
ab := newBuffer()
ab.append(terminal.HideCursor)
ab.append(terminal.ResetCursor)
e.drawRows(ab)
ab.append(terminal.ResetCursor)
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
}
return true
}
func (e *editor) drawRows(ab *buffer) {
for y :=0; y < e.rows; y += 1 {
if y == e.rows / 3 {
welcome := fmt.Sprintf("Gilo editor -- version %s", KiloVersion)
if len(welcome) > e.cols {
welcome = fn.TruncateString(welcome, e.cols)
}
padding := (e.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.rows - 1) {
ab.append("\r\n")
}
}
}