diff --git a/kilo.c b/kilo.c index 4a5ba08..ffa860c 100644 --- a/kilo.c +++ b/kilo.c @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -118,29 +119,57 @@ int getWindowSize(int *rows, int *cols) { return 0; } +/*** append buffer ***/ + +struct abuf { + char *b; + int len; +}; + +#define ABUF_INIT {NULL, 0} + +void abAppend(struct abuf *ab, const char *s, int len) { + char *new = realloc(ab->b, ab->len + len); + if (new == NULL) + return; + // Copy s starting at the end of the existing content. + memcpy(&new[ab->len], s, len); + ab->b = new; + ab->len += len; +} + +void abFree(struct abuf *ab) { + free(ab->b); +} + /*** output ***/ -void editorDrawRows() { +void editorDrawRows(struct abuf *ab) { for (int y = 0; y < E.screenrows; y++) { - write(STDOUT_FILENO, "~", 1); + abAppend(ab, "~", 1); // No new line on the last line, the terminal scrolls past the // first line otherwise. if (y < E.screenrows - 1) { - write(STDOUT_FILENO, "\r\n", 2); + abAppend(ab, "\r\n", 2); } } } void editorRefreshScreen() { + struct abuf ab = ABUF_INIT; // Clear the whole screen. - write(STDOUT_FILENO, "\x1b[2J", 4); + abAppend(&ab, "\x1b[2J", 4); // Move cursor to top left. - write(STDOUT_FILENO, "\x1b[H", 3); + abAppend(&ab, "\x1b[H", 3); - editorDrawRows(); + editorDrawRows(&ab); - write(STDOUT_FILENO, "\x1b[H", 3); + // Return cursor to top left after drawing. + abAppend(&ab, "\x1b[H", 3); + + write(STDOUT_FILENO, ab.b, ab.len); + abFree(&ab); } /*** input ***/