linenoise.c 35 KB

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