linenoise.c 39 KB

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