126 lines
2.1 KiB
Go
126 lines
2.1 KiB
Go
package editor
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
"timshome.page/gilo/fn"
|
|
"timshome.page/gilo/internal/ansi"
|
|
"timshome.page/gilo/internal/char"
|
|
"timshome.page/gilo/internal/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(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 {
|
|
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(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()
|
|
} |