From 8821964375f1f950ccfd3eecb1fbbee4cbfcd95a Mon Sep 17 00:00:00 2001 From: jmug Date: Thu, 19 Nov 2026 16:37:18 -0800 Subject: [PATCH] feat: Render tabs as spaces. --- kilo.c | 40 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/kilo.c b/kilo.c index 60880c5..4a8294c 100644 --- a/kilo.c +++ b/kilo.c @@ -17,6 +17,7 @@ /*** defines ***/ #define KILO_VERSION "0.0.1" +#define KILO_TAB_STOP 8 #define CTRL_KEY(k) ((k) & 0x1f) @@ -36,7 +37,9 @@ enum editorKey { typedef struct erow { int size; + int rsize; char *chars; + char *render; } erow; struct editorConfig { @@ -197,6 +200,33 @@ int getWindowSize(int *rows, int *cols) { /*** row operations ***/ +void editorUpdateRow(erow *row) { + int tabs = 0; + int j; + for (j = 0; j < row->size; j++) + if (row->chars[j] == '\t') + tabs++; + + free(row->render); + // tabs already counted as one char. + row->render = malloc(row->size + tabs*(KILO_TAB_STOP-1) + 1); + + int rdx = 0; + for (j = 0; j < row->size; j++) { + if (row->chars[j] == '\t') { + row->render[rdx++] = ' '; + // This doesn't just implement a given number of characters per tab, + // but the actual behavior of adjusting the size based on positioning. + while (rdx % KILO_TAB_STOP != 0) row->render[rdx++] = ' '; + } else { + row->render[rdx++] = row->chars[j]; + } + } + + row->render[rdx] = '\0'; + row->rsize = rdx; +} + void editorAppendRow(char *r, size_t len) { E.row = realloc(E.row, sizeof(erow) * (E.numrows + 1)); @@ -206,6 +236,10 @@ void editorAppendRow(char *r, size_t len) { memcpy(E.row[at].chars, r, len); E.row[at].chars[len] = '\0'; + E.row[at].rsize = 0; + E.row[at].render = NULL; + editorUpdateRow(&E.row[at]); + E.numrows++; } @@ -296,10 +330,12 @@ void editorDrawRows(struct abuf *ab) { abAppend(ab, "~", 1); } } else { - int len = E.row[filerow].size - E.coloff; + int len = E.row[filerow].rsize - E.coloff; if (len < 0) len = 0; - abAppend(ab, &E.row[filerow].chars[E.coloff], len); + if (len > E.screencols) + len = E.screencols; + abAppend(ab, &E.row[filerow].render[E.coloff], len); } // Erase the line content to the right of the cursor.