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