gilo/editor/editor.go

108 lines
1.8 KiB
Go
Raw Normal View History

2021-04-02 13:11:54 -04:00
// The main interface/implementation of the editor object
2021-03-19 16:36:02 -04:00
package editor
2021-03-19 17:03:56 -04:00
import (
2021-04-01 13:25:59 -04:00
"fmt"
"time"
2021-03-24 16:23:17 -04:00
"timshome.page/gilo/terminal"
2021-03-19 17:03:56 -04:00
)
2021-03-24 15:09:28 -04:00
// ----------------------------------------------------------------------------
// !Editor
// ----------------------------------------------------------------------------
2021-03-31 09:43:47 -04:00
type point struct {
x int
y int
}
2021-04-01 13:25:59 -04:00
type statusMsg struct {
message string
created time.Time
}
type editor struct {
2021-04-02 10:48:51 -04:00
screen *terminal.Screen
cursor *point
offset *point
document *document
status *statusMsg
quitTimes uint8
2021-04-02 10:48:51 -04:00
renderX int
2021-03-23 15:51:59 -04:00
}
func New() *editor {
screen := terminal.Size()
2021-04-01 09:41:16 -04:00
2021-04-01 13:25:59 -04:00
// Subtract rows for status bar and message bar/prompt
screen.Rows -= 2
2021-04-01 09:41:16 -04:00
2021-04-01 16:17:13 -04:00
cursor := &point{0, 0}
offset := &point{0, 0}
document := newDocument()
2021-04-01 13:25:59 -04:00
status := &statusMsg{
"",
time.Now(),
}
2021-03-31 09:43:47 -04:00
return &editor{
screen,
cursor,
offset,
document,
2021-04-01 13:25:59 -04:00
status,
KiloQuitTimes,
2021-03-31 14:56:46 -04:00
0,
2021-03-31 09:43:47 -04:00
}
2021-03-22 09:12:39 -04:00
}
2021-03-30 18:29:23 -04:00
func (e *editor) Open(filename string) {
e.document.open(filename)
2021-03-30 18:00:06 -04:00
}
2021-04-02 12:03:33 -04:00
func (e *editor) Save() {
2021-04-01 20:23:51 -04:00
size := e.document.save()
if size > 0 {
e.SetStatusMessage("%d bytes written to disk", size)
} else {
e.SetStatusMessage("Failed to save file")
}
}
2021-04-01 13:25:59 -04:00
func (e *editor) SetStatusMessage(template string, a ...interface{}) {
2021-04-01 16:17:13 -04:00
e.status = &statusMsg{
2021-04-01 13:25:59 -04:00
fmt.Sprintf(template, a...),
time.Now(),
}
}
2021-03-26 16:18:03 -04:00
func (e *editor) ProcessKeypress() bool {
2021-03-30 15:45:13 -04:00
ch, _ := terminal.ReadKey()
2021-03-24 15:52:35 -04:00
2021-04-02 11:57:24 -04:00
return e.processKeypressChar(ch)
}
2021-04-01 16:17:13 -04:00
func (e *editor) insertChar(ch rune) {
if e.cursor.y == e.document.rowCount() {
e.document.appendRow("")
}
e.document.rows[e.cursor.y].insertRune(ch, e.cursor.x)
e.cursor.x += 1
2021-04-02 10:07:37 -04:00
e.document.dirty = true
2021-04-01 16:17:13 -04:00
}
2021-04-02 10:48:51 -04:00
func (e *editor) delChar() {
if e.cursor.y == e.document.rowCount() {
return
}
if e.cursor.x > 0 {
e.document.rows[e.cursor.y].deleteRune(e.cursor.x - 1)
e.cursor.x -= 1
}
e.document.dirty = true
}