语法高亮(第七节)

彩色数字

让我们从尽可能简单地在屏幕上显示一些颜色开始。我们将尝试通过把每个数字字符都涂成红色来高亮显示数字。

kilo.c
步骤142
语法高亮 - 数字

/*** 包含的头文件 ***/
/*** 宏定义 ***/
/*** 数据 ***/
/*** 函数原型声明 ***/
/*** 终端相关操作 ***/
/*** 行操作 ***/
/*** 编辑器操作 ***/
/*** 文件输入输出 ***/
/*** 查找 ***/
/*** 追加缓冲区 ***/
/*** 输出 ***/
void editorScroll() { … }
void editorDrawRows(struct abuf *ab) {
  int y;
  for (y = 0; y < E.screenrows; y++) {
    int filerow = y + E.rowoff;
    if (filerow >= E.numrows) {
      if (E.numrows == 0 && y == E.screenrows / 3) {
        char welcome[80];
        int welcomelen = snprintf(welcome, sizeof(welcome),
          "Kilo 编辑器 -- 版本 %s", KILO_VERSION);
        if (welcomelen > E.screencols) welcomelen = E.screencols;
        int padding = (E.screencols - welcomelen) / 2;
        if (padding) {
          abAppend(ab, "~"1);
          padding--;
        }
        while (padding--) abAppend(ab, " "1);
        abAppend(ab, welcome, welcomelen);
      } else {
        abAppend(ab, "~"1);
      }
    } else {
      int len = E.row[filerow].rsize - E.coloff;
      if (len < 0) len = 0;
      if (len > E.screencols) len = E.screencols;
      char *c = &E.row[filerow].render[E.coloff];
      int j;
      for (j = 0; j < len; j++) {
        if (isdigit(c[j])) {
          abAppend(ab, "\x1b[31m"5);
          abAppend(ab, &c[j], 1);
          abAppend(ab, "\x1b[39m"5);
        } else {
          abAppend(ab, &c[j], 1);
        }
      }
    }
    abAppend(ab, "\x1b[K"3);
    abAppend(ab, "\r\n"2);
  }
}
void editorDrawStatusBar(struct abuf *ab) { … }
void editorDrawMessageBar(struct abuf *ab) { … }
void editorRefreshScreen() { … }
void editorSetStatusMessage(const char *fmt, ...) { … }
/*** 输入 ***/
/*** 初始化 ***/

编译通过
我们不能再直接把想要打印的render子字符串输入到abAppend()函数中了。从现在开始,我们必须逐个字符地进行处理。所以我们遍历这些字符,并对每个字符使用isdigit()函数来测试它是否是一个数字字符。如果是,我们就在它前面加上<esc>[31m转义序列,并在它后面加上<esc>[39m序列。

扫描二维码关注微信公众号,回复密码,即可获取密码

阅读剩余
THE END