First public alpha version.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by antirez · committed by antirez · the first commit · Browse files · 6 files·+1338 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+1338 added−0 removed
- other:+1338 added−0 removed
Provenance
- Commit
a9f98a9- Tree
ebf0cdf- Author
antirez <antirez@gmail.com>- Committer
antirez <antirez@gmail.com>
6 files changed+1338 added−0 removed
added:.gitignore+1 added
1+kiloadded:kilo.c+1272 added
1+/* Kilo -- A very simple editor in less than 1-kilo lines of code (as counted2+ * by "cloc"). Does not depend on libcurses, directly emits VT1003+ * escapes on the terminal.4+ *5+ * -----------------------------------------------------------------------6+ *7+ * Copyright (C) 2016 Salvatore Sanfilippo <antirez at gmail dot com>8+ *9+ * All rights reserved.10+ *11+ * Redistribution and use in source and binary forms, with or without12+ * modification, are permitted provided that the following conditions are13+ * met:14+ *15+ * * Redistributions of source code must retain the above copyright16+ * notice, this list of conditions and the following disclaimer.17+ *18+ * * Redistributions in binary form must reproduce the above copyright19+ * notice, this list of conditions and the following disclaimer in the20+ * documentation and/or other materials provided with the distribution.21+ *22+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS23+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT24+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR25+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT26+ * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,27+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT28+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,29+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY30+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT31+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE32+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.33+ */34+35+#define KILO_VERSION "1.0.0"36+37+#define _BSD_SOURCE38+#define _GNU_SOURCE39+40+#include <termios.h>41+#include <stdlib.h>42+#include <stdio.h>43+#include <errno.h>44+#include <string.h>45+#include <stdlib.h>46+#include <ctype.h>47+#include <sys/types.h>48+#include <sys/ioctl.h>49+#include <sys/time.h>50+#include <unistd.h>51+#include <stdarg.h>52+#include <fcntl.h>53+54+/* Syntax highlight types */55+#define HL_NORMAL 056+#define HL_NONPRINT 157+#define HL_COMMENT 2 /* Single line comment. */58+#define HL_MLCOMMENT 3 /* Multi-line comment. */59+#define HL_KEYWORD1 460+#define HL_KEYWORD2 561+#define HL_STRING 662+#define HL_NUMBER 763+#define HL_MATCH 8 /* Search match. */64+65+#define HL_HIGHLIGHT_STRINGS (1<<0)66+#define HL_HIGHLIGHT_NUMBERS (1<<1)67+68+struct editorSyntax {69+ char **filematch;70+ char **keywords;71+ char singleline_comment_start[2];72+ char multiline_comment_start[3];73+ char multiline_comment_end[3];74+ int flags;75+};76+77+/* This structure represents a single line of the file we are editing. */78+typedef struct erow {79+ int idx; /* Row index in the file, zero-based. */80+ int size; /* Size of the row, excluding the null term. */81+ int rsize; /* Size of the rendered row. */82+ char *chars; /* Row content. */83+ char *render; /* Row content "rendered" for screen (for TABs). */84+ unsigned char *hl; /* Syntax highlight type for each character in render.*/85+ int hl_oc; /* Row had open comment at end in last syntax highlight86+ check. */87+} erow;88+89+typedef struct hlcolor {90+ int r,g,b;91+} hlcolor;92+93+struct editorConfig {94+ int cx,cy; /* Cursor x and y position in characters */95+ int rowoff; /* Offset of row displayed. */96+ int coloff; /* Offset of column displayed. */97+ int screenrows; /* Number of rows that we can show */98+ int screencols; /* Number of cols that we can show */99+ int numrows; /* Number of rows */100+ int rawmode; /* Is terminal raw mode enabled? */101+ erow *row; /* Rows */102+ int dirty; /* File modified but not saved. */103+ char *filename; /* Currently open filename */104+ char statusmsg[80];105+ time_t statusmsg_time;106+ struct editorSyntax *syntax; /* Current syntax highlight, or NULL. */107+};108+109+static struct editorConfig E;110+111+enum KEY_ACTION{112+ KEY_NULL = 0, /* NULL */113+ CTRL_C = 3, /* Ctrl-c */114+ CTRL_D = 4, /* Ctrl-d */115+ CTRL_F = 6, /* Ctrl-f */116+ CTRL_H = 8, /* Ctrl-h */117+ TAB = 9, /* Tab */118+ CTRL_L = 12, /* Ctrl+l */119+ ENTER = 13, /* Enter */120+ CTRL_Q = 17, /* Ctrl-q */121+ CTRL_S = 19, /* Ctrl-s */122+ CTRL_U = 21, /* Ctrl-u */123+ ESC = 27, /* Escape */124+ BACKSPACE = 127, /* Backspace */125+ /* The following are just soft codes, not really reported by the126+ * terminal directly. */127+ ARROW_LEFT = 1000,128+ ARROW_RIGHT,129+ ARROW_UP,130+ ARROW_DOWN,131+ DEL_KEY,132+ HOME_KEY,133+ END_KEY,134+ PAGE_UP,135+ PAGE_DOWN136+};137+138+void editorSetStatusMessage(const char *fmt, ...);139+140+/* =========================== Syntax highlights DB =========================141+ *142+ * In order to add a new syntax, define two arrays with a list of file name143+ * matches and keywords. The file name matches are used in order to match144+ * a given syntax with a given file name: if a match pattern starts with a145+ * dot, it is matched as the last past of the filename, for example ".c".146+ * Otherwise the pattern is just searched inside the filenme, like "Makefile").147+ *148+ * The list of keywords to highlight is just a list of words, however if they149+ * a trailing '|' character is added at the end, they are highlighted in150+ * a different color, so that you can have two different sets of keywords.151+ *152+ * Finally add a stanza in the HLDB global variable with two two arrays153+ * of strings, and a set of flags in order to enable highlighting of154+ * comments and numbers.155+ *156+ * The characters for single and multi line comments must be exactly two157+ * and must be provided as well (see the C language example).158+ *159+ * There is no support to highlight patterns currently. */160+161+/* C / C++ */162+char *C_HL_extensions[] = {".c",".cpp",NULL};163+char *C_HL_keywords[] = {164+ /* A few C / C++ keywords */165+ "switch","if","while","for","break","continue","return","else",166+ "struct","union","typedef","static","enum","class",167+ /* C types */168+ "int|","long|","double|","float|","char|","unsigned|","signed|",169+ "void|",NULL170+};171+172+/* Here we define an array of syntax highlights by extensions, keywords,173+ * comments delimiters and flags. */174+struct editorSyntax HLDB[] = {175+ {176+ /* C / C++ */177+ C_HL_extensions,178+ C_HL_keywords,179+ "//","/*","*/",180+ HL_HIGHLIGHT_STRINGS | HL_HIGHLIGHT_NUMBERS181+ }182+};183+184+#define HLDB_ENTRIES (sizeof(HLDB)/sizeof(HLDB[0]))185+186+/* ======================= Low level terminal handling ====================== */187+188+static struct termios orig_termios; /* In order to restore at exit.*/189+190+void disableRawMode(int fd) {191+ /* Don't even check the return value as it's too late. */192+ if (E.rawmode) {193+ tcsetattr(fd,TCSAFLUSH,&orig_termios);194+ E.rawmode = 0;195+ }196+}197+198+/* Called at exit to avoid remaining in raw mode. */199+void editorAtExit(void) {200+ disableRawMode(STDIN_FILENO);201+}202+203+/* Raw mode: 1960 magic shit. */204+int enableRawMode(int fd) {205+ struct termios raw;206+207+ if (E.rawmode) return 0; /* Already enabled. */208+ if (!isatty(STDIN_FILENO)) goto fatal;209+ atexit(editorAtExit);210+ if (tcgetattr(fd,&orig_termios) == -1) goto fatal;211+212+ raw = orig_termios; /* modify the original mode */213+ /* input modes: no break, no CR to NL, no parity check, no strip char,214+ * no start/stop output control. */215+ raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);216+ /* output modes - disable post processing */217+ raw.c_oflag &= ~(OPOST);218+ /* control modes - set 8 bit chars */219+ raw.c_cflag |= (CS8);220+ /* local modes - choing off, canonical off, no extended functions,221+ * no signal chars (^Z,^C) */222+ raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);223+ /* control chars - set return condition: min number of bytes and timer. */224+ raw.c_cc[VMIN] = 0; /* Return each byte, or zero for timeout. */225+ raw.c_cc[VTIME] = 1; /* 100 ms timeout (unit is tens of second). */226+227+ /* put terminal in raw mode after flushing */228+ if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;229+ E.rawmode = 1;230+ return 0;231+232+fatal:233+ errno = ENOTTY;234+ return -1;235+}236+237+/* Read a key from the terminal put in raw mode, trying to handle238+ * escape sequences. */239+int editorReadKey(int fd) {240+ int nread;241+ char c, seq[3];242+ while ((nread = read(fd,&c,1)) == 0);243+ if (nread == -1) exit(1);244+245+ while(1) {246+ switch(c) {247+ case ESC: /* escape sequence */248+ /* If this is just an ESC, we'll timeout here. */249+ if (read(fd,seq,1) == 0) return ESC;250+ if (read(fd,seq+1,1) == 0) return ESC;251+252+ /* ESC [ sequences. */253+ if (seq[0] == '[') {254+ if (seq[1] >= '0' && seq[1] <= '9') {255+ /* Extended escape, read additional byte. */256+ if (read(fd,seq+2,1) == 0) return ESC;257+ if (seq[2] == '~') {258+ switch(seq[1]) {259+ case '3': return DEL_KEY;260+ case '5': return PAGE_UP;261+ case '6': return PAGE_DOWN;262+ }263+ }264+ } else {265+ switch(seq[1]) {266+ case 'A': return ARROW_UP;267+ case 'B': return ARROW_DOWN;268+ case 'C': return ARROW_RIGHT;269+ case 'D': return ARROW_LEFT;270+ case 'H': return HOME_KEY;271+ case 'F': return END_KEY;272+ }273+ }274+ }275+276+ /* ESC O sequences. */277+ else if (seq[0] == 'O') {278+ switch(seq[1]) {279+ case 'H': return HOME_KEY;280+ case 'F': return END_KEY;281+ }282+ }283+ break;284+ default:285+ return c;286+ }287+ }288+}289+290+/* Use the ESC [6n escape sequence to query the horizontal cursor position291+ * and return it. On error -1 is returned, on success the position of the292+ * cursor is stored at *rows and *cols and 0 is returned. */293+int getCursorPosition(int ifd, int ofd, int *rows, int *cols) {294+ char buf[32];295+ unsigned int i = 0;296+297+ /* Report cursor location */298+ if (write(ofd, "\x1b[6n", 4) != 4) return -1;299+300+ /* Read the response: ESC [ rows ; cols R */301+ while (i < sizeof(buf)-1) {302+ if (read(ifd,buf+i,1) != 1) break;303+ if (buf[i] == 'R') break;304+ i++;305+ }306+ buf[i] = '\0';307+308+ /* Parse it. */309+ if (buf[0] != ESC || buf[1] != '[') return -1;310+ if (sscanf(buf+2,"%d;%d",rows,cols) != 2) return -1;311+ return 0;312+}313+314+/* Try to get the number of columns in the current terminal. If the ioctl()315+ * call fails the function will try to query the terminal itself.316+ * Returns 0 on success, -1 on error. */317+int getWindowSize(int ifd, int ofd, int *rows, int *cols) {318+ struct winsize ws;319+320+ if (ioctl(1, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {321+ /* ioctl() failed. Try to query the terminal itself. */322+ int orig_row, orig_col, retval;323+324+ /* Get the initial position so we can restore it later. */325+ retval = getCursorPosition(ifd,ofd,&orig_row,&orig_col);326+ if (retval == -1) goto failed;327+328+ /* Go to right/bottom margin and get position. */329+ if (write(ofd,"\x1b[999C\x1b[999B",12) != 12) goto failed;330+ retval = getCursorPosition(ifd,ofd,rows,cols);331+ if (retval == -1) goto failed;332+333+ /* Restore position. */334+ char seq[32];335+ snprintf(seq,32,"\x1b[%d;%dH",orig_row,orig_col);336+ if (write(ofd,seq,strlen(seq)) == -1) {337+ /* Can't recover... */338+ }339+ return 0;340+ } else {341+ *cols = ws.ws_col;342+ *rows = ws.ws_row;343+ return 0;344+ }345+346+failed:347+ return -1;348+}349+350+/* ====================== Syntax highlight color scheme ==================== */351+352+int is_separator(int c) {353+ return c == '\0' || isspace(c) || strchr(",.()+-/*=~%[];",c) != NULL;354+}355+356+/* Return true if the specified row last char is part of a multi line comment357+ * that starts at this row or at one before, and does not end at the end358+ * of the row but spawns to the next row. */359+int editorRowHasOpenComment(erow *row) {360+ if (row->hl && row->rsize && row->hl[row->rsize-1] == HL_MLCOMMENT &&361+ (row->rsize < 2 || (row->render[row->rsize-2] != '*' ||362+ row->render[row->rsize-1] != '/'))) return 1;363+ return 0;364+}365+366+/* Set every byte of row->hl (that corresponds to every character in the line)367+ * to the right syntax highlight type (HL_* defines). */368+void editorUpdateSyntax(erow *row) {369+ row->hl = realloc(row->hl,row->rsize);370+ memset(row->hl,HL_NORMAL,row->rsize);371+372+ if (E.syntax == NULL) return; /* No syntax, everything is HL_NORMAL. */373+374+ int i, prev_sep, in_string, in_comment;375+ char *p;376+ char **keywords = E.syntax->keywords;377+ char *scs = E.syntax->singleline_comment_start;378+ char *mcs = E.syntax->multiline_comment_start;379+ char *mce = E.syntax->multiline_comment_end;380+381+ /* Point to the first non-space char. */382+ p = row->render;383+ i = 0; /* Current char offset */384+ while(*p && isspace(*p)) {385+ p++;386+ i++;387+ }388+ prev_sep = 1; /* Tell the parser if 'i' points to start of word. */389+ in_string = 0; /* Are we inside "" or '' ? */390+ in_comment = 0; /* Are we inside multi-line comment? */391+392+ /* If the previous line has an open comment, this line starts393+ * with an open comment state. */394+ if (row->idx > 0 && editorRowHasOpenComment(&E.row[row->idx-1]))395+ in_comment = 1;396+397+ while(*p) {398+ /* Handle // comments. */399+ if (prev_sep && *p == scs[0] && *(p+1) == scs[1]) {400+ /* From here to end is a comment */401+ memset(row->hl+i,HL_COMMENT,row->size-i);402+ return;403+ }404+405+ /* Handle multi line comments. */406+ if (in_comment) {407+ row->hl[i] = HL_MLCOMMENT;408+ if (*p == mce[0] && *(p+1) == mce[1]) {409+ row->hl[i+1] = HL_MLCOMMENT;410+ p += 2; i += 2;411+ in_comment = 0;412+ prev_sep = 1;413+ continue;414+ } else {415+ prev_sep = 0;416+ p++; i++;417+ continue;418+ }419+ } else if (*p == mcs[0] && *(p+1) == mcs[1]) {420+ row->hl[i] = HL_MLCOMMENT;421+ row->hl[i+1] = HL_MLCOMMENT;422+ p += 2; i += 2;423+ in_comment = 1;424+ prev_sep = 0;425+ continue;426+ }427+428+ /* Handle "" and '' */429+ if (in_string) {430+ row->hl[i] = HL_STRING;431+ if (*p == '\\') {432+ row->hl[i+1] = HL_STRING;433+ p += 2; i += 2;434+ prev_sep = 0;435+ continue;436+ }437+ if (*p == in_string) in_string = 0;438+ p++; i++;439+ continue;440+ } else {441+ if (*p == '"' || *p == '\'') {442+ in_string = *p;443+ row->hl[i] = HL_STRING;444+ p++; i++;445+ prev_sep = 0;446+ continue;447+ }448+ }449+450+ /* Handle non printable chars. */451+ if (!isprint(*p)) {452+ row->hl[i] = HL_NONPRINT;453+ p++; i++;454+ prev_sep = 0;455+ continue;456+ }457+458+ /* Handle numbers */459+ if ((isdigit(*p) && (prev_sep || row->hl[i-1] == HL_NUMBER)) ||460+ (*p == '.' && i >0 && row->hl[i-1] == HL_NUMBER)) {461+ row->hl[i] = HL_NUMBER;462+ p++; i++;463+ prev_sep = 0;464+ continue;465+ }466+467+ /* Handle keywords and lib calls */468+ if (prev_sep) {469+ int j;470+ for (j = 0; keywords[j]; j++) {471+ int klen = strlen(keywords[j]);472+ int kw2 = keywords[j][klen-1] == '|';473+ if (kw2) klen--;474+475+ if (!memcmp(p,keywords[j],klen) &&476+ is_separator(*(p+klen)))477+ {478+ /* Keyword */479+ memset(row->hl+i,kw2 ? HL_KEYWORD2 : HL_KEYWORD1,klen);480+ p += klen;481+ i += klen;482+ break;483+ }484+ }485+ if (keywords[j] != NULL) {486+ prev_sep = 0;487+ continue; /* We had a keyword match */488+ }489+ }490+491+ /* Not special chars */492+ prev_sep = is_separator(*p);493+ p++; i++;494+ }495+496+ /* Propagate syntax change to the next row if the open commen497+ * state changed. This may recursively affect all the following rows498+ * in the file. */499+ int oc = editorRowHasOpenComment(row);500+ if (row->hl_oc != oc && row->idx+1 < E.numrows)501+ editorUpdateSyntax(&E.row[row->idx+1]);502+ row->hl_oc = oc;503+}504+505+/* Maps syntax highlight token types to terminal colors. */506+int editorSyntaxToColor(int hl) {507+ switch(hl) {508+ case HL_COMMENT:509+ case HL_MLCOMMENT: return 36; /* cyan */510+ case HL_KEYWORD1: return 33; /* yellow */511+ case HL_KEYWORD2: return 32; /* green */512+ case HL_STRING: return 35; /* magenta */513+ case HL_NUMBER: return 31; /* red */514+ case HL_MATCH: return 34; /* blu */515+ default: return 37; /* white */516+ }517+}518+519+/* Select the syntax highlight scheme depending on the filename,520+ * setting it in the global state E.syntax. */521+void editorSelectSyntaxHighlight(char *filename) {522+ for (unsigned int j = 0; j < HLDB_ENTRIES; j++) {523+ struct editorSyntax *s = HLDB+j;524+ unsigned int i = 0;525+ while(s->filematch[i]) {526+ char *p;527+ int patlen = strlen(s->filematch[i]);528+ if ((p = strstr(filename,s->filematch[i])) != NULL) {529+ if (s->filematch[i][0] != '.' || p[patlen] == '\0') {530+ E.syntax = s;531+ return;532+ }533+ }534+ i++;535+ }536+ }537+}538+539+/* ======================= Editor rows implementation ======================= */540+541+/* Update the rendered version and the syntax highlight of a row. */542+void editorUpdateRow(erow *row) {543+ int tabs = 0, nonprint = 0, j, idx;544+545+ /* Create a version of the row we can directly print on the screen,546+ * respecting tabs, substituting non printable characters with '?'. */547+ free(row->render);548+ for (j = 0; j < row->size; j++)549+ if (row->chars[j] == TAB) tabs++;550+551+ row->render = malloc(row->size + tabs*8 + nonprint*9 + 1);552+ idx = 0;553+ for (j = 0; j < row->size; j++) {554+ if (row->chars[j] == TAB) {555+ row->render[idx++] = ' ';556+ while((idx+1) % 8 != 0) row->render[idx++] = ' ';557+ } else {558+ row->render[idx++] = row->chars[j];559+ }560+ }561+ row->rsize = idx;562+ row->render[idx] = '\0';563+564+ /* Update the syntax highlighting attributes of the row. */565+ editorUpdateSyntax(row);566+}567+568+/* Insert a row at the specified position, shifting the other rows on the bottom569+ * if required. */570+void editorInsertRow(int at, char *s, size_t len) {571+ if (at > E.numrows) return;572+ E.row = realloc(E.row,sizeof(erow)*(E.numrows+1));573+ if (at != E.numrows) {574+ memmove(E.row+at+1,E.row+at,sizeof(E.row[0])*(E.numrows-at));575+ for (int j = at+1; j <= E.numrows; j++) E.row[j].idx++;576+ }577+ E.row[at].size = len;578+ E.row[at].chars = malloc(len+1);579+ memcpy(E.row[at].chars,s,len+1);580+ E.row[at].hl = NULL;581+ E.row[at].hl_oc = 0;582+ E.row[at].render = NULL;583+ E.row[at].rsize = 0;584+ E.row[at].idx = at;585+ editorUpdateRow(E.row+at);586+ E.numrows++;587+ E.dirty++;588+}589+590+/* Free row's heap allocated stuff. */591+void editorFreeRow(erow *row) {592+ free(row->render);593+ free(row->chars);594+ free(row->hl);595+}596+597+/* Remove the row at the specified position, shifting the remainign on the598+ * top. */599+void editorDelRow(int at) {600+ erow *row;601+602+ if (at >= E.numrows) return;603+ row = E.row+at;604+ editorFreeRow(row);605+ memmove(E.row+at,E.row+at+1,sizeof(E.row[0])*(E.numrows-at-1));606+ for (int j = at; j < E.numrows-1; j++) E.row[j].idx++;607+ E.numrows--;608+ E.dirty++;609+}610+611+/* Turn the editor rows into a single heap-allocated string.612+ * Returns the pointer to the heap-allocated string and populate the613+ * integer pointed by 'buflen' with the size of the string, escluding614+ * the final nulterm. */615+char *editorRowsToString(int *buflen) {616+ char *buf = NULL, *p;617+ int totlen = 0;618+ int j;619+620+ /* Compute count of bytes */621+ for (j = 0; j < E.numrows; j++)622+ totlen += E.row[j].size+1; /* +1 is for "\n" at end of every row */623+ *buflen = totlen;624+ totlen++; /* Also make space for nulterm */625+626+ p = buf = malloc(totlen);627+ for (j = 0; j < E.numrows; j++) {628+ memcpy(p,E.row[j].chars,E.row[j].size);629+ p += E.row[j].size;630+ *p = '\n';631+ p++;632+ }633+ *p = '\0';634+ return buf;635+}636+637+/* Insert a character at the specified position in a row, moving the remaining638+ * chars on the right if needed. */639+void editorRowInsertChar(erow *row, int at, int c) {640+ if (at > row->size) {641+ /* Pad the string with spaces if the insert location is outside the642+ * current length by more than a single character. */643+ int padlen = at-row->size;644+ /* In the next line +2 means: new char and null term. */645+ row->chars = realloc(row->chars,row->size+padlen+2);646+ memset(row->chars+row->size,' ',padlen);647+ row->chars[row->size+padlen+1] = '\0';648+ row->size += padlen+1;649+ } else {650+ /* If we are in the middle of the string just make space for 1 new651+ * char plus the (already existing) null term. */652+ row->chars = realloc(row->chars,row->size+2);653+ memmove(row->chars+at+1,row->chars+at,row->size-at+1);654+ row->size++;655+ }656+ row->chars[at] = c;657+ editorUpdateRow(row);658+ E.dirty++;659+}660+661+/* Append the string 's' at the end of a row */662+void editorRowAppendString(erow *row, char *s, size_t len) {663+ row->chars = realloc(row->chars,row->size+len+1);664+ memcpy(row->chars+row->size,s,len);665+ row->size += len;666+ row->chars[row->size] = '\0';667+ editorUpdateRow(row);668+ E.dirty++;669+}670+671+/* Delete the character at offset 'at' from the specified row. */672+void editorRowDelChar(erow *row, int at) {673+ if (row->size <= at) return;674+ memmove(row->chars+at,row->chars+at+1,row->size-at);675+ editorUpdateRow(row);676+ row->size--;677+ E.dirty++;678+}679+680+/* Insert the specified char at the current prompt position. */681+void editorInsertChar(int c) {682+ int filerow = E.rowoff+E.cy;683+ int filecol = E.coloff+E.cx;684+ erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow];685+686+ /* If the row where the cursor is currently located does not exist in our687+ * logical representaion of the file, add enough empty rows as needed. */688+ if (!row) {689+ while(E.numrows <= filerow)690+ editorInsertRow(E.numrows,"",0);691+ }692+ row = &E.row[filerow];693+ editorRowInsertChar(row,filecol,c);694+ if (E.cx == E.screencols-1)695+ E.coloff++;696+ else697+ E.cx++;698+ E.dirty++;699+}700+701+/* Inserting a newline is slightly complex as we have to handle inserting a702+ * newline in the middle of a line, splitting the line as needed. */703+void editorInsertNewline(void) {704+ int filerow = E.rowoff+E.cy;705+ int filecol = E.coloff+E.cx;706+ erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow];707+708+ if (!row) {709+ if (filerow == E.numrows) {710+ editorInsertRow(filerow,"",0);711+ goto fixcursor;712+ }713+ return;714+ }715+ /* If the cursor is over the current line size, we want to conceptually716+ * think it's just over the last character. */717+ if (filecol >= row->size) filecol = row->size;718+ if (filecol == 0) {719+ editorInsertRow(filerow,"",0);720+ } else {721+ /* We are in the middle of a line. Split it between two rows. */722+ editorInsertRow(filerow+1,row->chars+filecol,row->size-filecol);723+ row = &E.row[filerow];724+ row->chars[filecol] = '\0';725+ row->size = filecol;726+ editorUpdateRow(row);727+ }728+fixcursor:729+ if (E.cy == E.screenrows-1) {730+ E.rowoff++;731+ } else {732+ E.cy++;733+ }734+ E.cx = 0;735+ E.coloff = 0;736+}737+738+/* Delete the char at the current prompt position. */739+void editorDelChar() {740+ int filerow = E.rowoff+E.cy;741+ int filecol = E.coloff+E.cx;742+ erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow];743+744+ if (!row || (filecol == 0 && filerow == 0)) return;745+ if (filecol == 0) {746+ /* Handle the case of column 0, we need to move the current line747+ * on the right of the previous one. */748+ filecol = E.row[filerow-1].size;749+ editorRowAppendString(&E.row[filerow-1],row->chars,row->size);750+ editorDelRow(filerow);751+ row = NULL;752+ if (E.cy == 0)753+ E.rowoff--;754+ else755+ E.cy--;756+ E.cx = filecol;757+ if (E.cx >= E.screencols) {758+ int shift = (E.screencols-E.cx)+1;759+ E.cx -= shift;760+ E.coloff += shift;761+ }762+ } else {763+ editorRowDelChar(row,filecol-1);764+ if (E.cx == 0 && E.coloff)765+ E.coloff--;766+ else767+ E.cx--;768+ }769+ if (row) editorUpdateRow(row);770+ E.dirty++;771+}772+773+/* Load the specified program in the editor memory and returns 0 on success774+ * or 1 on error. */775+int editorOpen(char *filename) {776+ FILE *fp;777+778+ E.dirty = 0;779+ free(E.filename);780+ E.filename = strdup(filename);781+782+ fp = fopen(filename,"r");783+ if (!fp) {784+ if (errno != ENOENT) {785+ perror("Opening file");786+ exit(1);787+ }788+ return 1;789+ }790+791+ char *line = NULL;792+ size_t linecap = 0;793+ ssize_t linelen;794+ while((linelen = getline(&line,&linecap,fp)) != -1) {795+ if (linelen && (line[linelen-1] == '\n' || line[linelen-1] == '\r'))796+ line[--linelen] = '\0';797+ editorInsertRow(E.numrows,line,linelen);798+ }799+ free(line);800+ fclose(fp);801+ E.dirty = 0;802+ return 0;803+}804+805+/* Save the current file on disk. Return 0 on success, 1 on error. */806+int editorSave(void) {807+ int len;808+ char *buf = editorRowsToString(&len);809+ int fd = open(E.filename,O_RDWR|O_CREAT,0644);810+ if (fd == -1) goto writeerr;811+812+ /* Use truncate + a single write(2) call in order to make saving813+ * a bit safer, under the limits of what we can do in a small editor. */814+ if (ftruncate(fd,len) == -1) goto writeerr;815+ if (write(fd,buf,len) != len) goto writeerr;816+817+ close(fd);818+ free(buf);819+ E.dirty = 0;820+ editorSetStatusMessage("%d bytes written on disk", len);821+ return 0;822+823+writeerr:824+ free(buf);825+ if (fd != -1) close(fd);826+ editorSetStatusMessage("Can't save! I/O error: %s",strerror(errno));827+ return 1;828+}829+830+/* ============================= Terminal update ============================ */831+832+/* We define a very simple "append buffer" structure, that is an heap833+ * allocated string where we can append to. This is useful in order to834+ * write all the escape sequences in a buffer and flush them to the standard835+ * output in a single call, to avoid flickering effects. */836+struct abuf {837+ char *b;838+ int len;839+};840+841+#define ABUF_INIT {NULL,0}842+843+void abAppend(struct abuf *ab, const char *s, int len) {844+ char *new = realloc(ab->b,ab->len+len);845+846+ if (new == NULL) return;847+ memcpy(new+ab->len,s,len);848+ ab->b = new;849+ ab->len += len;850+}851+852+void abFree(struct abuf *ab) {853+ free(ab->b);854+}855+856+/* This function writes the whole screen using VT100 escape characters857+ * starting from the logical state of the editor in the global state 'E'. */858+void editorRefreshScreen(void) {859+ int y;860+ erow *r;861+ char buf[32];862+ struct abuf ab = ABUF_INIT;863+864+ abAppend(&ab,"\x1b[?25l",6); /* Hide cursor. */865+ abAppend(&ab,"\x1b[H",3); /* Go home. */866+ for (y = 0; y < E.screenrows; y++) {867+ int filerow = E.rowoff+y;868+869+ if (filerow >= E.numrows) {870+ if (E.numrows == 0 && y == E.screenrows/3) {871+ char welcome[80];872+ int welcomelen = snprintf(welcome,sizeof(welcome),873+ "Kilo editor -- verison %s\x1b[0K\r\n", KILO_VERSION);874+ int padding = (E.screencols-welcomelen)/2;875+ if (padding) {876+ abAppend(&ab,"~",1);877+ padding--;878+ }879+ while(padding--) abAppend(&ab," ",1);880+ abAppend(&ab,welcome,welcomelen);881+ } else {882+ abAppend(&ab,"~\x1b[0K\r\n",7);883+ }884+ continue;885+ }886+887+ r = &E.row[filerow];888+889+ int len = r->rsize - E.coloff;890+ int current_color = -1;891+ if (len > 0) {892+ if (len > E.screencols) len = E.screencols;893+ char *c = r->render+E.coloff;894+ unsigned char *hl = r->hl+E.coloff;895+ int j;896+ for (j = 0; j < len; j++) {897+ if (hl[j] == HL_NONPRINT) {898+ char sym;899+ abAppend(&ab,"\x1b[7m",4);900+ if (c[j] <= 26)901+ sym = '@'+c[j];902+ else903+ sym = '?';904+ abAppend(&ab,&sym,1);905+ abAppend(&ab,"\x1b[0m",4);906+ } else if (hl[j] == HL_NORMAL) {907+ if (current_color != -1) {908+ abAppend(&ab,"\x1b[39m",5);909+ current_color = -1;910+ }911+ abAppend(&ab,c+j,1);912+ } else {913+ int color = editorSyntaxToColor(hl[j]);914+ if (color != current_color) {915+ char buf[16];916+ int clen = snprintf(buf,sizeof(buf),"\x1b[%dm",color);917+ current_color = color;918+ abAppend(&ab,buf,clen);919+ }920+ abAppend(&ab,c+j,1);921+ }922+ }923+ }924+ abAppend(&ab,"\x1b[39m",5);925+ abAppend(&ab,"\x1b[0K",4);926+ abAppend(&ab,"\r\n",2);927+ }928+929+ /* Create a two rows status. First row: */930+ abAppend(&ab,"\x1b[0K",4);931+ abAppend(&ab,"\x1b[7m",4);932+ char status[80], rstatus[80];933+ int len = snprintf(status, sizeof(status), "%.20s - %d lines %s",934+ E.filename, E.numrows, E.dirty ? "(modified)" : "");935+ int rlen = snprintf(rstatus, sizeof(rstatus),936+ "%d/%d",E.rowoff+E.cy+1,E.numrows);937+ if (len > E.screencols) len = E.screencols;938+ abAppend(&ab,status,len);939+ while(len < E.screencols) {940+ if (E.screencols - len == rlen) {941+ abAppend(&ab,rstatus,rlen);942+ break;943+ } else {944+ abAppend(&ab," ",1);945+ len++;946+ }947+ }948+ abAppend(&ab,"\x1b[0m\r\n",6);949+950+ /* Second row depends on E.statusmsg and the status message update time. */951+ abAppend(&ab,"\x1b[0K",4);952+ int msglen = strlen(E.statusmsg);953+ if (msglen && time(NULL)-E.statusmsg_time < 5)954+ abAppend(&ab,E.statusmsg,msglen <= E.screencols ? msglen : E.screencols);955+956+ /* Put cursor at its current position. Note that the horizontal position957+ * at which the cursor is displayed may be different compared to 'E.cx'958+ * because of TABs. */959+ int j;960+ int cx = 1;961+ int filerow = E.rowoff+E.cy;962+ erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow];963+ if (row) {964+ for (j = E.coloff; j < (E.cx+E.coloff); j++) {965+ if (j < row->size && row->chars[j] == TAB) cx += 7-((cx)%8);966+ cx++;967+ }968+ }969+ snprintf(buf,sizeof(buf),"\x1b[%d;%dH",E.cy+1,cx);970+ abAppend(&ab,buf,strlen(buf));971+ abAppend(&ab,"\x1b[?25h",6); /* Show cursor. */972+ write(STDOUT_FILENO,ab.b,ab.len);973+ abFree(&ab);974+}975+976+/* Set an editor status message for the second line of the status, at the977+ * end of the screen. */978+void editorSetStatusMessage(const char *fmt, ...) {979+ va_list ap;980+ va_start(ap,fmt);981+ vsnprintf(E.statusmsg,sizeof(E.statusmsg),fmt,ap);982+ va_end(ap);983+ E.statusmsg_time = time(NULL);984+}985+986+/* =============================== Find mode ================================ */987+988+#define KILO_QUERY_LEN 256989+990+void editorFind(int fd) {991+ char query[KILO_QUERY_LEN+1] = {0};992+ int qlen = 0;993+ int last_match = -1; /* Last line where a match was found. -1 for none. */994+ int find_next = 0; /* if 1 search next, if -1 search prev. */995+ int saved_hl_line = -1; /* No saved HL */996+ char *saved_hl = NULL;997+998+#define FIND_RESTORE_HL do { \999+ if (saved_hl) { \1000+ memcpy(E.row[saved_hl_line].hl,saved_hl, E.row[saved_hl_line].rsize); \1001+ saved_hl = NULL; \1002+ } \1003+} while (0)1004+1005+ /* Save the cursor position in order to restore it later. */1006+ int saved_cx = E.cx, saved_cy = E.cy;1007+ int saved_coloff = E.coloff, saved_rowoff = E.rowoff;1008+1009+ while(1) {1010+ editorSetStatusMessage(1011+ "Search: %s (Use ESC/Arrows/Enter)", query);1012+ editorRefreshScreen();1013+1014+ int c = editorReadKey(fd);1015+ if (c == DEL_KEY || c == CTRL_H || c == BACKSPACE) {1016+ if (qlen != 0) query[--qlen] = '\0';1017+ last_match = -1;1018+ } else if (c == ESC || c == ENTER) {1019+ if (c == ESC) {1020+ E.cx = saved_cx; E.cy = saved_cy;1021+ E.coloff = saved_coloff; E.rowoff = saved_rowoff;1022+ }1023+ FIND_RESTORE_HL;1024+ editorSetStatusMessage("");1025+ return;1026+ } else if (c == ARROW_RIGHT || c == ARROW_DOWN) {1027+ find_next = 1;1028+ } else if (c == ARROW_LEFT || c == ARROW_UP) {1029+ find_next = -1;1030+ } else if (isprint(c)) {1031+ if (qlen < KILO_QUERY_LEN) {1032+ query[qlen++] = c;1033+ query[qlen] = '\0';1034+ last_match = -1;1035+ }1036+ }1037+1038+ /* Search occurrence. */1039+ if (last_match == -1) find_next = 1;1040+ if (find_next) {1041+ char *match = NULL;1042+ int match_offset = 0;1043+ int i, current = last_match;1044+1045+ for (i = 0; i < E.numrows; i++) {1046+ current += find_next;1047+ if (current == -1) current = E.numrows-1;1048+ else if (current == E.numrows) current = 0;1049+ match = strstr(E.row[current].render,query);1050+ if (match) {1051+ match_offset = match-E.row[current].render;1052+ break;1053+ }1054+ }1055+ find_next = 0;1056+1057+ /* Highlight */1058+ FIND_RESTORE_HL;1059+1060+ if (match) {1061+ erow *row = &E.row[current];1062+ last_match = current;1063+ if (row->hl) {1064+ saved_hl_line = current;1065+ saved_hl = malloc(row->rsize);1066+ memcpy(saved_hl,row->hl,row->rsize);1067+ memset(row->hl+match_offset,HL_MATCH,qlen);1068+ }1069+ E.cy = 0;1070+ E.cx = match_offset;1071+ E.rowoff = current;1072+ E.coloff = 0;1073+ /* Scroll horizontally as needed. */1074+ if (E.cx > E.screencols) {1075+ int diff = E.cx - E.screencols;1076+ E.cx -= diff;1077+ E.coloff += diff;1078+ }1079+ }1080+ }1081+ }1082+}1083+1084+/* ========================= Editor events handling ======================== */1085+1086+/* Handle cursor position change because arrow keys were pressed. */1087+void editorMoveCursor(int key) {1088+ int filerow = E.rowoff+E.cy;1089+ int filecol = E.coloff+E.cx;1090+ int rowlen;1091+ erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow];1092+1093+ switch(key) {1094+ case ARROW_LEFT:1095+ if (E.cx == 0) {1096+ if (E.coloff) {1097+ E.coloff--;1098+ } else {1099+ if (filerow > 0) {1100+ E.cy--;1101+ E.cx = E.row[filerow-1].size;1102+ if (E.cx > E.screencols-1) {1103+ E.coloff = E.cx-E.screencols+1;1104+ E.cx = E.screencols-1;1105+ }1106+ }1107+ }1108+ } else {1109+ E.cx -= 1;1110+ }1111+ break;1112+ case ARROW_RIGHT:1113+ if (row && filecol < row->size) {1114+ if (E.cx == E.screencols-1) {1115+ E.coloff++;1116+ } else {1117+ E.cx += 1;1118+ }1119+ } else if (row && filecol == row->size) {1120+ E.cx = 0;1121+ E.coloff = 0;1122+ if (E.cy == E.screenrows-1) {1123+ E.rowoff++;1124+ } else {1125+ E.cy += 1;1126+ }1127+ }1128+ break;1129+ case ARROW_UP:1130+ if (E.cy == 0) {1131+ if (E.rowoff) E.rowoff--;1132+ } else {1133+ E.cy -= 1;1134+ }1135+ break;1136+ case ARROW_DOWN:1137+ if (filerow < E.numrows) {1138+ if (E.cy == E.screenrows-1) {1139+ E.rowoff++;1140+ } else {1141+ E.cy += 1;1142+ }1143+ }1144+ break;1145+ }1146+ /* Fix cx if the current line has not enough chars. */1147+ filerow = E.rowoff+E.cy;1148+ filecol = E.coloff+E.cx;1149+ row = (filerow >= E.numrows) ? NULL : &E.row[filerow];1150+ rowlen = row ? row->size : 0;1151+ if (filecol > rowlen) {1152+ E.cx -= filecol-rowlen;1153+ if (E.cx < 0) {1154+ E.coloff += E.cx;1155+ E.cx = 0;1156+ }1157+ }1158+}1159+1160+/* Process events arriving from the standard input, which is, the user1161+ * is typing stuff on the terminal. */1162+#define KILO_QUIT_TIMES 31163+void editorProcessKeypress(int fd) {1164+ /* When the file is modified, requires Ctrl-q to be pressed N times1165+ * before actually quitting. */1166+ static int quit_times = KILO_QUIT_TIMES;1167+1168+ int c = editorReadKey(fd);1169+ switch(c) {1170+ case ENTER: /* Enter */1171+ editorInsertNewline();1172+ break;1173+ case CTRL_C: /* Ctrl-c */1174+ /* We ignore ctrl-c, it can't be so simple to lose the changes1175+ * to the edited file. */1176+ break;1177+ case CTRL_Q: /* Ctrl-q */1178+ /* Quit if the file was already saved. */1179+ if (E.dirty && quit_times) {1180+ editorSetStatusMessage("WARNING!!! File has unsaved changes. "1181+ "Press Ctrl-Q %d more times to quit.", quit_times);1182+ quit_times--;1183+ return;1184+ }1185+ exit(0);1186+ break;1187+ case CTRL_S: /* Ctrl-s */1188+ editorSave();1189+ break;1190+ case CTRL_F:1191+ editorFind(fd);1192+ break;1193+ case BACKSPACE: /* Backspace */1194+ case CTRL_H: /* Ctrl-h */1195+ case DEL_KEY:1196+ editorDelChar();1197+ break;1198+ case PAGE_UP:1199+ case PAGE_DOWN:1200+ if (c == PAGE_UP && E.cy != 0)1201+ E.cy = 0;1202+ else if (c == PAGE_DOWN && E.cy != E.screenrows-1)1203+ E.cy = E.screenrows-1;1204+ {1205+ int times = E.screenrows;1206+ while(times--)1207+ editorMoveCursor(c == PAGE_UP ? ARROW_UP:1208+ ARROW_DOWN);1209+ }1210+ break;1211+1212+ case ARROW_UP:1213+ case ARROW_DOWN:1214+ case ARROW_LEFT:1215+ case ARROW_RIGHT:1216+ editorMoveCursor(c);1217+ break;1218+ case CTRL_L: /* ctrl+l, clear screen */1219+ /* Just refresht the line as side effect. */1220+ break;1221+ case ESC:1222+ /* Nothing to do for ESC in this mode. */1223+ break;1224+ default:1225+ editorInsertChar(c);1226+ break;1227+ }1228+1229+ quit_times = KILO_QUIT_TIMES; /* Reset it to the original value. */1230+}1231+1232+int editorFileWasModified(void) {1233+ return E.dirty;1234+}1235+1236+void initEditor(void) {1237+ E.cx = 0;1238+ E.cy = 0;1239+ E.rowoff = 0;1240+ E.coloff = 0;1241+ E.numrows = 0;1242+ E.row = NULL;1243+ E.dirty = 0;1244+ E.filename = NULL;1245+ E.syntax = NULL;1246+ if (getWindowSize(STDIN_FILENO,STDOUT_FILENO,1247+ &E.screenrows,&E.screencols) == -1)1248+ {1249+ perror("Unable to query the screen for size (columns / rows)");1250+ exit(1);1251+ }1252+ E.screenrows -= 2; /* Get room for status bar. */1253+}1254+1255+int main(int argc, char **argv) {1256+ if (argc != 2) {1257+ fprintf(stderr,"Usage: kilo <filename>\n");1258+ exit(1);1259+ }1260+1261+ initEditor();1262+ editorSelectSyntaxHighlight(argv[1]);1263+ editorOpen(argv[1]);1264+ enableRawMode(STDIN_FILENO);1265+ editorSetStatusMessage(1266+ "HELP: Ctrl-S = save | Ctrl-Q = quit | Ctrl-F = find");1267+ while(1) {1268+ editorRefreshScreen();1269+ editorProcessKeypress(STDIN_FILENO);1270+ }1271+ return 0;1272+}added:LICENSE+24 added
1+Copyright (c) 2016, Salvatore Sanfilippo <antirez at gmail dot com>2+3+All rights reserved.4+5+Redistribution and use in source and binary forms, with or without6+modification, are permitted provided that the following conditions are met:7+8+* Redistributions of source code must retain the above copyright notice,9+ this list of conditions and the following disclaimer.10+11+* Redistributions in binary form must reproduce the above copyright notice,12+ this list of conditions and the following disclaimer in the documentation13+ and/or other materials provided with the distribution.14+15+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND16+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED17+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE18+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR19+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES20+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;21+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON22+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT23+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS24+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.added:Makefile+7 added
1+all: kilo2+3+kilo: kilo.c4+ $(CC) -o kilo kilo.c -Wall -W -pedantic -std=c995+6+clean:7+ rm kiloadded:README.md+24 added
123456789101112131415161718192021222324Kilo===
Kilo is a small text editor in less than 1K lines of code (counted with cloc).
Usage: kilo <filename>
Keys:
CTRL-S: Save CTRL-Q: Quit CTRL-F: Find string in file (ESC to esc, arrows to navigate)
Kilo does not depend on any library (not even curses). It uses fairly standardVT100 (and similar terminals) escape sequences. The project is in alphastage and was written in just a few hours taking code from my other twoprojects, load81 and linenoise.
People are encouraged to use it as a starting point to write other editorsor command line interfaces that are more advanced than the usual REPLstyle CLI.
Kilo was written by Salvatore Sanfilippo aka antirez and is releasedunder the BSD 2 clause license.added:TODO+10 added
1+IMPORTANT2+===3+4+* Testing and stability to reach "usable" level.5+6+MAYBE7+===8+9+* Send alternate screen sequences if TERM=xterm: "\033[?1049h" and "\033[?1049l"10+* Improve internals to be more understandable.