Add save functionality
All checks were successful
timw4mail/gilo/pipeline/head This commit looks good

This commit is contained in:
Timothy Warren 2021-04-01 20:23:51 -04:00
parent 522a549c91
commit a1f62aa8cb
3 changed files with 58 additions and 2 deletions

View File

@ -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)
}

View File

@ -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()

View File

@ -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 {