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