gilo/editor/document.go

100 lines
1.5 KiB
Go
Raw Normal View History

package editor
import (
"bufio"
"log"
"os"
2021-04-02 13:11:54 -04:00
"timshome.page/gilo/internal/buffer"
)
type document struct {
2021-04-01 20:26:40 -04:00
dirty bool
filename string
rows []*row
}
func newDocument() *document {
var rows []*row
return &document{
2021-04-01 20:26:40 -04:00
false,
"",
rows,
}
}
func (d *document) open(filename string) {
file, err := os.Open(filename)
if err != nil {
log.Fatalf("failed to open file")
}
defer file.Close()
d.filename = filename
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
d.appendRow(scanner.Text())
}
2021-04-02 10:07:37 -04:00
d.dirty = false
}
2021-04-01 20:23:51 -04:00
func (d *document) save() int {
if d.filename == "" {
return 0
}
2021-04-01 20:26:40 -04:00
file, err := os.OpenFile(d.filename, os.O_RDWR|os.O_CREATE, 0644)
2021-04-01 20:23:51 -04:00
if err != nil {
panic("failed to open/create file for saving")
}
defer file.Close()
fileStr := d.toString()
fileLen := len(fileStr)
err = file.Truncate(int64(fileLen))
if err != nil {
panic("failed to truncate file")
}
size, err := file.WriteString(fileStr)
if err != nil {
panic("failed to save document to file")
}
if fileLen == size {
return size
}
2021-04-02 10:07:37 -04:00
d.dirty = false
2021-04-01 20:23:51 -04:00
return 0
}
func (d *document) appendRow(s string) {
newRow := newRow(s)
newRow.update()
d.rows = append(d.rows, newRow)
2021-04-02 10:07:37 -04:00
d.dirty = true
}
2021-04-01 20:23:51 -04:00
func (d *document) toString() string {
2021-04-02 13:11:54 -04:00
buf := buffer.NewBuffer()
2021-04-01 20:23:51 -04:00
for _, row := range d.rows {
2021-04-02 13:11:54 -04:00
buf.Append(row.toString())
buf.AppendRune('\n')
2021-04-01 20:23:51 -04:00
}
2021-04-02 13:11:54 -04:00
return buf.ToString()
2021-04-01 20:23:51 -04:00
}
func (d *document) rowCount() int {
return len(d.rows)
2021-04-01 16:17:13 -04:00
}