linenoise.cpp 44 KB

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