linenoise.c 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  1. /* linenoise.c -- guerrilla line editing library against the idea that a
  2. * line editing lib needs to be 20,000 lines of C code.
  3. *
  4. * You can find the latest source code at:
  5. *
  6. * http://github.com/antirez/linenoise
  7. *
  8. * Does a number of crazy assumptions that happen to be true in 99.9999% of
  9. * the 2010 UNIX computers around.
  10. *
  11. * ------------------------------------------------------------------------
  12. *
  13. * Copyright (c) 2010-2013, Salvatore Sanfilippo <antirez at gmail dot com>
  14. * Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
  15. *
  16. * All rights reserved.
  17. *
  18. * Redistribution and use in source and binary forms, with or without
  19. * modification, are permitted provided that the following conditions are
  20. * met:
  21. *
  22. * * Redistributions of source code must retain the above copyright
  23. * notice, this list of conditions and the following disclaimer.
  24. *
  25. * * Redistributions in binary form must reproduce the above copyright
  26. * notice, this list of conditions and the following disclaimer in the
  27. * documentation and/or other materials provided with the distribution.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  30. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  31. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  32. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  33. * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  34. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  35. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  36. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  37. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  38. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  39. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  40. *
  41. * ------------------------------------------------------------------------
  42. *
  43. * References:
  44. * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
  45. * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
  46. *
  47. * Todo list:
  48. * - Filter bogus Ctrl+<char> combinations.
  49. * - Win32 support
  50. *
  51. * Bloat:
  52. * - History search like Ctrl+r in readline?
  53. *
  54. * List of escape sequences used by this program, we do everything just
  55. * with three sequences. In order to be so cheap we may have some
  56. * flickering effect with some slow terminal, but the lesser sequences
  57. * the more compatible.
  58. *
  59. * EL (Erase Line)
  60. * Sequence: ESC [ n K
  61. * Effect: if n is 0 or missing, clear from cursor to end of line
  62. * Effect: if n is 1, clear from beginning of line to cursor
  63. * Effect: if n is 2, clear entire line
  64. *
  65. * CUF (CUrsor Forward)
  66. * Sequence: ESC [ n C
  67. * Effect: moves cursor forward n chars
  68. *
  69. * CUB (CUrsor Backward)
  70. * Sequence: ESC [ n D
  71. * Effect: moves cursor backward n chars
  72. *
  73. * The following is used to get the terminal width if getting
  74. * the width with the TIOCGWINSZ ioctl fails
  75. *
  76. * DSR (Device Status Report)
  77. * Sequence: ESC [ 6 n
  78. * Effect: reports the current cusor position as ESC [ n ; m R
  79. * where n is the row and m is the column
  80. *
  81. * When multi line mode is enabled, we also use an additional escape
  82. * sequence. However multi line editing is disabled by default.
  83. *
  84. * CUU (Cursor Up)
  85. * Sequence: ESC [ n A
  86. * Effect: moves cursor up of n chars.
  87. *
  88. * CUD (Cursor Down)
  89. * Sequence: ESC [ n B
  90. * Effect: moves cursor down of n chars.
  91. *
  92. * When linenoiseClearScreen() is called, two additional escape sequences
  93. * are used in order to clear the screen and position the cursor at home
  94. * position.
  95. *
  96. * CUP (Cursor position)
  97. * Sequence: ESC [ H
  98. * Effect: moves the cursor to upper left corner
  99. *
  100. * ED (Erase display)
  101. * Sequence: ESC [ 2 J
  102. * Effect: clear the whole screen
  103. *
  104. */
  105. #include <termios.h>
  106. #include <unistd.h>
  107. #include <stdlib.h>
  108. #include <stdio.h>
  109. #include <errno.h>
  110. #include <string.h>
  111. #include <stdlib.h>
  112. #include <ctype.h>
  113. #include <sys/types.h>
  114. #include <sys/ioctl.h>
  115. #include <unistd.h>
  116. #include "linenoise.h"
  117. #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
  118. #define LINENOISE_MAX_LINE 4096
  119. static char *unsupported_term[] = {"dumb","cons25","emacs",NULL};
  120. static linenoiseCompletionCallback *completionCallback = NULL;
  121. static struct termios orig_termios; /* In order to restore at exit.*/
  122. static int rawmode = 0; /* For atexit() function to check if restore is needed*/
  123. static int mlmode = 0; /* Multi line mode. Default is single line. */
  124. static int atexit_registered = 0; /* Register atexit just 1 time. */
  125. static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
  126. static int history_len = 0;
  127. static char **history = NULL;
  128. /* The linenoiseState structure represents the state during line editing.
  129. * We pass this state to functions implementing specific editing
  130. * functionalities. */
  131. struct linenoiseState {
  132. int ifd; /* Terminal stdin file descriptor. */
  133. int ofd; /* Terminal stdout file descriptor. */
  134. char *buf; /* Edited line buffer. */
  135. size_t buflen; /* Edited line buffer size. */
  136. const char *prompt; /* Prompt to display. */
  137. size_t plen; /* Prompt length. */
  138. size_t pos; /* Current cursor position. */
  139. size_t oldpos; /* Previous refresh cursor position. */
  140. size_t len; /* Current edited line length. */
  141. size_t cols; /* Number of columns in terminal. */
  142. size_t maxrows; /* Maximum num of rows used so far (multiline mode) */
  143. int history_index; /* The history index we are currently editing. */
  144. };
  145. enum KEY_ACTION{
  146. KEY_NULL = 0, /* NULL */
  147. CTRL_A = 1, /* Ctrl+a */
  148. CTRL_B = 2, /* Ctrl-b */
  149. CTRL_C = 3, /* Ctrl-c */
  150. CTRL_D = 4, /* Ctrl-d */
  151. CTRL_E = 5, /* Ctrl-e */
  152. CTRL_F = 6, /* Ctrl-f */
  153. CTRL_H = 8, /* Ctrl-h */
  154. TAB = 9, /* Tab */
  155. CTRL_K = 11, /* Ctrl+k */
  156. CTRL_L = 12, /* Ctrl+l */
  157. ENTER = 13, /* Enter */
  158. CTRL_N = 14, /* Ctrl-n */
  159. CTRL_P = 16, /* Ctrl-p */
  160. CTRL_T = 20, /* Ctrl-t */
  161. CTRL_U = 21, /* Ctrl+u */
  162. CTRL_W = 23, /* Ctrl+w */
  163. ESC = 27, /* Escape */
  164. BACKSPACE = 127 /* Backspace */
  165. };
  166. static void linenoiseAtExit(void);
  167. int linenoiseHistoryAdd(const char *line);
  168. static void refreshLine(struct linenoiseState *l);
  169. /* Debugging macro. */
  170. #if 0
  171. FILE *lndebug_fp = NULL;
  172. #define lndebug(...) \
  173. do { \
  174. if (lndebug_fp == NULL) { \
  175. lndebug_fp = fopen("/tmp/lndebug.txt","a"); \
  176. fprintf(lndebug_fp, \
  177. "[%d %d %d] p: %d, rows: %d, rpos: %d, max: %d, oldmax: %d\n", \
  178. (int)l->len,(int)l->pos,(int)l->oldpos,plen,rows,rpos, \
  179. (int)l->maxrows,old_rows); \
  180. } \
  181. fprintf(lndebug_fp, ", " __VA_ARGS__); \
  182. fflush(lndebug_fp); \
  183. } while (0)
  184. #else
  185. #define lndebug(fmt, ...)
  186. #endif
  187. /* ======================= Low level terminal handling ====================== */
  188. /* Set if to use or not the multi line mode. */
  189. void linenoiseSetMultiLine(int ml) {
  190. mlmode = ml;
  191. }
  192. /* Return true if the terminal name is in the list of terminals we know are
  193. * not able to understand basic escape sequences. */
  194. static int isUnsupportedTerm(void) {
  195. char *term = getenv("TERM");
  196. int j;
  197. if (term == NULL) return 0;
  198. for (j = 0; unsupported_term[j]; j++)
  199. if (!strcasecmp(term,unsupported_term[j])) return 1;
  200. return 0;
  201. }
  202. /* Raw mode: 1960 magic shit. */
  203. static int enableRawMode(int fd) {
  204. struct termios raw;
  205. if (!isatty(STDIN_FILENO)) goto fatal;
  206. if (!atexit_registered) {
  207. atexit(linenoiseAtExit);
  208. atexit_registered = 1;
  209. }
  210. if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
  211. raw = orig_termios; /* modify the original mode */
  212. /* input modes: no break, no CR to NL, no parity check, no strip char,
  213. * no start/stop output control. */
  214. raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
  215. /* output modes - disable post processing */
  216. raw.c_oflag &= ~(OPOST);
  217. /* control modes - set 8 bit chars */
  218. raw.c_cflag |= (CS8);
  219. /* local modes - choing off, canonical off, no extended functions,
  220. * no signal chars (^Z,^C) */
  221. raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
  222. /* control chars - set return condition: min number of bytes and timer.
  223. * We want read to return every single byte, without timeout. */
  224. raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
  225. /* put terminal in raw mode after flushing */
  226. if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
  227. rawmode = 1;
  228. return 0;
  229. fatal:
  230. errno = ENOTTY;
  231. return -1;
  232. }
  233. static void disableRawMode(int fd) {
  234. /* Don't even check the return value as it's too late. */
  235. if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1)
  236. rawmode = 0;
  237. }
  238. /* Use the ESC [6n escape sequence to query the horizontal cursor position
  239. * and return it. On error -1 is returned, on success the position of the
  240. * cursor. */
  241. static int getCursorPosition(int ifd, int ofd) {
  242. char buf[32];
  243. int cols, rows;
  244. unsigned int i = 0;
  245. /* Report cursor location */
  246. if (write(ofd, "\x1b[6n", 4) != 4) return -1;
  247. /* Read the response: ESC [ rows ; cols R */
  248. while (i < sizeof(buf)-1) {
  249. if (read(ifd,buf+i,1) != 1) break;
  250. if (buf[i] == 'R') break;
  251. i++;
  252. }
  253. buf[i] = '\0';
  254. /* Parse it. */
  255. if (buf[0] != ESC || buf[1] != '[') return -1;
  256. if (sscanf(buf+2,"%d;%d",&rows,&cols) != 2) return -1;
  257. return cols;
  258. }
  259. /* Try to get the number of columns in the current terminal, or assume 80
  260. * if it fails. */
  261. static int getColumns(int ifd, int ofd) {
  262. struct winsize ws;
  263. if (ioctl(1, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
  264. /* ioctl() failed. Try to query the terminal itself. */
  265. int start, cols;
  266. /* Get the initial position so we can restore it later. */
  267. start = getCursorPosition(ifd,ofd);
  268. if (start == -1) goto failed;
  269. /* Go to right margin and get position. */
  270. if (write(ofd,"\x1b[999C",6) != 6) goto failed;
  271. cols = getCursorPosition(ifd,ofd);
  272. if (cols == -1) goto failed;
  273. /* Restore position. */
  274. if (cols > start) {
  275. char seq[32];
  276. snprintf(seq,32,"\x1b[%dD",cols-start);
  277. if (write(ofd,seq,strlen(seq)) == -1) {
  278. /* Can't recover... */
  279. }
  280. }
  281. return cols;
  282. } else {
  283. return ws.ws_col;
  284. }
  285. failed:
  286. return 80;
  287. }
  288. /* Clear the screen. Used to handle ctrl+l */
  289. void linenoiseClearScreen(void) {
  290. if (write(STDOUT_FILENO,"\x1b[H\x1b[2J",7) <= 0) {
  291. /* nothing to do, just to avoid warning. */
  292. }
  293. }
  294. /* Beep, used for completion when there is nothing to complete or when all
  295. * the choices were already shown. */
  296. static void linenoiseBeep(void) {
  297. fprintf(stderr, "\x7");
  298. fflush(stderr);
  299. }
  300. /* ============================== Completion ================================ */
  301. /* Free a list of completion option populated by linenoiseAddCompletion(). */
  302. static void freeCompletions(linenoiseCompletions *lc) {
  303. size_t i;
  304. for (i = 0; i < lc->len; i++)
  305. free(lc->cvec[i]);
  306. if (lc->cvec != NULL)
  307. free(lc->cvec);
  308. }
  309. /* This is an helper function for linenoiseEdit() and is called when the
  310. * user types the <tab> key in order to complete the string currently in the
  311. * input.
  312. *
  313. * The state of the editing is encapsulated into the pointed linenoiseState
  314. * structure as described in the structure definition. */
  315. static int completeLine(struct linenoiseState *ls) {
  316. linenoiseCompletions lc = { 0, NULL };
  317. int nread, nwritten;
  318. char c = 0;
  319. completionCallback(ls->buf,&lc);
  320. if (lc.len == 0) {
  321. linenoiseBeep();
  322. } else {
  323. size_t stop = 0, i = 0;
  324. while(!stop) {
  325. /* Show completion or original buffer */
  326. if (i < lc.len) {
  327. struct linenoiseState saved = *ls;
  328. ls->len = ls->pos = strlen(lc.cvec[i]);
  329. ls->buf = lc.cvec[i];
  330. refreshLine(ls);
  331. ls->len = saved.len;
  332. ls->pos = saved.pos;
  333. ls->buf = saved.buf;
  334. } else {
  335. refreshLine(ls);
  336. }
  337. nread = read(ls->ifd,&c,1);
  338. if (nread <= 0) {
  339. freeCompletions(&lc);
  340. return -1;
  341. }
  342. switch(c) {
  343. case 9: /* tab */
  344. i = (i+1) % (lc.len+1);
  345. if (i == lc.len) linenoiseBeep();
  346. break;
  347. case 27: /* escape */
  348. /* Re-show original buffer */
  349. if (i < lc.len) refreshLine(ls);
  350. stop = 1;
  351. break;
  352. default:
  353. /* Update buffer and return */
  354. if (i < lc.len) {
  355. nwritten = snprintf(ls->buf,ls->buflen,"%s",lc.cvec[i]);
  356. ls->len = ls->pos = nwritten;
  357. }
  358. stop = 1;
  359. break;
  360. }
  361. }
  362. }
  363. freeCompletions(&lc);
  364. return c; /* Return last read character */
  365. }
  366. /* Register a callback function to be called for tab-completion. */
  367. void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
  368. completionCallback = fn;
  369. }
  370. /* This function is used by the callback function registered by the user
  371. * in order to add completion options given the input string when the
  372. * user typed <tab>. See the example.c source code for a very easy to
  373. * understand example. */
  374. void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
  375. size_t len = strlen(str);
  376. char *copy, **cvec;
  377. copy = malloc(len+1);
  378. if (copy == NULL) return;
  379. memcpy(copy,str,len+1);
  380. cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
  381. if (cvec == NULL) {
  382. free(copy);
  383. return;
  384. }
  385. lc->cvec = cvec;
  386. lc->cvec[lc->len++] = copy;
  387. }
  388. /* =========================== Line editing ================================= */
  389. /* We define a very simple "append buffer" structure, that is an heap
  390. * allocated string where we can append to. This is useful in order to
  391. * write all the escape sequences in a buffer and flush them to the standard
  392. * output in a single call, to avoid flickering effects. */
  393. struct abuf {
  394. char *b;
  395. int len;
  396. };
  397. static void abInit(struct abuf *ab) {
  398. ab->b = NULL;
  399. ab->len = 0;
  400. }
  401. static void abAppend(struct abuf *ab, const char *s, int len) {
  402. char *new = realloc(ab->b,ab->len+len);
  403. if (new == NULL) return;
  404. memcpy(new+ab->len,s,len);
  405. ab->b = new;
  406. ab->len += len;
  407. }
  408. static void abFree(struct abuf *ab) {
  409. free(ab->b);
  410. }
  411. /* Single line low level line refresh.
  412. *
  413. * Rewrite the currently edited line accordingly to the buffer content,
  414. * cursor position, and number of columns of the terminal. */
  415. static void refreshSingleLine(struct linenoiseState *l) {
  416. char seq[64];
  417. size_t plen = strlen(l->prompt);
  418. int fd = l->ofd;
  419. char *buf = l->buf;
  420. size_t len = l->len;
  421. size_t pos = l->pos;
  422. struct abuf ab;
  423. while((plen+pos) >= l->cols) {
  424. buf++;
  425. len--;
  426. pos--;
  427. }
  428. while (plen+len > l->cols) {
  429. len--;
  430. }
  431. abInit(&ab);
  432. /* Cursor to left edge */
  433. snprintf(seq,64,"\r");
  434. abAppend(&ab,seq,strlen(seq));
  435. /* Write the prompt and the current buffer content */
  436. abAppend(&ab,l->prompt,strlen(l->prompt));
  437. abAppend(&ab,buf,len);
  438. /* Erase to right */
  439. snprintf(seq,64,"\x1b[0K");
  440. abAppend(&ab,seq,strlen(seq));
  441. /* Move cursor to original position. */
  442. snprintf(seq,64,"\r\x1b[%dC", (int)(pos+plen));
  443. abAppend(&ab,seq,strlen(seq));
  444. if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */
  445. abFree(&ab);
  446. }
  447. /* Multi line low level line refresh.
  448. *
  449. * Rewrite the currently edited line accordingly to the buffer content,
  450. * cursor position, and number of columns of the terminal. */
  451. static void refreshMultiLine(struct linenoiseState *l) {
  452. char seq[64];
  453. int plen = strlen(l->prompt);
  454. int rows = (plen+l->len+l->cols-1)/l->cols; /* rows used by current buf. */
  455. int rpos = (plen+l->oldpos+l->cols)/l->cols; /* cursor relative row. */
  456. int rpos2; /* rpos after refresh. */
  457. int col; /* colum position, zero-based. */
  458. int old_rows = l->maxrows;
  459. int fd = l->ofd, j;
  460. struct abuf ab;
  461. /* Update maxrows if needed. */
  462. if (rows > (int)l->maxrows) l->maxrows = rows;
  463. /* First step: clear all the lines used before. To do so start by
  464. * going to the last row. */
  465. abInit(&ab);
  466. if (old_rows-rpos > 0) {
  467. lndebug("go down %d", old_rows-rpos);
  468. snprintf(seq,64,"\x1b[%dB", old_rows-rpos);
  469. abAppend(&ab,seq,strlen(seq));
  470. }
  471. /* Now for every row clear it, go up. */
  472. for (j = 0; j < old_rows-1; j++) {
  473. lndebug("clear+up");
  474. snprintf(seq,64,"\r\x1b[0K\x1b[1A");
  475. abAppend(&ab,seq,strlen(seq));
  476. }
  477. /* Clean the top line. */
  478. lndebug("clear");
  479. snprintf(seq,64,"\r\x1b[0K");
  480. abAppend(&ab,seq,strlen(seq));
  481. /* Write the prompt and the current buffer content */
  482. abAppend(&ab,l->prompt,strlen(l->prompt));
  483. abAppend(&ab,l->buf,l->len);
  484. /* If we are at the very end of the screen with our prompt, we need to
  485. * emit a newline and move the prompt to the first column. */
  486. if (l->pos &&
  487. l->pos == l->len &&
  488. (l->pos+plen) % l->cols == 0)
  489. {
  490. lndebug("<newline>");
  491. abAppend(&ab,"\n",1);
  492. snprintf(seq,64,"\r");
  493. abAppend(&ab,seq,strlen(seq));
  494. rows++;
  495. if (rows > (int)l->maxrows) l->maxrows = rows;
  496. }
  497. /* Move cursor to right position. */
  498. rpos2 = (plen+l->pos+l->cols)/l->cols; /* current cursor relative row. */
  499. lndebug("rpos2 %d", rpos2);
  500. /* Go up till we reach the expected positon. */
  501. if (rows-rpos2 > 0) {
  502. lndebug("go-up %d", rows-rpos2);
  503. snprintf(seq,64,"\x1b[%dA", rows-rpos2);
  504. abAppend(&ab,seq,strlen(seq));
  505. }
  506. /* Set column. */
  507. col = (plen+(int)l->pos) % (int)l->cols;
  508. lndebug("set col %d", 1+col);
  509. if (col)
  510. snprintf(seq,64,"\r\x1b[%dC", col);
  511. else
  512. snprintf(seq,64,"\r");
  513. abAppend(&ab,seq,strlen(seq));
  514. lndebug("\n");
  515. l->oldpos = l->pos;
  516. if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */
  517. abFree(&ab);
  518. }
  519. /* Calls the two low level functions refreshSingleLine() or
  520. * refreshMultiLine() according to the selected mode. */
  521. static void refreshLine(struct linenoiseState *l) {
  522. if (mlmode)
  523. refreshMultiLine(l);
  524. else
  525. refreshSingleLine(l);
  526. }
  527. /* Insert the character 'c' at cursor current position.
  528. *
  529. * On error writing to the terminal -1 is returned, otherwise 0. */
  530. int linenoiseEditInsert(struct linenoiseState *l, char c) {
  531. if (l->len < l->buflen) {
  532. if (l->len == l->pos) {
  533. l->buf[l->pos] = c;
  534. l->pos++;
  535. l->len++;
  536. l->buf[l->len] = '\0';
  537. if ((!mlmode && l->plen+l->len < l->cols) /* || mlmode */) {
  538. /* Avoid a full update of the line in the
  539. * trivial case. */
  540. if (write(l->ofd,&c,1) == -1) return -1;
  541. } else {
  542. refreshLine(l);
  543. }
  544. } else {
  545. memmove(l->buf+l->pos+1,l->buf+l->pos,l->len-l->pos);
  546. l->buf[l->pos] = c;
  547. l->len++;
  548. l->pos++;
  549. l->buf[l->len] = '\0';
  550. refreshLine(l);
  551. }
  552. }
  553. return 0;
  554. }
  555. /* Move cursor on the left. */
  556. void linenoiseEditMoveLeft(struct linenoiseState *l) {
  557. if (l->pos > 0) {
  558. l->pos--;
  559. refreshLine(l);
  560. }
  561. }
  562. /* Move cursor on the right. */
  563. void linenoiseEditMoveRight(struct linenoiseState *l) {
  564. if (l->pos != l->len) {
  565. l->pos++;
  566. refreshLine(l);
  567. }
  568. }
  569. /* Move cursor to the start of the line. */
  570. void linenoiseEditMoveHome(struct linenoiseState *l) {
  571. if (l->pos != 0) {
  572. l->pos = 0;
  573. refreshLine(l);
  574. }
  575. }
  576. /* Move cursor to the end of the line. */
  577. void linenoiseEditMoveEnd(struct linenoiseState *l) {
  578. if (l->pos != l->len) {
  579. l->pos = l->len;
  580. refreshLine(l);
  581. }
  582. }
  583. /* Substitute the currently edited line with the next or previous history
  584. * entry as specified by 'dir'. */
  585. #define LINENOISE_HISTORY_NEXT 0
  586. #define LINENOISE_HISTORY_PREV 1
  587. void linenoiseEditHistoryNext(struct linenoiseState *l, int dir) {
  588. if (history_len > 1) {
  589. /* Update the current history entry before to
  590. * overwrite it with the next one. */
  591. free(history[history_len - 1 - l->history_index]);
  592. history[history_len - 1 - l->history_index] = strdup(l->buf);
  593. /* Show the new entry */
  594. l->history_index += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1;
  595. if (l->history_index < 0) {
  596. l->history_index = 0;
  597. return;
  598. } else if (l->history_index >= history_len) {
  599. l->history_index = history_len-1;
  600. return;
  601. }
  602. strncpy(l->buf,history[history_len - 1 - l->history_index],l->buflen);
  603. l->buf[l->buflen-1] = '\0';
  604. l->len = l->pos = strlen(l->buf);
  605. refreshLine(l);
  606. }
  607. }
  608. /* Delete the character at the right of the cursor without altering the cursor
  609. * position. Basically this is what happens with the "Delete" keyboard key. */
  610. void linenoiseEditDelete(struct linenoiseState *l) {
  611. if (l->len > 0 && l->pos < l->len) {
  612. memmove(l->buf+l->pos,l->buf+l->pos+1,l->len-l->pos-1);
  613. l->len--;
  614. l->buf[l->len] = '\0';
  615. refreshLine(l);
  616. }
  617. }
  618. /* Backspace implementation. */
  619. void linenoiseEditBackspace(struct linenoiseState *l) {
  620. if (l->pos > 0 && l->len > 0) {
  621. memmove(l->buf+l->pos-1,l->buf+l->pos,l->len-l->pos);
  622. l->pos--;
  623. l->len--;
  624. l->buf[l->len] = '\0';
  625. refreshLine(l);
  626. }
  627. }
  628. /* Delete the previosu word, maintaining the cursor at the start of the
  629. * current word. */
  630. void linenoiseEditDeletePrevWord(struct linenoiseState *l) {
  631. size_t old_pos = l->pos;
  632. size_t diff;
  633. while (l->pos > 0 && l->buf[l->pos-1] == ' ')
  634. l->pos--;
  635. while (l->pos > 0 && l->buf[l->pos-1] != ' ')
  636. l->pos--;
  637. diff = old_pos - l->pos;
  638. memmove(l->buf+l->pos,l->buf+old_pos,l->len-old_pos+1);
  639. l->len -= diff;
  640. refreshLine(l);
  641. }
  642. /* This function is the core of the line editing capability of linenoise.
  643. * It expects 'fd' to be already in "raw mode" so that every key pressed
  644. * will be returned ASAP to read().
  645. *
  646. * The resulting string is put into 'buf' when the user type enter, or
  647. * when ctrl+d is typed.
  648. *
  649. * The function returns the length of the current buffer. */
  650. static int linenoiseEdit(int stdin_fd, int stdout_fd, char *buf, size_t buflen, const char *prompt)
  651. {
  652. struct linenoiseState l;
  653. /* Populate the linenoise state that we pass to functions implementing
  654. * specific editing functionalities. */
  655. l.ifd = stdin_fd;
  656. l.ofd = stdout_fd;
  657. l.buf = buf;
  658. l.buflen = buflen;
  659. l.prompt = prompt;
  660. l.plen = strlen(prompt);
  661. l.oldpos = l.pos = 0;
  662. l.len = 0;
  663. l.cols = getColumns(stdin_fd, stdout_fd);
  664. l.maxrows = 0;
  665. l.history_index = 0;
  666. /* Buffer starts empty. */
  667. l.buf[0] = '\0';
  668. l.buflen--; /* Make sure there is always space for the nulterm */
  669. /* The latest history entry is always our current buffer, that
  670. * initially is just an empty string. */
  671. linenoiseHistoryAdd("");
  672. if (write(l.ofd,prompt,l.plen) == -1) return -1;
  673. while(1) {
  674. char c;
  675. int nread;
  676. char seq[3];
  677. nread = read(l.ifd,&c,1);
  678. if (nread <= 0) return l.len;
  679. /* Only autocomplete when the callback is set. It returns < 0 when
  680. * there was an error reading from fd. Otherwise it will return the
  681. * character that should be handled next. */
  682. if (c == 9 && completionCallback != NULL) {
  683. c = completeLine(&l);
  684. /* Return on errors */
  685. if (c < 0) return l.len;
  686. /* Read next character when 0 */
  687. if (c == 0) continue;
  688. }
  689. switch(c) {
  690. case ENTER: /* enter */
  691. history_len--;
  692. free(history[history_len]);
  693. if (mlmode) linenoiseEditMoveEnd(&l);
  694. return (int)l.len;
  695. case CTRL_C: /* ctrl-c */
  696. errno = EAGAIN;
  697. return -1;
  698. case BACKSPACE: /* backspace */
  699. case 8: /* ctrl-h */
  700. linenoiseEditBackspace(&l);
  701. break;
  702. case CTRL_D: /* ctrl-d, remove char at right of cursor, or if the
  703. line is empty, act as end-of-file. */
  704. if (l.len > 0) {
  705. linenoiseEditDelete(&l);
  706. } else {
  707. history_len--;
  708. free(history[history_len]);
  709. return -1;
  710. }
  711. break;
  712. case CTRL_T: /* ctrl-t, swaps current character with previous. */
  713. if (l.pos > 0 && l.pos < l.len) {
  714. int aux = buf[l.pos-1];
  715. buf[l.pos-1] = buf[l.pos];
  716. buf[l.pos] = aux;
  717. if (l.pos != l.len-1) l.pos++;
  718. refreshLine(&l);
  719. }
  720. break;
  721. case CTRL_B: /* ctrl-b */
  722. linenoiseEditMoveLeft(&l);
  723. break;
  724. case CTRL_F: /* ctrl-f */
  725. linenoiseEditMoveRight(&l);
  726. break;
  727. case CTRL_P: /* ctrl-p */
  728. linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
  729. break;
  730. case CTRL_N: /* ctrl-n */
  731. linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
  732. break;
  733. case ESC: /* escape sequence */
  734. /* Read the next two bytes representing the escape sequence.
  735. * Use two calls to handle slow terminals returning the two
  736. * chars at different times. */
  737. if (read(l.ifd,seq,1) == -1) break;
  738. if (read(l.ifd,seq+1,1) == -1) break;
  739. /* ESC [ sequences. */
  740. if (seq[0] == '[') {
  741. if (seq[1] >= '0' && seq[1] <= '9') {
  742. /* Extended escape, read additional byte. */
  743. if (read(l.ifd,seq+2,1) == -1) break;
  744. if (seq[2] == '~') {
  745. switch(seq[1]) {
  746. case '3': /* Delete key. */
  747. linenoiseEditDelete(&l);
  748. break;
  749. }
  750. }
  751. } else {
  752. switch(seq[1]) {
  753. case 'A': /* Up */
  754. linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
  755. break;
  756. case 'B': /* Down */
  757. linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
  758. break;
  759. case 'C': /* Right */
  760. linenoiseEditMoveRight(&l);
  761. break;
  762. case 'D': /* Left */
  763. linenoiseEditMoveLeft(&l);
  764. break;
  765. case 'H': /* Home */
  766. linenoiseEditMoveHome(&l);
  767. break;
  768. case 'F': /* End*/
  769. linenoiseEditMoveEnd(&l);
  770. break;
  771. }
  772. }
  773. }
  774. /* ESC O sequences. */
  775. else if (seq[0] == 'O') {
  776. switch(seq[1]) {
  777. case 'H': /* Home */
  778. linenoiseEditMoveHome(&l);
  779. break;
  780. case 'F': /* End*/
  781. linenoiseEditMoveEnd(&l);
  782. break;
  783. }
  784. }
  785. break;
  786. default:
  787. if (linenoiseEditInsert(&l,c)) return -1;
  788. break;
  789. case CTRL_U: /* Ctrl+u, delete the whole line. */
  790. buf[0] = '\0';
  791. l.pos = l.len = 0;
  792. refreshLine(&l);
  793. break;
  794. case CTRL_K: /* Ctrl+k, delete from current to end of line. */
  795. buf[l.pos] = '\0';
  796. l.len = l.pos;
  797. refreshLine(&l);
  798. break;
  799. case CTRL_A: /* Ctrl+a, go to the start of the line */
  800. linenoiseEditMoveHome(&l);
  801. break;
  802. case CTRL_E: /* ctrl+e, go to the end of the line */
  803. linenoiseEditMoveEnd(&l);
  804. break;
  805. case CTRL_L: /* ctrl+l, clear screen */
  806. linenoiseClearScreen();
  807. refreshLine(&l);
  808. break;
  809. case CTRL_W: /* ctrl+w, delete previous word */
  810. linenoiseEditDeletePrevWord(&l);
  811. break;
  812. }
  813. }
  814. return l.len;
  815. }
  816. /* This special mode is used by linenoise in order to print scan codes
  817. * on screen for debugging / development purposes. It is implemented
  818. * by the linenoise_example program using the --keycodes option. */
  819. void linenoisePrintKeyCodes(void) {
  820. char quit[4];
  821. printf("Linenoise key codes debugging mode.\n"
  822. "Press keys to see scan codes. Type 'quit' at any time to exit.\n");
  823. if (enableRawMode(STDIN_FILENO) == -1) return;
  824. memset(quit,' ',4);
  825. while(1) {
  826. char c;
  827. int nread;
  828. nread = read(STDIN_FILENO,&c,1);
  829. if (nread <= 0) continue;
  830. memmove(quit,quit+1,sizeof(quit)-1); /* shift string to left. */
  831. quit[sizeof(quit)-1] = c; /* Insert current char on the right. */
  832. if (memcmp(quit,"quit",sizeof(quit)) == 0) break;
  833. printf("'%c' %02x (%d) (type quit to exit)\n",
  834. isprint(c) ? c : '?', (int)c, (int)c);
  835. printf("\r"); /* Go left edge manually, we are in raw mode. */
  836. fflush(stdout);
  837. }
  838. disableRawMode(STDIN_FILENO);
  839. }
  840. /* This function calls the line editing function linenoiseEdit() using
  841. * the STDIN file descriptor set in raw mode. */
  842. static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
  843. int count;
  844. if (buflen == 0) {
  845. errno = EINVAL;
  846. return -1;
  847. }
  848. if (!isatty(STDIN_FILENO)) {
  849. /* Not a tty: read from file / pipe. */
  850. if (fgets(buf, buflen, stdin) == NULL) return -1;
  851. count = strlen(buf);
  852. if (count && buf[count-1] == '\n') {
  853. count--;
  854. buf[count] = '\0';
  855. }
  856. } else {
  857. /* Interactive editing. */
  858. if (enableRawMode(STDIN_FILENO) == -1) return -1;
  859. count = linenoiseEdit(STDIN_FILENO, STDOUT_FILENO, buf, buflen, prompt);
  860. disableRawMode(STDIN_FILENO);
  861. printf("\n");
  862. }
  863. return count;
  864. }
  865. /* The high level function that is the main API of the linenoise library.
  866. * This function checks if the terminal has basic capabilities, just checking
  867. * for a blacklist of stupid terminals, and later either calls the line
  868. * editing function or uses dummy fgets() so that you will be able to type
  869. * something even in the most desperate of the conditions. */
  870. char *linenoise(const char *prompt) {
  871. char buf[LINENOISE_MAX_LINE];
  872. int count;
  873. if (isUnsupportedTerm()) {
  874. size_t len;
  875. printf("%s",prompt);
  876. fflush(stdout);
  877. if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
  878. len = strlen(buf);
  879. while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
  880. len--;
  881. buf[len] = '\0';
  882. }
  883. return strdup(buf);
  884. } else {
  885. count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
  886. if (count == -1) return NULL;
  887. return strdup(buf);
  888. }
  889. }
  890. /* ================================ History ================================= */
  891. /* Free the history, but does not reset it. Only used when we have to
  892. * exit() to avoid memory leaks are reported by valgrind & co. */
  893. static void freeHistory(void) {
  894. if (history) {
  895. int j;
  896. for (j = 0; j < history_len; j++)
  897. free(history[j]);
  898. free(history);
  899. }
  900. }
  901. /* At exit we'll try to fix the terminal to the initial conditions. */
  902. static void linenoiseAtExit(void) {
  903. disableRawMode(STDIN_FILENO);
  904. freeHistory();
  905. }
  906. /* This is the API call to add a new entry in the linenoise history.
  907. * It uses a fixed array of char pointers that are shifted (memmoved)
  908. * when the history max length is reached in order to remove the older
  909. * entry and make room for the new one, so it is not exactly suitable for huge
  910. * histories, but will work well for a few hundred of entries.
  911. *
  912. * Using a circular buffer is smarter, but a bit more complex to handle. */
  913. int linenoiseHistoryAdd(const char *line) {
  914. char *linecopy;
  915. if (history_max_len == 0) return 0;
  916. /* Initialization on first call. */
  917. if (history == NULL) {
  918. history = malloc(sizeof(char*)*history_max_len);
  919. if (history == NULL) return 0;
  920. memset(history,0,(sizeof(char*)*history_max_len));
  921. }
  922. /* Don't add duplicated lines. */
  923. if (history_len && !strcmp(history[history_len-1], line)) return 0;
  924. /* Add an heap allocated copy of the line in the history.
  925. * If we reached the max length, remove the older line. */
  926. linecopy = strdup(line);
  927. if (!linecopy) return 0;
  928. if (history_len == history_max_len) {
  929. free(history[0]);
  930. memmove(history,history+1,sizeof(char*)*(history_max_len-1));
  931. history_len--;
  932. }
  933. history[history_len] = linecopy;
  934. history_len++;
  935. return 1;
  936. }
  937. /* Set the maximum length for the history. This function can be called even
  938. * if there is already some history, the function will make sure to retain
  939. * just the latest 'len' elements if the new history length value is smaller
  940. * than the amount of items already inside the history. */
  941. int linenoiseHistorySetMaxLen(int len) {
  942. char **new;
  943. if (len < 1) return 0;
  944. if (history) {
  945. int tocopy = history_len;
  946. new = malloc(sizeof(char*)*len);
  947. if (new == NULL) return 0;
  948. /* If we can't copy everything, free the elements we'll not use. */
  949. if (len < tocopy) {
  950. int j;
  951. for (j = 0; j < tocopy-len; j++) free(history[j]);
  952. tocopy = len;
  953. }
  954. memset(new,0,sizeof(char*)*len);
  955. memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy);
  956. free(history);
  957. history = new;
  958. }
  959. history_max_len = len;
  960. if (history_len > history_max_len)
  961. history_len = history_max_len;
  962. return 1;
  963. }
  964. /* Save the history in the specified file. On success 0 is returned
  965. * otherwise -1 is returned. */
  966. int linenoiseHistorySave(const char *filename) {
  967. FILE *fp = fopen(filename,"w");
  968. int j;
  969. if (fp == NULL) return -1;
  970. for (j = 0; j < history_len; j++)
  971. fprintf(fp,"%s\n",history[j]);
  972. fclose(fp);
  973. return 0;
  974. }
  975. /* Load the history from the specified file. If the file does not exist
  976. * zero is returned and no operation is performed.
  977. *
  978. * If the file exists and the operation succeeded 0 is returned, otherwise
  979. * on error -1 is returned. */
  980. int linenoiseHistoryLoad(const char *filename) {
  981. FILE *fp = fopen(filename,"r");
  982. char buf[LINENOISE_MAX_LINE];
  983. if (fp == NULL) return -1;
  984. while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
  985. char *p;
  986. p = strchr(buf,'\r');
  987. if (!p) p = strchr(buf,'\n');
  988. if (p) *p = '\0';
  989. linenoiseHistoryAdd(buf);
  990. }
  991. fclose(fp);
  992. return 0;
  993. }