linenoise.cpp 44 KB

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