diff --git a/internal/editor/document/document.go b/internal/editor/document/document.go index 582ce7d..7bad7c0 100644 --- a/internal/editor/document/document.go +++ b/internal/editor/document/document.go @@ -87,6 +87,41 @@ func (d *Document) AppendRow(s string) { d.dirty = true } +func (d *Document) InsertRow(at int, s string) { + if at < 0 || at > d.RowCount() { + return + } + + var newRows []*Row + + // Split the array of rows at the specified index + start := d.rows[0:at] + end := d.rows[at : d.RowCount()] + + // Splice it back together + newRows = append(newRows, start...) + newRows = append(newRows, newRow(s)) + newRows = append(newRows, end...) + + d.rows = newRows + d.dirty = true +} + +func (d *Document) InsertNewline(at *gilo.Point) { + if at.X == 0 { + d.InsertRow(at.Y, "") + } else { + row := d.rows[at.Y] + + // Insert the characters right of the cursor to the next line + d.InsertRow(at.Y + 1, string(row.chars[at.X:row.Size()])) + + // Remove the characters copied to the next line + row.chars = row.chars[0:at.X] + row.update() + } +} + func (d *Document) MergeRows(to int, from int) { d.rows[to].appendString(d.rows[from].toString()) d.delRow(from) diff --git a/internal/editor/input.go b/internal/editor/input.go index 563ba2d..5340542 100644 --- a/internal/editor/input.go +++ b/internal/editor/input.go @@ -45,6 +45,9 @@ func (e *editor) processKeypressChar(ch rune) bool { e.Save() case key.Enter: + e.document.InsertNewline(e.cursor) + e.cursor.Y += 1 + e.cursor.X = 0 case key.Backspace, key.Ctrl('h'): e.delChar()