gilo/editor/editor.go

83 lines
1.4 KiB
Go
Raw Normal View History

2021-03-19 16:36:02 -04:00
package editor
2021-03-19 17:03:56 -04:00
import (
2021-03-24 15:09:28 -04:00
"fmt"
2021-03-24 15:52:35 -04:00
"timshome.page/gilo/fn"
2021-03-24 16:23:17 -04:00
"timshome.page/gilo/terminal"
2021-03-19 17:03:56 -04:00
)
2021-03-24 15:52:35 -04:00
const KiloVersion = "0.0.1"
2021-03-24 15:09:28 -04:00
// ----------------------------------------------------------------------------
// !Editor
// ----------------------------------------------------------------------------
type editor struct {
2021-03-23 15:51:59 -04:00
rows int
cols int
}
func New() *editor {
2021-03-24 15:09:28 -04:00
rows, cols := terminal.Size()
2021-03-24 15:09:28 -04:00
return &editor{rows, cols}
2021-03-22 09:12:39 -04:00
}
func (e *editor) RefreshScreen() {
2021-03-24 15:09:28 -04:00
ab := newBuffer()
2021-03-24 16:23:17 -04:00
ab.append(terminal.HideCursor)
ab.append(terminal.ResetCursor)
2021-03-22 09:12:39 -04:00
2021-03-24 15:09:28 -04:00
e.drawRows(ab)
2021-03-22 09:12:39 -04:00
2021-03-24 16:23:17 -04:00
ab.append(terminal.ResetCursor)
ab.append(terminal.ShowCursor)
2021-03-24 15:09:28 -04:00
terminal.Write(ab.toString())
2021-03-19 17:39:15 -04:00
}
func (e *editor) ProcessKeypress() bool {
2021-03-24 13:24:40 -04:00
ch, _ := terminal.ReadKey()
2021-03-19 17:39:15 -04:00
// Clean up on exit
2021-03-24 16:23:17 -04:00
if ch == fn.Ctrl('q') {
terminal.Write(terminal.ClearScreen + terminal.ResetCursor)
2021-03-19 17:39:15 -04:00
return false
}
2021-03-19 17:03:56 -04:00
return true
}
2021-03-24 15:09:28 -04:00
func (e *editor) drawRows(ab *buffer) {
for y :=0; y < e.rows; y += 1 {
2021-03-24 15:52:35 -04:00
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('~')
}
2021-03-24 16:23:17 -04:00
ab.append(terminal.ClearLine)
if y < (e.rows - 1) {
2021-03-24 15:09:28 -04:00
ab.append("\r\n")
}
}
2021-03-24 15:52:35 -04:00
}