diff --git a/kilo.c b/kilo.c index efe4073..cd23af4 100644 --- a/kilo.c +++ b/kilo.c @@ -38,6 +38,11 @@ enum editorKey { PAGE_DOWN, }; +enum editorHighlight { + HL_NORMAL = 0, + HL_NUMBER +}; + /*** data ***/ typedef struct erow { @@ -45,6 +50,7 @@ typedef struct erow { int rsize; char *chars; char *render; + unsigned char *hl; } erow; struct editorConfig { @@ -250,6 +256,35 @@ int getWindowSize(int *rows, int *cols) return 0; } +/*** syntax highlighting ***/ + +void editorUpdateSyntax(erow *row) +{ + row->hl = realloc(row->hl, row->rsize); + memset(row->hl, HL_NORMAL, row->rsize); + + int i; + for (i = 0; i < row->rsize; i++) + { + if (isdigit(row->render[i])) + { + row->hl[i] = HL_NUMBER; + } + } +} + +int editorSyntaxToColor(int hl) +{ + switch (hl) + { + case HL_NUMBER: + return 31; + + default: + return 37; + } +} + /*** row operations ***/ int editorRowCxToRx(erow *row, int cx) @@ -324,6 +359,8 @@ void editorUpdateRow(erow *row) } row->render[idx] = '\0'; row->rsize = idx; + + editorUpdateSyntax(row); } void editorInsertRow(int at, char *s, size_t len) @@ -343,6 +380,7 @@ void editorInsertRow(int at, char *s, size_t len) E.row[at].rsize = 0; E.row[at].render = NULL; + E.row[at].hl = NULL; editorUpdateRow(&E.row[at]); E.numrows++; @@ -353,6 +391,7 @@ void editorFreeRow(erow *row) { free(row->render); free(row->chars); + free(row->hl); } void editorDelRow(int at) @@ -744,7 +783,36 @@ void editorDrawRows(struct abuf *ab) len = E.screencols; } - abAppend(ab, &E.row[filerow].render[E.coloff], len); + char *c = &E.row[filerow].render[E.coloff]; + unsigned char *hl = &E.row[filerow].hl[E.coloff]; + int current_color = -1; + int j; + for (j = 0; j < len; j++) + { + if (hl[j] == HL_NORMAL) + { + if (current_color != -1) + { + abAppend(ab, "\x1b[39m", 5); + current_color = -1; + } + + abAppend(ab, &c[j], 1); + } + else + { + int color = editorSyntaxToColor(hl[j]); + if (color != current_color) + { + current_color = color; + char buf[16]; + int clen = snprintf(buf, sizeof(buf), "\x1b[%dm", color); + abAppend(ab, buf, clen); + } + abAppend(ab, &c[j], 1); + } + } + abAppend(ab, "\x1b[39m", 5); } abAppend(ab, "\x1b[K", 3);