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.
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
65 * CUF (CUrsor Forward)
67 * Effect: moves cursor forward of n chars
69 * CR (Carriage Return)
71 * Effect: moves cursor to column 1
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.
105 #ifdef _WIN32 /* Windows platform, either MinGW or Visual Studio (MSVC) */
108 #define USE_WINCONSOLE
110 #define HAVE_UNISTD_H
112 /* Microsoft headers don't like old POSIX names */
113 #define strdup _strdup
114 #define snprintf _snprintf
118 #include <sys/ioctl.h>
119 #include <sys/poll.h>
121 #define HAVE_UNISTD_H
133 #include <sys/types.h>
135 #include "linenoise.h"
138 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
139 #define LINENOISE_MAX_LINE 4096
141 #define ctrl(C) ((C) - '@')
143 /* Use -ve numbers here to co-exist with normal unicode chars */
150 SPECIAL_DELETE = -24,
155 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
156 static int history_len = 0;
157 static char **history = NULL;
159 /* Structure to contain the status of the current (being edited) line */
161 char *buf; /* Current buffer. Always null terminated */
162 int bufmax; /* Size of the buffer, including space for the null termination */
163 int len; /* Number of bytes in 'buf' */
164 int chars; /* Number of chars in 'buf' (utf-8 chars) */
165 int pos; /* Cursor position, measured in chars */
166 int cols; /* Size of the window, in chars */
168 #if defined(USE_TERMIOS)
169 int fd; /* Terminal fd */
170 #elif defined(USE_WINCONSOLE)
171 HANDLE outh; /* Console output handle */
172 HANDLE inh; /* Console input handle */
173 int rows; /* Screen rows */
174 int x; /* Current column during output */
175 int y; /* Current row */
179 static int fd_read(struct current *current);
180 static int getWindowSize(struct current *current);
182 void linenoiseHistoryFree(void) {
186 for (j = 0; j < history_len; j++)
193 #if defined(USE_TERMIOS)
194 static void linenoiseAtExit(void);
195 static struct termios orig_termios; /* in order to restore at exit */
196 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
197 static int atexit_registered = 0; /* register atexit just 1 time */
199 static const char *unsupported_term[] = {"dumb","cons25",NULL};
201 static int isUnsupportedTerm(void) {
202 char *term = getenv("TERM");
206 for (j = 0; unsupported_term[j]; j++) {
207 if (strcasecmp(term, unsupported_term[j]) == 0) {
215 static int enableRawMode(struct current *current) {
218 current->fd = STDIN_FILENO;
220 if (!isatty(current->fd) || isUnsupportedTerm() ||
221 tcgetattr(current->fd, &orig_termios) == -1) {
227 if (!atexit_registered) {
228 atexit(linenoiseAtExit);
229 atexit_registered = 1;
232 raw = orig_termios; /* modify the original mode */
233 /* input modes: no break, no CR to NL, no parity check, no strip char,
234 * no start/stop output control. */
235 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
236 /* output modes - disable post processing */
237 raw.c_oflag &= ~(OPOST);
238 /* control modes - set 8 bit chars */
239 raw.c_cflag |= (CS8);
240 /* local modes - choing off, canonical off, no extended functions,
241 * no signal chars (^Z,^C) */
242 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
243 /* control chars - set return condition: min number of bytes and timer.
244 * We want read to return every single byte, without timeout. */
245 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
247 /* put terminal in raw mode after flushing */
248 if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
257 static void disableRawMode(struct current *current) {
258 /* Don't even check the return value as it's too late. */
259 if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
263 /* At exit we'll try to fix the terminal to the initial conditions. */
264 static void linenoiseAtExit(void) {
266 tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
268 linenoiseHistoryFree();
271 /* gcc/glibc insists that we care about the return code of write!
272 * Clarification: This means that a void-cast like "(void) (EXPR)"
275 #define IGNORE_RC(EXPR) if (EXPR) {}
277 /* This is fdprintf() on some systems, but use a different
278 * name to avoid conflicts
280 static void fd_printf(int fd, const char *format, ...)
286 va_start(args, format);
287 n = vsnprintf(buf, sizeof(buf), format, args);
289 IGNORE_RC(write(fd, buf, n));
292 static void clearScreen(struct current *current)
294 fd_printf(current->fd, "\x1b[H\x1b[2J");
297 static void cursorToLeft(struct current *current)
299 fd_printf(current->fd, "\r");
302 static int outputChars(struct current *current, const char *buf, int len)
304 return write(current->fd, buf, len);
307 static void outputControlChar(struct current *current, char ch)
309 fd_printf(current->fd, "\x1b[7m^%c\x1b[0m", ch);
312 static void eraseEol(struct current *current)
314 fd_printf(current->fd, "\x1b[0K");
317 static void setCursorPos(struct current *current, int x)
319 fd_printf(current->fd, "\r\x1b[%dC", x);
323 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
325 * A timeout of -1 means to wait forever.
327 * Returns -1 if no char is received within the time or an error occurs.
329 static int fd_read_char(int fd, int timeout)
337 if (poll(&p, 1, timeout) == 0) {
341 if (read(fd, &c, 1) != 1) {
348 * Reads a complete utf-8 character
349 * and returns the unicode value, or -1 on error.
351 static int fd_read(struct current *current)
359 if (read(current->fd, &buf[0], 1) != 1) {
362 n = utf8_charlen(buf[0]);
363 if (n < 1 || n > 3) {
366 for (i = 1; i < n; i++) {
367 if (read(current->fd, &buf[i], 1) != 1) {
372 /* decode and return the character */
373 utf8_tounicode(buf, &c);
376 return fd_read_char(current->fd, -1);
380 static int getWindowSize(struct current *current)
384 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
385 current->cols = ws.ws_col;
389 /* Failed to query the window size. Perhaps we are on a serial terminal.
390 * Try to query the width by sending the cursor as far to the right
391 * and reading back the cursor position.
392 * Note that this is only done once per call to linenoise rather than
393 * every time the line is refreshed for efficiency reasons.
395 if (current->cols == 0) {
398 /* Move cursor far right and report cursor position, then back to the left */
399 fd_printf(current->fd, "\x1b[999C" "\x1b[6n");
401 /* Parse the response: ESC [ rows ; cols R */
402 if (fd_read_char(current->fd, 100) == 0x1b && fd_read_char(current->fd, 100) == '[') {
405 int ch = fd_read_char(current->fd, 100);
410 else if (ch == 'R') {
412 if (n != 0 && n < 1000) {
417 else if (ch >= 0 && ch <= '9') {
418 n = n * 10 + ch - '0';
430 * If escape (27) was received, reads subsequent
431 * chars to determine if this is a known special key.
433 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
435 * If no additional char is received within a short time,
438 static int check_special(int fd)
440 int c = fd_read_char(fd, 50);
447 c2 = fd_read_char(fd, 50);
451 if (c == '[' || c == 'O') {
452 /* Potential arrow key */
459 return SPECIAL_RIGHT;
468 if (c == '[' && c2 >= '1' && c2 <= '8') {
469 /* extended escape */
470 c = fd_read_char(fd, 50);
474 return SPECIAL_DELETE;
481 while (c != -1 && c != '~') {
482 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
483 c = fd_read_char(fd, 50);
489 #elif defined(USE_WINCONSOLE)
491 static DWORD orig_consolemode = 0;
493 static int enableRawMode(struct current *current) {
497 current->outh = GetStdHandle(STD_OUTPUT_HANDLE);
498 current->inh = GetStdHandle(STD_INPUT_HANDLE);
500 if (!PeekConsoleInput(current->inh, &irec, 1, &n)) {
503 if (getWindowSize(current) != 0) {
506 if (GetConsoleMode(current->inh, &orig_consolemode)) {
507 SetConsoleMode(current->inh, ENABLE_PROCESSED_INPUT);
512 static void disableRawMode(struct current *current)
514 SetConsoleMode(current->inh, orig_consolemode);
517 static void clearScreen(struct current *current)
519 COORD topleft = { 0, 0 };
522 FillConsoleOutputCharacter(current->outh, ' ',
523 current->cols * current->rows, topleft, &n);
524 FillConsoleOutputAttribute(current->outh,
525 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN,
526 current->cols * current->rows, topleft, &n);
527 SetConsoleCursorPosition(current->outh, topleft);
530 static void cursorToLeft(struct current *current)
532 COORD pos = { 0, (SHORT)current->y };
535 FillConsoleOutputAttribute(current->outh,
536 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, current->cols, pos, &n);
540 static int outputChars(struct current *current, const char *buf, int len)
542 COORD pos = { (SHORT)current->x, (SHORT)current->y };
545 WriteConsoleOutputCharacter(current->outh, buf, len, pos, &n);
550 static void outputControlChar(struct current *current, char ch)
552 COORD pos = { (SHORT)current->x, (SHORT)current->y };
555 FillConsoleOutputAttribute(current->outh, BACKGROUND_INTENSITY, 2, pos, &n);
556 outputChars(current, "^", 1);
557 outputChars(current, &ch, 1);
560 static void eraseEol(struct current *current)
562 COORD pos = { (SHORT)current->x, (SHORT)current->y };
565 FillConsoleOutputCharacter(current->outh, ' ', current->cols - current->x, pos, &n);
568 static void setCursorPos(struct current *current, int x)
570 COORD pos = { (SHORT)x, (SHORT)current->y };
572 SetConsoleCursorPosition(current->outh, pos);
576 static int fd_read(struct current *current)
581 if (WaitForSingleObject(current->inh, INFINITE) != WAIT_OBJECT_0) {
584 if (!ReadConsoleInput (current->inh, &irec, 1, &n)) {
587 if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown) {
588 KEY_EVENT_RECORD *k = &irec.Event.KeyEvent;
589 if (k->dwControlKeyState & ENHANCED_KEY) {
590 switch (k->wVirtualKeyCode) {
594 return SPECIAL_RIGHT;
600 return SPECIAL_DELETE;
607 /* Note that control characters are already translated in AsciiChar */
610 return k->uChar.UnicodeChar;
612 return k->uChar.AsciiChar;
620 static int getWindowSize(struct current *current)
622 CONSOLE_SCREEN_BUFFER_INFO info;
623 if (!GetConsoleScreenBufferInfo(current->outh, &info)) {
626 current->cols = info.dwSize.X;
627 current->rows = info.dwSize.Y;
628 if (current->cols <= 0 || current->rows <= 0) {
632 current->y = info.dwCursorPosition.Y;
633 current->x = info.dwCursorPosition.X;
638 static int utf8_getchars(char *buf, int c)
641 return utf8_fromunicode(buf, c);
649 * Returns the unicode character at the given offset,
652 static int get_char(struct current *current, int pos)
654 if (pos >= 0 && pos < current->chars) {
656 int i = utf8_index(current->buf, pos);
657 (void)utf8_tounicode(current->buf + i, &c);
663 static void refreshLine(const char *prompt, struct current *current)
669 const char *buf = current->buf;
670 int chars = current->chars;
671 int pos = current->pos;
676 /* Should intercept SIGWINCH. For now, just get the size every time */
677 getWindowSize(current);
679 plen = strlen(prompt);
680 pchars = utf8_strlen(prompt, plen);
682 /* Account for a line which is too long to fit in the window.
683 * Note that control chars require an extra column
686 /* How many cols are required to the left of 'pos'?
687 * The prompt, plus one extra for each control char
689 n = pchars + utf8_strlen(buf, current->len);
691 for (i = 0; i < pos; i++) {
692 b += utf8_tounicode(buf + b, &ch);
698 /* If too many are need, strip chars off the front of 'buf'
699 * until it fits. Note that if the current char is a control character,
700 * we need one extra col.
702 if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
706 while (n >= current->cols && pos > 0) {
707 b = utf8_tounicode(buf, &ch);
717 /* Cursor to left edge, then the prompt */
718 cursorToLeft(current);
719 outputChars(current, prompt, plen);
721 /* Now the current buffer content */
723 /* Need special handling for control characters.
724 * If we hit 'cols', stop.
726 b = 0; /* unwritted bytes */
727 n = 0; /* How many control chars were written */
728 for (i = 0; i < chars; i++) {
730 int w = utf8_tounicode(buf + b, &ch);
734 if (pchars + i + n >= current->cols) {
738 /* A control character, so write the buffer so far */
739 outputChars(current, buf, b);
742 outputControlChar(current, ch + '@');
751 outputChars(current, buf, b);
753 /* Erase to right, move cursor to original position */
755 setCursorPos(current, pos + pchars + backup);
758 static void set_current(struct current *current, const char *str)
760 strncpy(current->buf, str, current->bufmax);
761 current->buf[current->bufmax - 1] = 0;
762 current->len = strlen(current->buf);
763 current->pos = current->chars = utf8_strlen(current->buf, current->len);
766 static int has_room(struct current *current, int bytes)
768 return current->len + bytes < current->bufmax - 1;
772 * Removes the char at 'pos'.
774 * Returns 1 if the line needs to be refreshed, 2 if not
775 * and 0 if nothing was removed
777 static int remove_char(struct current *current, int pos)
779 if (pos >= 0 && pos < current->chars) {
782 p1 = utf8_index(current->buf, pos);
783 p2 = p1 + utf8_index(current->buf + p1, 1);
786 /* optimise remove char in the case of removing the last char */
787 if (current->pos == pos + 1 && current->pos == current->chars) {
788 if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
790 fd_printf(current->fd, "\b \b");
795 /* Move the null char too */
796 memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
797 current->len -= (p2 - p1);
800 if (current->pos > pos) {
809 * Insert 'ch' at position 'pos'
811 * Returns 1 if the line needs to be refreshed, 2 if not
812 * and 0 if nothing was inserted (no room)
814 static int insert_char(struct current *current, int pos, int ch)
817 int n = utf8_getchars(buf, ch);
819 if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
822 p1 = utf8_index(current->buf, pos);
826 /* optimise the case where adding a single char to the end and no scrolling is needed */
827 if (current->pos == pos && current->chars == pos) {
828 if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
829 IGNORE_RC(write(current->fd, buf, n));
835 memmove(current->buf + p2, current->buf + p1, current->len - p1);
836 memcpy(current->buf + p1, buf, n);
840 if (current->pos >= pos) {
849 * Returns 0 if no chars were removed or non-zero otherwise.
851 static int remove_chars(struct current *current, int pos, int n)
854 while (n-- && remove_char(current, pos)) {
860 #ifndef NO_COMPLETION
861 static linenoiseCompletionCallback *completionCallback = NULL;
865 fprintf(stderr, "\x7");
870 static void freeCompletions(linenoiseCompletions *lc) {
872 for (i = 0; i < lc->len; i++)
877 static int completeLine(struct current *current) {
878 linenoiseCompletions lc = { 0, NULL };
881 completionCallback(current->buf,&lc);
885 size_t stop = 0, i = 0;
888 /* Show completion or original buffer */
890 struct current tmp = *current;
891 tmp.buf = lc.cvec[i];
892 tmp.pos = tmp.len = strlen(tmp.buf);
893 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
894 refreshLine(current->prompt, &tmp);
896 refreshLine(current->prompt, current);
899 c = fd_read(current);
906 i = (i+1) % (lc.len+1);
907 if (i == lc.len) beep();
909 case 27: /* escape */
910 /* Re-show original buffer */
912 refreshLine(current->prompt, current);
917 /* Update buffer and return */
919 set_current(current,lc.cvec[i]);
927 freeCompletions(&lc);
928 return c; /* Return last read character */
931 /* Register a callback function to be called for tab-completion. */
932 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
933 completionCallback = fn;
936 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
937 lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
938 lc->cvec[lc->len++] = strdup(str);
943 static int linenoisePrompt(struct current *current) {
944 int history_index = 0;
946 /* The latest history entry is always our current buffer, that
947 * initially is just an empty string. */
948 linenoiseHistoryAdd("");
950 set_current(current, "");
951 refreshLine(current->prompt, current);
955 int c = fd_read(current);
957 #ifndef NO_COMPLETION
958 /* Only autocomplete when the callback is set. It returns < 0 when
959 * there was an error reading from fd. Otherwise it will return the
960 * character that should be handled next. */
961 if (c == '\t' && current->pos == current->chars && completionCallback != NULL) {
962 c = completeLine(current);
963 /* Return on errors */
964 if (c < 0) return current->len;
965 /* Read next character when 0 */
966 if (c == 0) continue;
971 if (c == -1) return current->len;
973 if (c == 27) { /* escape sequence */
974 c = check_special(current->fd);
978 case '\r': /* enter */
980 free(history[history_len]);
982 case ctrl('C'): /* ctrl-c */
985 case 127: /* backspace */
987 if (remove_char(current, current->pos - 1) == 1) {
988 refreshLine(current->prompt, current);
991 case ctrl('D'): /* ctrl-d */
992 if (current->len == 0) {
993 /* Empty line, so EOF */
995 free(history[history_len]);
998 /* Otherwise fall through to delete char to right of cursor */
1000 if (remove_char(current, current->pos) == 1) {
1001 refreshLine(current->prompt, current);
1004 case ctrl('W'): /* ctrl-w */
1005 /* eat any spaces on the left */
1007 int pos = current->pos;
1008 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1012 /* now eat any non-spaces on the left */
1013 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1017 if (remove_chars(current, pos, current->pos - pos)) {
1018 refreshLine(current->prompt, current);
1022 case ctrl('R'): /* ctrl-r */
1024 /* Display the reverse-i-search prompt and process chars */
1029 int searchpos = history_len - 1;
1034 const char *p = NULL;
1038 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1039 refreshLine(rprompt, current);
1040 c = fd_read(current);
1041 if (c == ctrl('H') || c == 127) {
1043 int p = utf8_index(rbuf, --rchars);
1045 rlen = strlen(rbuf);
1051 c = check_special(current->fd);
1054 if (c == ctrl('P') || c == SPECIAL_UP) {
1055 /* Search for the previous (earlier) match */
1056 if (searchpos > 0) {
1061 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1062 /* Search for the next (later) match */
1063 if (searchpos < history_len) {
1069 else if (c >= ' ') {
1070 if (rlen >= (int)sizeof(rbuf) + 3) {
1074 n = utf8_getchars(rbuf + rlen, c);
1079 /* Adding a new char resets the search location */
1080 searchpos = history_len - 1;
1083 /* Exit from incremental search mode */
1087 /* Now search through the history for a match */
1088 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1089 p = strstr(history[searchpos], rbuf);
1092 if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
1093 /* But it is identical, so skip it */
1096 /* Copy the matching line and set the cursor position */
1097 set_current(current,history[searchpos]);
1098 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1103 /* No match, so don't add it */
1109 if (c == ctrl('G') || c == ctrl('C')) {
1110 /* ctrl-g terminates the search with no effect */
1111 set_current(current, "");
1114 else if (c == ctrl('J')) {
1115 /* ctrl-j terminates the search leaving the buffer in place */
1118 /* Go process the char normally */
1119 refreshLine(current->prompt, current);
1123 case ctrl('T'): /* ctrl-t */
1124 if (current->pos > 0 && current->pos < current->chars) {
1125 c = get_char(current, current->pos);
1126 remove_char(current, current->pos);
1127 insert_char(current, current->pos - 1, c);
1128 refreshLine(current->prompt, current);
1131 case ctrl('V'): /* ctrl-v */
1132 if (has_room(current, 3)) {
1133 /* Insert the ^V first */
1134 if (insert_char(current, current->pos, c)) {
1135 refreshLine(current->prompt, current);
1136 /* Now wait for the next char. Can insert anything except \0 */
1137 c = fd_read(current);
1139 /* Remove the ^V first */
1140 remove_char(current, current->pos - 1);
1142 /* Insert the actual char */
1143 insert_char(current, current->pos, c);
1145 refreshLine(current->prompt, current);
1151 if (current->pos > 0) {
1153 refreshLine(current->prompt, current);
1158 if (current->pos < current->chars) {
1160 refreshLine(current->prompt, current);
1168 if (history_len > 1) {
1169 /* Update the current history entry before to
1170 * overwrite it with tne next one. */
1171 free(history[history_len-1-history_index]);
1172 history[history_len-1-history_index] = strdup(current->buf);
1173 /* Show the new entry */
1174 history_index += dir;
1175 if (history_index < 0) {
1178 } else if (history_index >= history_len) {
1179 history_index = history_len-1;
1182 set_current(current, history[history_len-1-history_index]);
1183 refreshLine(current->prompt, current);
1186 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1189 refreshLine(current->prompt, current);
1191 case ctrl('E'): /* ctrl+e, go to the end of the line */
1193 current->pos = current->chars;
1194 refreshLine(current->prompt, current);
1196 case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
1197 if (remove_chars(current, 0, current->pos)) {
1198 refreshLine(current->prompt, current);
1201 case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
1202 if (remove_chars(current, current->pos, current->chars - current->pos)) {
1203 refreshLine(current->prompt, current);
1206 case ctrl('L'): /* Ctrl+L, clear screen */
1207 clearScreen(current);
1208 /* Force recalc of window size for serial terminals */
1210 refreshLine(current->prompt, current);
1213 /* Only tab is allowed without ^V */
1214 if (c == '\t' || c >= ' ') {
1215 if (insert_char(current, current->pos, c) == 1) {
1216 refreshLine(current->prompt, current);
1222 return current->len;
1225 char *linenoise(const char *prompt)
1228 struct current current;
1229 char buf[LINENOISE_MAX_LINE];
1231 if (enableRawMode(¤t) == -1) {
1232 printf("%s", prompt);
1234 if (fgets(buf, sizeof(buf), stdin) == NULL) {
1237 count = strlen(buf);
1238 if (count && buf[count-1] == '\n') {
1246 current.bufmax = sizeof(buf);
1250 current.prompt = prompt;
1252 count = linenoisePrompt(¤t);
1253 disableRawMode(¤t);
1262 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1263 int linenoiseHistoryAdd(const char *line) {
1266 if (history_max_len == 0) return 0;
1267 if (history == NULL) {
1268 history = (char **)malloc(sizeof(char*)*history_max_len);
1269 if (history == NULL) return 0;
1270 memset(history,0,(sizeof(char*)*history_max_len));
1273 /* do not insert duplicate lines into history */
1274 if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1278 linecopy = strdup(line);
1279 if (!linecopy) return 0;
1280 if (history_len == history_max_len) {
1282 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1285 history[history_len] = linecopy;
1290 int linenoiseHistorySetMaxLen(int len) {
1293 if (len < 1) return 0;
1295 int tocopy = history_len;
1297 newHistory = (char **)malloc(sizeof(char*)*len);
1298 if (newHistory == NULL) return 0;
1299 if (len < tocopy) tocopy = len;
1300 memcpy(newHistory,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
1302 history = newHistory;
1304 history_max_len = len;
1305 if (history_len > history_max_len)
1306 history_len = history_max_len;
1310 /* Save the history in the specified file. On success 0 is returned
1311 * otherwise -1 is returned. */
1312 int linenoiseHistorySave(const char *filename) {
1313 FILE *fp = fopen(filename,"w");
1316 if (fp == NULL) return -1;
1317 for (j = 0; j < history_len; j++) {
1318 const char *str = history[j];
1319 /* Need to encode backslash, nl and cr */
1324 else if (*str == '\n') {
1327 else if (*str == '\r') {
1342 /* Load the history from the specified file. If the file does not exist
1343 * zero is returned and no operation is performed.
1345 * If the file exists and the operation succeeded 0 is returned, otherwise
1346 * on error -1 is returned. */
1347 int linenoiseHistoryLoad(const char *filename) {
1348 FILE *fp = fopen(filename,"r");
1349 char buf[LINENOISE_MAX_LINE];
1351 if (fp == NULL) return -1;
1353 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1356 /* Decode backslash escaped values */
1357 for (src = dest = buf; *src; src++) {
1365 else if (*src == 'r') {
1373 /* Remove trailing newline */
1374 if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1379 linenoiseHistoryAdd(buf);
1385 /* Provide access to the history buffer.
1387 * If 'len' is not NULL, the length is stored in *len.
1389 char **linenoiseHistory(int *len) {