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.
4 * You can find the latest source code at:
6 * http://github.com/msteveb/linenoise
7 * (forked from http://github.com/antirez/linenoise)
9 * Does a number of crazy assumptions that happen to be true in 99.9999% of
10 * the 2010 UNIX computers around.
12 * ------------------------------------------------------------------------
14 * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
15 * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
16 * Copyright (c) 2011, Steve Bennett <steveb at workware dot net dot au>
18 * All rights reserved.
20 * Redistribution and use in source and binary forms, with or without
21 * modification, are permitted provided that the following conditions are
24 * * Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
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.
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.
43 * ------------------------------------------------------------------------
46 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
47 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
54 * List of escape sequences used by this program, we do everything just
55 * a few 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.
59 * CHA (Cursor Horizontal Absolute)
61 * Effect: moves cursor to column n (1 based)
65 * Effect: if n is 0 or missing, clear from cursor to end of line
66 * Effect: if n is 1, clear from beginning of line to cursor
67 * Effect: if n is 2, clear entire line
69 * CUF (CUrsor Forward)
71 * Effect: moves cursor forward of n chars
73 * The following are used to clear the screen: ESC [ H ESC [ 2 J
74 * This is actually composed of two sequences:
78 * Effect: moves the cursor to upper left corner
80 * ED2 (Clear entire screen)
82 * Effect: clear the whole screen
84 * == For highlighting control characters, we also use the following two ==
87 * Effect: Uses some standout mode such as reverse video
91 * Effect: Exit standout mode
93 * == Only used if TIOCGWINSZ fails ==
94 * DSR/CPR (Report cursor position)
96 * Effect: reports current cursor position as ESC [ NNN ; MMM R
100 * If __MINGW32__ is defined, the win32 console API is used.
101 * This could probably be made to work for the msvc compiler too.
102 * This support based in part on work by Jon Griffiths.
108 #define USE_WINCONSOLE
111 #include <sys/ioctl.h>
112 #include <sys/poll.h>
123 #include <sys/types.h>
126 #include "linenoise.h"
129 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
130 #define LINENOISE_MAX_LINE 4096
132 #define ctrl(C) ((C) - '@')
134 /* Use -ve numbers here to co-exist with normal unicode chars */
141 SPECIAL_DELETE = -24,
146 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
147 static int history_len = 0;
148 static char **history = NULL;
150 /* Structure to contain the status of the current (being edited) line */
152 char *buf; /* Current buffer. Always null terminated */
153 int bufmax; /* Size of the buffer, including space for the null termination */
154 int len; /* Number of bytes in 'buf' */
155 int chars; /* Number of chars in 'buf' (utf-8 chars) */
156 int pos; /* Cursor position, measured in chars */
157 int cols; /* Size of the window, in chars */
159 #if defined(USE_TERMIOS)
160 int fd; /* Terminal fd */
161 #elif defined(USE_WINCONSOLE)
162 HANDLE outh; /* Console output handle */
163 HANDLE inh; /* Console input handle */
164 int rows; /* Screen rows */
165 int x; /* Current column during output */
166 int y; /* Current row */
170 static int fd_read(struct current *current);
171 static int getWindowSize(struct current *current);
173 void linenoiseHistoryFree(void) {
177 for (j = 0; j < history_len; j++)
184 #if defined(USE_TERMIOS)
185 static void linenoiseAtExit(void);
186 static struct termios orig_termios; /* in order to restore at exit */
187 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
188 static int atexit_registered = 0; /* register atexit just 1 time */
190 static const char *unsupported_term[] = {"dumb","cons25",NULL};
192 static int isUnsupportedTerm(void) {
193 char *term = getenv("TERM");
197 for (j = 0; unsupported_term[j]; j++) {
198 if (strcasecmp(term, unsupported_term[j]) == 0) {
206 static int enableRawMode(struct current *current) {
209 current->fd = STDIN_FILENO;
211 if (!isatty(current->fd) || isUnsupportedTerm() ||
212 tcgetattr(current->fd, &orig_termios) == -1) {
218 if (!atexit_registered) {
219 atexit(linenoiseAtExit);
220 atexit_registered = 1;
223 raw = orig_termios; /* modify the original mode */
224 /* input modes: no break, no CR to NL, no parity check, no strip char,
225 * no start/stop output control. */
226 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
227 /* output modes - disable post processing */
228 raw.c_oflag &= ~(OPOST);
229 /* control modes - set 8 bit chars */
230 raw.c_cflag |= (CS8);
231 /* local modes - choing off, canonical off, no extended functions,
232 * no signal chars (^Z,^C) */
233 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
234 /* control chars - set return condition: min number of bytes and timer.
235 * We want read to return every single byte, without timeout. */
236 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
238 /* put terminal in raw mode after flushing */
239 if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
248 static void disableRawMode(struct current *current) {
249 /* Don't even check the return value as it's too late. */
250 if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
254 /* At exit we'll try to fix the terminal to the initial conditions. */
255 static void linenoiseAtExit(void) {
257 tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
259 linenoiseHistoryFree();
262 /* gcc/glibc insists that we care about the return code of write! */
263 #define IGNORE_RC(EXPR) if (EXPR) {}
265 /* This is fdprintf() on some systems, but use a different
266 * name to avoid conflicts
268 static void fd_printf(int fd, const char *format, ...)
274 va_start(args, format);
275 n = vsnprintf(buf, sizeof(buf), format, args);
277 IGNORE_RC(write(fd, buf, n));
280 static void clearScreen(struct current *current)
282 fd_printf(current->fd, "\x1b[H\x1b[2J");
285 static void cursorToLeft(struct current *current)
287 fd_printf(current->fd, "\x1b[1G");
290 static int outputChars(struct current *current, const char *buf, int len)
292 return write(current->fd, buf, len);
295 static void outputControlChar(struct current *current, char ch)
297 fd_printf(current->fd, "\033[7m^%c\033[0m", ch);
300 static void eraseEol(struct current *current)
302 fd_printf(current->fd, "\x1b[0K");
305 static void setCursorPos(struct current *current, int x)
307 fd_printf(current->fd, "\x1b[1G\x1b[%dC", x);
311 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
313 * A timeout of -1 means to wait forever.
315 * Returns -1 if no char is received within the time or an error occurs.
317 static int fd_read_char(int fd, int timeout)
325 if (poll(&p, 1, timeout) == 0) {
329 if (read(fd, &c, 1) != 1) {
336 * Reads a complete utf-8 character
337 * and returns the unicode value, or -1 on error.
339 static int fd_read(struct current *current)
347 if (read(current->fd, &buf[0], 1) != 1) {
350 n = utf8_charlen(buf[0]);
351 if (n < 1 || n > 3) {
354 for (i = 1; i < n; i++) {
355 if (read(current->fd, &buf[i], 1) != 1) {
360 /* decode and return the character */
361 utf8_tounicode(buf, &c);
364 return fd_read_char(current->fd, -1);
368 static int getWindowSize(struct current *current)
372 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
373 current->cols = ws.ws_col;
377 /* Failed to query the window size. Perhaps we are on a serial terminal.
378 * Try to query the width by sending the cursor as far to the right
379 * and reading back the cursor position.
380 * Note that this is only done once per call to linenoise rather than
381 * every time the line is refreshed for efficiency reasons.
383 if (current->cols == 0) {
386 /* Move cursor far right and report cursor position */
387 fd_printf(current->fd, "\x1b[999G" "\x1b[6n");
389 /* Parse the response: ESC [ rows ; cols R */
390 if (fd_read_char(current->fd, 100) == 0x1b && fd_read_char(current->fd, 100) == '[') {
393 int ch = fd_read_char(current->fd, 100);
398 else if (ch == 'R') {
400 if (n != 0 && n < 1000) {
405 else if (ch >= 0 && ch <= '9') {
406 n = n * 10 + ch - '0';
418 * If escape (27) was received, reads subsequent
419 * chars to determine if this is a known special key.
421 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
423 * If no additional char is received within a short time,
426 static int check_special(int fd)
428 int c = fd_read_char(fd, 50);
435 c2 = fd_read_char(fd, 50);
439 if (c == '[' || c == 'O') {
440 /* Potential arrow key */
447 return SPECIAL_RIGHT;
456 if (c == '[' && c2 >= '1' && c2 <= '8') {
457 /* extended escape */
458 c = fd_read_char(fd, 50);
462 return SPECIAL_DELETE;
469 while (c != -1 && c != '~') {
470 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
471 c = fd_read_char(fd, 50);
477 #elif defined(USE_WINCONSOLE)
479 static DWORD orig_consolemode = 0;
481 static int enableRawMode(struct current *current) {
485 current->outh = GetStdHandle(STD_OUTPUT_HANDLE);
486 current->inh = GetStdHandle(STD_INPUT_HANDLE);
488 if (!PeekConsoleInput(current->inh, &irec, 1, &n)) {
491 if (getWindowSize(current) != 0) {
494 if (GetConsoleMode(current->inh, &orig_consolemode)) {
495 SetConsoleMode(current->inh, ENABLE_PROCESSED_INPUT);
500 static void disableRawMode(struct current *current)
502 SetConsoleMode(current->inh, orig_consolemode);
505 static void clearScreen(struct current *current)
507 COORD topleft = { 0, 0 };
510 FillConsoleOutputCharacter(current->outh, ' ',
511 current->cols * current->rows, topleft, &n);
512 FillConsoleOutputAttribute(current->outh,
513 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN,
514 current->cols * current->rows, topleft, &n);
515 SetConsoleCursorPosition(current->outh, topleft);
518 static void cursorToLeft(struct current *current)
520 COORD pos = { 0, current->y };
523 FillConsoleOutputAttribute(current->outh,
524 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, current->cols, pos, &n);
528 static int outputChars(struct current *current, const char *buf, int len)
530 COORD pos = { current->x, current->y };
531 WriteConsoleOutputCharacter(current->outh, buf, len, pos, 0);
536 static void outputControlChar(struct current *current, char ch)
538 COORD pos = { current->x, current->y };
541 FillConsoleOutputAttribute(current->outh, BACKGROUND_INTENSITY, 2, pos, &n);
542 outputChars(current, "^", 1);
543 outputChars(current, &ch, 1);
546 static void eraseEol(struct current *current)
548 COORD pos = { current->x, current->y };
551 FillConsoleOutputCharacter(current->outh, ' ', current->cols - current->x, pos, &n);
554 static void setCursorPos(struct current *current, int x)
556 COORD pos = { x, current->y };
558 SetConsoleCursorPosition(current->outh, pos);
562 static int fd_read(struct current *current)
567 if (WaitForSingleObject(current->inh, INFINITE) != WAIT_OBJECT_0) {
570 if (!ReadConsoleInput (current->inh, &irec, 1, &n)) {
573 if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown) {
574 KEY_EVENT_RECORD *k = &irec.Event.KeyEvent;
575 if (k->dwControlKeyState & ENHANCED_KEY) {
576 switch (k->wVirtualKeyCode) {
580 return SPECIAL_RIGHT;
586 return SPECIAL_DELETE;
593 /* Note that control characters are already translated in AsciiChar */
596 return k->uChar.UnicodeChar;
598 return k->uChar.AsciiChar;
606 static int getWindowSize(struct current *current)
608 CONSOLE_SCREEN_BUFFER_INFO info;
609 if (!GetConsoleScreenBufferInfo(current->outh, &info)) {
612 current->cols = info.dwSize.X;
613 current->rows = info.dwSize.Y;
614 if (current->cols <= 0 || current->rows <= 0) {
618 current->y = info.dwCursorPosition.Y;
619 current->x = info.dwCursorPosition.X;
624 static int utf8_getchars(char *buf, int c)
627 return utf8_fromunicode(buf, c);
635 * Returns the unicode character at the given offset,
638 static int get_char(struct current *current, int pos)
640 if (pos >= 0 && pos < current->chars) {
642 int i = utf8_index(current->buf, pos);
643 (void)utf8_tounicode(current->buf + i, &c);
649 static void refreshLine(const char *prompt, struct current *current)
655 const char *buf = current->buf;
656 int chars = current->chars;
657 int pos = current->pos;
662 /* Should intercept SIGWINCH. For now, just get the size every time */
663 getWindowSize(current);
665 plen = strlen(prompt);
666 pchars = utf8_strlen(prompt, plen);
668 /* Account for a line which is too long to fit in the window.
669 * Note that control chars require an extra column
672 /* How many cols are required to the left of 'pos'?
673 * The prompt, plus one extra for each control char
675 n = pchars + utf8_strlen(buf, current->len);
677 for (i = 0; i < pos; i++) {
678 b += utf8_tounicode(buf + b, &ch);
684 /* If too many are need, strip chars off the front of 'buf'
685 * until it fits. Note that if the current char is a control character,
686 * we need one extra col.
688 if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
692 while (n >= current->cols) {
693 b = utf8_tounicode(buf, &ch);
703 /* Cursor to left edge, then the prompt */
704 cursorToLeft(current);
705 outputChars(current, prompt, plen);
707 /* Now the current buffer content */
709 /* Need special handling for control characters.
710 * If we hit 'cols', stop.
712 b = 0; /* unwritted bytes */
713 n = 0; /* How many control chars were written */
714 for (i = 0; i < chars; i++) {
716 int w = utf8_tounicode(buf + b, &ch);
720 if (pchars + i + n >= current->cols) {
724 /* A control character, so write the buffer so far */
725 outputChars(current, buf, b);
728 outputControlChar(current, ch + '@');
737 outputChars(current, buf, b);
739 /* Erase to right, move cursor to original position */
741 setCursorPos(current, pos + pchars + backup);
744 static void set_current(struct current *current, const char *str)
746 strncpy(current->buf, str, current->bufmax);
747 current->buf[current->bufmax - 1] = 0;
748 current->len = strlen(current->buf);
749 current->pos = current->chars = utf8_strlen(current->buf, current->len);
752 static int has_room(struct current *current, int bytes)
754 return current->len + bytes < current->bufmax - 1;
758 * Removes the char at 'pos'.
760 * Returns 1 if the line needs to be refreshed, 2 if not
761 * and 0 if nothing was removed
763 static int remove_char(struct current *current, int pos)
765 if (pos >= 0 && pos < current->chars) {
768 p1 = utf8_index(current->buf, pos);
769 p2 = p1 + utf8_index(current->buf + p1, 1);
772 /* optimise remove char in the case of removing the last char */
773 if (current->pos == pos + 1 && current->pos == current->chars) {
774 if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
776 fd_printf(current->fd, "\b \b");
781 /* Move the null char too */
782 memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
783 current->len -= (p2 - p1);
786 if (current->pos > pos) {
795 * Insert 'ch' at position 'pos'
797 * Returns 1 if the line needs to be refreshed, 2 if not
798 * and 0 if nothing was inserted (no room)
800 static int insert_char(struct current *current, int pos, int ch)
803 int n = utf8_getchars(buf, ch);
805 if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
808 p1 = utf8_index(current->buf, pos);
812 /* optimise the case where adding a single char to the end and no scrolling is needed */
813 if (current->pos == pos && current->chars == pos) {
814 if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
815 IGNORE_RC(write(current->fd, buf, n));
821 memmove(current->buf + p2, current->buf + p1, current->len - p1);
822 memcpy(current->buf + p1, buf, n);
826 if (current->pos >= pos) {
835 * Returns 0 if no chars were removed or non-zero otherwise.
837 static int remove_chars(struct current *current, int pos, int n)
840 while (n-- && remove_char(current, pos)) {
846 #ifndef NO_COMPLETION
847 static linenoiseCompletionCallback *completionCallback = NULL;
851 fprintf(stderr, "\x7");
856 static void freeCompletions(linenoiseCompletions *lc) {
858 for (i = 0; i < lc->len; i++)
863 static int completeLine(struct current *current) {
864 linenoiseCompletions lc = { 0, NULL };
867 completionCallback(current->buf,&lc);
871 size_t stop = 0, i = 0;
874 /* Show completion or original buffer */
876 struct current tmp = *current;
877 tmp.buf = lc.cvec[i];
878 tmp.pos = tmp.len = strlen(tmp.buf);
879 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
880 refreshLine(current->prompt, &tmp);
882 refreshLine(current->prompt, current);
885 c = fd_read(current);
892 i = (i+1) % (lc.len+1);
893 if (i == lc.len) beep();
895 case 27: /* escape */
896 /* Re-show original buffer */
898 refreshLine(current->prompt, current);
903 /* Update buffer and return */
905 set_current(current,lc.cvec[i]);
913 freeCompletions(&lc);
914 return c; /* Return last read character */
917 /* Register a callback function to be called for tab-completion. */
918 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
919 completionCallback = fn;
922 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
923 lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
924 lc->cvec[lc->len++] = strdup(str);
929 static int linenoisePrompt(struct current *current) {
930 int history_index = 0;
932 /* The latest history entry is always our current buffer, that
933 * initially is just an empty string. */
934 linenoiseHistoryAdd("");
936 set_current(current, "");
937 refreshLine(current->prompt, current);
941 int c = fd_read(current);
943 #ifndef NO_COMPLETION
944 /* Only autocomplete when the callback is set. It returns < 0 when
945 * there was an error reading from fd. Otherwise it will return the
946 * character that should be handled next. */
947 if (c == 9 && completionCallback != NULL) {
948 c = completeLine(current);
949 /* Return on errors */
950 if (c < 0) return current->len;
951 /* Read next character when 0 */
952 if (c == 0) continue;
957 if (c == -1) return current->len;
959 if (c == 27) { /* escape sequence */
960 c = check_special(current->fd);
964 case '\r': /* enter */
966 free(history[history_len]);
968 case ctrl('C'): /* ctrl-c */
971 case 127: /* backspace */
973 if (remove_char(current, current->pos - 1) == 1) {
974 refreshLine(current->prompt, current);
977 case ctrl('D'): /* ctrl-d */
978 if (current->len == 0) {
979 /* Empty line, so EOF */
981 free(history[history_len]);
984 /* Otherwise fall through to delete char to right of cursor */
986 if (remove_char(current, current->pos) == 1) {
987 refreshLine(current->prompt, current);
990 case ctrl('W'): /* ctrl-w */
991 /* eat any spaces on the left */
993 int pos = current->pos;
994 while (pos > 0 && get_char(current, pos - 1) == ' ') {
998 /* now eat any non-spaces on the left */
999 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1003 if (remove_chars(current, pos, current->pos - pos)) {
1004 refreshLine(current->prompt, current);
1008 case ctrl('R'): /* ctrl-r */
1010 /* Display the reverse-i-search prompt and process chars */
1015 int searchpos = history_len - 1;
1020 const char *p = NULL;
1024 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1025 refreshLine(rprompt, current);
1026 c = fd_read(current);
1027 if (c == ctrl('H') || c == 127) {
1029 int p = utf8_index(rbuf, --rchars);
1031 rlen = strlen(rbuf);
1037 c = check_special(current->fd);
1040 if (c == ctrl('P') || c == SPECIAL_UP) {
1041 /* Search for the previous (earlier) match */
1042 if (searchpos > 0) {
1047 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1048 /* Search for the next (later) match */
1049 if (searchpos < history_len) {
1055 else if (c >= ' ') {
1056 if (rlen >= (int)sizeof(rbuf) + 3) {
1060 n = utf8_getchars(rbuf + rlen, c);
1065 /* Adding a new char resets the search location */
1066 searchpos = history_len - 1;
1069 /* Exit from incremental search mode */
1073 /* Now search through the history for a match */
1074 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1075 p = strstr(history[searchpos], rbuf);
1078 if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
1079 /* But it is identical, so skip it */
1082 /* Copy the matching line and set the cursor position */
1083 set_current(current,history[searchpos]);
1084 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1089 /* No match, so don't add it */
1095 if (c == ctrl('G') || c == ctrl('C')) {
1096 /* ctrl-g terminates the search with no effect */
1097 set_current(current, "");
1100 else if (c == ctrl('J')) {
1101 /* ctrl-j terminates the search leaving the buffer in place */
1104 /* Go process the char normally */
1105 refreshLine(current->prompt, current);
1109 case ctrl('T'): /* ctrl-t */
1110 if (current->pos > 0 && current->pos < current->chars) {
1111 c = get_char(current, current->pos);
1112 remove_char(current, current->pos);
1113 insert_char(current, current->pos - 1, c);
1114 refreshLine(current->prompt, current);
1117 case ctrl('V'): /* ctrl-v */
1118 if (has_room(current, 3)) {
1119 /* Insert the ^V first */
1120 if (insert_char(current, current->pos, c)) {
1121 refreshLine(current->prompt, current);
1122 /* Now wait for the next char. Can insert anything except \0 */
1123 c = fd_read(current);
1125 /* Remove the ^V first */
1126 remove_char(current, current->pos - 1);
1128 /* Insert the actual char */
1129 insert_char(current, current->pos, c);
1131 refreshLine(current->prompt, current);
1137 if (current->pos > 0) {
1139 refreshLine(current->prompt, current);
1144 if (current->pos < current->chars) {
1146 refreshLine(current->prompt, current);
1154 if (history_len > 1) {
1155 /* Update the current history entry before to
1156 * overwrite it with tne next one. */
1157 free(history[history_len-1-history_index]);
1158 history[history_len-1-history_index] = strdup(current->buf);
1159 /* Show the new entry */
1160 history_index += dir;
1161 if (history_index < 0) {
1164 } else if (history_index >= history_len) {
1165 history_index = history_len-1;
1168 set_current(current, history[history_len-1-history_index]);
1169 refreshLine(current->prompt, current);
1172 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1175 refreshLine(current->prompt, current);
1177 case ctrl('E'): /* ctrl+e, go to the end of the line */
1179 current->pos = current->chars;
1180 refreshLine(current->prompt, current);
1182 case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
1183 if (remove_chars(current, 0, current->pos)) {
1184 refreshLine(current->prompt, current);
1187 case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
1188 if (remove_chars(current, current->pos, current->chars - current->pos)) {
1189 refreshLine(current->prompt, current);
1192 case ctrl('L'): /* Ctrl+L, clear screen */
1193 clearScreen(current);
1194 /* Force recalc of window size for serial terminals */
1196 refreshLine(current->prompt, current);
1199 /* Only tab is allowed without ^V */
1200 if (c == '\t' || c >= ' ') {
1201 if (insert_char(current, current->pos, c) == 1) {
1202 refreshLine(current->prompt, current);
1208 return current->len;
1211 char *linenoise(const char *prompt)
1214 struct current current;
1215 char buf[LINENOISE_MAX_LINE];
1217 if (enableRawMode(¤t) == -1) {
1218 printf("%s", prompt);
1220 if (fgets(buf, sizeof(buf), stdin) == NULL) {
1223 count = strlen(buf);
1224 if (count && buf[count-1] == '\n') {
1232 current.bufmax = sizeof(buf);
1236 current.prompt = prompt;
1238 count = linenoisePrompt(¤t);
1239 disableRawMode(¤t);
1248 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1249 int linenoiseHistoryAdd(const char *line) {
1252 if (history_max_len == 0) return 0;
1253 if (history == NULL) {
1254 history = (char **)malloc(sizeof(char*)*history_max_len);
1255 if (history == NULL) return 0;
1256 memset(history,0,(sizeof(char*)*history_max_len));
1259 /* do not insert duplicate lines into history */
1260 if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1264 linecopy = strdup(line);
1265 if (!linecopy) return 0;
1266 if (history_len == history_max_len) {
1268 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1271 history[history_len] = linecopy;
1276 int linenoiseHistorySetMaxLen(int len) {
1279 if (len < 1) return 0;
1281 int tocopy = history_len;
1283 newHistory = (char **)malloc(sizeof(char*)*len);
1284 if (newHistory == NULL) return 0;
1285 if (len < tocopy) tocopy = len;
1286 memcpy(newHistory,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
1288 history = newHistory;
1290 history_max_len = len;
1291 if (history_len > history_max_len)
1292 history_len = history_max_len;
1296 /* Save the history in the specified file. On success 0 is returned
1297 * otherwise -1 is returned. */
1298 int linenoiseHistorySave(const char *filename) {
1299 FILE *fp = fopen(filename,"w");
1302 if (fp == NULL) return -1;
1303 for (j = 0; j < history_len; j++) {
1304 const char *str = history[j];
1305 /* Need to encode backslash, nl and cr */
1310 else if (*str == '\n') {
1313 else if (*str == '\r') {
1328 /* Load the history from the specified file. If the file does not exist
1329 * zero is returned and no operation is performed.
1331 * If the file exists and the operation succeeded 0 is returned, otherwise
1332 * on error -1 is returned. */
1333 int linenoiseHistoryLoad(const char *filename) {
1334 FILE *fp = fopen(filename,"r");
1335 char buf[LINENOISE_MAX_LINE];
1337 if (fp == NULL) return -1;
1339 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1342 /* Decode backslash escaped values */
1343 for (src = dest = buf; *src; src++) {
1351 else if (*src == 'r') {
1359 /* Remove trailing newline */
1360 if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1365 linenoiseHistoryAdd(buf);
1371 /* Provide access to the history buffer.
1373 * If 'len' is not NULL, the length is stored in *len.
1375 char **linenoiseHistory(int *len) {