From 9248b9d56057bcb7b13f7ececeb4233ac7ccfbd0 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Tue, 20 Aug 2019 12:02:40 -0400 Subject: [PATCH] Insert new lines --- kilo.c | 36 ++++++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/kilo.c b/kilo.c index 9fedc36..6a0ecac 100644 --- a/kilo.c +++ b/kilo.c @@ -303,11 +303,16 @@ void editorUpdateRow(erow *row) row->rsize = idx; } -void editorAppendRow(char *s, size_t len) +void editorInsertRow(int at, char *s, size_t len) { - E.row = realloc(E.row, sizeof(erow) * (E.numrows + 1)); + if (at < 0 || at > E.numrows) + { + return; + } + + E.row = realloc(E.row, sizeof(erow) * (E.numrows + 1)); + memmove(&E.row[at + 1], &E.row[at], sizeof(erow) * (E.numrows - at)); - int at = E.numrows; E.row[at].size = len; E.row[at].chars = malloc(len + 1); memcpy(E.row[at].chars, s, len); @@ -383,12 +388,31 @@ void editorInsertChar(int c) { if (E.cy == E.numrows) { - editorAppendRow("", 0); + editorInsertRow(E.numrows, "", 0); } editorRowInsertChar(&E.row[E.cy], E.cx, c); E.cx++; } +void editorInsertNewline() +{ + if (E.cx == 0) + { + editorInsertRow(E.cy, "", 0); + } + else + { + erow *row = &E.row[E.cy]; + editorInsertRow(E.cy + 1, &row->chars[E.cx], row->size - E.cx); + row = &E.row[E.cy]; + row->size = E.cx; + row->chars[row->size] = '\0'; + editorUpdateRow(row); + } + E.cy++; + E.cx = 0; +} + void editorDelChar() { if (E.cy == E.numrows) @@ -463,7 +487,7 @@ void editorOpen(char *filename) { linelen--; } - editorAppendRow(line, linelen); + editorInsertRow(E.numrows, line, linelen); } free(line); @@ -766,7 +790,7 @@ void editorProcessKeypress() switch (c) { case '\r': - /* TODO */ + editorInsertNewline(); break; case CTRL_KEY('q'):