1
0
Fork 0
gilo/editor/document.go

91 lines
1.3 KiB
Go

package editor
import (
"bufio"
"log"
"os"
)
type document struct {
filename string
rows []*row
}
func newDocument() *document {
var rows []*row
return &document{
"",
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())
}
}
func (d *document) save() int {
if d.filename == "" {
return 0
}
file, err := os.OpenFile(d.filename, os.O_RDWR | os.O_CREATE, 0644)
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
}
return 0
}
func (d *document) appendRow(s string) {
newRow := newRow(s)
newRow.update()
d.rows = append(d.rows, newRow)
}
func (d *document) toString() string {
buf := newBuffer()
for _, row := range d.rows {
buf.append(row.toString())
buf.appendRune('\n')
}
return buf.toString()
}
func (d *document) rowCount() int {
return len(d.rows)
}