linenoise.c 39 KB

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