C语言构建您自己的文本编辑器
原项目地址:
https://github.com/antirez/kilo/blob/master/kilo.c
它在单个文件中大约有1000行C,没有依赖性,它在最小的编辑器中实现了您期望的所有基本功能,以及语法高亮显示和搜索功能。
首先是一个文本编辑器的核心数据结构和控制逻辑的部分定义。每个结构体(struct)和类型定义(typedef)都是为了支持编辑器的功能而精心设计的。下面是主要组件的详细解释:
struct editorSyntax
这个结构体用于定义和管理文本编辑器中语法高亮的规则。它包括几个关键字段:
char **filematch;:一个字符串数组,用于匹配文件类型。例如,可以根据文件扩展名(如.c、.h等)来应用特定的语法高亮规则。char **keywords;:关键字字符串数组,用于语法高亮显示。通常区分语言关键字和常规文本。char singleline_comment_start[2];:单行注释的开始标记,如 C 语言中的//。char multiline_comment_start[3];和char multiline_comment_end[3];:多行注释的开始和结束标记,如 C 语言中的/*和*/。int flags;:标志位,用于控制语法高亮的一些特定行为。
typedef struct erow
erow 代表编辑器中的一行文本。它包括以下字段:
int idx;:行在文件中的索引,从0开始。int size;和int rsize;:分别代表行的原始大小和渲染后的大小。渲染大小指的是考虑特殊字符(如制表符TAB)展开后的大小。char *chars;和char *render;:分别存储行的原始内容和渲染内容。unsigned char *hl;:每个渲染字符的语法高亮类型。int hl_oc;:指示该行在上一次语法高亮检查中是否以开放的多行注释结束。
typedef struct hlcolor
用于定义语法高亮颜色的结构,包括RGB颜色值。
struct editorConfig
这个结构体维护编辑器的全局状态和配置,包括:
- 光标位置、屏幕偏移量、屏幕尺寸、文件行数等基础信息。
int rawmode;:指示终端是否处于原始模式(raw mode),在这种模式下,终端不会处理输入的特殊字符,如Ctrl+C等。erow *row;:指向erow结构的数组,表示文件的各个行。int dirty;:标志位,指示文件自上次保存以来是否被修改过。char *filename;:当前打开文件的名称。char statusmsg[80];和time_t statusmsg_time;:用于显示和维护状态消息及其显示时间。struct editorSyntax *syntax;:指向当前使用的语法高亮规则。
enum KEY_ACTION
定义了一系列键盘动作的枚举,包括各种控制键(如Ctrl+C、Ctrl+Q等)和软编码键(如方向键、Home键等)。这些动作用于编辑器的事件处理逻辑中,用于响应用户的按键操作。
static struct editorConfig E;
声明了一个editorConfig类型的静态全局变量E,它在编辑器运行期间持续存储编辑器的状态和配置。
总的来说,这段代码是一个文本编辑器的数据结构和功能定义的一部分,涵盖了从基本的文本处理到语法高亮等高级功能的实现基础。
struct editorSyntax {
char **filematch;
char **keywords;
char singleline_comment_start[2];
char multiline_comment_start[3];
char multiline_comment_end[3];
int flags;
};
/* This structure represents a single line of the file we are editing. */
typedef struct erow {
int idx; /* Row index in the file, zero-based. */
int size; /* Size of the row, excluding the null term. */
int rsize; /* Size of the rendered row. */
char *chars; /* Row content. */
char *render; /* Row content "rendered" for screen (for TABs). */
unsigned char *hl; /* Syntax highlight type for each character in render.*/
int hl_oc; /* Row had open comment at end in last syntax highlight
check. */
} erow;
typedef struct hlcolor {
int r,g,b;
} hlcolor;
struct editorConfig {
int cx,cy; /* Cursor x and y position in characters */
int rowoff; /* Offset of row displayed. */
int coloff; /* Offset of column displayed. */
int screenrows; /* Number of rows that we can show */
int screencols; /* Number of cols that we can show */
int numrows; /* Number of rows */
int rawmode; /* Is terminal raw mode enabled? */
erow *row; /* Rows */
int dirty; /* File modified but not saved. */
char *filename; /* Currently open filename */
char statusmsg[80];
time_t statusmsg_time;
struct editorSyntax *syntax; /* Current syntax highlight, or NULL. */
};
static struct editorConfig E;
enum KEY_ACTION{
KEY_NULL = 0, /* NULL */
CTRL_C = 3, /* Ctrl-c */
CTRL_D = 4, /* Ctrl-d */
CTRL_F = 6, /* Ctrl-f */
CTRL_H = 8, /* Ctrl-h */
TAB = 9, /* Tab */
CTRL_L = 12, /* Ctrl+l */
ENTER = 13, /* Enter */
CTRL_Q = 17, /* Ctrl-q */
CTRL_S = 19, /* Ctrl-s */
CTRL_U = 21, /* Ctrl-u */
ESC = 27, /* Escape */
BACKSPACE = 127, /* Backspace */
/* The following are just soft codes, not really reported by the
* terminal directly. */
ARROW_LEFT = 1000,
ARROW_RIGHT,
ARROW_UP,
ARROW_DOWN,
DEL_KEY,
HOME_KEY,
END_KEY,
PAGE_UP,
PAGE_DOWN
};纤细吧解释一下
接下来实现语法高亮,并且如何处理终端的原始模式来直接读取和写入输入输出,绕过常规的终端处理。下面是对代码的详细解释:
语法高亮数据库 (Syntax highlights DB)
- 文件类型与关键词匹配 :为了添加对新语法的支持,你需要定义两个数组,一个是文件名匹配模式的列表,另一个是需要高亮的关键词列表。如果文件名匹配模式以点(
.)开头,它会匹配文件名的最后一部分(例如,.c匹配C语言文件)。否则,这个模式会被搜索在整个文件名中(如Makefile)。 - 关键词高亮 :关键词列表中的元素,如果在末尾加上一个
|字符,这个词会以不同的颜色高亮,允许你为不同的关键词集合设置不同的颜色。 - 语法高亮的配置 :最后,通过在
HLDB全局变量中添加一段配置,包括上述两个数组、注释和数字的高亮标志,以及单行和多行注释的字符,来完成语法高亮的设置。
低级终端处理 (Low level terminal handling)
这部分代码演示了如何处理终端的原始模式,这是一种绕过普通终端行为直接与终端交互的模式,它对于编写文本编辑器等需要处理按键事件的程序非常有用。
- 原始模式启用和禁用 :原始模式下,输入不会被缓冲,也不会被解释成特殊字符(如Ctrl+C)。这意味着程序可以读取并直接响应每个按键。
enableRawMode函数启用原始模式,disableRawMode函数禁用原始模式,恢复到终端的默认行为。 - 原始模式配置 :在原始模式下,对
termios结构体的配置是非常重要的,它定义了终端I/O的各种行为。例如,取消回车到新行的映射、关闭回显、关闭规范输入处理等。 - 退出时恢复默认模式 :
editorAtExit函数确保在程序退出时禁用原始模式,防止终端处于不可预期的状态。
void editorSetStatusMessage(const char *fmt, ...);
/* =========================== Syntax highlights DB =========================
* * In order to add a new syntax, define two arrays with a list of file name
* matches and keywords. The file name matches are used in order to match
* a given syntax with a given file name: if a match pattern starts with a
* dot, it is matched as the last past of the filename, for example ".c".
* Otherwise the pattern is just searched inside the filenme, like "Makefile").
* * The list of keywords to highlight is just a list of words, however if they
* a trailing '|' character is added at the end, they are highlighted in
* a different color, so that you can have two different sets of keywords.
* * Finally add a stanza in the HLDB global variable with two two arrays
* of strings, and a set of flags in order to enable highlighting of
* comments and numbers.
* * The characters for single and multi line comments must be exactly two
* and must be provided as well (see the C language example).
* * There is no support to highlight patterns currently. */
/* C / C++ */
char *C_HL_extensions[] = {".c",".h",".cpp",".hpp",".cc",NULL};
char *C_HL_keywords[] = {
/* C Keywords */
"auto","break","case","continue","default","do","else","enum",
"extern","for","goto","if","register","return","sizeof","static",
"struct","switch","typedef","union","volatile","while","NULL",
/* C++ Keywords */
"alignas","alignof","and","and_eq","asm","bitand","bitor","class",
"compl","constexpr","const_cast","deltype","delete","dynamic_cast",
"explicit","export","false","friend","inline","mutable","namespace",
"new","noexcept","not","not_eq","nullptr","operator","or","or_eq",
"private","protected","public","reinterpret_cast","static_assert",
"static_cast","template","this","thread_local","throw","true","try",
"typeid","typename","virtual","xor","xor_eq",
/* C types */
"int|","long|","double|","float|","char|","unsigned|","signed|",
"void|","short|","auto|","const|","bool|",NULL
};
/* Here we define an array of syntax highlights by extensions, keywords,
* comments delimiters and flags. */
struct editorSyntax HLDB[] = {
{
/* C / C++ */
C_HL_extensions,
C_HL_keywords,
"//","/*","*/",
HL_HIGHLIGHT_STRINGS | HL_HIGHLIGHT_NUMBERS
}
};
#define HLDB_ENTRIES (sizeof(HLDB)/sizeof(HLDB[0]))
/* ======================= Low level terminal handling ====================== */
static struct termios orig_termios; /* In order to restore at exit.*/
void disableRawMode(int fd) {
/* Don't even check the return value as it's too late. */
if (E.rawmode) {
tcsetattr(fd,TCSAFLUSH,&orig_termios);
E.rawmode = 0;
}
}
/* Called at exit to avoid remaining in raw mode. */
void editorAtExit(void) {
disableRawMode(STDIN_FILENO);
}
/* Raw mode: 1960 magic shit. */
int enableRawMode(int fd) {
struct termios raw;
if (E.rawmode) return 0; /* Already enabled. */
if (!isatty(STDIN_FILENO)) goto fatal;
atexit(editorAtExit);
if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
raw = orig_termios; /* modify the original mode */
/* input modes: no break, no CR to NL, no parity check, no strip char,
* no start/stop output control. */
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
/* output modes - disable post processing */
raw.c_oflag &= ~(OPOST);
/* control modes - set 8 bit chars */
raw.c_cflag |= (CS8);
/* local modes - choing off, canonical off, no extended functions,
* no signal chars (^Z,^C) */
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
/* control chars - set return condition: min number of bytes and timer. */
raw.c_cc[VMIN] = 0; /* Return each byte, or zero for timeout. */
raw.c_cc[VTIME] = 1; /* 100 ms timeout (unit is tens of second). */
/* put terminal in raw mode after flushing */
if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
E.rawmode = 1;
return 0;
fatal:
errno = ENOTTY;
return -1;
}
终端窗口大小的获取和代码编辑器中的语法高亮处理。以下是对这两部分功能代码的详细解释:
1. 终端窗口大小的获取
**getCursorPosition(int ifd, int ofd, int rows, int cols)函数 :这个函数的目的是获取终端的光标位置。通过发送特殊的终端控制序列 "\x1b[6n"(询问光标位置),然后读取终端返回的响应,响应格式应该是 "\x1b[行;列R"。函数解析这个响应来设置rows和cols参数为光标的当前位置。如果过程中有任何错误发生(如写入或读取失败),函数返回-1。
**getWindowSize(int ifd, int ofd, int rows, int cols)函数 :此函数尝试获取当前终端窗口的大小。首先,它尝试使用ioctl()系统调用和TIOCGWINSZ命令来直接获取窗口大小。如果这个方法成功,函数就使用这些值设置rows和cols并返回0。如果ioctl()调用失败或返回的列数为0,函数转而尝试通过移动光标到估计的最远位置(通过发送"\x1b[999C\x1b[999B"序列),然后使用getCursorPosition()来猜测窗口的大小。之后,函数会恢复光标的原始位置并返回。
2. 代码编辑器中的语法高亮处理
is_separator(int c)函数 :检查给定的字符c是否是一个“分隔符”。分隔符包括空字符、空格或特定的标点符号,这些都用于界定代码中的关键字或表达式的边界。
*editorRowHasOpenComment(erow row)函数 :检查传入的行(row)是否以一个尚未关闭的多行注释开始。这对于决定下一行的语法高亮是非常重要的,因为多行注释可以跨越多个行。
*editorUpdateSyntax(erow row)函数 :这个函数为编辑器中的每一行文本更新语法高亮。它根据当前的语法规则(如字符串、注释、关键字等)给行中的每个字符分配一个高亮类型。这包括处理单行和多行注释、字符串、数字、关键字以及非打印字符。此函数还会检查是否有开放的多行注释,如果有,会相应地更新下一行的高亮状态。
int getCursorPosition(int ifd, int ofd, int *rows, int *cols) {
char buf[32];
unsigned int i = 0;
/* Report cursor location */
if (write(ofd, "\x1b[6n", 4) != 4) return -1;
/* Read the response: ESC [ rows ; cols R */
while (i < sizeof(buf)-1) {
if (read(ifd,buf+i,1) != 1) break;
if (buf[i] == 'R') break;
i++;
}
buf[i] = '\0';
/* Parse it. */
if (buf[0] != ESC || buf[1] != '[') return -1;
if (sscanf(buf+2,"%d;%d",rows,cols) != 2) return -1;
return 0;
}
/* Try to get the number of columns in the current terminal. If the ioctl()
* call fails the function will try to query the terminal itself.
* Returns 0 on success, -1 on error. */
int getWindowSize(int ifd, int ofd, int *rows, int *cols) {
struct winsize ws;
if (ioctl(1, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
/* ioctl() failed. Try to query the terminal itself. */
int orig_row, orig_col, retval;
/* Get the initial position so we can restore it later. */
retval = getCursorPosition(ifd,ofd,&orig_row,&orig_col);
if (retval == -1) goto failed;
/* Go to right/bottom margin and get position. */
if (write(ofd,"\x1b[999C\x1b[999B",12) != 12) goto failed;
retval = getCursorPosition(ifd,ofd,rows,cols);
if (retval == -1) goto failed;
/* Restore position. */
char seq[32];
snprintf(seq,32,"\x1b[%d;%dH",orig_row,orig_col);
if (write(ofd,seq,strlen(seq)) == -1) {
/* Can't recover... */
}
return 0;
} else {
*cols = ws.ws_col;
*rows = ws.ws_row;
return 0;
}
failed:
return -1;
}
/* ====================== Syntax highlight color scheme ==================== */
int is_separator(int c) {
return c == '\0' || isspace(c) || strchr(",.()+-/*=~%[];",c) != NULL;
}
/* Return true if the specified row last char is part of a multi line comment
* that starts at this row or at one before, and does not end at the end
* of the row but spawns to the next row. */
int editorRowHasOpenComment(erow *row) {
if (row->hl && row->rsize && row->hl[row->rsize-1] == HL_MLCOMMENT &&
(row->rsize < 2 || (row->render[row->rsize-2] != '*' ||
row->render[row->rsize-1] != '/'))) return 1;
return 0;
}
/* Set every byte of row->hl (that corresponds to every character in the line)
* to the right syntax highlight type (HL_* defines). */
void editorUpdateSyntax(erow *row) {
row->hl = realloc(row->hl,row->rsize);
memset(row->hl,HL_NORMAL,row->rsize);
if (E.syntax == NULL) return; /* No syntax, everything is HL_NORMAL. */
int i, prev_sep, in_string, in_comment;
char *p;
char **keywords = E.syntax->keywords;
char *scs = E.syntax->singleline_comment_start;
char *mcs = E.syntax->multiline_comment_start;
char *mce = E.syntax->multiline_comment_end;
/* Point to the first non-space char. */
p = row->render;
i = 0; /* Current char offset */
while(*p && isspace(*p)) {
p++;
i++;
}
prev_sep = 1; /* Tell the parser if 'i' points to start of word. */
in_string = 0; /* Are we inside "" or '' ? */
in_comment = 0; /* Are we inside multi-line comment? */
/* If the previous line has an open comment, this line starts
* with an open comment state. */
if (row->idx > 0 && editorRowHasOpenComment(&E.row[row->idx-1]))
in_comment = 1;
while(*p) {
/* Handle // comments. */
if (prev_sep && *p == scs[0] && *(p+1) == scs[1]) {
/* From here to end is a comment */
memset(row->hl+i,HL_COMMENT,row->size-i);
return;
}
/* Handle multi line comments. */
if (in_comment) {
row->hl[i] = HL_MLCOMMENT;
if (*p == mce[0] && *(p+1) == mce[1]) {
row->hl[i+1] = HL_MLCOMMENT;
p += 2; i += 2;
in_comment = 0;
prev_sep = 1;
continue;
} else {
prev_sep = 0;
p++; i++;
continue;
}
} else if (*p == mcs[0] && *(p+1) == mcs[1]) {
row->hl[i] = HL_MLCOMMENT;
row->hl[i+1] = HL_MLCOMMENT;
p += 2; i += 2;
in_comment = 1;
prev_sep = 0;
continue;
}
/* Handle "" and '' */
if (in_string) {
row->hl[i] = HL_STRING;
if (*p == '\ ') {
row->hl[i+1] = HL_STRING;
p += 2; i += 2;
prev_sep = 0;
continue;
}
if (*p == in_string) in_string = 0;
p++; i++;
continue;
} else {
if (*p == '"' || *p == '\'') {
in_string = *p;
row->hl[i] = HL_STRING;
p++; i++;
prev_sep = 0;
continue;
}
}
/* Handle non printable chars. */
if (!isprint(*p)) {
row->hl[i] = HL_NONPRINT;
p++; i++;
prev_sep = 0;
continue;
}
/* Handle numbers */
if ((isdigit(*p) && (prev_sep || row->hl[i-1] == HL_NUMBER)) ||
(*p == '.' && i >0 && row->hl[i-1] == HL_NUMBER)) {
row->hl[i] = HL_NUMBER;
p++; i++;
prev_sep = 0;
continue;
}
/* Handle keywords and lib calls */
if (prev_sep) {
int j;
for (j = 0; keywords[j]; j++) {
int klen = strlen(keywords[j]);
int kw2 = keywords[j][klen-1] == '|';
if (kw2) klen--;
if (!memcmp(p,keywords[j],klen) &&
is_separator(*(p+klen)))
{
/* Keyword */
memset(row->hl+i,kw2 ? HL_KEYWORD2 : HL_KEYWORD1,klen);
p += klen;
i += klen;
break;
}
}
if (keywords[j] != NULL) {
prev_sep = 0;
continue; /* We had a keyword match */
}
}
/* Not special chars */
prev_sep = is_separator(*p);
p++; i++;
}
/* Propagate syntax change to the next row if the open commen
* state changed. This may recursively affect all the following rows
* in the file. */
int oc = editorRowHasOpenComment(row);
if (row->hl_oc != oc && row->idx+1 < E.numrows)
editorUpdateSyntax(&E.row[row->idx+1]);
row->hl_oc = oc;
}
e接下里是处理文本的显示、语法高亮和行的增删。以下是各个部分的详细解释:
语法高亮颜色 (editorSyntaxToColor 函数)
editorSyntaxToColor 函数根据提供的高亮类型(hl),返回对应的终端颜色代码。这里使用的颜色代码是ANSI颜色代码:
- 注释 (
HL_COMMENT,HL_MLCOMMENT): 青色(cyan,ANSI颜色代码36) - 关键词1 (
HL_KEYWORD1): 黄色(yellow,ANSI颜色代码33) - 关键词2 (
HL_KEYWORD2): 绿色(green,ANSI颜色代码32) - 字符串 (
HL_STRING): 品红(magenta,ANSI颜色代码35) - 数字 (
HL_NUMBER): 红色(red,ANSI颜色代码31) - 匹配项 (
HL_MATCH): 蓝色(blue,ANSI颜色代码34) - 默认 (其他情况): 白色(white,ANSI颜色代码37)
选择语法高亮方案 (editorSelectSyntaxHighlight 函数)
editorSelectSyntaxHighlight 函数根据提供的文件名,选择适当的语法高亮方案,并设置全局状态E.syntax。这个函数遍历一个包含不同语法高亮方案的数据库(HLDB),尝试匹配文件名。如果文件名匹配了某个方案的模式(包括扩展名或特定文件名),则选择该方案。
更新行的渲染版本和语法高亮 (editorUpdateRow 函数)
editorUpdateRow 函数更新给定行的渲染版本和语法高亮。这个函数首先计算行中的制表符数量,因为它们需要特别处理(通常将一个制表符展开为多个空格,以保持文本对齐)。然后,它分配足够的空间来存储渲染后的行,并将原始行的字符复制到渲染行中,将制表符替换为适当数量的空格。最后,它调用editorUpdateSyntax函数(这部分代码未提供)来更新行的语法高亮数据。
插入新行 (editorInsertRow 函数)
editorInsertRow 函数在指定位置插入一个新行。如果插入位置超出了当前文档的长度,函数将不执行任何操作。否则,它会调整行数组的大小来容纳新行,并将其他行向下移动。然后为新行分配内存,复制提供的文本,并初始化其他行状态。最后,更新新行的渲染版本和语法高亮。
释放行资源 (editorFreeRow 函数)
editorFreeRow 函数释放行结构erow中的动态分配内存。这包括行的渲染版本、原始文本和语法高亮信息。
删除行 (editorDelRow 函数)
editorDelRow 函数删除指定位置的行,并释放该行的资源。然后它将其他行向上移动来填补空缺,并更新行索引和编辑器的脏标记(E.dirty),以指示文档已经被修改。
int editorSyntaxToColor(int hl) {
switch(hl) {
case HL_COMMENT:
case HL_MLCOMMENT: return 36; /* cyan */
case HL_KEYWORD1: return 33; /* yellow */
case HL_KEYWORD2: return 32; /* green */
case HL_STRING: return 35; /* magenta */
case HL_NUMBER: return 31; /* red */
case HL_MATCH: return 34; /* blu */
default: return 37; /* white */
}
}
/* Select the syntax highlight scheme depending on the filename,
* setting it in the global state E.syntax. */
void editorSelectSyntaxHighlight(char *filename) {
for (unsigned int j = 0; j < HLDB_ENTRIES; j++) {
struct editorSyntax *s = HLDB+j;
unsigned int i = 0;
while(s->filematch[i]) {
char *p;
int patlen = strlen(s->filematch[i]);
if ((p = strstr(filename,s->filematch[i])) != NULL) {
if (s->filematch[i][0] != '.' || p[patlen] == '\0') {
E.syntax = s;
return;
}
}
i++;
}
}
}
/* ======================= Editor rows implementation ======================= */
/* Update the rendered version and the syntax highlight of a row. */
void editorUpdateRow(erow *row) {
unsigned int tabs = 0, nonprint = 0;
int j, idx;
/* Create a version of the row we can directly print on the screen,
* respecting tabs, substituting non printable characters with '?'. */
free(row->render);
for (j = 0; j < row->size; j++)
if (row->chars[j] == TAB) tabs++;
unsigned long long allocsize =
(unsigned long long) row->size + tabs*8 + nonprint*9 + 1;
if (allocsize > UINT32_MAX) {
printf("Some line of the edited file is too long for kilo\n");
exit(1);
}
row->render = malloc(row->size + tabs*8 + nonprint*9 + 1);
idx = 0;
for (j = 0; j < row->size; j++) {
if (row->chars[j] == TAB) {
row->render[idx++] = ' ';
while((idx+1) % 8 != 0) row->render[idx++] = ' ';
} else {
row->render[idx++] = row->chars[j];
}
}
row->rsize = idx;
row->render[idx] = '\0';
/* Update the syntax highlighting attributes of the row. */
editorUpdateSyntax(row);
}
/* Insert a row at the specified position, shifting the other rows on the bottom
* if required. */
void editorInsertRow(int at, char *s, size_t len) {
if (at > E.numrows) return;
E.row = realloc(E.row,sizeof(erow)*(E.numrows+1));
if (at != E.numrows) {
memmove(E.row+at+1,E.row+at,sizeof(E.row[0])*(E.numrows-at));
for (int j = at+1; j <= E.numrows; j++) E.row[j].idx++;
}
E.row[at].size = len;
E.row[at].chars = malloc(len+1);
memcpy(E.row[at].chars,s,len+1);
E.row[at].hl = NULL;
E.row[at].hl_oc = 0;
E.row[at].render = NULL;
E.row[at].rsize = 0;
E.row[at].idx = at;
editorUpdateRow(E.row+at);
E.numrows++;
E.dirty++;
}
/* Free row's heap allocated stuff. */
void editorFreeRow(erow *row) {
free(row->render);
free(row->chars);
free(row->hl);
}
/* Remove the row at the specified position, shifting the remainign on the
* top. */
void editorDelRow(int at) {
erow *row;
if (at >= E.numrows) return;
row = E.row+at;
editorFreeRow(row);
memmove(E.row+at,E.row+at+1,sizeof(E.row[0])*(E.numrows-at-1));
for (int j = at; j < E.numrows-1; j++) E.row[j].idx++;
E.numrows--;
E.dirty++;
}详细解释int editorSyntaxToColor(int hl) {
switch(hl) {
case HL_COMMENT:
case HL_MLCOMMENT: return 36; /* cyan */
case HL_KEYWORD1: return 33; /* yellow */
case HL_KEYWORD2: return 32; /* green */
case HL_STRING: return 35; /* magenta */
case HL_NUMBER: return 31; /* red */
case HL_MATCH: return 34; /* blu */
default: return 37; /* white */
}
}
/* Select the syntax highlight scheme depending on the filename,
* setting it in the global state E.syntax. */
void editorSelectSyntaxHighlight(char *filename) {
for (unsigned int j = 0; j < HLDB_ENTRIES; j++) {
struct editorSyntax *s = HLDB+j;
unsigned int i = 0;
while(s->filematch[i]) {
char *p;
int patlen = strlen(s->filematch[i]);
if ((p = strstr(filename,s->filematch[i])) != NULL) {
if (s->filematch[i][0] != '.' || p[patlen] == '\0') {
E.syntax = s;
return;
}
}
i++;
}
}
}
/* ======================= Editor rows implementation ======================= */
/* Update the rendered version and the syntax highlight of a row. */
void editorUpdateRow(erow *row) {
unsigned int tabs = 0, nonprint = 0;
int j, idx;
/* Create a version of the row we can directly print on the screen,
* respecting tabs, substituting non printable characters with '?'. */
free(row->render);
for (j = 0; j < row->size; j++)
if (row->chars[j] == TAB) tabs++;
unsigned long long allocsize =
(unsigned long long) row->size + tabs*8 + nonprint*9 + 1;
if (allocsize > UINT32_MAX) {
printf("Some line of the edited file is too long for kilo\n");
exit(1);
}
row->render = malloc(row->size + tabs*8 + nonprint*9 + 1);
idx = 0;
for (j = 0; j < row->size; j++) {
if (row->chars[j] == TAB) {
row->render[idx++] = ' ';
while((idx+1) % 8 != 0) row->render[idx++] = ' ';
} else {
row->render[idx++] = row->chars[j];
}
}
row->rsize = idx;
row->render[idx] = '\0';
/* Update the syntax highlighting attributes of the row. */
editorUpdateSyntax(row);
}
/* Insert a row at the specified position, shifting the other rows on the bottom
* if required. */
void editorInsertRow(int at, char *s, size_t len) {
if (at > E.numrows) return;
E.row = realloc(E.row,sizeof(erow)*(E.numrows+1));
if (at != E.numrows) {
memmove(E.row+at+1,E.row+at,sizeof(E.row[0])*(E.numrows-at));
for (int j = at+1; j <= E.numrows; j++) E.row[j].idx++;
}
E.row[at].size = len;
E.row[at].chars = malloc(len+1);
memcpy(E.row[at].chars,s,len+1);
E.row[at].hl = NULL;
E.row[at].hl_oc = 0;
E.row[at].render = NULL;
E.row[at].rsize = 0;
E.row[at].idx = at;
editorUpdateRow(E.row+at);
E.numrows++;
E.dirty++;
}
/* Free row's heap allocated stuff. */
void editorFreeRow(erow *row) {
free(row->render);
free(row->chars);
free(row->hl);
}
/* Remove the row at the specified position, shifting the remainign on the
* top. */
void editorDelRow(int at) {
erow *row;
if (at >= E.numrows) return;
row = E.row+at;
editorFreeRow(row);
memmove(E.row+at,E.row+at+1,sizeof(E.row[0])*(E.numrows-at-1));
for (int j = at; j < E.numrows-1; j++) E.row[j].idx++;
E.numrows--;
E.dirty++;
}
处理文本中行的插入、删除、追加字符和插入新行等操作:
editorRowsToString
- 功能:将编辑器中的所有行转换为一个单一的、堆分配的字符串。
- 实现:首先计算所需的总字节长度(每一行的长度加上每行末尾的换行符),然后分配相应的内存。
- 遍历每一行,将行内容和换行符复制到分配的内存中,并确保字符串以空字符
\0结尾。
editorRowInsertChar
- 功能:在指定行的指定位置插入一个字符,必要时向右移动剩余字符。
- 实现:如果插入位置超出当前行长度,则通过添加空格来填充,并分配额外空间存放新字符和空字符。否则,只需为新字符和空字符重新分配空间,并将现有字符向右移动。
editorRowAppendString
- 功能:在行末尾追加一个字符串。
- 实现:重新分配足够的内存以容纳现有行内容和追加的字符串,然后复制字符串到行的末尾,并更新行的大小。
editorRowDelChar
- 功能:从指定行删除位于
at位置的字符。 - 实现:使用
memmove将at位置之后的字符向左移动一位,从而覆盖掉需要删除的字符,并更新行的大小。
editorInsertChar
- 功能:在当前光标位置插入一个字符。
- 实现:首先确定光标所在的行,如果不存在则创建新行。然后在指定位置插入字符。根据需要更新光标位置或显示偏移。
editorInsertNewline
- 功能:插入一个新行,如果需要则将当前行分割。
- 实现:如果光标位于行末尾或行不存在,则直接添加一个新行。如果光标在行中间,则将当前行从光标位置分割为两行。
整体上,这段代码展示了一个文本编辑器核心编辑功能的实现,包括处理行的插入、删除、分割和合并等操作。通过管理一个行结构体数组并在用户编辑时动态更新这些结构体,编辑器能够有效地反映用户的编辑操作。
/* Turn the editor rows into a single heap-allocated string.
* Returns the pointer to the heap-allocated string and populate the
* integer pointed by 'buflen' with the size of the string, escluding
* the final nulterm. */
char *editorRowsToString(int *buflen) {
char *buf = NULL, *p;
int totlen = 0;
int j;
/* Compute count of bytes */
for (j = 0; j < E.numrows; j++)
totlen += E.row[j].size+1; /* +1 is for "\n" at end of every row */
*buflen = totlen;
totlen++; /* Also make space for nulterm */
p = buf = malloc(totlen);
for (j = 0; j < E.numrows; j++) {
memcpy(p,E.row[j].chars,E.row[j].size);
p += E.row[j].size;
*p = '\n';
p++;
}
*p = '\0';
return buf;
}
/* Insert a character at the specified position in a row, moving the remaining
* chars on the right if needed. */
void editorRowInsertChar(erow *row, int at, int c) {
if (at > row->size) {
/* Pad the string with spaces if the insert location is outside the
* current length by more than a single character. */
int padlen = at-row->size;
/* In the next line +2 means: new char and null term. */
row->chars = realloc(row->chars,row->size+padlen+2);
memset(row->chars+row->size,' ',padlen);
row->chars[row->size+padlen+1] = '\0';
row->size += padlen+1;
} else {
/* If we are in the middle of the string just make space for 1 new
* char plus the (already existing) null term. */
row->chars = realloc(row->chars,row->size+2);
memmove(row->chars+at+1,row->chars+at,row->size-at+1);
row->size++;
}
row->chars[at] = c;
editorUpdateRow(row);
E.dirty++;
}
/* Append the string 's' at the end of a row */
void editorRowAppendString(erow *row, char *s, size_t len) {
row->chars = realloc(row->chars,row->size+len+1);
memcpy(row->chars+row->size,s,len);
row->size += len;
row->chars[row->size] = '\0';
editorUpdateRow(row);
E.dirty++;
}
/* Delete the character at offset 'at' from the specified row. */
void editorRowDelChar(erow *row, int at) {
if (row->size <= at) return;
memmove(row->chars+at,row->chars+at+1,row->size-at);
editorUpdateRow(row);
row->size--;
E.dirty++;
}
/* Insert the specified char at the current prompt position. */
void editorInsertChar(int c) {
int filerow = E.rowoff+E.cy;
int filecol = E.coloff+E.cx;
erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow];
/* If the row where the cursor is currently located does not exist in our
* logical representaion of the file, add enough empty rows as needed. */
if (!row) {
while(E.numrows <= filerow)
editorInsertRow(E.numrows,"",0);
}
row = &E.row[filerow];
editorRowInsertChar(row,filecol,c);
if (E.cx == E.screencols-1)
E.coloff++;
else
E.cx++;
E.dirty++;
}
/* Inserting a newline is slightly complex as we have to handle inserting a
* newline in the middle of a line, splitting the line as needed. */
void editorInsertNewline(void) {
int filerow = E.rowoff+E.cy;
int filecol = E.coloff+E.cx;
erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow];
if (!row) {
if (filerow == E.numrows) {
editorInsertRow(filerow,"",0);
goto fixcursor;
}
return;
}
/* If the cursor is over the current line size, we want to conceptually
* think it's just over the last character. */
if (filecol >= row->size) filecol = row->size;
if (filecol == 0) {
editorInsertRow(filerow,"",0);
} else {
/* We are in the middle of a line. Split it between two rows. */
editorInsertRow(filerow+1,row->chars+filecol,row->size-filecol);
row = &E.row[filerow];
row->chars[filecol] = '\0';
row->size = filecol;
editorUpdateRow(row);
}
fixcursor:
if (E.cy == E.screenrows-1) {
E.rowoff++;
} else {
E.cy++;
}
E.cx = 0;
E.coloff = 0;
}
进入编辑、打开和保存文件的关键部分。
editorDelChar() - 删除字符
这个函数用于从编辑器中的当前位置删除一个字符。功能分为两大情况:
当前光标位于行首 :如果光标在一行的开始位置且不是文档的开始位置,那么该行会被追加到前一行的末尾,当前行被删除。光标随之移动到被合并的行末,如果光标的新位置超出了屏幕,会相应调整屏幕的偏移量。
光标位于行中其他位置 :直接删除光标左侧的字符,并将光标向左移动一位。如果光标已经在屏幕最左边,但存在列偏移,则减少列偏移量以显示更多左侧的文本。
editorOpen(char *filename) - 打开文件
这个函数尝试打开一个文件,并将其内容加载到编辑器中。首先,它会释放之前打开文件的名称(如果有),然后存储新文件的名称。接着,以只读模式打开指定的文件。使用getline()函数逐行读取文件内容,将每行末尾的换行符替换为字符串结束符\0,并将这些行添加到编辑器的数据结构中。最后,关闭文件,并将“脏”标志重置为0,表示当前编辑内容与磁盘文件同步。
editorSave(void) - 保存文件
该函数将当前编辑器中的内容保存到磁盘上。首先,它将编辑器中所有行的内容转换成一个连续的字符串。然后,尝试以读写模式打开(如果不存在则创建)当前文件,设置文件的长度来匹配即将写入的数据长度。使用单次write()调用将所有数据写入文件,确保原子性地写入数据。如果写入成功,关闭文件,释放缓冲区,更新状态信息,并将“脏”标志重置为0。如果写入过程中发生任何错误,显示错误信息并返回1
void editorDelChar() {
int filerow = E.rowoff+E.cy;
int filecol = E.coloff+E.cx;
erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow];
if (!row || (filecol == 0 && filerow == 0)) return;
if (filecol == 0) {
/* Handle the case of column 0, we need to move the current line
* on the right of the previous one. */
filecol = E.row[filerow-1].size;
editorRowAppendString(&E.row[filerow-1],row->chars,row->size);
editorDelRow(filerow);
row = NULL;
if (E.cy == 0)
E.rowoff--;
else
E.cy--;
E.cx = filecol;
if (E.cx >= E.screencols) {
int shift = (E.screencols-E.cx)+1;
E.cx -= shift;
E.coloff += shift;
}
} else {
editorRowDelChar(row,filecol-1);
if (E.cx == 0 && E.coloff)
E.coloff--;
else
E.cx--;
}
if (row) editorUpdateRow(row);
E.dirty++;
}
/* Load the specified program in the editor memory and returns 0 on success
* or 1 on error. */
int editorOpen(char *filename) {
FILE *fp;
E.dirty = 0;
free(E.filename);
size_t fnlen = strlen(filename)+1;
E.filename = malloc(fnlen);
memcpy(E.filename,filename,fnlen);
fp = fopen(filename,"r");
if (!fp) {
if (errno != ENOENT) {
perror("Opening file");
exit(1);
}
return 1;
}
char *line = NULL;
size_t linecap = 0;
ssize_t linelen;
while((linelen = getline(&line,&linecap,fp)) != -1) {
if (linelen && (line[linelen-1] == '\n' || line[linelen-1] == '\r'))
line[--linelen] = '\0';
editorInsertRow(E.numrows,line,linelen);
}
free(line);
fclose(fp);
E.dirty = 0;
return 0;
}
/* Save the current file on disk. Return 0 on success, 1 on error. */
int editorSave(void) {
int len;
char *buf = editorRowsToString(&len);
int fd = open(E.filename,O_RDWR|O_CREAT,0644);
if (fd == -1) goto writeerr;
/* Use truncate + a single write(2) call in order to make saving
* a bit safer, under the limits of what we can do in a small editor. */
if (ftruncate(fd,len) == -1) goto writeerr;
if (write(fd,buf,len) != len) goto writeerr;
close(fd);
free(buf);
E.dirty = 0;
editorSetStatusMessage("%d bytes written on disk", len);
return 0;
writeerr:
free(buf);
if (fd != -1) close(fd);
editorSetStatusMessage("Can't save! I/O error: %s",strerror(errno));
return 1;
}
详细讲诶好死
这是屏幕刷新功能的实现。它使用了许多终端控制序列来控制屏幕上的输出,例如隐藏光标、移动光标、改变文本颜色等。整个函数的目的是根据编辑器的内部状态(如当前打开的文件内容、光标位置等)来重新绘制整个屏幕。
隐藏光标和移动光标到屏幕开头 :
* 使用`"\x1b[?25l"`序列隐藏光标,防止在屏幕刷新过程中出现闪烁。
* 使用`"\x1b[H"`将光标移动到屏幕的左上角("家"位置)。
绘制文本行或欢迎信息 :
* 循环遍历屏幕上的每一行。
* 如果当前行没有对应的文件内容行,则显示一个波浪线`"~"`(类似于vim编辑器),或者如果文件为空则显示欢迎信息。
* 如果当前行对应于文件中的一行,则根据该行的内容和语法高亮信息来绘制文本。
绘制状态栏和消息栏 :
* 状态栏显示文件名、文件行数以及是否被修改等信息。
* 消息栏显示一些临时消息,如保存状态等,这些消息会在一定时间后消失。
处理特殊字符和语法高亮 :
* 对于非打印字符,使用特殊的背景和字符(例如用`@`加上控制字符的ASCII值)来表示。
* 根据语法高亮信息改变文本颜色。
计算并设置光标位置 :
* 计算光标在屏幕上的实际位置,考虑到了制表符TAB的存在,它会占据多个字符的位置。
* 使用`"\x1b[%d;%dH"`序列将光标移动到计算出的位置。
显示光标和刷新屏幕 :
* 最后,使用`"\x1b[?25h"`序列显示光标,并通过`write`函数将构建好的输出缓冲区(`ab`)内容写入`STDOUT`,完成屏幕的刷新。
void editorRefreshScreen(void) {
int y;
erow *r;
char buf[32];
struct abuf ab = ABUF_INIT;
abAppend(&ab,"\x1b[?25l",6); /* Hide cursor. */
abAppend(&ab,"\x1b[H",3); /* Go home. */
for (y = 0; y < E.screenrows; y++) {
int filerow = E.rowoff+y;
if (filerow >= E.numrows) {
if (E.numrows == 0 && y == E.screenrows/3) {
char welcome[80];
int welcomelen = snprintf(welcome,sizeof(welcome),
"Kilo editor -- verison %s\x1b[0K\r\n", KILO_VERSION);
int padding = (E.screencols-welcomelen)/2;
if (padding) {
abAppend(&ab,"~",1);
padding--;
}
while(padding--) abAppend(&ab," ",1);
abAppend(&ab,welcome,welcomelen);
} else {
abAppend(&ab,"~\x1b[0K\r\n",7);
}
continue;
}
r = &E.row[filerow];
int len = r->rsize - E.coloff;
int current_color = -1;
if (len > 0) {
if (len > E.screencols) len = E.screencols;
char *c = r->render+E.coloff;
unsigned char *hl = r->hl+E.coloff;
int j;
for (j = 0; j < len; j++) {
if (hl[j] == HL_NONPRINT) {
char sym;
abAppend(&ab,"\x1b[7m",4);
if (c[j] <= 26)
sym = '@'+c[j];
else
sym = '?';
abAppend(&ab,&sym,1);
abAppend(&ab,"\x1b[0m",4);
} else 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) {
char buf[16];
int clen = snprintf(buf,sizeof(buf),"\x1b[%dm",color);
current_color = color;
abAppend(&ab,buf,clen);
}
abAppend(&ab,c+j,1);
}
}
}
abAppend(&ab,"\x1b[39m",5);
abAppend(&ab,"\x1b[0K",4);
abAppend(&ab,"\r\n",2);
}
/* Create a two rows status. First row: */
abAppend(&ab,"\x1b[0K",4);
abAppend(&ab,"\x1b[7m",4);
char status[80], rstatus[80];
int len = snprintf(status, sizeof(status), "%.20s - %d lines %s",
E.filename, E.numrows, E.dirty ? "(modified)" : "");
int rlen = snprintf(rstatus, sizeof(rstatus),
"%d/%d",E.rowoff+E.cy+1,E.numrows);
if (len > E.screencols) len = E.screencols;
abAppend(&ab,status,len);
while(len < E.screencols) {
if (E.screencols - len == rlen) {
abAppend(&ab,rstatus,rlen);
break;
} else {
abAppend(&ab," ",1);
len++;
}
}
abAppend(&ab,"\x1b[0m\r\n",6);
/* Second row depends on E.statusmsg and the status message update time. */
abAppend(&ab,"\x1b[0K",4);
int msglen = strlen(E.statusmsg);
if (msglen && time(NULL)-E.statusmsg_time < 5)
abAppend(&ab,E.statusmsg,msglen <= E.screencols ? msglen : E.screencols);
/* Put cursor at its current position. Note that the horizontal position
* at which the cursor is displayed may be different compared to 'E.cx'
* because of TABs. */
int j;
int cx = 1;
int filerow = E.rowoff+E.cy;
erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow];
if (row) {
for (j = E.coloff; j < (E.cx+E.coloff); j++) {
if (j < row->size && row->chars[j] == TAB) cx += 7-((cx)%8);
cx++;
}
}
snprintf(buf,sizeof(buf),"\x1b[%d;%dH",E.cy+1,cx);
abAppend(&ab,buf,strlen(buf));
abAppend(&ab,"\x1b[?25h",6); /* Show cursor. */
write(STDOUT_FILENO,ab.b,ab.len);
abFree(&ab);
}
展示了如何在编辑器中设置状态消息、实现查找模式、以及处理用户通过箭头按键改变光标位置的事件。这看起来是一个简化的编辑器,类似于Kilo编辑器或其他小型文本编辑器的实现。
设置状态消息(editorSetStatusMessage 函数)
这个函数用于在编辑器的状态栏上显示一个格式化的消息。它使用了vsnprintf来格式化一个可变参数列表,然后将格式化后的字符串和当前时间保存到全局编辑器状态中。这样,状态消息可以在屏幕下方的状态栏中显示给用户。
查找模式(editorFind 函数)
这个查找功能允许用户在文本中搜索字符串。用户可以通过输入来动态地更新搜索查询,并且用方向键查找下一个或上一个匹配项。如果用户按下ESC或Enter键,搜索会停止,并根据用户的操作回到搜索前的光标位置或结束搜索。
在这个函数中,还实现了一个高亮显示搜索结果的功能。当找到匹配的字符串时,它会在内部保存当前行的高亮状态,然后将匹配字符串的高亮设置为特殊高亮(HL_MATCH),以便在屏幕上突出显示。当用户退出搜索模式或者改变搜索查询时,原有的高亮状态会被恢复。
编辑器事件处理(editorMoveCursor 函数)
这个函数负责处理光标的移动,包括上下左右箭头键的操作。它考虑到了多种情况,比如光标在屏幕边缘时的滚动处理、光标在文本行尾时移动到下一行的开头等。这个函数确保了光标总是在有效的文本区域内,并且当用户尝试移动到当前视图外的部分时,视图会相应地滚动。
void editorSetStatusMessage(const char *fmt, ...) {
va_list ap;
va_start(ap,fmt);
vsnprintf(E.statusmsg,sizeof(E.statusmsg),fmt,ap);
va_end(ap);
E.statusmsg_time = time(NULL);
}
/* =============================== Find mode ================================ */
#define KILO_QUERY_LEN 256
void editorFind(int fd) {
char query[KILO_QUERY_LEN+1] = {0};
int qlen = 0;
int last_match = -1; /* Last line where a match was found. -1 for none. */
int find_next = 0; /* if 1 search next, if -1 search prev. */
int saved_hl_line = -1; /* No saved HL */
char *saved_hl = NULL;
#define FIND_RESTORE_HL do { \
if (saved_hl) { \
memcpy(E.row[saved_hl_line].hl,saved_hl, E.row[saved_hl_line].rsize); \
free(saved_hl); \
saved_hl = NULL; \
} \
} while (0)
/* Save the cursor position in order to restore it later. */
int saved_cx = E.cx, saved_cy = E.cy;
int saved_coloff = E.coloff, saved_rowoff = E.rowoff;
while(1) {
editorSetStatusMessage(
"Search: %s (Use ESC/Arrows/Enter)", query);
editorRefreshScreen();
int c = editorReadKey(fd);
if (c == DEL_KEY || c == CTRL_H || c == BACKSPACE) {
if (qlen != 0) query[--qlen] = '\0';
last_match = -1;
} else if (c == ESC || c == ENTER) {
if (c == ESC) {
E.cx = saved_cx; E.cy = saved_cy;
E.coloff = saved_coloff; E.rowoff = saved_rowoff;
}
FIND_RESTORE_HL;
editorSetStatusMessage("");
return;
} else if (c == ARROW_RIGHT || c == ARROW_DOWN) {
find_next = 1;
} else if (c == ARROW_LEFT || c == ARROW_UP) {
find_next = -1;
} else if (isprint(c)) {
if (qlen < KILO_QUERY_LEN) {
query[qlen++] = c;
query[qlen] = '\0';
last_match = -1;
}
}
/* Search occurrence. */
if (last_match == -1) find_next = 1;
if (find_next) {
char *match = NULL;
int match_offset = 0;
int i, current = last_match;
for (i = 0; i < E.numrows; i++) {
current += find_next;
if (current == -1) current = E.numrows-1;
else if (current == E.numrows) current = 0;
match = strstr(E.row[current].render,query);
if (match) {
match_offset = match-E.row[current].render;
break;
}
}
find_next = 0;
/* Highlight */
FIND_RESTORE_HL;
if (match) {
erow *row = &E.row[current];
last_match = current;
if (row->hl) {
saved_hl_line = current;
saved_hl = malloc(row->rsize);
memcpy(saved_hl,row->hl,row->rsize);
memset(row->hl+match_offset,HL_MATCH,qlen);
}
E.cy = 0;
E.cx = match_offset;
E.rowoff = current;
E.coloff = 0;
/* Scroll horizontally as needed. */
if (E.cx > E.screencols) {
int diff = E.cx - E.screencols;
E.cx -= diff;
E.coloff += diff;
}
}
}
}
}
/* ========================= Editor events handling ======================== */
/* Handle cursor position change because arrow keys were pressed. */
void editorMoveCursor(int key) {
int filerow = E.rowoff+E.cy;
int filecol = E.coloff+E.cx;
int rowlen;
erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow];
switch(key) {
case ARROW_LEFT:
if (E.cx == 0) {
if (E.coloff) {
E.coloff--;
} else {
if (filerow > 0) {
E.cy--;
E.cx = E.row[filerow-1].size;
if (E.cx > E.screencols-1) {
E.coloff = E.cx-E.screencols+1;
E.cx = E.screencols-1;
}
}
}
} else {
E.cx -= 1;
}
break;
case ARROW_RIGHT:
if (row && filecol < row->size) {
if (E.cx == E.screencols-1) {
E.coloff++;
} else {
E.cx += 1;
}
} else if (row && filecol == row->size) {
E.cx = 0;
E.coloff = 0;
if (E.cy == E.screenrows-1) {
E.rowoff++;
} else {
E.cy += 1;
}
}
break;
case ARROW_UP:
if (E.cy == 0) {
if (E.rowoff) E.rowoff--;
} else {
E.cy -= 1;
}
break;
case ARROW_DOWN:
if (filerow < E.numrows) {
if (E.cy == E.screenrows-1) {
E.rowoff++;
} else {
E.cy += 1;
}
}
break;
}
/* Fix cx if the current line has not enough chars. */
filerow = E.rowoff+E.cy;
filecol = E.coloff+E.cx;
row = (filerow >= E.numrows) ? NULL : &E.row[filerow];
rowlen = row ? row->size : 0;
if (filecol > rowlen) {
E.cx -= filecol-rowlen;
if (E.cx < 0) {
E.coloff += E.cx;
E.cx = 0;
}
}
}
这段代码实现了一个简单的文本编辑器,命名为kilo。它运行在终端中,允许用户编辑文件,并支持一些基本的操作,如移动光标、插入删除字符、保存文件和搜索等。下面,我将逐一解释这段代码的关键部分。
初始化编辑器(initEditor)
- 初始化编辑器的状态,包括光标位置、行偏移、列偏移、文件行数等。
- 调用
updateWindowSize获取终端的大小,以调整编辑器窗口的大小。 - 注册
SIGWINCH信号处理函数handleSigWinCh,以便在窗口大小变化时更新编辑器的视图。
主函数(main)
- 参数检查 :确保用户提供了一个文件名,否则显示使用说明并退出。
- 初始化编辑器 :设置编辑器的初始状态。
- 打开文件 :加载用户指定的文件内容到编辑器中。
- 启用原始模式 :更改终端设置,以便能够逐字节处理输入,而不是等待换行符。
- 主循环 :不断刷新屏幕并处理用户的按键输入。
处理按键输入(editorProcessKeypress)
根据用户按下的键执行不同的操作:
- Ctrl-Q :如果文件已修改,需要连按几次才能退出。否则直接退出。
- Ctrl-S :保存文件。
- Ctrl-F :进入查找模式。
- 方向键 :移动光标。
- Page Up/Page Down :快速滚动。
- Backspace/Ctrl-H/Del :删除字符。
- Enter :插入新行。
- 其他键 :插入字符。
移动光标(editorMoveCursor)
处理光标移动逻辑,包括处理边界情况,如光标跨行移动或达到屏幕边缘时的情况。
更新窗口大小(updateWindowSize)
调用getWindowSize获取终端大小,并调整编辑器的视图大小,留出状态栏的空间。
信号处理(handleSigWinCh)
当终端窗口大小变化时,更新编辑器的视图大小,并刷新屏幕。
void editorRefreshScreen(void) {
int y;
erow *r;
char buf[32];
struct abuf ab = ABUF_INIT;
abAppend(&ab,"\x1b[?25l",6); /* Hide cursor. */
abAppend(&ab,"\x1b[H",3); /* Go home. */
for (y = 0; y < E.screenrows; y++) {
int filerow = E.rowoff+y;
if (filerow >= E.numrows) {
if (E.numrows == 0 && y == E.screenrows/3) {
char welcome[80];
int welcomelen = snprintf(welcome,sizeof(welcome),
"Kilo editor -- verison %s\x1b[0K\r\n", KILO_VERSION);
int padding = (E.screencols-welcomelen)/2;
if (padding) {
abAppend(&ab,"~",1);
padding--;
}
while(padding--) abAppend(&ab," ",1);
abAppend(&ab,welcome,welcomelen);
} else {
abAppend(&ab,"~\x1b[0K\r\n",7);
}
continue;
}
r = &E.row[filerow];
int len = r->rsize - E.coloff;
int current_color = -1;
if (len > 0) {
if (len > E.screencols) len = E.screencols;
char *c = r->render+E.coloff;
unsigned char *hl = r->hl+E.coloff;
int j;
for (j = 0; j < len; j++) {
if (hl[j] == HL_NONPRINT) {
char sym;
abAppend(&ab,"\x1b[7m",4);
if (c[j] <= 26)
sym = '@'+c[j];
else
sym = '?';
abAppend(&ab,&sym,1);
abAppend(&ab,"\x1b[0m",4);
} else 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) {
char buf[16];
int clen = snprintf(buf,sizeof(buf),"\x1b[%dm",color);
current_color = color;
abAppend(&ab,buf,clen);
}
abAppend(&ab,c+j,1);
}
}
}
abAppend(&ab,"\x1b[39m",5);
abAppend(&ab,"\x1b[0K",4);
abAppend(&ab,"\r\n",2);
}
/* Create a two rows status. First row: */
abAppend(&ab,"\x1b[0K",4);
abAppend(&ab,"\x1b[7m",4);
char status[80], rstatus[80];
int len = snprintf(status, sizeof(status), "%.20s - %d lines %s",
E.filename, E.numrows, E.dirty ? "(modified)" : "");
int rlen = snprintf(rstatus, sizeof(rstatus),
"%d/%d",E.rowoff+E.cy+1,E.numrows);
if (len > E.screencols) len = E.screencols;
abAppend(&ab,status,len);
while(len < E.screencols) {
if (E.screencols - len == rlen) {
abAppend(&ab,rstatus,rlen);
break;
} else {
abAppend(&ab," ",1);
len++;
}
}
abAppend(&ab,"\x1b[0m\r\n",6);
/* Second row depends on E.statusmsg and the status message update time. */
abAppend(&ab,"\x1b[0K",4);
int msglen = strlen(E.statusmsg);
if (msglen && time(NULL)-E.statusmsg_time < 5)
abAppend(&ab,E.statusmsg,msglen <= E.screencols ? msglen : E.screencols);
/* Put cursor at its current position. Note that the horizontal position
* at which the cursor is displayed may be different compared to 'E.cx'
* because of TABs. */
int j;
int cx = 1;
int filerow = E.rowoff+E.cy;
erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow];
if (row) {
for (j = E.coloff; j < (E.cx+E.coloff); j++) {
if (j < row->size && row->chars[j] == TAB) cx += 7-((cx)%8);
cx++;
}
}
snprintf(buf,sizeof(buf),"\x1b[%d;%dH",E.cy+1,cx);
abAppend(&ab,buf,strlen(buf));
abAppend(&ab,"\x1b[?25h",6); /* Show cursor. */
write(STDOUT_FILENO,ab.b,ab.len);
abFree(&ab);
}
