00001 /* 00002 * $Id: linenoise.c,v 1.3 2020年05月22日 05:53:27 johns Exp $ 00003 * 00004 * Modified linenoise from the standard distribution by adding 00005 * user context parameters for each of the callbacks, so that 00006 * the caller can pass in runtime-generated lists of command 00007 * completion strings without the use of global variables or 00008 * other undesirable methods. 00009 * 00010 * Further modifications were made to the linenoise Unix TTY handling code 00011 * to allow VMD to control TTY buffer flushes when switching between raw and 00012 * cooked TTY mode. This is required so that VMD can switch to raw mode 00013 * for character-at-a-time input, so that linenoise doesn't have 00014 * blocking behavior that prevents the VMD main loop from free-running. 00015 * With these changes, VMD free runs except when in actual command editing. 00016 * Correct handling of VMD console output is made more complex by entry 00017 * and return from raw TTY mode, but it is a much more usable scenario 00018 * for the end user. 00019 */ 00020 00021 /* linenoise.c -- guerrilla line editing library against the idea that a 00022 * line editing lib needs to be 20,000 lines of C code. 00023 * 00024 * You can find the latest source code at: 00025 * 00026 * http://github.com/antirez/linenoise 00027 * 00028 * Does a number of crazy assumptions that happen to be true in 99.9999% of 00029 * the 2010 UNIX computers around. 00030 * 00031 * ------------------------------------------------------------------------ 00032 * 00033 * Copyright (c) 2010-2016, Salvatore Sanfilippo <antirez at gmail dot com> 00034 * Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com> 00035 * 00036 * All rights reserved. 00037 * 00038 * Redistribution and use in source and binary forms, with or without 00039 * modification, are permitted provided that the following conditions are 00040 * met: 00041 * 00042 * * Redistributions of source code must retain the above copyright 00043 * notice, this list of conditions and the following disclaimer. 00044 * 00045 * * Redistributions in binary form must reproduce the above copyright 00046 * notice, this list of conditions and the following disclaimer in the 00047 * documentation and/or other materials provided with the distribution. 00048 * 00049 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 00050 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 00051 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 00052 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 00053 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 00054 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 00055 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 00056 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 00057 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 00058 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 00059 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 00060 * 00061 * ------------------------------------------------------------------------ 00062 * 00063 * References: 00064 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html 00065 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html 00066 * 00067 * Todo list: 00068 * - Filter bogus Ctrl+<char> combinations. 00069 * - Win32 support 00070 * 00071 * Bloat: 00072 * - History search like Ctrl+r in readline? 00073 * 00074 * List of escape sequences used by this program, we do everything just 00075 * with three sequences. In order to be so cheap we may have some 00076 * flickering effect with some slow terminal, but the lesser sequences 00077 * the more compatible. 00078 * 00079 * EL (Erase Line) 00080 * Sequence: ESC [ n K 00081 * Effect: if n is 0 or missing, clear from cursor to end of line 00082 * Effect: if n is 1, clear from beginning of line to cursor 00083 * Effect: if n is 2, clear entire line 00084 * 00085 * CUF (CUrsor Forward) 00086 * Sequence: ESC [ n C 00087 * Effect: moves cursor forward n chars 00088 * 00089 * CUB (CUrsor Backward) 00090 * Sequence: ESC [ n D 00091 * Effect: moves cursor backward n chars 00092 * 00093 * The following is used to get the terminal width if getting 00094 * the width with the TIOCGWINSZ ioctl fails 00095 * 00096 * DSR (Device Status Report) 00097 * Sequence: ESC [ 6 n 00098 * Effect: reports the current cusor position as ESC [ n ; m R 00099 * where n is the row and m is the column 00100 * 00101 * When multi line mode is enabled, we also use an additional escape 00102 * sequence. However multi line editing is disabled by default. 00103 * 00104 * CUU (Cursor Up) 00105 * Sequence: ESC [ n A 00106 * Effect: moves cursor up of n chars. 00107 * 00108 * CUD (Cursor Down) 00109 * Sequence: ESC [ n B 00110 * Effect: moves cursor down of n chars. 00111 * 00112 * When linenoiseClearScreen() is called, two additional escape sequences 00113 * are used in order to clear the screen and position the cursor at home 00114 * position. 00115 * 00116 * CUP (Cursor position) 00117 * Sequence: ESC [ H 00118 * Effect: moves the cursor to upper left corner 00119 * 00120 * ED (Erase display) 00121 * Sequence: ESC [ 2 J 00122 * Effect: clear the whole screen 00123 * 00124 */ 00125 00126 #include <termios.h> 00127 #include <unistd.h> 00128 #include <stdlib.h> 00129 #include <stdio.h> 00130 #include <errno.h> 00131 #include <string.h> 00132 #include <stdlib.h> 00133 #include <ctype.h> 00134 #include <sys/stat.h> 00135 #include <sys/types.h> 00136 #include <sys/ioctl.h> 00137 #include <unistd.h> 00138 #include "linenoise.h" 00139 00140 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100 00141 #define LINENOISE_MAX_LINE 4096 00142 static char *unsupported_term[] = {"dumb","cons25","emacs",NULL}; 00143 static linenoiseCompletionCallback *completionCallback = NULL; 00144 static void * completionCallbackCtx = NULL; 00145 static linenoiseHintsCallback *hintsCallback = NULL; 00146 static void * hintsCallbackCtx = NULL; 00147 static linenoiseFreeHintsCallback *freeHintsCallback = NULL; 00148 static void * freeHintsCallbackCtx = NULL; 00149 00150 static struct termios orig_termios; /* In order to restore at exit.*/ 00151 static int maskmode = 0; /* Show "***" instead of input. For passwords. */ 00152 static int rawmode = 0; /* For atexit() function to check if restore is needed*/ 00153 static int mlmode = 0; /* Multi line mode. Default is single line. */ 00154 static int atexit_registered = 0; /* Register atexit just 1 time. */ 00155 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN; 00156 static int history_len = 0; 00157 static char **history = NULL; 00158 00159 /* The linenoiseState structure represents the state during line editing. 00160 * We pass this state to functions implementing specific editing 00161 * functionalities. */ 00162 struct linenoiseState { 00163 int ifd; /* Terminal stdin file descriptor. */ 00164 int ofd; /* Terminal stdout file descriptor. */ 00165 char *buf; /* Edited line buffer. */ 00166 size_t buflen; /* Edited line buffer size. */ 00167 const char *prompt; /* Prompt to display. */ 00168 size_t plen; /* Prompt length. */ 00169 size_t pos; /* Current cursor position. */ 00170 size_t oldpos; /* Previous refresh cursor position. */ 00171 size_t len; /* Current edited line length. */ 00172 size_t cols; /* Number of columns in terminal. */ 00173 size_t maxrows; /* Maximum num of rows used so far (multiline mode) */ 00174 int history_index; /* The history index we are currently editing. */ 00175 }; 00176 00177 enum KEY_ACTION{ 00178 KEY_NULL = 0, /* NULL */ 00179 CTRL_A = 1, /* Ctrl+a */ 00180 CTRL_B = 2, /* Ctrl-b */ 00181 CTRL_C = 3, /* Ctrl-c */ 00182 CTRL_D = 4, /* Ctrl-d */ 00183 CTRL_E = 5, /* Ctrl-e */ 00184 CTRL_F = 6, /* Ctrl-f */ 00185 CTRL_H = 8, /* Ctrl-h */ 00186 TAB = 9, /* Tab */ 00187 CTRL_K = 11, /* Ctrl+k */ 00188 CTRL_L = 12, /* Ctrl+l */ 00189 ENTER = 13, /* Enter */ 00190 CTRL_N = 14, /* Ctrl-n */ 00191 CTRL_P = 16, /* Ctrl-p */ 00192 CTRL_T = 20, /* Ctrl-t */ 00193 CTRL_U = 21, /* Ctrl+u */ 00194 CTRL_W = 23, /* Ctrl+w */ 00195 ESC = 27, /* Escape */ 00196 BACKSPACE = 127 /* Backspace */ 00197 }; 00198 00199 static void linenoiseAtExit(void); 00200 int linenoiseHistoryAdd(const char *line); 00201 static void refreshLine(struct linenoiseState *l); 00202 00203 /* Debugging macro. */ 00204 #if 0 00205 FILE *lndebug_fp = NULL; 00206 #define lndebug(...) \ 00207 do { \ 00208 if (lndebug_fp == NULL) { \ 00209 lndebug_fp = fopen("/tmp/lndebug.txt","a"); \ 00210 fprintf(lndebug_fp, \ 00211 "[%d %d %d] p: %d, rows: %d, rpos: %d, max: %d, oldmax: %d\n", \ 00212 (int)l->len,(int)l->pos,(int)l->oldpos,plen,rows,rpos, \ 00213 (int)l->maxrows,old_rows); \ 00214 } \ 00215 fprintf(lndebug_fp, ", " __VA_ARGS__); \ 00216 fflush(lndebug_fp); \ 00217 } while (0) 00218 #else 00219 #define lndebug(fmt, ...) 00220 #endif 00221 00222 /* ======================= Low level terminal handling ====================== */ 00223 00224 /* Enable "mask mode". When it is enabled, instead of the input that 00225 * the user is typing, the terminal will just display a corresponding 00226 * number of asterisks, like "****". This is useful for passwords and other 00227 * secrets that should not be displayed. */ 00228 void linenoiseMaskModeEnable(void) { 00229 maskmode = 1; 00230 } 00231 00232 /* Disable mask mode. */ 00233 void linenoiseMaskModeDisable(void) { 00234 maskmode = 0; 00235 } 00236 00237 /* Set if to use or not the multi line mode. */ 00238 void linenoiseSetMultiLine(int ml) { 00239 mlmode = ml; 00240 } 00241 00242 /* Return true if the terminal name is in the list of terminals we know are 00243 * not able to understand basic escape sequences. */ 00244 static int isUnsupportedTerm(void) { 00245 char *term = getenv("TERM"); 00246 int j; 00247 00248 if (term == NULL) return 0; 00249 for (j = 0; unsupported_term[j]; j++) 00250 if (!strcasecmp(term,unsupported_term[j])) return 1; 00251 return 0; 00252 } 00253 00254 /* Raw mode: 1960 magic shit. */ 00255 int enableRawMode(int fd, int flush) { 00256 struct termios raw; 00257 00258 if (!isatty(STDIN_FILENO)) goto fatal; 00259 if (!atexit_registered) { 00260 atexit(linenoiseAtExit); 00261 atexit_registered = 1; 00262 } 00263 if (tcgetattr(fd,&orig_termios) == -1) goto fatal; 00264 00265 raw = orig_termios; /* modify the original mode */ 00266 /* input modes: no break, no CR to NL, no parity check, no strip char, 00267 * no start/stop output control. */ 00268 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); 00269 /* output modes - disable post processing */ 00270 raw.c_oflag &= ~(OPOST); 00271 /* control modes - set 8 bit chars */ 00272 raw.c_cflag |= (CS8); 00273 /* local modes - choing off, canonical off, no extended functions, 00274 * no signal chars (^Z,^C) */ 00275 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); 00276 /* control chars - set return condition: min number of bytes and timer. 00277 * We want read to return every single byte, without timeout. */ 00278 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */ 00279 00280 /* put terminal in raw mode after flushing */ 00281 if (tcsetattr(fd,(flush) ? TCSAFLUSH : TCSANOW, &raw) < 0) goto fatal; 00282 rawmode = 1; 00283 return 0; 00284 00285 fatal: 00286 errno = ENOTTY; 00287 return -1; 00288 } 00289 00290 void disableRawMode(int fd, int flush) { 00291 /* Don't even check the return value as it's too late. */ 00292 if (rawmode && tcsetattr(fd,(flush) ? TCSAFLUSH : TCSANOW,&orig_termios) != -1) 00293 rawmode = 0; 00294 } 00295 00296 /* Use the ESC [6n escape sequence to query the horizontal cursor position 00297 * and return it. On error -1 is returned, on success the position of the 00298 * cursor. */ 00299 static int getCursorPosition(int ifd, int ofd) { 00300 char buf[32]; 00301 int cols, rows; 00302 unsigned int i = 0; 00303 00304 /* Report cursor location */ 00305 if (write(ofd, "\x1b[6n", 4) != 4) return -1; 00306 00307 /* Read the response: ESC [ rows ; cols R */ 00308 while (i < sizeof(buf)-1) { 00309 if (read(ifd,buf+i,1) != 1) break; 00310 if (buf[i] == 'R') break; 00311 i++; 00312 } 00313 buf[i] = '0円'; 00314 00315 /* Parse it. */ 00316 if (buf[0] != ESC || buf[1] != '[') return -1; 00317 if (sscanf(buf+2,"%d;%d",&rows,&cols) != 2) return -1; 00318 return cols; 00319 } 00320 00321 /* Try to get the number of columns in the current terminal, or assume 80 00322 * if it fails. */ 00323 static int getColumns(int ifd, int ofd) { 00324 struct winsize ws; 00325 00326 if (ioctl(1, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) { 00327 /* ioctl() failed. Try to query the terminal itself. */ 00328 int start, cols; 00329 00330 /* Get the initial position so we can restore it later. */ 00331 start = getCursorPosition(ifd,ofd); 00332 if (start == -1) goto failed; 00333 00334 /* Go to right margin and get position. */ 00335 if (write(ofd,"\x1b[999C",6) != 6) goto failed; 00336 cols = getCursorPosition(ifd,ofd); 00337 if (cols == -1) goto failed; 00338 00339 /* Restore position. */ 00340 if (cols > start) { 00341 char seq[32]; 00342 snprintf(seq,32,"\x1b[%dD",cols-start); 00343 if (write(ofd,seq,strlen(seq)) == -1) { 00344 /* Can't recover... */ 00345 } 00346 } 00347 return cols; 00348 } else { 00349 return ws.ws_col; 00350 } 00351 00352 failed: 00353 return 80; 00354 } 00355 00356 /* Clear the screen. Used to handle ctrl+l */ 00357 void linenoiseClearScreen(void) { 00358 if (write(STDOUT_FILENO,"\x1b[H\x1b[2J",7) <= 0) { 00359 /* nothing to do, just to avoid warning. */ 00360 } 00361 } 00362 00363 /* Beep, used for completion when there is nothing to complete or when all 00364 * the choices were already shown. */ 00365 static void linenoiseBeep(void) { 00366 fprintf(stderr, "\x7"); 00367 fflush(stderr); 00368 } 00369 00370 /* ============================== Completion ================================ */ 00371 00372 /* Free a list of completion option populated by linenoiseAddCompletion(). */ 00373 static void freeCompletions(linenoiseCompletions *lc) { 00374 size_t i; 00375 for (i = 0; i < lc->len; i++) 00376 free(lc->cvec[i]); 00377 if (lc->cvec != NULL) 00378 free(lc->cvec); 00379 } 00380 00381 /* This is an helper function for linenoiseEdit() and is called when the 00382 * user types the <tab> key in order to complete the string currently in the 00383 * input. 00384 * 00385 * The state of the editing is encapsulated into the pointed linenoiseState 00386 * structure as described in the structure definition. */ 00387 static int completeLine(struct linenoiseState *ls) { 00388 linenoiseCompletions lc = { 0, NULL }; 00389 int nread, nwritten; 00390 char c = 0; 00391 00392 completionCallback(completionCallbackCtx,ls->buf,&lc); 00393 if (lc.len == 0) { 00394 linenoiseBeep(); 00395 } else { 00396 size_t stop = 0, i = 0; 00397 00398 while(!stop) { 00399 /* Show completion or original buffer */ 00400 if (i < lc.len) { 00401 struct linenoiseState saved = *ls; 00402 00403 ls->len = ls->pos = strlen(lc.cvec[i]); 00404 ls->buf = lc.cvec[i]; 00405 refreshLine(ls); 00406 ls->len = saved.len; 00407 ls->pos = saved.pos; 00408 ls->buf = saved.buf; 00409 } else { 00410 refreshLine(ls); 00411 } 00412 00413 nread = read(ls->ifd,&c,1); 00414 if (nread <= 0) { 00415 freeCompletions(&lc); 00416 return -1; 00417 } 00418 00419 switch(c) { 00420 case 9: /* tab */ 00421 i = (i+1) % (lc.len+1); 00422 if (i == lc.len) linenoiseBeep(); 00423 break; 00424 case 27: /* escape */ 00425 /* Re-show original buffer */ 00426 if (i < lc.len) refreshLine(ls); 00427 stop = 1; 00428 break; 00429 default: 00430 /* Update buffer and return */ 00431 if (i < lc.len) { 00432 nwritten = snprintf(ls->buf,ls->buflen,"%s",lc.cvec[i]); 00433 ls->len = ls->pos = nwritten; 00434 } 00435 stop = 1; 00436 break; 00437 } 00438 } 00439 } 00440 00441 freeCompletions(&lc); 00442 return c; /* Return last read character */ 00443 } 00444 00445 /* Register a callback function to be called for tab-completion. */ 00446 void linenoiseSetCompletionCallback(void *uctx, linenoiseCompletionCallback *fn) { 00447 completionCallbackCtx = uctx; 00448 completionCallback = fn; 00449 } 00450 00451 /* Register a hits function to be called to show hits to the user at the 00452 * right of the prompt. */ 00453 void linenoiseSetHintsCallback(void *uctx, linenoiseHintsCallback *fn) { 00454 hintsCallbackCtx = uctx; 00455 hintsCallback = fn; 00456 } 00457 00458 /* Register a function to free the hints returned by the hints callback 00459 * registered with linenoiseSetHintsCallback(). */ 00460 void linenoiseSetFreeHintsCallback(void *uctx, linenoiseFreeHintsCallback *fn) { 00461 freeHintsCallbackCtx = uctx; 00462 freeHintsCallback = fn; 00463 } 00464 00465 /* This function is used by the callback function registered by the user 00466 * in order to add completion options given the input string when the 00467 * user typed <tab>. See the example.c source code for a very easy to 00468 * understand example. */ 00469 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) { 00470 size_t len = strlen(str); 00471 char *copy, **cvec; 00472 00473 copy = malloc(len+1); 00474 if (copy == NULL) return; 00475 memcpy(copy,str,len+1); 00476 cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1)); 00477 if (cvec == NULL) { 00478 free(copy); 00479 return; 00480 } 00481 lc->cvec = cvec; 00482 lc->cvec[lc->len++] = copy; 00483 } 00484 00485 /* =========================== Line editing ================================= */ 00486 00487 /* We define a very simple "append buffer" structure, that is an heap 00488 * allocated string where we can append to. This is useful in order to 00489 * write all the escape sequences in a buffer and flush them to the standard 00490 * output in a single call, to avoid flickering effects. */ 00491 struct abuf { 00492 char *b; 00493 int len; 00494 }; 00495 00496 static void abInit(struct abuf *ab) { 00497 ab->b = NULL; 00498 ab->len = 0; 00499 } 00500 00501 static void abAppend(struct abuf *ab, const char *s, int len) { 00502 char *new = realloc(ab->b,ab->len+len); 00503 00504 if (new == NULL) return; 00505 memcpy(new+ab->len,s,len); 00506 ab->b = new; 00507 ab->len += len; 00508 } 00509 00510 static void abFree(struct abuf *ab) { 00511 free(ab->b); 00512 } 00513 00514 /* Helper of refreshSingleLine() and refreshMultiLine() to show hints 00515 * to the right of the prompt. */ 00516 void refreshShowHints(struct abuf *ab, struct linenoiseState *l, int plen) { 00517 char seq[64]; 00518 if (hintsCallback && plen+l->len < l->cols) { 00519 int color = -1, bold = 0; 00520 char *hint = hintsCallback(hintsCallbackCtx, l->buf,&color,&bold); 00521 if (hint) { 00522 int hintlen = strlen(hint); 00523 int hintmaxlen = l->cols-(plen+l->len); 00524 if (hintlen > hintmaxlen) hintlen = hintmaxlen; 00525 if (bold == 1 && color == -1) color = 37; 00526 if (color != -1 || bold != 0) 00527 snprintf(seq,64,"033円[%d;%d;49m",bold,color); 00528 else 00529 seq[0] = '0円'; 00530 abAppend(ab,seq,strlen(seq)); 00531 abAppend(ab,hint,hintlen); 00532 if (color != -1 || bold != 0) 00533 abAppend(ab,"033円[0m",4); 00534 /* Call the function to free the hint returned. */ 00535 if (freeHintsCallback) freeHintsCallback(freeHintsCallbackCtx, hint); 00536 } 00537 } 00538 } 00539 00540 /* Single line low level line refresh. 00541 * 00542 * Rewrite the currently edited line accordingly to the buffer content, 00543 * cursor position, and number of columns of the terminal. */ 00544 static void refreshSingleLine(struct linenoiseState *l) { 00545 char seq[64]; 00546 size_t plen = strlen(l->prompt); 00547 int fd = l->ofd; 00548 char *buf = l->buf; 00549 size_t len = l->len; 00550 size_t pos = l->pos; 00551 struct abuf ab; 00552 00553 while((plen+pos) >= l->cols) { 00554 buf++; 00555 len--; 00556 pos--; 00557 } 00558 while (plen+len > l->cols) { 00559 len--; 00560 } 00561 00562 abInit(&ab); 00563 /* Cursor to left edge */ 00564 snprintf(seq,64,"\r"); 00565 abAppend(&ab,seq,strlen(seq)); 00566 /* Write the prompt and the current buffer content */ 00567 abAppend(&ab,l->prompt,strlen(l->prompt)); 00568 if (maskmode == 1) { 00569 while (len--) abAppend(&ab,"*",1); 00570 } else { 00571 abAppend(&ab,buf,len); 00572 } 00573 /* Show hits if any. */ 00574 refreshShowHints(&ab,l,plen); 00575 /* Erase to right */ 00576 snprintf(seq,64,"\x1b[0K"); 00577 abAppend(&ab,seq,strlen(seq)); 00578 /* Move cursor to original position. */ 00579 snprintf(seq,64,"\r\x1b[%dC", (int)(pos+plen)); 00580 abAppend(&ab,seq,strlen(seq)); 00581 if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */ 00582 abFree(&ab); 00583 } 00584 00585 /* Multi line low level line refresh. 00586 * 00587 * Rewrite the currently edited line accordingly to the buffer content, 00588 * cursor position, and number of columns of the terminal. */ 00589 static void refreshMultiLine(struct linenoiseState *l) { 00590 char seq[64]; 00591 int plen = strlen(l->prompt); 00592 int rows = (plen+l->len+l->cols-1)/l->cols; /* rows used by current buf. */ 00593 int rpos = (plen+l->oldpos+l->cols)/l->cols; /* cursor relative row. */ 00594 int rpos2; /* rpos after refresh. */ 00595 int col; /* colum position, zero-based. */ 00596 int old_rows = l->maxrows; 00597 int fd = l->ofd, j; 00598 struct abuf ab; 00599 00600 /* Update maxrows if needed. */ 00601 if (rows > (int)l->maxrows) l->maxrows = rows; 00602 00603 /* First step: clear all the lines used before. To do so start by 00604 * going to the last row. */ 00605 abInit(&ab); 00606 if (old_rows-rpos > 0) { 00607 lndebug("go down %d", old_rows-rpos); 00608 snprintf(seq,64,"\x1b[%dB", old_rows-rpos); 00609 abAppend(&ab,seq,strlen(seq)); 00610 } 00611 00612 /* Now for every row clear it, go up. */ 00613 for (j = 0; j < old_rows-1; j++) { 00614 lndebug("clear+up"); 00615 snprintf(seq,64,"\r\x1b[0K\x1b[1A"); 00616 abAppend(&ab,seq,strlen(seq)); 00617 } 00618 00619 /* Clean the top line. */ 00620 lndebug("clear"); 00621 snprintf(seq,64,"\r\x1b[0K"); 00622 abAppend(&ab,seq,strlen(seq)); 00623 00624 /* Write the prompt and the current buffer content */ 00625 abAppend(&ab,l->prompt,strlen(l->prompt)); 00626 if (maskmode == 1) { 00627 unsigned int i; 00628 for (i = 0; i < l->len; i++) abAppend(&ab,"*",1); 00629 } else { 00630 abAppend(&ab,l->buf,l->len); 00631 } 00632 00633 /* Show hits if any. */ 00634 refreshShowHints(&ab,l,plen); 00635 00636 /* If we are at the very end of the screen with our prompt, we need to 00637 * emit a newline and move the prompt to the first column. */ 00638 if (l->pos && 00639 l->pos == l->len && 00640 (l->pos+plen) % l->cols == 0) 00641 { 00642 lndebug("<newline>"); 00643 abAppend(&ab,"\n",1); 00644 snprintf(seq,64,"\r"); 00645 abAppend(&ab,seq,strlen(seq)); 00646 rows++; 00647 if (rows > (int)l->maxrows) l->maxrows = rows; 00648 } 00649 00650 /* Move cursor to right position. */ 00651 rpos2 = (plen+l->pos+l->cols)/l->cols; /* current cursor relative row. */ 00652 lndebug("rpos2 %d", rpos2); 00653 00654 /* Go up till we reach the expected positon. */ 00655 if (rows-rpos2 > 0) { 00656 lndebug("go-up %d", rows-rpos2); 00657 snprintf(seq,64,"\x1b[%dA", rows-rpos2); 00658 abAppend(&ab,seq,strlen(seq)); 00659 } 00660 00661 /* Set column. */ 00662 col = (plen+(int)l->pos) % (int)l->cols; 00663 lndebug("set col %d", 1+col); 00664 if (col) 00665 snprintf(seq,64,"\r\x1b[%dC", col); 00666 else 00667 snprintf(seq,64,"\r"); 00668 abAppend(&ab,seq,strlen(seq)); 00669 00670 lndebug("\n"); 00671 l->oldpos = l->pos; 00672 00673 if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */ 00674 abFree(&ab); 00675 } 00676 00677 /* Calls the two low level functions refreshSingleLine() or 00678 * refreshMultiLine() according to the selected mode. */ 00679 static void refreshLine(struct linenoiseState *l) { 00680 if (mlmode) 00681 refreshMultiLine(l); 00682 else 00683 refreshSingleLine(l); 00684 } 00685 00686 /* Insert the character 'c' at cursor current position. 00687 * 00688 * On error writing to the terminal -1 is returned, otherwise 0. */ 00689 int linenoiseEditInsert(struct linenoiseState *l, char c) { 00690 if (l->len < l->buflen) { 00691 if (l->len == l->pos) { 00692 l->buf[l->pos] = c; 00693 l->pos++; 00694 l->len++; 00695 l->buf[l->len] = '0円'; 00696 if ((!mlmode && l->plen+l->len < l->cols && !hintsCallback)) { 00697 /* Avoid a full update of the line in the 00698 * trivial case. */ 00699 char d = (maskmode==1) ? '*' : c; 00700 if (write(l->ofd,&d,1) == -1) return -1; 00701 } else { 00702 refreshLine(l); 00703 } 00704 } else { 00705 memmove(l->buf+l->pos+1,l->buf+l->pos,l->len-l->pos); 00706 l->buf[l->pos] = c; 00707 l->len++; 00708 l->pos++; 00709 l->buf[l->len] = '0円'; 00710 refreshLine(l); 00711 } 00712 } 00713 return 0; 00714 } 00715 00716 /* Move cursor on the left. */ 00717 void linenoiseEditMoveLeft(struct linenoiseState *l) { 00718 if (l->pos > 0) { 00719 l->pos--; 00720 refreshLine(l); 00721 } 00722 } 00723 00724 /* Move cursor on the right. */ 00725 void linenoiseEditMoveRight(struct linenoiseState *l) { 00726 if (l->pos != l->len) { 00727 l->pos++; 00728 refreshLine(l); 00729 } 00730 } 00731 00732 /* Move cursor to the start of the line. */ 00733 void linenoiseEditMoveHome(struct linenoiseState *l) { 00734 if (l->pos != 0) { 00735 l->pos = 0; 00736 refreshLine(l); 00737 } 00738 } 00739 00740 /* Move cursor to the end of the line. */ 00741 void linenoiseEditMoveEnd(struct linenoiseState *l) { 00742 if (l->pos != l->len) { 00743 l->pos = l->len; 00744 refreshLine(l); 00745 } 00746 } 00747 00748 /* Substitute the currently edited line with the next or previous history 00749 * entry as specified by 'dir'. */ 00750 #define LINENOISE_HISTORY_NEXT 0 00751 #define LINENOISE_HISTORY_PREV 1 00752 void linenoiseEditHistoryNext(struct linenoiseState *l, int dir) { 00753 if (history_len > 1) { 00754 /* Update the current history entry before to 00755 * overwrite it with the next one. */ 00756 free(history[history_len - 1 - l->history_index]); 00757 history[history_len - 1 - l->history_index] = strdup(l->buf); 00758 /* Show the new entry */ 00759 l->history_index += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1; 00760 if (l->history_index < 0) { 00761 l->history_index = 0; 00762 return; 00763 } else if (l->history_index >= history_len) { 00764 l->history_index = history_len-1; 00765 return; 00766 } 00767 strncpy(l->buf,history[history_len - 1 - l->history_index],l->buflen); 00768 l->buf[l->buflen-1] = '0円'; 00769 l->len = l->pos = strlen(l->buf); 00770 refreshLine(l); 00771 } 00772 } 00773 00774 /* Delete the character at the right of the cursor without altering the cursor 00775 * position. Basically this is what happens with the "Delete" keyboard key. */ 00776 void linenoiseEditDelete(struct linenoiseState *l) { 00777 if (l->len > 0 && l->pos < l->len) { 00778 memmove(l->buf+l->pos,l->buf+l->pos+1,l->len-l->pos-1); 00779 l->len--; 00780 l->buf[l->len] = '0円'; 00781 refreshLine(l); 00782 } 00783 } 00784 00785 /* Backspace implementation. */ 00786 void linenoiseEditBackspace(struct linenoiseState *l) { 00787 if (l->pos > 0 && l->len > 0) { 00788 memmove(l->buf+l->pos-1,l->buf+l->pos,l->len-l->pos); 00789 l->pos--; 00790 l->len--; 00791 l->buf[l->len] = '0円'; 00792 refreshLine(l); 00793 } 00794 } 00795 00796 /* Delete the previosu word, maintaining the cursor at the start of the 00797 * current word. */ 00798 void linenoiseEditDeletePrevWord(struct linenoiseState *l) { 00799 size_t old_pos = l->pos; 00800 size_t diff; 00801 00802 while (l->pos > 0 && l->buf[l->pos-1] == ' ') 00803 l->pos--; 00804 while (l->pos > 0 && l->buf[l->pos-1] != ' ') 00805 l->pos--; 00806 diff = old_pos - l->pos; 00807 memmove(l->buf+l->pos,l->buf+old_pos,l->len-old_pos+1); 00808 l->len -= diff; 00809 refreshLine(l); 00810 } 00811 00812 /* This function is the core of the line editing capability of linenoise. 00813 * It expects 'fd' to be already in "raw mode" so that every key pressed 00814 * will be returned ASAP to read(). 00815 * 00816 * The resulting string is put into 'buf' when the user type enter, or 00817 * when ctrl+d is typed. 00818 * 00819 * The function returns the length of the current buffer. */ 00820 static int linenoiseEdit(int stdin_fd, int stdout_fd, char *buf, size_t buflen, const char *prompt) 00821 { 00822 struct linenoiseState l; 00823 00824 /* Populate the linenoise state that we pass to functions implementing 00825 * specific editing functionalities. */ 00826 l.ifd = stdin_fd; 00827 l.ofd = stdout_fd; 00828 l.buf = buf; 00829 l.buflen = buflen; 00830 l.prompt = prompt; 00831 l.plen = strlen(prompt); 00832 l.oldpos = l.pos = 0; 00833 l.len = 0; 00834 l.cols = getColumns(stdin_fd, stdout_fd); 00835 l.maxrows = 0; 00836 l.history_index = 0; 00837 00838 /* Buffer starts empty. */ 00839 l.buf[0] = '0円'; 00840 l.buflen--; /* Make sure there is always space for the nulterm */ 00841 00842 /* The latest history entry is always our current buffer, that 00843 * initially is just an empty string. */ 00844 linenoiseHistoryAdd(""); 00845 00846 if (write(l.ofd,prompt,l.plen) == -1) return -1; 00847 while(1) { 00848 char c; 00849 int nread; 00850 char seq[3]; 00851 00852 nread = read(l.ifd,&c,1); 00853 if (nread <= 0) return l.len; 00854 00855 /* Only autocomplete when the callback is set. It returns < 0 when 00856 * there was an error reading from fd. Otherwise it will return the 00857 * character that should be handled next. */ 00858 if (c == 9 && completionCallback != NULL) { 00859 c = completeLine(&l); 00860 /* Return on errors */ 00861 if (c < 0) return l.len; 00862 /* Read next character when 0 */ 00863 if (c == 0) continue; 00864 } 00865 00866 switch(c) { 00867 case ENTER: /* enter */ 00868 history_len--; 00869 free(history[history_len]); 00870 if (mlmode) linenoiseEditMoveEnd(&l); 00871 if (hintsCallback) { 00872 /* Force a refresh without hints to leave the previous 00873 * line as the user typed it after a newline. */ 00874 linenoiseHintsCallback *hc = hintsCallback; 00875 hintsCallback = NULL; 00876 refreshLine(&l); 00877 hintsCallback = hc; 00878 } 00879 return (int)l.len; 00880 case CTRL_C: /* ctrl-c */ 00881 errno = EAGAIN; 00882 return -1; 00883 case BACKSPACE: /* backspace */ 00884 case 8: /* ctrl-h */ 00885 linenoiseEditBackspace(&l); 00886 break; 00887 case CTRL_D: /* ctrl-d, remove char at right of cursor, or if the 00888 line is empty, act as end-of-file. */ 00889 if (l.len > 0) { 00890 linenoiseEditDelete(&l); 00891 } else { 00892 history_len--; 00893 free(history[history_len]); 00894 return -1; 00895 } 00896 break; 00897 case CTRL_T: /* ctrl-t, swaps current character with previous. */ 00898 if (l.pos > 0 && l.pos < l.len) { 00899 int aux = buf[l.pos-1]; 00900 buf[l.pos-1] = buf[l.pos]; 00901 buf[l.pos] = aux; 00902 if (l.pos != l.len-1) l.pos++; 00903 refreshLine(&l); 00904 } 00905 break; 00906 case CTRL_B: /* ctrl-b */ 00907 linenoiseEditMoveLeft(&l); 00908 break; 00909 case CTRL_F: /* ctrl-f */ 00910 linenoiseEditMoveRight(&l); 00911 break; 00912 case CTRL_P: /* ctrl-p */ 00913 linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV); 00914 break; 00915 case CTRL_N: /* ctrl-n */ 00916 linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT); 00917 break; 00918 case ESC: /* escape sequence */ 00919 /* Read the next two bytes representing the escape sequence. 00920 * Use two calls to handle slow terminals returning the two 00921 * chars at different times. */ 00922 if (read(l.ifd,seq,1) == -1) break; 00923 if (read(l.ifd,seq+1,1) == -1) break; 00924 00925 /* ESC [ sequences. */ 00926 if (seq[0] == '[') { 00927 if (seq[1] >= '0' && seq[1] <= '9') { 00928 /* Extended escape, read additional byte. */ 00929 if (read(l.ifd,seq+2,1) == -1) break; 00930 if (seq[2] == '~') { 00931 switch(seq[1]) { 00932 case '3': /* Delete key. */ 00933 linenoiseEditDelete(&l); 00934 break; 00935 } 00936 } 00937 } else { 00938 switch(seq[1]) { 00939 case 'A': /* Up */ 00940 linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV); 00941 break; 00942 case 'B': /* Down */ 00943 linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT); 00944 break; 00945 case 'C': /* Right */ 00946 linenoiseEditMoveRight(&l); 00947 break; 00948 case 'D': /* Left */ 00949 linenoiseEditMoveLeft(&l); 00950 break; 00951 case 'H': /* Home */ 00952 linenoiseEditMoveHome(&l); 00953 break; 00954 case 'F': /* End*/ 00955 linenoiseEditMoveEnd(&l); 00956 break; 00957 } 00958 } 00959 } 00960 00961 /* ESC O sequences. */ 00962 else if (seq[0] == 'O') { 00963 switch(seq[1]) { 00964 case 'H': /* Home */ 00965 linenoiseEditMoveHome(&l); 00966 break; 00967 case 'F': /* End*/ 00968 linenoiseEditMoveEnd(&l); 00969 break; 00970 } 00971 } 00972 break; 00973 default: 00974 if (linenoiseEditInsert(&l,c)) return -1; 00975 break; 00976 case CTRL_U: /* Ctrl+u, delete the whole line. */ 00977 buf[0] = '0円'; 00978 l.pos = l.len = 0; 00979 refreshLine(&l); 00980 break; 00981 case CTRL_K: /* Ctrl+k, delete from current to end of line. */ 00982 buf[l.pos] = '0円'; 00983 l.len = l.pos; 00984 refreshLine(&l); 00985 break; 00986 case CTRL_A: /* Ctrl+a, go to the start of the line */ 00987 linenoiseEditMoveHome(&l); 00988 break; 00989 case CTRL_E: /* ctrl+e, go to the end of the line */ 00990 linenoiseEditMoveEnd(&l); 00991 break; 00992 case CTRL_L: /* ctrl+l, clear screen */ 00993 linenoiseClearScreen(); 00994 refreshLine(&l); 00995 break; 00996 case CTRL_W: /* ctrl+w, delete previous word */ 00997 linenoiseEditDeletePrevWord(&l); 00998 break; 00999 } 01000 } 01001 return l.len; 01002 } 01003 01004 /* This special mode is used by linenoise in order to print scan codes 01005 * on screen for debugging / development purposes. It is implemented 01006 * by the linenoise_example program using the --keycodes option. */ 01007 void linenoisePrintKeyCodes(void) { 01008 char quit[4]; 01009 01010 printf("Linenoise key codes debugging mode.\n" 01011 "Press keys to see scan codes. Type 'quit' at any time to exit.\n"); 01012 if (enableRawMode(STDIN_FILENO, 1) == -1) return; 01013 memset(quit,' ',4); 01014 while(1) { 01015 char c; 01016 int nread; 01017 01018 nread = read(STDIN_FILENO,&c,1); 01019 if (nread <= 0) continue; 01020 memmove(quit,quit+1,sizeof(quit)-1); /* shift string to left. */ 01021 quit[sizeof(quit)-1] = c; /* Insert current char on the right. */ 01022 if (memcmp(quit,"quit",sizeof(quit)) == 0) break; 01023 01024 printf("'%c' %02x (%d) (type quit to exit)\n", 01025 isprint(c) ? c : '?', (int)c, (int)c); 01026 printf("\r"); /* Go left edge manually, we are in raw mode. */ 01027 fflush(stdout); 01028 } 01029 disableRawMode(STDIN_FILENO, 1); 01030 } 01031 01032 /* This function calls the line editing function linenoiseEdit() using 01033 * the STDIN file descriptor set in raw mode. */ 01034 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) { 01035 int count; 01036 01037 if (buflen == 0) { 01038 errno = EINVAL; 01039 return -1; 01040 } 01041 01042 if (enableRawMode(STDIN_FILENO, 0) == -1) return -1; 01043 count = linenoiseEdit(STDIN_FILENO, STDOUT_FILENO, buf, buflen, prompt); 01044 disableRawMode(STDIN_FILENO, 1); 01045 printf("\n"); 01046 return count; 01047 } 01048 01049 /* This function is called when linenoise() is called with the standard 01050 * input file descriptor not attached to a TTY. So for example when the 01051 * program using linenoise is called in pipe or with a file redirected 01052 * to its standard input. In this case, we want to be able to return the 01053 * line regardless of its length (by default we are limited to 4k). */ 01054 static char *linenoiseNoTTY(void) { 01055 char *line = NULL; 01056 size_t len = 0, maxlen = 0; 01057 01058 while(1) { 01059 if (len == maxlen) { 01060 if (maxlen == 0) maxlen = 16; 01061 maxlen *= 2; 01062 char *oldval = line; 01063 line = realloc(line,maxlen); 01064 if (line == NULL) { 01065 if (oldval) free(oldval); 01066 return NULL; 01067 } 01068 } 01069 int c = fgetc(stdin); 01070 if (c == EOF || c == '\n') { 01071 if (c == EOF && len == 0) { 01072 free(line); 01073 return NULL; 01074 } else { 01075 line[len] = '0円'; 01076 return line; 01077 } 01078 } else { 01079 line[len] = c; 01080 len++; 01081 } 01082 } 01083 } 01084 01085 /* The high level function that is the main API of the linenoise library. 01086 * This function checks if the terminal has basic capabilities, just checking 01087 * for a blacklist of stupid terminals, and later either calls the line 01088 * editing function or uses dummy fgets() so that you will be able to type 01089 * something even in the most desperate of the conditions. */ 01090 char *linenoise(const char *prompt) { 01091 char buf[LINENOISE_MAX_LINE]; 01092 int count; 01093 01094 if (!isatty(STDIN_FILENO)) { 01095 /* Not a tty: read from file / pipe. In this mode we don't want any 01096 * limit to the line size, so we call a function to handle that. */ 01097 return linenoiseNoTTY(); 01098 } else if (isUnsupportedTerm()) { 01099 size_t len; 01100 01101 printf("%s",prompt); 01102 fflush(stdout); 01103 if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL; 01104 len = strlen(buf); 01105 while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) { 01106 len--; 01107 buf[len] = '0円'; 01108 } 01109 return strdup(buf); 01110 } else { 01111 count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt); 01112 if (count == -1) return NULL; 01113 return strdup(buf); 01114 } 01115 } 01116 01117 /* This is just a wrapper the user may want to call in order to make sure 01118 * the linenoise returned buffer is freed with the same allocator it was 01119 * created with. Useful when the main program is using an alternative 01120 * allocator. */ 01121 void linenoiseFree(void *ptr) { 01122 free(ptr); 01123 } 01124 01125 /* ================================ History ================================= */ 01126 01127 /* Free the history, but does not reset it. Only used when we have to 01128 * exit() to avoid memory leaks are reported by valgrind & co. */ 01129 static void freeHistory(void) { 01130 if (history) { 01131 int j; 01132 01133 for (j = 0; j < history_len; j++) 01134 free(history[j]); 01135 free(history); 01136 } 01137 } 01138 01139 /* At exit we'll try to fix the terminal to the initial conditions. */ 01140 static void linenoiseAtExit(void) { 01141 disableRawMode(STDIN_FILENO, 1); 01142 freeHistory(); 01143 } 01144 01145 /* This is the API call to add a new entry in the linenoise history. 01146 * It uses a fixed array of char pointers that are shifted (memmoved) 01147 * when the history max length is reached in order to remove the older 01148 * entry and make room for the new one, so it is not exactly suitable for huge 01149 * histories, but will work well for a few hundred of entries. 01150 * 01151 * Using a circular buffer is smarter, but a bit more complex to handle. */ 01152 int linenoiseHistoryAdd(const char *line) { 01153 char *linecopy; 01154 01155 if (history_max_len == 0) return 0; 01156 01157 /* Initialization on first call. */ 01158 if (history == NULL) { 01159 history = malloc(sizeof(char*)*history_max_len); 01160 if (history == NULL) return 0; 01161 memset(history,0,(sizeof(char*)*history_max_len)); 01162 } 01163 01164 /* Don't add duplicated lines. */ 01165 if (history_len && !strcmp(history[history_len-1], line)) return 0; 01166 01167 /* Add an heap allocated copy of the line in the history. 01168 * If we reached the max length, remove the older line. */ 01169 linecopy = strdup(line); 01170 if (!linecopy) return 0; 01171 if (history_len == history_max_len) { 01172 free(history[0]); 01173 memmove(history,history+1,sizeof(char*)*(history_max_len-1)); 01174 history_len--; 01175 } 01176 history[history_len] = linecopy; 01177 history_len++; 01178 return 1; 01179 } 01180 01181 /* Set the maximum length for the history. This function can be called even 01182 * if there is already some history, the function will make sure to retain 01183 * just the latest 'len' elements if the new history length value is smaller 01184 * than the amount of items already inside the history. */ 01185 int linenoiseHistorySetMaxLen(int len) { 01186 char **new; 01187 01188 if (len < 1) return 0; 01189 if (history) { 01190 int tocopy = history_len; 01191 01192 new = malloc(sizeof(char*)*len); 01193 if (new == NULL) return 0; 01194 01195 /* If we can't copy everything, free the elements we'll not use. */ 01196 if (len < tocopy) { 01197 int j; 01198 01199 for (j = 0; j < tocopy-len; j++) free(history[j]); 01200 tocopy = len; 01201 } 01202 memset(new,0,sizeof(char*)*len); 01203 memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy); 01204 free(history); 01205 history = new; 01206 } 01207 history_max_len = len; 01208 if (history_len > history_max_len) 01209 history_len = history_max_len; 01210 return 1; 01211 } 01212 01213 /* Save the history in the specified file. On success 0 is returned 01214 * otherwise -1 is returned. */ 01215 int linenoiseHistorySave(const char *filename) { 01216 mode_t old_umask = umask(S_IXUSR|S_IRWXG|S_IRWXO); 01217 FILE *fp; 01218 int j; 01219 01220 fp = fopen(filename,"w"); 01221 umask(old_umask); 01222 if (fp == NULL) return -1; 01223 chmod(filename,S_IRUSR|S_IWUSR); 01224 for (j = 0; j < history_len; j++) 01225 fprintf(fp,"%s\n",history[j]); 01226 fclose(fp); 01227 return 0; 01228 } 01229 01230 /* Load the history from the specified file. If the file does not exist 01231 * zero is returned and no operation is performed. 01232 * 01233 * If the file exists and the operation succeeded 0 is returned, otherwise 01234 * on error -1 is returned. */ 01235 int linenoiseHistoryLoad(const char *filename) { 01236 FILE *fp = fopen(filename,"r"); 01237 char buf[LINENOISE_MAX_LINE]; 01238 01239 if (fp == NULL) return -1; 01240 01241 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) { 01242 char *p; 01243 01244 p = strchr(buf,'\r'); 01245 if (!p) p = strchr(buf,'\n'); 01246 if (p) *p = '0円'; 01247 linenoiseHistoryAdd(buf); 01248 } 01249 fclose(fp); 01250 return 0; 01251 }