You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

linenoise.c 38KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  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-2016, 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 linenoiseHintsCallback *hintsCallback = NULL;
  122. static linenoiseFreeHintsCallback *freeHintsCallback = NULL;
  123. static struct termios orig_termios; /* In order to restore at exit.*/
  124. static int rawmode = 0; /* For atexit() function to check if restore is needed*/
  125. static int mlmode = 0; /* Multi line mode. Default is single line. */
  126. static int atexit_registered = 0; /* Register atexit just 1 time. */
  127. static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
  128. static int history_len = 0;
  129. static char **history = NULL;
  130. /* The linenoiseState structure represents the state during line editing.
  131. * We pass this state to functions implementing specific editing
  132. * functionalities. */
  133. struct linenoiseState {
  134. int ifd; /* Terminal stdin file descriptor. */
  135. int ofd; /* Terminal stdout file descriptor. */
  136. char *buf; /* Edited line buffer. */
  137. size_t buflen; /* Edited line buffer size. */
  138. const char *prompt; /* Prompt to display. */
  139. size_t plen; /* Prompt length. */
  140. size_t pos; /* Current cursor position. */
  141. size_t oldpos; /* Previous refresh cursor position. */
  142. size_t len; /* Current edited line length. */
  143. size_t cols; /* Number of columns in terminal. */
  144. size_t maxrows; /* Maximum num of rows used so far (multiline mode) */
  145. int history_index; /* The history index we are currently editing. */
  146. };
  147. enum KEY_ACTION{
  148. KEY_NULL = 0, /* NULL */
  149. CTRL_A = 1, /* Ctrl+a */
  150. CTRL_B = 2, /* Ctrl-b */
  151. CTRL_C = 3, /* Ctrl-c */
  152. CTRL_D = 4, /* Ctrl-d */
  153. CTRL_E = 5, /* Ctrl-e */
  154. CTRL_F = 6, /* Ctrl-f */
  155. CTRL_H = 8, /* Ctrl-h */
  156. TAB = 9, /* Tab */
  157. CTRL_K = 11, /* Ctrl+k */
  158. CTRL_L = 12, /* Ctrl+l */
  159. ENTER = 13, /* Enter */
  160. CTRL_N = 14, /* Ctrl-n */
  161. CTRL_P = 16, /* Ctrl-p */
  162. CTRL_T = 20, /* Ctrl-t */
  163. CTRL_U = 21, /* Ctrl+u */
  164. CTRL_W = 23, /* Ctrl+w */
  165. ESC = 27, /* Escape */
  166. BACKSPACE = 127 /* Backspace */
  167. };
  168. static void linenoiseAtExit(void);
  169. int linenoiseHistoryAdd(const char *line);
  170. static void refreshLine(struct linenoiseState *l);
  171. /* Debugging macro. */
  172. #if 0
  173. FILE *lndebug_fp = NULL;
  174. #define lndebug(...) \
  175. do { \
  176. if (lndebug_fp == NULL) { \
  177. lndebug_fp = fopen("/tmp/lndebug.txt","a"); \
  178. fprintf(lndebug_fp, \
  179. "[%d %d %d] p: %d, rows: %d, rpos: %d, max: %d, oldmax: %d\n", \
  180. (int)l->len,(int)l->pos,(int)l->oldpos,plen,rows,rpos, \
  181. (int)l->maxrows,old_rows); \
  182. } \
  183. fprintf(lndebug_fp, ", " __VA_ARGS__); \
  184. fflush(lndebug_fp); \
  185. } while (0)
  186. #else
  187. #define lndebug(...)
  188. #endif
  189. /* ======================= Low level terminal handling ====================== */
  190. /* Set if to use or not the multi line mode. */
  191. void linenoiseSetMultiLine(int ml) {
  192. mlmode = ml;
  193. }
  194. /* Return true if the terminal name is in the list of terminals we know are
  195. * not able to understand basic escape sequences. */
  196. static int isUnsupportedTerm(void) {
  197. char *term = getenv("TERM");
  198. int j;
  199. if (term == NULL) return 0;
  200. for (j = 0; unsupported_term[j]; j++)
  201. if (!strcasecmp(term,unsupported_term[j])) return 1;
  202. return 0;
  203. }
  204. /* Raw mode: 1960 magic shit. */
  205. static int enableRawMode(int fd) {
  206. struct termios raw;
  207. if (!isatty(STDIN_FILENO)) goto fatal;
  208. if (!atexit_registered) {
  209. atexit(linenoiseAtExit);
  210. atexit_registered = 1;
  211. }
  212. if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
  213. raw = orig_termios; /* modify the original mode */
  214. /* input modes: no break, no CR to NL, no parity check, no strip char,
  215. * no start/stop output control. */
  216. raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
  217. /* output modes - disable post processing */
  218. raw.c_oflag &= ~(OPOST);
  219. /* control modes - set 8 bit chars */
  220. raw.c_cflag |= (CS8);
  221. /* local modes - choing off, canonical off, no extended functions,
  222. * no signal chars (^Z,^C) */
  223. raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
  224. /* control chars - set return condition: min number of bytes and timer.
  225. * We want read to return every single byte, without timeout. */
  226. raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
  227. /* put terminal in raw mode after flushing */
  228. if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
  229. rawmode = 1;
  230. return 0;
  231. fatal:
  232. errno = ENOTTY;
  233. return -1;
  234. }
  235. static void disableRawMode(int fd) {
  236. /* Don't even check the return value as it's too late. */
  237. if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1)
  238. rawmode = 0;
  239. }
  240. /* Use the ESC [6n escape sequence to query the horizontal cursor position
  241. * and return it. On error -1 is returned, on success the position of the
  242. * cursor. */
  243. static int getCursorPosition(int ifd, int ofd) {
  244. char buf[32];
  245. int cols, rows;
  246. unsigned int i = 0;
  247. /* Report cursor location */
  248. if (write(ofd, "\x1b[6n", 4) != 4) return -1;
  249. /* Read the response: ESC [ rows ; cols R */
  250. while (i < sizeof(buf)-1) {
  251. if (read(ifd,buf+i,1) != 1) break;
  252. if (buf[i] == 'R') break;
  253. i++;
  254. }
  255. buf[i] = '\0';
  256. /* Parse it. */
  257. if (buf[0] != ESC || buf[1] != '[') return -1;
  258. if (sscanf(buf+2,"%d;%d",&rows,&cols) != 2) return -1;
  259. return cols;
  260. }
  261. /* Try to get the number of columns in the current terminal, or assume 80
  262. * if it fails. */
  263. static int getColumns(int ifd, int ofd) {
  264. struct winsize ws;
  265. if (ioctl(1, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
  266. /* ioctl() failed. Try to query the terminal itself. */
  267. int start, cols;
  268. /* Get the initial position so we can restore it later. */
  269. start = getCursorPosition(ifd,ofd);
  270. if (start == -1) goto failed;
  271. /* Go to right margin and get position. */
  272. if (write(ofd,"\x1b[999C",6) != 6) goto failed;
  273. cols = getCursorPosition(ifd,ofd);
  274. if (cols == -1) goto failed;
  275. /* Restore position. */
  276. if (cols > start) {
  277. char seq[32];
  278. snprintf(seq,32,"\x1b[%dD",cols-start);
  279. if (write(ofd,seq,strlen(seq)) == -1) {
  280. /* Can't recover... */
  281. }
  282. }
  283. return cols;
  284. } else {
  285. return ws.ws_col;
  286. }
  287. failed:
  288. return 80;
  289. }
  290. /* Clear the screen. Used to handle ctrl+l */
  291. void linenoiseClearScreen(void) {
  292. if (write(STDOUT_FILENO,"\x1b[H\x1b[2J",7) <= 0) {
  293. /* nothing to do, just to avoid warning. */
  294. }
  295. }
  296. /* Beep, used for completion when there is nothing to complete or when all
  297. * the choices were already shown. */
  298. static void linenoiseBeep(void) {
  299. fprintf(stderr, "\x7");
  300. fflush(stderr);
  301. }
  302. /* ============================== Completion ================================ */
  303. /* Free a list of completion option populated by linenoiseAddCompletion(). */
  304. static void freeCompletions(linenoiseCompletions *lc) {
  305. size_t i;
  306. for (i = 0; i < lc->len; i++)
  307. free(lc->cvec[i]);
  308. if (lc->cvec != NULL)
  309. free(lc->cvec);
  310. }
  311. /* This is an helper function for linenoiseEdit() and is called when the
  312. * user types the <tab> key in order to complete the string currently in the
  313. * input.
  314. *
  315. * The state of the editing is encapsulated into the pointed linenoiseState
  316. * structure as described in the structure definition. */
  317. static int completeLine(struct linenoiseState *ls) {
  318. linenoiseCompletions lc = { 0, NULL };
  319. int nread, nwritten;
  320. char c = 0;
  321. completionCallback(ls->buf,&lc);
  322. if (lc.len == 0) {
  323. linenoiseBeep();
  324. } else {
  325. size_t stop = 0, i = 0;
  326. while(!stop) {
  327. /* Show completion or original buffer */
  328. if (i < lc.len) {
  329. struct linenoiseState saved = *ls;
  330. ls->len = ls->pos = strlen(lc.cvec[i]);
  331. ls->buf = lc.cvec[i];
  332. refreshLine(ls);
  333. ls->len = saved.len;
  334. ls->pos = saved.pos;
  335. ls->buf = saved.buf;
  336. } else {
  337. refreshLine(ls);
  338. }
  339. nread = read(ls->ifd,&c,1);
  340. if (nread <= 0) {
  341. freeCompletions(&lc);
  342. return -1;
  343. }
  344. switch(c) {
  345. case 9: /* tab */
  346. i = (i+1) % (lc.len+1);
  347. if (i == lc.len) linenoiseBeep();
  348. break;
  349. case 27: /* escape */
  350. /* Re-show original buffer */
  351. if (i < lc.len) refreshLine(ls);
  352. stop = 1;
  353. break;
  354. default:
  355. /* Update buffer and return */
  356. if (i < lc.len) {
  357. nwritten = snprintf(ls->buf,ls->buflen,"%s",lc.cvec[i]);
  358. ls->len = ls->pos = nwritten;
  359. }
  360. stop = 1;
  361. break;
  362. }
  363. }
  364. }
  365. freeCompletions(&lc);
  366. return c; /* Return last read character */
  367. }
  368. /* Register a callback function to be called for tab-completion. */
  369. void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
  370. completionCallback = fn;
  371. }
  372. /* Register a hits function to be called to show hits to the user at the
  373. * right of the prompt. */
  374. void linenoiseSetHintsCallback(linenoiseHintsCallback *fn) {
  375. hintsCallback = fn;
  376. }
  377. /* Register a function to free the hints returned by the hints callback
  378. * registered with linenoiseSetHintsCallback(). */
  379. void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *fn) {
  380. freeHintsCallback = fn;
  381. }
  382. /* This function is used by the callback function registered by the user
  383. * in order to add completion options given the input string when the
  384. * user typed <tab>. See the example.c source code for a very easy to
  385. * understand example. */
  386. void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
  387. size_t len = strlen(str);
  388. char *copy, **cvec;
  389. copy = malloc(len+1);
  390. if (copy == NULL) return;
  391. memcpy(copy,str,len+1);
  392. cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
  393. if (cvec == NULL) {
  394. free(copy);
  395. return;
  396. }
  397. lc->cvec = cvec;
  398. lc->cvec[lc->len++] = copy;
  399. }
  400. /* =========================== Line editing ================================= */
  401. /* We define a very simple "append buffer" structure, that is an heap
  402. * allocated string where we can append to. This is useful in order to
  403. * write all the escape sequences in a buffer and flush them to the standard
  404. * output in a single call, to avoid flickering effects. */
  405. struct abuf {
  406. char *b;
  407. int len;
  408. };
  409. static void abInit(struct abuf *ab) {
  410. ab->b = NULL;
  411. ab->len = 0;
  412. }
  413. static void abAppend(struct abuf *ab, const char *s, int len) {
  414. char *new = realloc(ab->b,ab->len+len);
  415. if (new == NULL) return;
  416. memcpy(new+ab->len,s,len);
  417. ab->b = new;
  418. ab->len += len;
  419. }
  420. static void abFree(struct abuf *ab) {
  421. free(ab->b);
  422. }
  423. /* Helper of refreshSingleLine() and refreshMultiLine() to show hints
  424. * to the right of the prompt. */
  425. void refreshShowHints(struct abuf *ab, struct linenoiseState *l, int plen) {
  426. char seq[64];
  427. if (hintsCallback && plen+l->len < l->cols) {
  428. int color = -1, bold = 0;
  429. char *hint = hintsCallback(l->buf,&color,&bold);
  430. if (hint) {
  431. int hintlen = strlen(hint);
  432. int hintmaxlen = l->cols-(plen+l->len);
  433. if (hintlen > hintmaxlen) hintlen = hintmaxlen;
  434. if (bold == 1 && color == -1) color = 37;
  435. if (color != -1 || bold != 0)
  436. snprintf(seq,64,"\033[%d;%d;49m",bold,color);
  437. abAppend(ab,seq,strlen(seq));
  438. abAppend(ab,hint,hintlen);
  439. if (color != -1 || bold != 0)
  440. abAppend(ab,"\033[0m",4);
  441. /* Call the function to free the hint returned. */
  442. if (freeHintsCallback) freeHintsCallback(hint);
  443. }
  444. }
  445. }
  446. /* Single line low level line refresh.
  447. *
  448. * Rewrite the currently edited line accordingly to the buffer content,
  449. * cursor position, and number of columns of the terminal. */
  450. static void refreshSingleLine(struct linenoiseState *l) {
  451. char seq[64];
  452. size_t plen = strlen(l->prompt);
  453. int fd = l->ofd;
  454. char *buf = l->buf;
  455. size_t len = l->len;
  456. size_t pos = l->pos;
  457. struct abuf ab;
  458. while((plen+pos) >= l->cols) {
  459. buf++;
  460. len--;
  461. pos--;
  462. }
  463. while (plen+len > l->cols) {
  464. len--;
  465. }
  466. abInit(&ab);
  467. /* Cursor to left edge */
  468. snprintf(seq,64,"\r");
  469. abAppend(&ab,seq,strlen(seq));
  470. /* Write the prompt and the current buffer content */
  471. abAppend(&ab,l->prompt,strlen(l->prompt));
  472. abAppend(&ab,buf,len);
  473. /* Show hits if any. */
  474. refreshShowHints(&ab,l,plen);
  475. /* Erase to right */
  476. snprintf(seq,64,"\x1b[0K");
  477. abAppend(&ab,seq,strlen(seq));
  478. /* Move cursor to original position. */
  479. snprintf(seq,64,"\r\x1b[%dC", (int)(pos+plen));
  480. abAppend(&ab,seq,strlen(seq));
  481. if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */
  482. abFree(&ab);
  483. }
  484. /* Multi line low level line refresh.
  485. *
  486. * Rewrite the currently edited line accordingly to the buffer content,
  487. * cursor position, and number of columns of the terminal. */
  488. static void refreshMultiLine(struct linenoiseState *l) {
  489. char seq[64];
  490. int plen = strlen(l->prompt);
  491. int rows = (plen+l->len+l->cols-1)/l->cols; /* rows used by current buf. */
  492. int rpos = (plen+l->oldpos+l->cols)/l->cols; /* cursor relative row. */
  493. int rpos2; /* rpos after refresh. */
  494. int col; /* colum position, zero-based. */
  495. int old_rows = l->maxrows;
  496. int fd = l->ofd, j;
  497. struct abuf ab;
  498. /* Update maxrows if needed. */
  499. if (rows > (int)l->maxrows) l->maxrows = rows;
  500. /* First step: clear all the lines used before. To do so start by
  501. * going to the last row. */
  502. abInit(&ab);
  503. if (old_rows-rpos > 0) {
  504. lndebug("go down %d", old_rows-rpos);
  505. snprintf(seq,64,"\x1b[%dB", old_rows-rpos);
  506. abAppend(&ab,seq,strlen(seq));
  507. }
  508. /* Now for every row clear it, go up. */
  509. for (j = 0; j < old_rows-1; j++) {
  510. lndebug("clear+up");
  511. snprintf(seq,64,"\r\x1b[0K\x1b[1A");
  512. abAppend(&ab,seq,strlen(seq));
  513. }
  514. /* Clean the top line. */
  515. lndebug("clear");
  516. snprintf(seq,64,"\r\x1b[0K");
  517. abAppend(&ab,seq,strlen(seq));
  518. /* Write the prompt and the current buffer content */
  519. abAppend(&ab,l->prompt,strlen(l->prompt));
  520. abAppend(&ab,l->buf,l->len);
  521. /* Show hits if any. */
  522. refreshShowHints(&ab,l,plen);
  523. /* If we are at the very end of the screen with our prompt, we need to
  524. * emit a newline and move the prompt to the first column. */
  525. if (l->pos &&
  526. l->pos == l->len &&
  527. (l->pos+plen) % l->cols == 0)
  528. {
  529. lndebug("<newline>");
  530. abAppend(&ab,"\n",1);
  531. snprintf(seq,64,"\r");
  532. abAppend(&ab,seq,strlen(seq));
  533. rows++;
  534. if (rows > (int)l->maxrows) l->maxrows = rows;
  535. }
  536. /* Move cursor to right position. */
  537. rpos2 = (plen+l->pos+l->cols)/l->cols; /* current cursor relative row. */
  538. lndebug("rpos2 %d", rpos2);
  539. /* Go up till we reach the expected positon. */
  540. if (rows-rpos2 > 0) {
  541. lndebug("go-up %d", rows-rpos2);
  542. snprintf(seq,64,"\x1b[%dA", rows-rpos2);
  543. abAppend(&ab,seq,strlen(seq));
  544. }
  545. /* Set column. */
  546. col = (plen+(int)l->pos) % (int)l->cols;
  547. lndebug("set col %d", 1+col);
  548. if (col)
  549. snprintf(seq,64,"\r\x1b[%dC", col);
  550. else
  551. snprintf(seq,64,"\r");
  552. abAppend(&ab,seq,strlen(seq));
  553. lndebug("\n");
  554. l->oldpos = l->pos;
  555. if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */
  556. abFree(&ab);
  557. }
  558. /* Calls the two low level functions refreshSingleLine() or
  559. * refreshMultiLine() according to the selected mode. */
  560. static void refreshLine(struct linenoiseState *l) {
  561. if (mlmode)
  562. refreshMultiLine(l);
  563. else
  564. refreshSingleLine(l);
  565. }
  566. /* Insert the character 'c' at cursor current position.
  567. *
  568. * On error writing to the terminal -1 is returned, otherwise 0. */
  569. int linenoiseEditInsert(struct linenoiseState *l, char c) {
  570. if (l->len < l->buflen) {
  571. if (l->len == l->pos) {
  572. l->buf[l->pos] = c;
  573. l->pos++;
  574. l->len++;
  575. l->buf[l->len] = '\0';
  576. if ((!mlmode && l->plen+l->len < l->cols && !hintsCallback)) {
  577. /* Avoid a full update of the line in the
  578. * trivial case. */
  579. if (write(l->ofd,&c,1) == -1) return -1;
  580. } else {
  581. refreshLine(l);
  582. }
  583. } else {
  584. memmove(l->buf+l->pos+1,l->buf+l->pos,l->len-l->pos);
  585. l->buf[l->pos] = c;
  586. l->len++;
  587. l->pos++;
  588. l->buf[l->len] = '\0';
  589. refreshLine(l);
  590. }
  591. }
  592. return 0;
  593. }
  594. /* Move cursor on the left. */
  595. void linenoiseEditMoveLeft(struct linenoiseState *l) {
  596. if (l->pos > 0) {
  597. l->pos--;
  598. refreshLine(l);
  599. }
  600. }
  601. /* Move cursor on the right. */
  602. void linenoiseEditMoveRight(struct linenoiseState *l) {
  603. if (l->pos != l->len) {
  604. l->pos++;
  605. refreshLine(l);
  606. }
  607. }
  608. /* Move cursor to the start of the line. */
  609. void linenoiseEditMoveHome(struct linenoiseState *l) {
  610. if (l->pos != 0) {
  611. l->pos = 0;
  612. refreshLine(l);
  613. }
  614. }
  615. /* Move cursor to the end of the line. */
  616. void linenoiseEditMoveEnd(struct linenoiseState *l) {
  617. if (l->pos != l->len) {
  618. l->pos = l->len;
  619. refreshLine(l);
  620. }
  621. }
  622. /* Substitute the currently edited line with the next or previous history
  623. * entry as specified by 'dir'. */
  624. #define LINENOISE_HISTORY_NEXT 0
  625. #define LINENOISE_HISTORY_PREV 1
  626. void linenoiseEditHistoryNext(struct linenoiseState *l, int dir) {
  627. if (history_len > 1) {
  628. /* Update the current history entry before to
  629. * overwrite it with the next one. */
  630. free(history[history_len - 1 - l->history_index]);
  631. history[history_len - 1 - l->history_index] = strdup(l->buf);
  632. /* Show the new entry */
  633. l->history_index += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1;
  634. if (l->history_index < 0) {
  635. l->history_index = 0;
  636. return;
  637. } else if (l->history_index >= history_len) {
  638. l->history_index = history_len-1;
  639. return;
  640. }
  641. strncpy(l->buf,history[history_len - 1 - l->history_index],l->buflen);
  642. l->buf[l->buflen-1] = '\0';
  643. l->len = l->pos = strlen(l->buf);
  644. refreshLine(l);
  645. }
  646. }
  647. /* Delete the character at the right of the cursor without altering the cursor
  648. * position. Basically this is what happens with the "Delete" keyboard key. */
  649. void linenoiseEditDelete(struct linenoiseState *l) {
  650. if (l->len > 0 && l->pos < l->len) {
  651. memmove(l->buf+l->pos,l->buf+l->pos+1,l->len-l->pos-1);
  652. l->len--;
  653. l->buf[l->len] = '\0';
  654. refreshLine(l);
  655. }
  656. }
  657. /* Backspace implementation. */
  658. void linenoiseEditBackspace(struct linenoiseState *l) {
  659. if (l->pos > 0 && l->len > 0) {
  660. memmove(l->buf+l->pos-1,l->buf+l->pos,l->len-l->pos);
  661. l->pos--;
  662. l->len--;
  663. l->buf[l->len] = '\0';
  664. refreshLine(l);
  665. }
  666. }
  667. /* Delete the previosu word, maintaining the cursor at the start of the
  668. * current word. */
  669. void linenoiseEditDeletePrevWord(struct linenoiseState *l) {
  670. size_t old_pos = l->pos;
  671. size_t diff;
  672. while (l->pos > 0 && l->buf[l->pos-1] == ' ')
  673. l->pos--;
  674. while (l->pos > 0 && l->buf[l->pos-1] != ' ')
  675. l->pos--;
  676. diff = old_pos - l->pos;
  677. memmove(l->buf+l->pos,l->buf+old_pos,l->len-old_pos+1);
  678. l->len -= diff;
  679. refreshLine(l);
  680. }
  681. /* This function is the core of the line editing capability of linenoise.
  682. * It expects 'fd' to be already in "raw mode" so that every key pressed
  683. * will be returned ASAP to read().
  684. *
  685. * The resulting string is put into 'buf' when the user type enter, or
  686. * when ctrl+d is typed.
  687. *
  688. * The function returns the length of the current buffer. */
  689. static int linenoiseEdit(int stdin_fd, int stdout_fd, char *buf, size_t buflen, const char *prompt)
  690. {
  691. struct linenoiseState l;
  692. /* Populate the linenoise state that we pass to functions implementing
  693. * specific editing functionalities. */
  694. l.ifd = stdin_fd;
  695. l.ofd = stdout_fd;
  696. l.buf = buf;
  697. l.buflen = buflen;
  698. l.prompt = prompt;
  699. l.plen = strlen(prompt);
  700. l.oldpos = l.pos = 0;
  701. l.len = 0;
  702. l.cols = getColumns(stdin_fd, stdout_fd);
  703. l.maxrows = 0;
  704. l.history_index = 0;
  705. /* Buffer starts empty. */
  706. l.buf[0] = '\0';
  707. l.buflen--; /* Make sure there is always space for the nulterm */
  708. /* The latest history entry is always our current buffer, that
  709. * initially is just an empty string. */
  710. linenoiseHistoryAdd("");
  711. if (write(l.ofd,prompt,l.plen) == -1) return -1;
  712. while(1) {
  713. char c;
  714. int nread;
  715. char seq[3];
  716. nread = read(l.ifd,&c,1);
  717. if (nread <= 0) return l.len;
  718. /* Only autocomplete when the callback is set. It returns < 0 when
  719. * there was an error reading from fd. Otherwise it will return the
  720. * character that should be handled next. */
  721. if (c == 9 && completionCallback != NULL) {
  722. c = completeLine(&l);
  723. /* Return on errors */
  724. if (c < 0) return l.len;
  725. /* Read next character when 0 */
  726. if (c == 0) continue;
  727. }
  728. switch(c) {
  729. case ENTER: /* enter */
  730. history_len--;
  731. free(history[history_len]);
  732. if (mlmode) linenoiseEditMoveEnd(&l);
  733. if (hintsCallback) {
  734. /* Force a refresh without hints to leave the previous
  735. * line as the user typed it after a newline. */
  736. linenoiseHintsCallback *hc = hintsCallback;
  737. hintsCallback = NULL;
  738. refreshLine(&l);
  739. hintsCallback = hc;
  740. }
  741. return (int)l.len;
  742. case CTRL_C: /* ctrl-c */
  743. errno = EAGAIN;
  744. return -1;
  745. case BACKSPACE: /* backspace */
  746. case 8: /* ctrl-h */
  747. linenoiseEditBackspace(&l);
  748. break;
  749. case CTRL_D: /* ctrl-d, remove char at right of cursor, or if the
  750. line is empty, act as end-of-file. */
  751. if (l.len > 0) {
  752. linenoiseEditDelete(&l);
  753. } else {
  754. history_len--;
  755. free(history[history_len]);
  756. return -1;
  757. }
  758. break;
  759. case CTRL_T: /* ctrl-t, swaps current character with previous. */
  760. if (l.pos > 0 && l.pos < l.len) {
  761. int aux = buf[l.pos-1];
  762. buf[l.pos-1] = buf[l.pos];
  763. buf[l.pos] = aux;
  764. if (l.pos != l.len-1) l.pos++;
  765. refreshLine(&l);
  766. }
  767. break;
  768. case CTRL_B: /* ctrl-b */
  769. linenoiseEditMoveLeft(&l);
  770. break;
  771. case CTRL_F: /* ctrl-f */
  772. linenoiseEditMoveRight(&l);
  773. break;
  774. case CTRL_P: /* ctrl-p */
  775. linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
  776. break;
  777. case CTRL_N: /* ctrl-n */
  778. linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
  779. break;
  780. case ESC: /* escape sequence */
  781. /* Read the next two bytes representing the escape sequence.
  782. * Use two calls to handle slow terminals returning the two
  783. * chars at different times. */
  784. if (read(l.ifd,seq,1) == -1) break;
  785. if (read(l.ifd,seq+1,1) == -1) break;
  786. /* ESC [ sequences. */
  787. if (seq[0] == '[') {
  788. if (seq[1] >= '0' && seq[1] <= '9') {
  789. /* Extended escape, read additional byte. */
  790. if (read(l.ifd,seq+2,1) == -1) break;
  791. if (seq[2] == '~') {
  792. switch(seq[1]) {
  793. case '3': /* Delete key. */
  794. linenoiseEditDelete(&l);
  795. break;
  796. }
  797. }
  798. } else {
  799. switch(seq[1]) {
  800. case 'A': /* Up */
  801. linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
  802. break;
  803. case 'B': /* Down */
  804. linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
  805. break;
  806. case 'C': /* Right */
  807. linenoiseEditMoveRight(&l);
  808. break;
  809. case 'D': /* Left */
  810. linenoiseEditMoveLeft(&l);
  811. break;
  812. case 'H': /* Home */
  813. linenoiseEditMoveHome(&l);
  814. break;
  815. case 'F': /* End*/
  816. linenoiseEditMoveEnd(&l);
  817. break;
  818. }
  819. }
  820. }
  821. /* ESC O sequences. */
  822. else if (seq[0] == 'O') {
  823. switch(seq[1]) {
  824. case 'H': /* Home */
  825. linenoiseEditMoveHome(&l);
  826. break;
  827. case 'F': /* End*/
  828. linenoiseEditMoveEnd(&l);
  829. break;
  830. }
  831. }
  832. break;
  833. default:
  834. if (linenoiseEditInsert(&l,c)) return -1;
  835. break;
  836. case CTRL_U: /* Ctrl+u, delete the whole line. */
  837. buf[0] = '\0';
  838. l.pos = l.len = 0;
  839. refreshLine(&l);
  840. break;
  841. case CTRL_K: /* Ctrl+k, delete from current to end of line. */
  842. buf[l.pos] = '\0';
  843. l.len = l.pos;
  844. refreshLine(&l);
  845. break;
  846. case CTRL_A: /* Ctrl+a, go to the start of the line */
  847. linenoiseEditMoveHome(&l);
  848. break;
  849. case CTRL_E: /* ctrl+e, go to the end of the line */
  850. linenoiseEditMoveEnd(&l);
  851. break;
  852. case CTRL_L: /* ctrl+l, clear screen */
  853. linenoiseClearScreen();
  854. refreshLine(&l);
  855. break;
  856. case CTRL_W: /* ctrl+w, delete previous word */
  857. linenoiseEditDeletePrevWord(&l);
  858. break;
  859. }
  860. }
  861. return l.len;
  862. }
  863. /* This special mode is used by linenoise in order to print scan codes
  864. * on screen for debugging / development purposes. It is implemented
  865. * by the linenoise_example program using the --keycodes option. */
  866. void linenoisePrintKeyCodes(void) {
  867. char quit[4];
  868. printf("Linenoise key codes debugging mode.\n"
  869. "Press keys to see scan codes. Type 'quit' at any time to exit.\n");
  870. if (enableRawMode(STDIN_FILENO) == -1) return;
  871. memset(quit,' ',4);
  872. while(1) {
  873. char c;
  874. int nread;
  875. nread = read(STDIN_FILENO,&c,1);
  876. if (nread <= 0) continue;
  877. memmove(quit,quit+1,sizeof(quit)-1); /* shift string to left. */
  878. quit[sizeof(quit)-1] = c; /* Insert current char on the right. */
  879. if (memcmp(quit,"quit",sizeof(quit)) == 0) break;
  880. printf("'%c' %02x (%d) (type quit to exit)\n",
  881. isprint(c) ? c : '?', (int)c, (int)c);
  882. printf("\r"); /* Go left edge manually, we are in raw mode. */
  883. fflush(stdout);
  884. }
  885. disableRawMode(STDIN_FILENO);
  886. }
  887. /* This function calls the line editing function linenoiseEdit() using
  888. * the STDIN file descriptor set in raw mode. */
  889. static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
  890. int count;
  891. if (buflen == 0) {
  892. errno = EINVAL;
  893. return -1;
  894. }
  895. if (enableRawMode(STDIN_FILENO) == -1) return -1;
  896. count = linenoiseEdit(STDIN_FILENO, STDOUT_FILENO, buf, buflen, prompt);
  897. disableRawMode(STDIN_FILENO);
  898. printf("\n");
  899. return count;
  900. }
  901. /* This function is called when linenoise() is called with the standard
  902. * input file descriptor not attached to a TTY. So for example when the
  903. * program using linenoise is called in pipe or with a file redirected
  904. * to its standard input. In this case, we want to be able to return the
  905. * line regardless of its length (by default we are limited to 4k). */
  906. static char *linenoiseNoTTY(void) {
  907. char *line = NULL;
  908. size_t len = 0, maxlen = 0;
  909. while(1) {
  910. if (len == maxlen) {
  911. if (maxlen == 0) maxlen = 16;
  912. maxlen *= 2;
  913. char *oldval = line;
  914. line = realloc(line,maxlen);
  915. if (line == NULL) {
  916. if (oldval) free(oldval);
  917. return NULL;
  918. }
  919. }
  920. int c = fgetc(stdin);
  921. if (c == EOF || c == '\n') {
  922. if (c == EOF && len == 0) {
  923. free(line);
  924. return NULL;
  925. } else {
  926. line[len] = '\0';
  927. return line;
  928. }
  929. } else {
  930. line[len] = c;
  931. len++;
  932. }
  933. }
  934. }
  935. /* The high level function that is the main API of the linenoise library.
  936. * This function checks if the terminal has basic capabilities, just checking
  937. * for a blacklist of stupid terminals, and later either calls the line
  938. * editing function or uses dummy fgets() so that you will be able to type
  939. * something even in the most desperate of the conditions. */
  940. char *linenoise(const char *prompt) {
  941. char buf[LINENOISE_MAX_LINE];
  942. int count;
  943. if (!isatty(STDIN_FILENO)) {
  944. /* Not a tty: read from file / pipe. In this mode we don't want any
  945. * limit to the line size, so we call a function to handle that. */
  946. return linenoiseNoTTY();
  947. } else if (isUnsupportedTerm()) {
  948. size_t len;
  949. printf("%s",prompt);
  950. fflush(stdout);
  951. if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
  952. len = strlen(buf);
  953. while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
  954. len--;
  955. buf[len] = '\0';
  956. }
  957. return strdup(buf);
  958. } else {
  959. count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
  960. if (count == -1) return NULL;
  961. return strdup(buf);
  962. }
  963. }
  964. /* This is just a wrapper the user may want to call in order to make sure
  965. * the linenoise returned buffer is freed with the same allocator it was
  966. * created with. Useful when the main program is using an alternative
  967. * allocator. */
  968. void linenoiseFree(void *ptr) {
  969. free(ptr);
  970. }
  971. /* ================================ History ================================= */
  972. /* Free the history, but does not reset it. Only used when we have to
  973. * exit() to avoid memory leaks are reported by valgrind & co. */
  974. static void freeHistory(void) {
  975. if (history) {
  976. int j;
  977. for (j = 0; j < history_len; j++)
  978. free(history[j]);
  979. free(history);
  980. }
  981. }
  982. /* At exit we'll try to fix the terminal to the initial conditions. */
  983. static void linenoiseAtExit(void) {
  984. disableRawMode(STDIN_FILENO);
  985. freeHistory();
  986. }
  987. /* This is the API call to add a new entry in the linenoise history.
  988. * It uses a fixed array of char pointers that are shifted (memmoved)
  989. * when the history max length is reached in order to remove the older
  990. * entry and make room for the new one, so it is not exactly suitable for huge
  991. * histories, but will work well for a few hundred of entries.
  992. *
  993. * Using a circular buffer is smarter, but a bit more complex to handle. */
  994. int linenoiseHistoryAdd(const char *line) {
  995. char *linecopy;
  996. if (history_max_len == 0) return 0;
  997. /* Initialization on first call. */
  998. if (history == NULL) {
  999. history = malloc(sizeof(char*)*history_max_len);
  1000. if (history == NULL) return 0;
  1001. memset(history,0,(sizeof(char*)*history_max_len));
  1002. }
  1003. /* Don't add duplicated lines. */
  1004. if (history_len && !strcmp(history[history_len-1], line)) return 0;
  1005. /* Add an heap allocated copy of the line in the history.
  1006. * If we reached the max length, remove the older line. */
  1007. linecopy = strdup(line);
  1008. if (!linecopy) return 0;
  1009. if (history_len == history_max_len) {
  1010. free(history[0]);
  1011. memmove(history,history+1,sizeof(char*)*(history_max_len-1));
  1012. history_len--;
  1013. }
  1014. history[history_len] = linecopy;
  1015. history_len++;
  1016. return 1;
  1017. }
  1018. /* Set the maximum length for the history. This function can be called even
  1019. * if there is already some history, the function will make sure to retain
  1020. * just the latest 'len' elements if the new history length value is smaller
  1021. * than the amount of items already inside the history. */
  1022. int linenoiseHistorySetMaxLen(int len) {
  1023. char **new;
  1024. if (len < 1) return 0;
  1025. if (history) {
  1026. int tocopy = history_len;
  1027. new = malloc(sizeof(char*)*len);
  1028. if (new == NULL) return 0;
  1029. /* If we can't copy everything, free the elements we'll not use. */
  1030. if (len < tocopy) {
  1031. int j;
  1032. for (j = 0; j < tocopy-len; j++) free(history[j]);
  1033. tocopy = len;
  1034. }
  1035. memset(new,0,sizeof(char*)*len);
  1036. memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy);
  1037. free(history);
  1038. history = new;
  1039. }
  1040. history_max_len = len;
  1041. if (history_len > history_max_len)
  1042. history_len = history_max_len;
  1043. return 1;
  1044. }
  1045. /* Save the history in the specified file. On success 0 is returned
  1046. * otherwise -1 is returned. */
  1047. int linenoiseHistorySave(const char *filename) {
  1048. FILE *fp = fopen(filename,"w");
  1049. int j;
  1050. if (fp == NULL) return -1;
  1051. for (j = 0; j < history_len; j++)
  1052. fprintf(fp,"%s\n",history[j]);
  1053. fclose(fp);
  1054. return 0;
  1055. }
  1056. /* Load the history from the specified file. If the file does not exist
  1057. * zero is returned and no operation is performed.
  1058. *
  1059. * If the file exists and the operation succeeded 0 is returned, otherwise
  1060. * on error -1 is returned. */
  1061. int linenoiseHistoryLoad(const char *filename) {
  1062. FILE *fp = fopen(filename,"r");
  1063. char buf[LINENOISE_MAX_LINE];
  1064. if (fp == NULL) return -1;
  1065. while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
  1066. char *p;
  1067. p = strchr(buf,'\r');
  1068. if (!p) p = strchr(buf,'\n');
  1069. if (p) *p = '\0';
  1070. linenoiseHistoryAdd(buf);
  1071. }
  1072. fclose(fp);
  1073. return 0;
  1074. }