package editor import ( "bufio" "log" "os" "timshome.page/gilo/internal/buffer" ) type document struct { dirty bool filename string rows []*row } func newDocument() *document { var rows []*row return &document{ 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()) } d.dirty = false } 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 } d.dirty = false return 0 } func (d *document) appendRow(s string) { newRow := newRow(s) newRow.update() d.rows = append(d.rows, newRow) d.dirty = true } func (d *document) toString() string { buf := buffer.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) }