linenoise.c 38 KB

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