ki.c 43 KB

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