basic syntax highlighting

This commit is contained in:
Timothy Warren 2019-08-20 15:57:15 -04:00
parent be036bbee3
commit dc71f7f9a3

70
kilo.c
View File

@ -38,6 +38,11 @@ enum editorKey {
PAGE_DOWN, PAGE_DOWN,
}; };
enum editorHighlight {
HL_NORMAL = 0,
HL_NUMBER
};
/*** data ***/ /*** data ***/
typedef struct erow { typedef struct erow {
@ -45,6 +50,7 @@ typedef struct erow {
int rsize; int rsize;
char *chars; char *chars;
char *render; char *render;
unsigned char *hl;
} erow; } erow;
struct editorConfig { struct editorConfig {
@ -250,6 +256,35 @@ int getWindowSize(int *rows, int *cols)
return 0; 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 ***/ /*** row operations ***/
int editorRowCxToRx(erow *row, int cx) int editorRowCxToRx(erow *row, int cx)
@ -324,6 +359,8 @@ void editorUpdateRow(erow *row)
} }
row->render[idx] = '\0'; row->render[idx] = '\0';
row->rsize = idx; row->rsize = idx;
editorUpdateSyntax(row);
} }
void editorInsertRow(int at, char *s, size_t len) 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].rsize = 0;
E.row[at].render = NULL; E.row[at].render = NULL;
E.row[at].hl = NULL;
editorUpdateRow(&E.row[at]); editorUpdateRow(&E.row[at]);
E.numrows++; E.numrows++;
@ -353,6 +391,7 @@ void editorFreeRow(erow *row)
{ {
free(row->render); free(row->render);
free(row->chars); free(row->chars);
free(row->hl);
} }
void editorDelRow(int at) void editorDelRow(int at)
@ -744,7 +783,36 @@ void editorDrawRows(struct abuf *ab)
len = E.screencols; 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); abAppend(ab, "\x1b[K", 3);