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/antirez/linenoise
8 * Does a number of crazy assumptions that happen to be true in 99.9999% of
9 * the 2010 UNIX computers around.
11 * ------------------------------------------------------------------------
13 * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
14 * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
16 * All rights reserved.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
22 * * Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
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.
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.
41 * ------------------------------------------------------------------------
44 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
45 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
49 * - Save and load history containing newlines
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
102 #define USE_WINCONSOLE
105 #include <sys/ioctl.h>
106 #include <sys/poll.h>
117 #include <sys/types.h>
120 #include "linenoise.h"
123 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
124 #define LINENOISE_MAX_LINE 4096
126 #define ctrl(C) ((C) - '@')
128 /* Use -ve numbers here to co-exist with normal unicode chars */
135 SPECIAL_DELETE = -24,
140 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
141 static int history_len = 0;
142 static char **history = NULL;
144 /* Structure to contain the status of the current (being edited) line */
146 char *buf; /* Current buffer. Always null terminated */
147 int bufmax; /* Size of the buffer, including space for the null termination */
148 int len; /* Number of bytes in 'buf' */
149 int chars; /* Number of chars in 'buf' (utf-8 chars) */
150 int pos; /* Cursor position, measured in chars */
151 int cols; /* Size of the window, in chars */
153 #if defined(USE_TERMIOS)
154 int fd; /* Terminal fd */
155 #elif defined(USE_WINCONSOLE)
156 HANDLE outh; /* Console output handle */
157 HANDLE inh; /* Console input handle */
158 int rows; /* Screen rows */
159 int x; /* Current column during output */
160 int y; /* Current row */
164 static int fd_read(struct current *current);
165 static int getWindowSize(struct current *current);
167 void linenoiseHistoryFree(void) {
171 for (j = 0; j < history_len; j++)
178 #if defined(USE_TERMIOS)
179 static void linenoiseAtExit(void);
180 static struct termios orig_termios; /* in order to restore at exit */
181 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
182 static int atexit_registered = 0; /* register atexit just 1 time */
184 static const char *unsupported_term[] = {"dumb","cons25",NULL};
186 static int isUnsupportedTerm(void) {
187 char *term = getenv("TERM");
191 for (j = 0; unsupported_term[j]; j++) {
192 if (strcasecmp(term, unsupported_term[j]) == 0) {
200 static int enableRawMode(struct current *current) {
203 current->fd = STDIN_FILENO;
205 if (!isatty(current->fd) || isUnsupportedTerm() ||
206 tcgetattr(current->fd, &orig_termios) == -1) {
212 if (!atexit_registered) {
213 atexit(linenoiseAtExit);
214 atexit_registered = 1;
217 raw = orig_termios; /* modify the original mode */
218 /* input modes: no break, no CR to NL, no parity check, no strip char,
219 * no start/stop output control. */
220 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
221 /* output modes - disable post processing */
222 raw.c_oflag &= ~(OPOST);
223 /* control modes - set 8 bit chars */
224 raw.c_cflag |= (CS8);
225 /* local modes - choing off, canonical off, no extended functions,
226 * no signal chars (^Z,^C) */
227 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
228 /* control chars - set return condition: min number of bytes and timer.
229 * We want read to return every single byte, without timeout. */
230 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
232 /* put terminal in raw mode after flushing */
233 if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
242 static void disableRawMode(struct current *current) {
243 /* Don't even check the return value as it's too late. */
244 if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
248 /* At exit we'll try to fix the terminal to the initial conditions. */
249 static void linenoiseAtExit(void) {
251 tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
253 linenoiseHistoryFree();
256 /* gcc/glibc insists that we care about the return code of write! */
257 #define IGNORE_RC(EXPR) if (EXPR) {}
259 /* This is fdprintf() on some systems, but use a different
260 * name to avoid conflicts
262 static void fd_printf(int fd, const char *format, ...)
268 va_start(args, format);
269 n = vsnprintf(buf, sizeof(buf), format, args);
271 IGNORE_RC(write(fd, buf, n));
274 static void clearScreen(struct current *current)
276 fd_printf(current->fd, "\x1b[H\x1b[2J");
279 static void cursorToLeft(struct current *current)
281 fd_printf(current->fd, "\x1b[1G");
284 static int outputChars(struct current *current, const char *buf, int len)
286 return write(current->fd, buf, len);
289 static void outputControlChar(struct current *current, char ch)
291 fd_printf(current->fd, "\033[7m^%c\033[0m", ch);
294 static void eraseEol(struct current *current)
296 fd_printf(current->fd, "\x1b[0K");
299 static void setCursorPos(struct current *current, int x)
301 fd_printf(current->fd, "\x1b[1G\x1b[%dC", x);
305 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
307 * A timeout of -1 means to wait forever.
309 * Returns -1 if no char is received within the time or an error occurs.
311 static int fd_read_char(int fd, int timeout)
319 if (poll(&p, 1, timeout) == 0) {
323 if (read(fd, &c, 1) != 1) {
330 * Reads a complete utf-8 character
331 * and returns the unicode value, or -1 on error.
333 static int fd_read(struct current *current)
341 if (read(current->fd, &buf[0], 1) != 1) {
344 n = utf8_charlen(buf[0]);
345 if (n < 1 || n > 3) {
348 for (i = 1; i < n; i++) {
349 if (read(current->fd, &buf[i], 1) != 1) {
354 /* decode and return the character */
355 utf8_tounicode(buf, &c);
358 return fd_read_char(current->fd, -1);
362 static int getWindowSize(struct current *current)
366 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
367 current->cols = ws.ws_col;
371 /* Failed to query the window size. Perhaps we are on a serial terminal.
372 * Try to query the width by sending the cursor as far to the right
373 * and reading back the cursor position.
374 * Note that this is only done once per call to linenoise rather than
375 * every time the line is refreshed for efficiency reasons.
377 if (current->cols == 0) {
380 /* Move cursor far right and report cursor position */
381 fd_printf(current->fd, "\x1b[999G" "\x1b[6n");
383 /* Parse the response: ESC [ rows ; cols R */
384 if (fd_read_char(current->fd, 100) == 0x1b && fd_read_char(current->fd, 100) == '[') {
387 int ch = fd_read_char(current->fd, 100);
392 else if (ch == 'R') {
394 if (n != 0 && n < 1000) {
399 else if (ch >= 0 && ch <= '9') {
400 n = n * 10 + ch - '0';
412 * If escape (27) was received, reads subsequent
413 * chars to determine if this is a known special key.
415 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
417 * If no additional char is received within a short time,
420 static int check_special(int fd)
422 int c = fd_read_char(fd, 50);
429 c2 = fd_read_char(fd, 50);
433 if (c == '[' || c == 'O') {
434 /* Potential arrow key */
441 return SPECIAL_RIGHT;
450 if (c == '[' && c2 >= '1' && c2 <= '6') {
451 /* extended escape */
452 int c3 = fd_read_char(fd, 50);
453 if (c2 == '3' && c3 == '~') {
454 /* delete char under cursor */
455 return SPECIAL_DELETE;
457 while (c3 != -1 && c3 != '~') {
458 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
459 c3 = fd_read_char(fd, 50);
465 #elif defined(USE_WINCONSOLE)
467 static DWORD orig_consolemode = 0;
469 static int enableRawMode(struct current *current) {
473 current->outh = GetStdHandle(STD_OUTPUT_HANDLE);
474 current->inh = GetStdHandle(STD_INPUT_HANDLE);
476 if (!PeekConsoleInput(current->inh, &irec, 1, &n)) {
479 if (getWindowSize(current) != 0) {
482 if (GetConsoleMode(current->inh, &orig_consolemode)) {
483 SetConsoleMode(current->inh, ENABLE_PROCESSED_INPUT);
488 static void disableRawMode(struct current *current)
490 SetConsoleMode(current->inh, orig_consolemode);
493 static void clearScreen(struct current *current)
495 COORD topleft = { 0, 0 };
498 FillConsoleOutputCharacter(current->outh, ' ',
499 current->cols * current->rows, topleft, &n);
500 FillConsoleOutputAttribute(current->outh,
501 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN,
502 current->cols * current->rows, topleft, &n);
503 SetConsoleCursorPosition(current->outh, topleft);
506 static void cursorToLeft(struct current *current)
508 COORD pos = { 0, current->y };
511 FillConsoleOutputAttribute(current->outh,
512 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, current->cols, pos, &n);
516 static int outputChars(struct current *current, const char *buf, int len)
518 COORD pos = { current->x, current->y };
519 WriteConsoleOutputCharacter(current->outh, buf, len, pos, 0);
524 static void outputControlChar(struct current *current, char ch)
526 COORD pos = { current->x, current->y };
529 FillConsoleOutputAttribute(current->outh, BACKGROUND_INTENSITY, 2, pos, &n);
530 outputChars(current, "^", 1);
531 outputChars(current, &ch, 1);
534 static void eraseEol(struct current *current)
536 COORD pos = { current->x, current->y };
539 FillConsoleOutputCharacter(current->outh, ' ', current->cols - current->x, pos, &n);
542 static void setCursorPos(struct current *current, int x)
544 COORD pos = { x, current->y };
546 SetConsoleCursorPosition(current->outh, pos);
550 static int fd_read(struct current *current)
555 if (WaitForSingleObject(current->inh, INFINITE) != WAIT_OBJECT_0) {
558 if (!ReadConsoleInput (current->inh, &irec, 1, &n)) {
561 if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown) {
562 KEY_EVENT_RECORD *k = &irec.Event.KeyEvent;
563 if (k->dwControlKeyState & ENHANCED_KEY) {
564 switch (k->wVirtualKeyCode) {
568 return SPECIAL_RIGHT;
574 return SPECIAL_DELETE;
581 /* Note that control characters are already translated in AsciiChar */
584 return k->uChar.UnicodeChar;
586 return k->uChar.AsciiChar;
594 static int getWindowSize(struct current *current)
596 CONSOLE_SCREEN_BUFFER_INFO info;
597 if (!GetConsoleScreenBufferInfo(current->outh, &info)) {
600 current->cols = info.dwSize.X;
601 current->rows = info.dwSize.Y;
602 if (current->cols <= 0 || current->rows <= 0) {
606 current->y = info.dwCursorPosition.Y;
607 current->x = info.dwCursorPosition.X;
612 static int utf8_getchars(char *buf, int c)
615 return utf8_fromunicode(buf, c);
623 * Returns the unicode character at the given offset,
626 static int get_char(struct current *current, int pos)
628 if (pos >= 0 && pos < current->chars) {
630 int i = utf8_index(current->buf, pos);
631 (void)utf8_tounicode(current->buf + i, &c);
637 static void refreshLine(const char *prompt, struct current *current)
643 const char *buf = current->buf;
644 int chars = current->chars;
645 int pos = current->pos;
650 /* Should intercept SIGWINCH. For now, just get the size every time */
651 getWindowSize(current);
653 plen = strlen(prompt);
654 pchars = utf8_strlen(prompt, plen);
656 /* Account for a line which is too long to fit in the window.
657 * Note that control chars require an extra column
660 /* How many cols are required to the left of 'pos'?
661 * The prompt, plus one extra for each control char
663 n = pchars + utf8_strlen(buf, current->len);
665 for (i = 0; i < pos; i++) {
666 b += utf8_tounicode(buf + b, &ch);
672 /* If too many are need, strip chars off the front of 'buf'
673 * until it fits. Note that if the current char is a control character,
674 * we need one extra col.
676 if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
680 while (n >= current->cols) {
681 b = utf8_tounicode(buf, &ch);
691 /* Cursor to left edge, then the prompt */
692 cursorToLeft(current);
693 outputChars(current, prompt, plen);
695 /* Now the current buffer content */
697 /* Need special handling for control characters.
698 * If we hit 'cols', stop.
700 b = 0; /* unwritted bytes */
701 n = 0; /* How many control chars were written */
702 for (i = 0; i < chars; i++) {
704 int w = utf8_tounicode(buf + b, &ch);
708 if (pchars + i + n >= current->cols) {
712 /* A control character, so write the buffer so far */
713 outputChars(current, buf, b);
716 outputControlChar(current, ch + '@');
725 outputChars(current, buf, b);
727 /* Erase to right, move cursor to original position */
729 setCursorPos(current, pos + pchars + backup);
732 static void set_current(struct current *current, const char *str)
734 strncpy(current->buf, str, current->bufmax);
735 current->buf[current->bufmax - 1] = 0;
736 current->len = strlen(current->buf);
737 current->pos = current->chars = utf8_strlen(current->buf, current->len);
740 static int has_room(struct current *current, int bytes)
742 return current->len + bytes < current->bufmax - 1;
746 * Removes the char at 'pos'.
748 * Returns 1 if the line needs to be refreshed, 2 if not
749 * and 0 if nothing was removed
751 static int remove_char(struct current *current, int pos)
753 if (pos >= 0 && pos < current->chars) {
756 p1 = utf8_index(current->buf, pos);
757 p2 = p1 + utf8_index(current->buf + p1, 1);
760 /* optimise remove char in the case of removing the last char */
761 if (current->pos == pos + 1 && current->pos == current->chars) {
762 if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
764 fd_printf(current->fd, "\b \b");
769 /* Move the null char too */
770 memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
771 current->len -= (p2 - p1);
774 if (current->pos > pos) {
783 * Insert 'ch' at position 'pos'
785 * Returns 1 if the line needs to be refreshed, 2 if not
786 * and 0 if nothing was inserted (no room)
788 static int insert_char(struct current *current, int pos, int ch)
791 int n = utf8_getchars(buf, ch);
793 if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
796 p1 = utf8_index(current->buf, pos);
800 /* optimise the case where adding a single char to the end and no scrolling is needed */
801 if (current->pos == pos && current->chars == pos) {
802 if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
803 IGNORE_RC(write(current->fd, buf, n));
809 memmove(current->buf + p2, current->buf + p1, current->len - p1);
810 memcpy(current->buf + p1, buf, n);
814 if (current->pos >= pos) {
823 * Returns 0 if no chars were removed or non-zero otherwise.
825 static int remove_chars(struct current *current, int pos, int n)
828 while (n-- && remove_char(current, pos)) {
834 #ifndef NO_COMPLETION
835 static linenoiseCompletionCallback *completionCallback = NULL;
839 fprintf(stderr, "\x7");
844 static void freeCompletions(linenoiseCompletions *lc) {
846 for (i = 0; i < lc->len; i++)
851 static int completeLine(struct current *current) {
852 linenoiseCompletions lc = { 0, NULL };
855 completionCallback(current->buf,&lc);
859 size_t stop = 0, i = 0;
862 /* Show completion or original buffer */
864 struct current tmp = *current;
865 tmp.buf = lc.cvec[i];
866 tmp.pos = tmp.len = strlen(tmp.buf);
867 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
868 refreshLine(current->prompt, &tmp);
870 refreshLine(current->prompt, current);
873 c = fd_read(current);
880 i = (i+1) % (lc.len+1);
881 if (i == lc.len) beep();
883 case 27: /* escape */
884 /* Re-show original buffer */
886 refreshLine(current->prompt, current);
891 /* Update buffer and return */
893 set_current(current,lc.cvec[i]);
901 freeCompletions(&lc);
902 return c; /* Return last read character */
905 /* Register a callback function to be called for tab-completion. */
906 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
907 completionCallback = fn;
910 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
911 lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
912 lc->cvec[lc->len++] = strdup(str);
917 static int linenoisePrompt(struct current *current) {
918 int history_index = 0;
920 /* The latest history entry is always our current buffer, that
921 * initially is just an empty string. */
922 linenoiseHistoryAdd("");
924 set_current(current, "");
925 refreshLine(current->prompt, current);
929 int c = fd_read(current);
931 #ifndef NO_COMPLETION
932 /* Only autocomplete when the callback is set. It returns < 0 when
933 * there was an error reading from fd. Otherwise it will return the
934 * character that should be handled next. */
935 if (c == 9 && completionCallback != NULL) {
936 c = completeLine(current);
937 /* Return on errors */
938 if (c < 0) return current->len;
939 /* Read next character when 0 */
940 if (c == 0) continue;
945 if (c == -1) return current->len;
947 if (c == 27) { /* escape sequence */
948 c = check_special(current->fd);
952 case '\r': /* enter */
954 free(history[history_len]);
956 case ctrl('C'): /* ctrl-c */
959 case 127: /* backspace */
961 if (remove_char(current, current->pos - 1) == 1) {
962 refreshLine(current->prompt, current);
965 case ctrl('D'): /* ctrl-d */
966 if (current->len == 0) {
967 /* Empty line, so EOF */
969 free(history[history_len]);
972 /* Otherwise delete char to right of cursor */
973 if (remove_char(current, current->pos)) {
974 refreshLine(current->prompt, current);
977 case ctrl('W'): /* ctrl-w */
978 /* eat any spaces on the left */
980 int pos = current->pos;
981 while (pos > 0 && get_char(current, pos - 1) == ' ') {
985 /* now eat any non-spaces on the left */
986 while (pos > 0 && get_char(current, pos - 1) != ' ') {
990 if (remove_chars(current, pos, current->pos - pos)) {
991 refreshLine(current->prompt, current);
995 case ctrl('R'): /* ctrl-r */
997 /* Display the reverse-i-search prompt and process chars */
1002 int searchpos = history_len - 1;
1007 const char *p = NULL;
1011 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1012 refreshLine(rprompt, current);
1013 c = fd_read(current);
1014 if (c == ctrl('H') || c == 127) {
1016 int p = utf8_index(rbuf, --rchars);
1018 rlen = strlen(rbuf);
1024 c = check_special(current->fd);
1027 if (c == ctrl('P') || c == SPECIAL_UP) {
1028 /* Search for the previous (earlier) match */
1029 if (searchpos > 0) {
1034 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1035 /* Search for the next (later) match */
1036 if (searchpos < history_len) {
1042 else if (c >= ' ') {
1043 if (rlen >= (int)sizeof(rbuf) + 3) {
1047 n = utf8_getchars(rbuf + rlen, c);
1052 /* Adding a new char resets the search location */
1053 searchpos = history_len - 1;
1056 /* Exit from incremental search mode */
1060 /* Now search through the history for a match */
1061 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1062 p = strstr(history[searchpos], rbuf);
1065 if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
1066 /* But it is identical, so skip it */
1069 /* Copy the matching line and set the cursor position */
1070 set_current(current,history[searchpos]);
1071 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1076 /* No match, so don't add it */
1082 if (c == ctrl('G') || c == ctrl('C')) {
1083 /* ctrl-g terminates the search with no effect */
1084 set_current(current, "");
1087 else if (c == ctrl('J')) {
1088 /* ctrl-j terminates the search leaving the buffer in place */
1091 /* Go process the char normally */
1092 refreshLine(current->prompt, current);
1096 case ctrl('T'): /* ctrl-t */
1097 if (current->pos > 0 && current->pos < current->chars) {
1098 c = get_char(current, current->pos);
1099 remove_char(current, current->pos);
1100 insert_char(current, current->pos - 1, c);
1101 refreshLine(current->prompt, current);
1104 case ctrl('V'): /* ctrl-v */
1105 if (has_room(current, 3)) {
1106 /* Insert the ^V first */
1107 if (insert_char(current, current->pos, c)) {
1108 refreshLine(current->prompt, current);
1109 /* Now wait for the next char. Can insert anything except \0 */
1110 c = fd_read(current);
1112 /* Remove the ^V first */
1113 remove_char(current, current->pos - 1);
1115 /* Insert the actual char */
1116 insert_char(current, current->pos, c);
1118 refreshLine(current->prompt, current);
1124 if (current->pos > 0) {
1126 refreshLine(current->prompt, current);
1131 if (current->pos < current->chars) {
1133 refreshLine(current->prompt, current);
1141 if (history_len > 1) {
1142 /* Update the current history entry before to
1143 * overwrite it with tne next one. */
1144 free(history[history_len-1-history_index]);
1145 history[history_len-1-history_index] = strdup(current->buf);
1146 /* Show the new entry */
1147 history_index += dir;
1148 if (history_index < 0) {
1151 } else if (history_index >= history_len) {
1152 history_index = history_len-1;
1155 set_current(current, history[history_len-1-history_index]);
1156 refreshLine(current->prompt, current);
1160 case SPECIAL_DELETE:
1161 if (remove_char(current, current->pos) == 1) {
1162 refreshLine(current->prompt, current);
1167 refreshLine(current->prompt, current);
1170 current->pos = current->chars;
1171 refreshLine(current->prompt, current);
1174 /* Only tab is allowed without ^V */
1175 if (c == '\t' || c >= ' ') {
1176 if (insert_char(current, current->pos, c) == 1) {
1177 refreshLine(current->prompt, current);
1181 case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
1182 if (remove_chars(current, 0, current->pos)) {
1183 refreshLine(current->prompt, current);
1186 case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
1187 if (remove_chars(current, current->pos, current->chars - current->pos)) {
1188 refreshLine(current->prompt, current);
1191 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1193 refreshLine(current->prompt, current);
1195 case ctrl('E'): /* ctrl+e, go to the end of the line */
1196 current->pos = current->chars;
1197 refreshLine(current->prompt, current);
1199 case ctrl('L'): /* Ctrl+L, clear screen */
1201 clearScreen(current);
1202 /* Force recalc of window size for serial terminals */
1204 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));
1258 linecopy = strdup(line);
1259 if (!linecopy) return 0;
1260 if (history_len == history_max_len) {
1262 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1265 history[history_len] = linecopy;
1270 int linenoiseHistorySetMaxLen(int len) {
1273 if (len < 1) return 0;
1275 int tocopy = history_len;
1277 newHistory = (char **)malloc(sizeof(char*)*len);
1278 if (newHistory == NULL) return 0;
1279 if (len < tocopy) tocopy = len;
1280 memcpy(newHistory,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
1282 history = newHistory;
1284 history_max_len = len;
1285 if (history_len > history_max_len)
1286 history_len = history_max_len;
1290 /* Save the history in the specified file. On success 0 is returned
1291 * otherwise -1 is returned. */
1292 int linenoiseHistorySave(const char *filename) {
1293 FILE *fp = fopen(filename,"w");
1296 if (fp == NULL) return -1;
1297 for (j = 0; j < history_len; j++) {
1298 const char *str = history[j];
1299 /* Need to encode backslash, nl and cr */
1304 else if (*str == '\n') {
1307 else if (*str == '\r') {
1322 /* Load the history from the specified file. If the file does not exist
1323 * zero is returned and no operation is performed.
1325 * If the file exists and the operation succeeded 0 is returned, otherwise
1326 * on error -1 is returned. */
1327 int linenoiseHistoryLoad(const char *filename) {
1328 FILE *fp = fopen(filename,"r");
1329 char buf[LINENOISE_MAX_LINE];
1331 if (fp == NULL) return -1;
1333 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1336 /* Decode backslash escaped values */
1337 for (src = dest = buf; *src; src++) {
1345 else if (*src == 'r') {
1353 /* Remove trailing newline */
1354 if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1359 linenoiseHistoryAdd(buf);
1365 /* Provide access to the history buffer.
1367 * If 'len' is not NULL, the length is stored in *len.
1369 char **linenoiseHistory(int *len) {