gilo/internal/editor/editor.go
2021-03-24 15:20:57 -04:00

103 lines
1.7 KiB
Go

package editor
import (
"fmt"
"strings"
"timshome.page/gilo/internal/ansi"
"timshome.page/gilo/internal/char"
"timshome.page/gilo/internal/terminal"
)
// ----------------------------------------------------------------------------
// !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(ansi.HideCursor)
ab.append(ansi.ResetCursor)
e.drawRows(ab)
ab.append(ansi.ResetCursor)
ab.append(ansi.ShowCursor)
terminal.Write(ab.toString())
}
func (e *editor) ProcessKeypress() bool {
ch, _ := terminal.ReadKey()
// Clean up on exit
if ch == char.Ctrl('q') {
terminal.Write(ansi.ClearScreen + ansi.ResetCursor)
return false
}
return true
}
func (e *editor) drawRows(ab *buffer) {
for y :=0; y < e.rows; y += 1 {
ab.appendRune('~')
ab.append(ansi.ClearLine)
if y < (e.rows - 1) {
ab.append("\r\n")
}
}
}
// ----------------------------------------------------------------------------
// !buffer
// ----------------------------------------------------------------------------
type buffer struct {
buf *strings.Builder
}
func newBuffer() *buffer {
var buf strings.Builder
b := new(buffer)
b.buf = &buf
return b
}
func (b *buffer) appendRune(r rune) int {
size, _ := b.buf.WriteRune(r)
return size
}
func (b *buffer) append(s string) int {
size, _ := b.buf.WriteString(s)
return size
}
func (b *buffer) appendLn(s string) int {
str := fmt.Sprintf("%s\r\n", s)
size, _ := b.buf.WriteString(str)
return size
}
func (b *buffer) toString() string {
return b.buf.String()
}