Merge pull request #6 from anephtali/cosmetics

Cosmetics (typos, tabs and whitespaces)
This commit is contained in:
Daniel Morales authored and GitHub committed 2017-04-15 18:57:39 +02:00
commit f42c5e7e87
1 file changed
+172 -172
+172 -172
View File
@@ -17,8 +17,8 @@
/*** Include section ***/ /*** Include section ***/
// We add them above our includes, because the header // We add them above our includes, because the header
// files we are including use the macros to decide what // files we are including use the macros to decide what
// features to expose. These macros remove some compilation // features to expose. These macros remove some compilation
// warnings. See // warnings. See
// https://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html // https://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html
@@ -71,22 +71,22 @@ typedef struct editor_row {
} editor_row; } editor_row;
struct editor_syntax { struct editor_syntax {
// filetype field is the name of the filetype that will be displayed // file_type field is the name of the filetype that will be displayed
// to the user in the status bar. // to the user in the status bar.
char* file_type; char* file_type;
// filematch is an array of strings, where each string contains a // file_match is an array of strings, where each string contains a
// pattern to match a filename against. If the filename matches, // pattern to match a filename against. If the filename matches,
// then the file will be recognized as having that filetype. // then the file will be recognized as having that filetype.
char** file_match; char** file_match;
// This will be a NULL-terminated array of strings, each string containing // This will be a NULL-terminated array of strings, each string containing
// a keyword. To differentiate between the two types of keywords, // a keyword. To differentiate between the two types of keywords,
// we’ll terminate the second type of keywords with a pipe (|) // we’ll terminate the second type of keywords with a pipe (|)
// character (also known as a vertical bar). // character (also known as a vertical bar).
char** keywords; char** keywords;
// We let each language specify its own single-line comment pattern. // We let each language specify its own single-line comment pattern.
char* singleline_comment_start; char* singleline_comment_start;
// flags is a bit field that will contain flags for whether to // flags is a bit field that will contain flags for whether to
// highlight numbers and whether to highlight strings for that // highlight numbers and whether to highlight strings for that
// filetype. // filetype.
char* multiline_comment_start; char* multiline_comment_start;
char* multiline_comment_end; char* multiline_comment_end;
@@ -107,7 +107,7 @@ struct editor_config {
char* file_name; char* file_name;
char status_msg[80]; char status_msg[80];
time_t status_msg_time; time_t status_msg_time;
char* copied_char_buffer; char* copied_char_buffer;
struct editor_syntax* syntax; struct editor_syntax* syntax;
struct termios orig_termios; struct termios orig_termios;
} ec; } ec;
@@ -183,41 +183,41 @@ char* PYTHON_HL_keywords[] = {
"and", "as", "assert", "break", "class", "continue", "def", "del", "elif", "and", "as", "assert", "break", "class", "continue", "def", "del", "elif",
"else", "except", "exec", "finally", "for", "from", "global", "if", "import", "else", "except", "exec", "finally", "for", "from", "global", "if", "import",
"in", "is", "lambda", "not", "or", "pass", "print", "raise", "return", "try", "in", "is", "lambda", "not", "or", "pass", "print", "raise", "return", "try",
"while", "with", "yield", "while", "with", "yield",
"buffer|", "bytearray|", "complex|", "False|", "float|", "frozenset|", "int|", "buffer|", "bytearray|", "complex|", "False|", "float|", "frozenset|", "int|",
"list|", "long|", "None|", "set|", "str|", "tuple|", "True|", "type|", "list|", "long|", "None|", "set|", "str|", "tuple|", "True|", "type|",
"unicode|", "xrange|", NULL "unicode|", "xrange|", NULL
}; };
char* BASH_HL_keywords[] = { char* BASH_HL_keywords[] = {
"case", "do", "done", "elif", "else", "esac", "fi", "for", "function", "if", "case", "do", "done", "elif", "else", "esac", "fi", "for", "function", "if",
"in", "select", "then", "time", "until", "while", "alias", "bg", "bind", "break", "in", "select", "then", "time", "until", "while", "alias", "bg", "bind", "break",
"builtin", "cd", "command", "continue", "declare", "dirs", "disown", "echo", "builtin", "cd", "command", "continue", "declare", "dirs", "disown", "echo",
"enable", "eval", "exec", "exit", "export", "fc", "fg", "getopts", "hash", "help", "enable", "eval", "exec", "exit", "export", "fc", "fg", "getopts", "hash", "help",
"history", "jobs", "kill", "let", "local", "logout", "popd", "pushd", "pwd", "read", "history", "jobs", "kill", "let", "local", "logout", "popd", "pushd", "pwd", "read",
"readonly", "return", "set", "shift", "suspend", "test", "times", "trap", "type", "readonly", "return", "set", "shift", "suspend", "test", "times", "trap", "type",
"typeset", "ulimit", "umask", "unalias", "unset", "wait", "printf", NULL "typeset", "ulimit", "umask", "unalias", "unset", "wait", "printf", NULL
}; };
char* JS_HL_keywords[] = { char* JS_HL_keywords[] = {
"break", "case", "catch", "class", "const", "continue", "debugger", "default", "break", "case", "catch", "class", "const", "continue", "debugger", "default",
"delete", "do", "else", "enum", "export", "extends", "finally", "for", "function", "delete", "do", "else", "enum", "export", "extends", "finally", "for", "function",
"if", "implements", "import", "in", "instanceof", "interface", "let", "new", "if", "implements", "import", "in", "instanceof", "interface", "let", "new",
"package", "private", "protected", "public", "return", "static", "super", "switch", "package", "private", "protected", "public", "return", "static", "super", "switch",
"this", "throw", "try", "typeof", "var", "void", "while", "with", "yield", "true", "this", "throw", "try", "typeof", "var", "void", "while", "with", "yield", "true",
"false", "null", "NaN", "global", "window", "prototype", "constructor", "document", "false", "null", "NaN", "global", "window", "prototype", "constructor", "document",
"isNaN", "arguments", "undefined", "isNaN", "arguments", "undefined",
"Infinity|", "Array|", "Object|", "Number|", "String|", "Boolean|", "Function|", "Infinity|", "Array|", "Object|", "Number|", "String|", "Boolean|", "Function|",
"ArrayBuffer|", "DataView|", "Float32Array|", "Float64Array|", "Int8Array|", "ArrayBuffer|", "DataView|", "Float32Array|", "Float64Array|", "Int8Array|",
"Int16Array|", "Int32Array|", "Uint8Array|", "Uint8ClampedArray|", "Uint32Array|", "Int16Array|", "Int32Array|", "Uint8Array|", "Uint8ClampedArray|", "Uint32Array|",
"Date|", "Error|", "Map|", "RegExp|", "Symbol|", "WeakMap|", "WeakSet|", "Set|", NULL "Date|", "Error|", "Map|", "RegExp|", "Symbol|", "WeakMap|", "WeakSet|", "Set|", NULL
}; };
char* PHP_HL_keywords[] = { char* PHP_HL_keywords[] = {
"__halt_compiler", "break", "clone", "die", "empty", "endswitch", "final", "global", "__halt_compiler", "break", "clone", "die", "empty", "endswitch", "final", "global",
"include_once", "list", "private", "return", "try", "xor", "abstract", "callable", "include_once", "list", "private", "return", "try", "xor", "abstract", "callable",
"const", "do", "enddeclare", "endwhile", "finally", "goto", "instanceof", "namespace", "const", "do", "enddeclare", "endwhile", "finally", "goto", "instanceof", "namespace",
"protected", "static", "unset", "yield", "and", "case", "continue", "echo", "endfor", "protected", "static", "unset", "yield", "and", "case", "continue", "echo", "endfor",
"eval", "for", "if", "insteadof", "new", "public", "switch", "use", "array", "catch", "eval", "for", "if", "insteadof", "new", "public", "switch", "use", "array", "catch",
@@ -227,44 +227,44 @@ char* PHP_HL_keywords[] = {
}; };
char* JSON_HL_keywords[] = { char* JSON_HL_keywords[] = {
NULL NULL
}; };
char* XML_HL_keywords[] = { char* XML_HL_keywords[] = {
NULL NULL
}; };
char* SQL_HL_keywords[] = { char* SQL_HL_keywords[] = {
"SELECT", "FROM", "DROP", "CREATE", "TABLE", "DEFAULT", "FOREIGN", "UPDATE", "LOCK", "SELECT", "FROM", "DROP", "CREATE", "TABLE", "DEFAULT", "FOREIGN", "UPDATE", "LOCK",
"INSERT", "INTO", "VALUES", "LOCK", "UNLOCK", "WHERE", "DINSTINCT", "BETWEEN", "NOT", "INSERT", "INTO", "VALUES", "LOCK", "UNLOCK", "WHERE", "DINSTINCT", "BETWEEN", "NOT",
"NULL", "TO", "ON", "ORDER", "GROUP", "IF", "BY", "HAVING", "USING", "UNION", "UNIQUE", "NULL", "TO", "ON", "ORDER", "GROUP", "IF", "BY", "HAVING", "USING", "UNION", "UNIQUE",
"AUTO_INCREMENT", "LIKE", "WITH", "INNER", "OUTER", "JOIN", "COLUMN", "DATABASE", "EXISTS", "AUTO_INCREMENT", "LIKE", "WITH", "INNER", "OUTER", "JOIN", "COLUMN", "DATABASE", "EXISTS",
"NATURAL", "LIMIT", "UNSIGNED", "MAX", "MIN", "PRECISION", "ALTER", "DELETE", "CASCADE", "NATURAL", "LIMIT", "UNSIGNED", "MAX", "MIN", "PRECISION", "ALTER", "DELETE", "CASCADE",
"PRIMARY", "KEY", "CONSTRAINT", "ENGINE", "CHARSET", "REFERENCES", "WRITE", "PRIMARY", "KEY", "CONSTRAINT", "ENGINE", "CHARSET", "REFERENCES", "WRITE",
"BIT|", "TINYINT|", "BOOL|", "BOOLEAN|", "SMALLINT|", "MEDIUMINT|", "INT|", "INTEGER|", "BIT|", "TINYINT|", "BOOL|", "BOOLEAN|", "SMALLINT|", "MEDIUMINT|", "INT|", "INTEGER|",
"BIGINT|", "DOUBLE|", "DECIMAL|", "DEC|" "FLOAT|", "DATE|", "DATETIME|", "TIMESTAMP|", "BIGINT|", "DOUBLE|", "DECIMAL|", "DEC|" "FLOAT|", "DATE|", "DATETIME|", "TIMESTAMP|",
"TIME|", "YEAR|", "CHAR|", "VARCHAR|", "TEXT|", "ENUM|", "SET|", "BLOB|", "VARBINARY|", "TIME|", "YEAR|", "CHAR|", "VARCHAR|", "TEXT|", "ENUM|", "SET|", "BLOB|", "VARBINARY|",
"TINYBLOB|", "TINYTEXT|", "MEDIUMBLOB|", "MEDIUMTEXT|", "LONGTEXT|", "TINYBLOB|", "TINYTEXT|", "MEDIUMBLOB|", "MEDIUMTEXT|", "LONGTEXT|",
"select", "from", "drop", "create", "table", "default", "foreign", "update", "lock", "select", "from", "drop", "create", "table", "default", "foreign", "update", "lock",
"insert", "into", "values", "lock", "unlock", "where", "dinstinct", "between", "not", "insert", "into", "values", "lock", "unlock", "where", "dinstinct", "between", "not",
"null", "to", "on", "order", "group", "if", "by", "having", "using", "union", "unique", "null", "to", "on", "order", "group", "if", "by", "having", "using", "union", "unique",
"auto_increment", "like", "with", "inner", "outer", "join", "column", "database", "exists", "auto_increment", "like", "with", "inner", "outer", "join", "column", "database", "exists",
"natural", "limit", "unsigned", "max", "min", "precision", "alter", "delete", "cascade", "natural", "limit", "unsigned", "max", "min", "precision", "alter", "delete", "cascade",
"primary", "key", "constraint", "engine", "charset", "references", "write", "primary", "key", "constraint", "engine", "charset", "references", "write",
"bit|", "tinyint|", "bool|", "boolean|", "smallint|", "mediumint|", "int|", "integer|", "bit|", "tinyint|", "bool|", "boolean|", "smallint|", "mediumint|", "int|", "integer|",
"bigint|", "double|", "decimal|", "dec|" "float|", "date|", "datetime|", "timestamp|", "bigint|", "double|", "decimal|", "dec|" "float|", "date|", "datetime|", "timestamp|",
"time|", "year|", "char|", "varchar|", "text|", "enum|", "set|", "blob|", "varbinary|", "time|", "year|", "char|", "varchar|", "text|", "enum|", "set|", "blob|", "varbinary|",
"tinyblob|", "tinytext|", "mediumblob|", "mediumtext|", "longtext|", NULL "tinyblob|", "tinytext|", "mediumblob|", "mediumtext|", "longtext|", NULL
}; };
char* RUBY_HL_keywords[] = { char* RUBY_HL_keywords[] = {
"__ENCODING__", "__LINE__", "__FILE__", "BEGIN", "END", "alias", "and", "begin", "break", "__ENCODING__", "__LINE__", "__FILE__", "BEGIN", "END", "alias", "and", "begin", "break",
"case", "class", "def", "defined?", "do", "else", "elsif", "end", "ensure", "for", "if", "case", "class", "def", "defined?", "do", "else", "elsif", "end", "ensure", "for", "if",
"in", "module", "next", "not", "or", "redo", "rescue", "retry", "return", "self", "super", "in", "module", "next", "not", "or", "redo", "rescue", "retry", "return", "self", "super",
"then", "undef", "unless", "until", "when", "while", "yield", NULL "then", "undef", "unless", "until", "when", "while", "yield", NULL
}; };
struct editor_syntax HL_DB[] = { struct editor_syntax HL_DB[] = {
@@ -418,18 +418,18 @@ void enableRawMode() {
// Setting character size to 8 bits per byte (it should be // Setting character size to 8 bits per byte (it should be
// like that on most systems, but whatever). // like that on most systems, but whatever).
raw.c_cflag |= (CS8); raw.c_cflag |= (CS8);
// Using NOT operator on ECHO | ICANON | IEXTEN | ISIG and // Using NOT operator on ECHO | ICANON | IEXTEN | ISIG and
// then bitwise-AND them with flags field in order to // then bitwise-AND them with flags field in order to
// force c_lflag 4th bit to become 0. This disables // force c_lflag 4th bit to become 0. This disables
// chars being printed (ECHO) and let us turn off // chars being printed (ECHO) and let us turn off
// canonical mode in order to read input byte-by-byte // canonical mode in order to read input byte-by-byte
// instead of line-by-line (ICANON), ISIG disables // instead of line-by-line (ICANON), ISIG disables
// Ctrl-C command and IEXTEN the Ctrl-V one. // Ctrl-C command and IEXTEN the Ctrl-V one.
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
// read() function now returns as soon as there is any // read() function now returns as soon as there is any
// input to be read. // input to be read.
raw.c_cc[VMIN] = 0; raw.c_cc[VMIN] = 0;
// Forcing read() function to return every 1/10 of a // Forcing read() function to return every 1/10 of a
// second if there is nothing to read. // second if there is nothing to read.
raw.c_cc[VTIME] = 1; raw.c_cc[VTIME] = 1;
@@ -511,7 +511,7 @@ int editorReadKey() {
int getWindowSize(int* screen_rows, int* screen_cols) { int getWindowSize(int* screen_rows, int* screen_cols) {
struct winsize ws; struct winsize ws;
// Getting window size thanks to ioctl into the given // Getting window size thanks to ioctl into the given
// winsize struct. // winsize struct.
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) { if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
return -1; return -1;
@@ -574,9 +574,9 @@ void consoleBufferClose() {
/*** Syntax highlighting ***/ /*** Syntax highlighting ***/
int isSeparator(int c) { int isSeparator(int c) {
// strchr() looks to see if any one of the characters in the first string // strchr() looks to see if any one of the characters in the first string
// appear in the second string. If so, it returns a pointer to the // appear in the second string. If so, it returns a pointer to the
// character in the second string that matched. Otherwise, it // character in the second string that matched. Otherwise, it
// returns NULL. // returns NULL.
return isspace(c) || c == '\0' || strchr(",.()+-/*=~%<>[];", c) != NULL; return isspace(c) || c == '\0' || strchr(",.()+-/*=~%<>[];", c) != NULL;
} }
@@ -588,7 +588,7 @@ int isAlsoNumber(int c) {
void editorUpdateSyntax(editor_row* row) { void editorUpdateSyntax(editor_row* row) {
row -> highlight = realloc(row -> highlight, row -> render_size); row -> highlight = realloc(row -> highlight, row -> render_size);
// void * memset ( void * ptr, int value, size_t num ); // void * memset ( void * ptr, int value, size_t num );
// Sets the first num bytes of the block of memory pointed by ptr to // Sets the first num bytes of the block of memory pointed by ptr to
// the specified value. With this we set all characters to HL_NORMAL. // the specified value. With this we set all characters to HL_NORMAL.
memset(row -> highlight, HL_NORMAL, row -> render_size); memset(row -> highlight, HL_NORMAL, row -> render_size);
@@ -618,9 +618,9 @@ void editorUpdateSyntax(editor_row* row) {
if (scs_len && !in_string && !in_comment) { if (scs_len && !in_string && !in_comment) {
// int strncmp ( const char * str1, const char * str2, size_t num ); // int strncmp ( const char * str1, const char * str2, size_t num );
// Compares up to num characters of the C string str1 to those of the C string str2. // Compares up to num characters of the C string str1 to those of the C string str2.
// This function starts comparing the first character of each string. If they are // This function starts comparing the first character of each string. If they are
// equal to each other, it continues with the following pairs until the characters // equal to each other, it continues with the following pairs until the characters
// differ, until a terminating null-character is reached, or until num characters // differ, until a terminating null-character is reached, or until num characters
// match in both strings, whichever happens first. // match in both strings, whichever happens first.
if (!strncmp(&row -> render[i], scs, scs_len)) { if (!strncmp(&row -> render[i], scs, scs_len)) {
memset(&row -> highlight[i], HL_SL_COMMENT, row -> render_size - i); memset(&row -> highlight[i], HL_SL_COMMENT, row -> render_size - i);
@@ -647,16 +647,16 @@ void editorUpdateSyntax(editor_row* row) {
in_comment = 1; in_comment = 1;
continue; continue;
} }
} }
if (ec.syntax -> flags & HL_HIGHLIGHT_STRINGS) { if (ec.syntax -> flags & HL_HIGHLIGHT_STRINGS) {
if (in_string) { if (in_string) {
row -> highlight[i] = HL_STRING; row -> highlight[i] = HL_STRING;
// If we’re in a string and the current character is a backslash (\), // If we’re in a string and the current character is a backslash (\),
// and there’s at least one more character in that line that comes // and there’s at least one more character in that line that comes
// after the backslash, then we highlight the character that comes // after the backslash, then we highlight the character that comes
// after the backslash with HL_STRING and consume it. We increment // after the backslash with HL_STRING and consume it. We increment
// i by 2 to consume both characters at once. // i by 2 to consume both characters at once.
if (c == '\\' && i + 1 < row -> render_size) { if (c == '\\' && i + 1 < row -> render_size) {
row -> highlight[i + 1] = HL_STRING; row -> highlight[i + 1] = HL_STRING;
@@ -716,19 +716,19 @@ void editorUpdateSyntax(editor_row* row) {
} }
int changed = (row -> hl_open_comment != in_comment); int changed = (row -> hl_open_comment != in_comment);
// This tells us whether the row ended as an unclosed multi-line // This tells us whether the row ended as an unclosed multi-line
// comment or not. // comment or not.
row -> hl_open_comment = in_comment; row -> hl_open_comment = in_comment;
// A user could comment out an entire file just by changing one line. // A user could comment out an entire file just by changing one line.
// So it seems like we need to update the syntax of all the lines // So it seems like we need to update the syntax of all the lines
// following the current line. However, we know the highlighting // following the current line. However, we know the highlighting
// of the next line will not change if the value of this line’s // of the next line will not change if the value of this line’s
// // // hl_open_comment did not change. So we check if it changed, and // // // hl_open_comment did not change. So we check if it changed, and
// // only call editorUpdateSyntax() on the next line if // // only call editorUpdateSyntax() on the next line if
// hl_open_comment changed (and if there is a next line in the file). // hl_open_comment changed (and if there is a next line in the file).
// Because editorUpdateSyntax() keeps calling itself with the next // Because editorUpdateSyntax() keeps calling itself with the next
// line, the change will continue to propagate to more and more lines // line, the change will continue to propagate to more and more lines
// until one of them is unchanged, at which point we know that all // until one of them is unchanged, at which point we know that all
// the lines after that one must be unchanged as well. // the lines after that one must be unchanged as well.
if (changed && row -> idx + 1 < ec.num_rows) if (changed && row -> idx + 1 < ec.num_rows)
editorUpdateSyntax(&ec.row[row -> idx + 1]); editorUpdateSyntax(&ec.row[row -> idx + 1]);
@@ -762,7 +762,7 @@ void editorSelectSyntaxHighlight() {
while (es -> file_match[i]) { while (es -> file_match[i]) {
char* p = strstr(ec.file_name, es -> file_match[i]); char* p = strstr(ec.file_name, es -> file_match[i]);
if (p != NULL) { if (p != NULL) {
// Returns a pointer to the first occurrence of str2 in str1, // Returns a pointer to the first occurrence of str2 in str1,
// or a null pointer if str2 is not part of str1. // or a null pointer if str2 is not part of str1.
int pat_len = strlen(es -> file_match[i]); int pat_len = strlen(es -> file_match[i]);
if (es -> file_match[i][0] != '.' || p[pat_len] == '\0') { if (es -> file_match[i][0] != '.' || p[pat_len] == '\0') {
@@ -786,13 +786,13 @@ void editorSelectSyntaxHighlight() {
int editorRowCursorXToRenderX(editor_row* row, int cursor_x) { int editorRowCursorXToRenderX(editor_row* row, int cursor_x) {
int render_x = 0; int render_x = 0;
int j; int j;
// For each character, if its a tab we use rx % TTE_TAB_STOP // For each character, if its a tab we use rx % TTE_TAB_STOP
// to find out how many columns we are to the right of the last // to find out how many columns we are to the right of the last
// tab stop, and then subtract that from TTE_TAB_STOP - 1 to // tab stop, and then subtract that from TTE_TAB_STOP - 1 to
// find out how many columns we are to the left of the next tab // find out how many columns we are to the left of the next tab
// stop. We add that amount to rx to get just to the left of the // stop. We add that amount to rx to get just to the left of the
// next tab stop, and then the unconditional rx++ statement gets // next tab stop, and then the unconditional rx++ statement gets
// us right on the next tab stop. Notice how this works even if // us right on the next tab stop. Notice how this works even if
// we are currently on a tab stop. // we are currently on a tab stop.
for (j = 0; j < cursor_x; j++) { for (j = 0; j < cursor_x; j++) {
if (row -> chars[j] == '\t') if (row -> chars[j] == '\t')
@@ -817,12 +817,12 @@ int editorRowRenderXToCursorX(editor_row* row, int render_x) {
} }
void editorUpdateRow(editor_row* row) { void editorUpdateRow(editor_row* row) {
// First, we have to loop through the chars of the row // First, we have to loop through the chars of the row
// and count the tabs in order to know how much memory // and count the tabs in order to know how much memory
// to allocate for render. The maximum number of characters // to allocate for render. The maximum number of characters
// needed for each tab is 8. row->size already counts 1 for // needed for each tab is 8. row->size already counts 1 for
// each tab, so we multiply the number of tabs by 7 and add // each tab, so we multiply the number of tabs by 7 and add
// that to row->size to get the maximum amount of memory we'll // that to row->size to get the maximum amount of memory we'll
// need for the rendered row. // need for the rendered row.
int tabs = 0; int tabs = 0;
int j; int j;
@@ -833,10 +833,10 @@ void editorUpdateRow(editor_row* row) {
free(row -> render); free(row -> render);
row -> render = malloc(row -> size + tabs * (TTE_TAB_STOP - 1) + 1); row -> render = malloc(row -> size + tabs * (TTE_TAB_STOP - 1) + 1);
// After allocating the memory, we check whether the current character // After allocating the memory, we check whether the current character
// is a tab. If it is, we append one space (because each tab must // is a tab. If it is, we append one space (because each tab must
// advance the cursor forward at least one column), and then append // advance the cursor forward at least one column), and then append
// spaces until we get to a tab stop, which is a column that is // spaces until we get to a tab stop, which is a column that is
// divisible by 8 // divisible by 8
int idx = 0; int idx = 0;
for (j = 0; j < row -> size; j++) { for (j = 0; j < row -> size; j++) {
@@ -844,7 +844,7 @@ void editorUpdateRow(editor_row* row) {
row -> render[idx++] = ' '; row -> render[idx++] = ' ';
while (idx % TTE_TAB_STOP != 0) while (idx % TTE_TAB_STOP != 0)
row -> render[idx++] = ' '; row -> render[idx++] = ' ';
} else } else
row -> render[idx++] = row -> chars[j]; row -> render[idx++] = row -> chars[j];
} }
row -> render[idx] = '\0'; row -> render[idx] = '\0';
@@ -913,38 +913,38 @@ void editorFlipRow(int dir) {
int first = (dir == 1) ? ec.cursor_y - 1 : ec.cursor_y; int first = (dir == 1) ? ec.cursor_y - 1 : ec.cursor_y;
editorUpdateSyntax(&ec.row[first]); editorUpdateSyntax(&ec.row[first]);
editorUpdateSyntax(&ec.row[first] + 1); editorUpdateSyntax(&ec.row[first] + 1);
if (ec.num_rows - ec.cursor_y > 2) if (ec.num_rows - ec.cursor_y > 2)
editorUpdateSyntax(&ec.row[first] + 2); editorUpdateSyntax(&ec.row[first] + 2);
ec.cursor_y -= dir; ec.cursor_y -= dir;
ec.dirty++; ec.dirty++;
} }
void editorCopy(int cut) { void editorCopy(int cut) {
ec.copied_char_buffer = realloc(ec.copied_char_buffer, strlen(ec.row[ec.cursor_y].chars) + 1); ec.copied_char_buffer = realloc(ec.copied_char_buffer, strlen(ec.row[ec.cursor_y].chars) + 1);
strcpy(ec.copied_char_buffer, ec.row[ec.cursor_y].chars); strcpy(ec.copied_char_buffer, ec.row[ec.cursor_y].chars);
editorSetStatusMessage(cut ? "Content cutted" : "Content copied"); editorSetStatusMessage(cut ? "Content cut" : "Content copied");
} }
void editorCut() { void editorCut() {
editorCopy(-1); editorCopy(-1);
editorDelRow(ec.cursor_y); editorDelRow(ec.cursor_y);
if (ec.num_rows - ec.cursor_y > 0) if (ec.num_rows - ec.cursor_y > 0)
editorUpdateSyntax(&ec.row[ec.cursor_y]); editorUpdateSyntax(&ec.row[ec.cursor_y]);
if (ec.num_rows - ec.cursor_y > 1) if (ec.num_rows - ec.cursor_y > 1)
editorUpdateSyntax(&ec.row[ec.cursor_y + 1]); editorUpdateSyntax(&ec.row[ec.cursor_y + 1]);
ec.cursor_x = ec.cursor_y == ec.num_rows ? 0 : ec.row[ec.cursor_y].size; ec.cursor_x = ec.cursor_y == ec.num_rows ? 0 : ec.row[ec.cursor_y].size;
} }
void editorPaste() { void editorPaste() {
if (ec.copied_char_buffer == NULL) if (ec.copied_char_buffer == NULL)
return; return;
if (ec.cursor_y == ec.num_rows) if (ec.cursor_y == ec.num_rows)
editorInsertRow(ec.cursor_y, ec.copied_char_buffer, strlen(ec.copied_char_buffer)); editorInsertRow(ec.cursor_y, ec.copied_char_buffer, strlen(ec.copied_char_buffer));
else else
editorRowAppendString(&ec.row[ec.cursor_y], ec.copied_char_buffer, strlen(ec.copied_char_buffer)); editorRowAppendString(&ec.row[ec.cursor_y], ec.copied_char_buffer, strlen(ec.copied_char_buffer));
ec.cursor_x += strlen(ec.copied_char_buffer); ec.cursor_x += strlen(ec.copied_char_buffer);
} }
void editorRowInsertChar(editor_row* row, int at, int c) { void editorRowInsertChar(editor_row* row, int at, int c) {
@@ -963,7 +963,7 @@ void editorRowInsertChar(editor_row* row, int at, int c) {
} }
void editorInsertNewline() { void editorInsertNewline() {
// If we're at the beginning of a line, all we have to do is insert // If we're at the beginning of a line, all we have to do is insert
// a new blank row before the line we're on. // a new blank row before the line we're on.
if (ec.cursor_x == 0) { if (ec.cursor_x == 0) {
editorInsertRow(ec.cursor_y, "", 0); editorInsertRow(ec.cursor_y, "", 0);
@@ -1013,7 +1013,7 @@ void editorInsertChar(int c) {
} }
void editorDelChar() { void editorDelChar() {
// If the cursor is pats the end of the file, there's nothing to delete. // If the cursor is past the end of the file, there's nothing to delete.
if (ec.cursor_y == ec.num_rows) if (ec.cursor_y == ec.num_rows)
return; return;
// Cursor is at the beginning of a file, there's nothing to delete. // Cursor is at the beginning of a file, there's nothing to delete.
@@ -1039,7 +1039,7 @@ char* editorRowsToString(int* buf_len) {
int total_len = 0; int total_len = 0;
int j; int j;
// Adding up the lengths of each row of text, adding 1 // Adding up the lengths of each row of text, adding 1
// to each one for the newline character we'll add to // to each one for the newline character we'll add to
// the end of each line. // the end of each line.
for (j = 0; j < ec.num_rows; j++) { for (j = 0; j < ec.num_rows; j++) {
total_len += ec.row[j].size + 1; total_len += ec.row[j].size + 1;
@@ -1142,7 +1142,7 @@ void editorSearchCallback(char* query, int key) {
saved_hightlight = NULL; saved_hightlight = NULL;
} }
// Checking if the user pressed Enter or Escape, in which case // Checking if the user pressed Enter or Escape, in which case
// they are leaving search mode so we return immediately. // they are leaving search mode so we return immediately.
if (key == '\r' || key == '\x1b') { if (key == '\r' || key == '\x1b') {
last_match = -1; last_match = -1;
@@ -1203,7 +1203,7 @@ void editorSearch() {
if (query) { if (query) {
free(query); free(query);
// If query is NULL, that means they pressed Escape, so in that case we // If query is NULL, that means they pressed Escape, so in that case we
// restore the cursor previous position. // restore the cursor previous position.
} else { } else {
ec.cursor_x = saved_cursor_x; ec.cursor_x = saved_cursor_x;
@@ -1242,11 +1242,11 @@ void editorScroll() {
ec.render_x = 0; ec.render_x = 0;
if (ec.cursor_y < ec.num_rows) if (ec.cursor_y < ec.num_rows)
ec.render_x = editorRowCursorXToRenderX(&ec.row[ec.cursor_y], ec.cursor_x); ec.render_x = editorRowCursorXToRenderX(&ec.row[ec.cursor_y], ec.cursor_x);
// The first if statement checks if the cursor is above the visible window, // The first if statement checks if the cursor is above the visible window,
// and if so, scrolls up to where the cursor is. The second if statement checks // and if so, scrolls up to where the cursor is. The second if statement checks
// if the cursor is past the bottom of the visible window, and contains slightly // if the cursor is past the bottom of the visible window, and contains slightly
// more complicated arithmetic because ec.row_offset refers to what's at the top // more complicated arithmetic because ec.row_offset refers to what's at the top
// of the screen, and we have to get ec.screen_rows involved to talk about what's // of the screen, and we have to get ec.screen_rows involved to talk about what's
// at the bottom of the screen. // at the bottom of the screen.
if (ec.cursor_y < ec.row_offset) if (ec.cursor_y < ec.row_offset)
ec.row_offset = ec.cursor_y; ec.row_offset = ec.cursor_y;
@@ -1262,8 +1262,8 @@ void editorScroll() {
void editorDrawStatusBar(struct a_buf* ab) { void editorDrawStatusBar(struct a_buf* ab) {
// This switches to inverted colors. // This switches to inverted colors.
// NOTE: // NOTE:
// The m command (Select Graphic Rendition) causes the text printed // The m command (Select Graphic Rendition) causes the text printed
// after it to be printed with various possible attributes including // after it to be printed with various possible attributes including
// bold (1), underscore (4), blink (5), and inverted colors (7). An // bold (1), underscore (4), blink (5), and inverted colors (7). An
// argument of 0 clears all attributes (the default one). See // argument of 0 clears all attributes (the default one). See
// http://vt100.net/docs/vt100-ug/chapter3.html#SGR for more info. // http://vt100.net/docs/vt100-ug/chapter3.html#SGR for more info.
@@ -1325,17 +1325,17 @@ void editorDrawWelcomeMessage(struct a_buf* ab) {
abufAppend(ab, welcome, welcome_len); abufAppend(ab, welcome, welcome_len);
} }
// The ... argument makes editorSetStatusMessage() a variadic function, // The ... argument makes editorSetStatusMessage() a variadic function,
// meaning it can take any number of arguments. C's way of dealing with // meaning it can take any number of arguments. C's way of dealing with
// these arguments is by having you call va_start() and va_end() on a // these arguments is by having you call va_start() and va_end() on a
// // value of type va_list. The last argument before the ... (in this // // value of type va_list. The last argument before the ... (in this
// case, msg) must be passed to va_start(), so that the address of // case, msg) must be passed to va_start(), so that the address of
// the next arguments is known. Then, between the va_start() and // the next arguments is known. Then, between the va_start() and
// va_end() calls, you would call va_arg() and pass it the type of // va_end() calls, you would call va_arg() and pass it the type of
// the next argument (which you usually get from the given format // the next argument (which you usually get from the given format
// string) and it would return the value of that argument. In // string) and it would return the value of that argument. In
// this case, we pass msg and args to vsnprintf() and it takes care // this case, we pass msg and args to vsnprintf() and it takes care
// of reading the format string and calling va_arg() to get each // of reading the format string and calling va_arg() to get each
// argument. // argument.
void editorSetStatusMessage(const char* msg, ...) { void editorSetStatusMessage(const char* msg, ...) {
va_list args; va_list args;
@@ -1356,14 +1356,14 @@ void editorDrawRows(struct a_buf* ab) {
abufAppend(ab, "~", 1); abufAppend(ab, "~", 1);
} else { } else {
int len = ec.row[file_row].render_size - ec.col_offset; int len = ec.row[file_row].render_size - ec.col_offset;
// len can be a negative number, meaning the user scrolled // len can be a negative number, meaning the user scrolled
// horizontally past the end of the line. In that case, we set // horizontally past the end of the line. In that case, we set
// len to 0 so that nothing is displayed on that line. // len to 0 so that nothing is displayed on that line.
if (len < 0) if (len < 0)
len = 0; len = 0;
if (len > ec.screen_cols) if (len > ec.screen_cols)
len = ec.screen_cols; len = ec.screen_cols;
char* c = &ec.row[file_row].render[ec.col_offset]; char* c = &ec.row[file_row].render[ec.col_offset];
unsigned char* highlight = &ec.row[file_row].highlight[ec.col_offset]; unsigned char* highlight = &ec.row[file_row].highlight[ec.col_offset];
int current_color = -1; int current_color = -1;
@@ -1424,7 +1424,7 @@ void editorRefreshScreen() {
editorDrawRows(&ab); editorDrawRows(&ab);
editorDrawStatusBar(&ab); editorDrawStatusBar(&ab);
editorDrawMessageBar(&ab); editorDrawMessageBar(&ab);
// Moving the cursor where it should be. // Moving the cursor where it should be.
char buf[32]; char buf[32];
snprintf(buf, sizeof(buf), "\x1b[%d;%dH", (ec.cursor_y - ec.row_offset) + 1, (ec.render_x - ec.col_offset) + 1); snprintf(buf, sizeof(buf), "\x1b[%d;%dH", (ec.cursor_y - ec.row_offset) + 1, (ec.render_x - ec.col_offset) + 1);
@@ -1432,7 +1432,7 @@ void editorRefreshScreen() {
// Showing again the cursor. // Showing again the cursor.
abufAppend(&ab, "\x1b[?25h", 6); abufAppend(&ab, "\x1b[?25h", 6);
// Writing all content at once // Writing all content at once
write(STDOUT_FILENO, ab.buf, ab.len); write(STDOUT_FILENO, ab.buf, ab.len);
abufFree(&ab); abufFree(&ab);
@@ -1443,9 +1443,9 @@ void editorClearScreen() {
// - (1 byte) \x1b : escape character // - (1 byte) \x1b : escape character
// - (3 bytes) [2J : Clears the entire screen, see // - (3 bytes) [2J : Clears the entire screen, see
// http://vt100.net/docs/vt100-ug/chapter3.html#ED // http://vt100.net/docs/vt100-ug/chapter3.html#ED
// for more info. // for more info.
write(STDOUT_FILENO, "\x1b[2J", 4); write(STDOUT_FILENO, "\x1b[2J", 4);
// Writing 3 bytes to reposition the cursor back at // Writing 3 bytes to reposition the cursor back at
// the top-left corner, see // the top-left corner, see
// http://vt100.net/docs/vt100-ug/chapter3.html#CUP // http://vt100.net/docs/vt100-ug/chapter3.html#CUP
// for more info. // for more info.
@@ -1552,7 +1552,7 @@ void editorProcessKeypress() {
} }
editorClearScreen(); editorClearScreen();
consoleBufferClose(); consoleBufferClose();
exit(0); exit(0);
break; break;
case CTRL_KEY('s'): case CTRL_KEY('s'):
editorSave(); editorSave();
@@ -1563,22 +1563,22 @@ void editorProcessKeypress() {
break; break;
case CTRL_KEY('d'): case CTRL_KEY('d'):
if (ec.cursor_y < ec.num_rows - 1) if (ec.cursor_y < ec.num_rows - 1)
editorFlipRow(-1); editorFlipRow(-1);
break; break;
case CTRL_KEY('x'): case CTRL_KEY('x'):
if (ec.cursor_y < ec.num_rows) if (ec.cursor_y < ec.num_rows)
editorCut(); editorCut();
break; break;
case CTRL_KEY('c'): case CTRL_KEY('c'):
if (ec.cursor_y < ec.num_rows) if (ec.cursor_y < ec.num_rows)
editorCopy(0); editorCopy(0);
break; break;
case CTRL_KEY('v'): case CTRL_KEY('v'):
editorPaste(); editorPaste();
break; break;
case CTRL_KEY('p'): case CTRL_KEY('p'):
consoleBufferClose(); consoleBufferClose();
kill(0, SIGTSTP); kill(0, SIGTSTP);
case ARROW_UP: case ARROW_UP:
case ARROW_DOWN: case ARROW_DOWN:
case ARROW_LEFT: case ARROW_LEFT:
@@ -1640,15 +1640,15 @@ void initEditor() {
ec.file_name = NULL; ec.file_name = NULL;
ec.status_msg[0] = '\0'; ec.status_msg[0] = '\0';
ec.status_msg_time = 0; ec.status_msg_time = 0;
ec.copied_char_buffer = NULL; ec.copied_char_buffer = NULL;
ec.syntax = NULL; ec.syntax = NULL;
editorUpdateWindowSize(); editorUpdateWindowSize();
// The SIGWINCH signal is sent to a process when its controlling // The SIGWINCH signal is sent to a process when its controlling
// terminal changes its size (a window change). // terminal changes its size (a window change).
signal(SIGWINCH, editorHandleSigwinch); signal(SIGWINCH, editorHandleSigwinch);
// The SIGCONT signal instructs the operating system to continue // The SIGCONT signal instructs the operating system to continue
// (restart) a process previously paused by the SIGSTOP or SIGTSTP // (restart) a process previously paused by the SIGSTOP or SIGTSTP
// signal. // signal.
signal(SIGCONT, editorHandleSigcont); signal(SIGCONT, editorHandleSigcont);
} }