From a1f62aa8cbd7a1908ea338888c98e06146738592 Mon Sep 17 00:00:00 2001 From: "Timothy J. Warren" Date: Thu, 1 Apr 2021 20:23:51 -0400 Subject: [PATCH] Add save functionality --- editor/document.go | 43 +++++++++++++++++++++++++++++++++++++++++++ editor/editor.go | 15 ++++++++++++++- gilo.go | 2 +- 3 files changed, 58 insertions(+), 2 deletions(-) diff --git a/editor/document.go b/editor/document.go index 3601672..a1a80c2 100644 --- a/editor/document.go +++ b/editor/document.go @@ -36,12 +36,55 @@ func (d *document) open(filename string) { } } +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) } diff --git a/editor/editor.go b/editor/editor.go index 812acf5..68630c6 100644 --- a/editor/editor.go +++ b/editor/editor.go @@ -58,6 +58,16 @@ func (e *editor) Open(filename string) { e.document.open(filename) } +func (e *editor) save() { + size := e.document.save() + + if size > 0 { + e.SetStatusMessage("%d bytes written to disk", size) + } else { + e.SetStatusMessage("Failed to save file") + } +} + func (e *editor) SetStatusMessage(template string, a ...interface{}) { e.status = &statusMsg{ fmt.Sprintf(template, a...), @@ -75,11 +85,14 @@ func (e *editor) ProcessKeypress() bool { return false + case key.Ctrl('s'): + e.save() + case key.Enter: case key.Backspace, key.Ctrl('h'): - case key.Esc: + case key.Esc, key.Ctrl('l'): // Modifier keys that return ANSI escape sequences str := parseEscapeSequence() diff --git a/gilo.go b/gilo.go index 3ab9f8b..669e8ac 100644 --- a/gilo.go +++ b/gilo.go @@ -29,7 +29,7 @@ func main() { e.Open(os.Args[1]) } - e.SetStatusMessage("HELP: Ctrl-Q = quit") + e.SetStatusMessage("HELP: Ctrl-S = save | Ctrl-Q = quit") // The input loop for {