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++)
194 #if defined(USE_TERMIOS)
195 static void linenoiseAtExit(void);
196 static struct termios orig_termios; /* in order to restore at exit */
197 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
198 static int atexit_registered = 0; /* register atexit just 1 time */
200 static const char *unsupported_term[] = {"dumb","cons25",NULL};
202 static int isUnsupportedTerm(void) {
203 char *term = getenv("TERM");
207 for (j = 0; unsupported_term[j]; j++) {
208 if (strcasecmp(term, unsupported_term[j]) == 0) {
216 static int enableRawMode(struct current *current) {
219 current->fd = STDIN_FILENO;
221 if (!isatty(current->fd) || isUnsupportedTerm() ||
222 tcgetattr(current->fd, &orig_termios) == -1) {
228 if (!atexit_registered) {
229 atexit(linenoiseAtExit);
230 atexit_registered = 1;
233 raw = orig_termios; /* modify the original mode */
234 /* input modes: no break, no CR to NL, no parity check, no strip char,
235 * no start/stop output control. */
236 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
237 /* output modes - disable post processing */
238 raw.c_oflag &= ~(OPOST);
239 /* control modes - set 8 bit chars */
240 raw.c_cflag |= (CS8);
241 /* local modes - choing off, canonical off, no extended functions,
242 * no signal chars (^Z,^C) */
243 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
244 /* control chars - set return condition: min number of bytes and timer.
245 * We want read to return every single byte, without timeout. */
246 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
248 /* put terminal in raw mode after flushing */
249 if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
258 static void disableRawMode(struct current *current) {
259 /* Don't even check the return value as it's too late. */
260 if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
264 /* At exit we'll try to fix the terminal to the initial conditions. */
265 static void linenoiseAtExit(void) {
267 tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
269 linenoiseHistoryFree();
272 /* gcc/glibc insists that we care about the return code of write!
273 * Clarification: This means that a void-cast like "(void) (EXPR)"
276 #define IGNORE_RC(EXPR) if (EXPR) {}
278 /* This is fdprintf() on some systems, but use a different
279 * name to avoid conflicts
281 static void fd_printf(int fd, const char *format, ...)
287 va_start(args, format);
288 n = vsnprintf(buf, sizeof(buf), format, args);
290 IGNORE_RC(write(fd, buf, n));
293 static void clearScreen(struct current *current)
295 fd_printf(current->fd, "\x1b[H\x1b[2J");
298 static void cursorToLeft(struct current *current)
300 fd_printf(current->fd, "\r");
303 static int outputChars(struct current *current, const char *buf, int len)
305 return write(current->fd, buf, len);
308 static void outputControlChar(struct current *current, char ch)
310 fd_printf(current->fd, "\x1b[7m^%c\x1b[0m", ch);
313 static void eraseEol(struct current *current)
315 fd_printf(current->fd, "\x1b[0K");
318 static void setCursorPos(struct current *current, int x)
320 fd_printf(current->fd, "\r\x1b[%dC", x);
324 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
326 * A timeout of -1 means to wait forever.
328 * Returns -1 if no char is received within the time or an error occurs.
330 static int fd_read_char(int fd, int timeout)
338 if (poll(&p, 1, timeout) == 0) {
342 if (read(fd, &c, 1) != 1) {
349 * Reads a complete utf-8 character
350 * and returns the unicode value, or -1 on error.
352 static int fd_read(struct current *current)
360 if (read(current->fd, &buf[0], 1) != 1) {
363 n = utf8_charlen(buf[0]);
364 if (n < 1 || n > 3) {
367 for (i = 1; i < n; i++) {
368 if (read(current->fd, &buf[i], 1) != 1) {
373 /* decode and return the character */
374 utf8_tounicode(buf, &c);
377 return fd_read_char(current->fd, -1);
381 static int getWindowSize(struct current *current)
385 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
386 current->cols = ws.ws_col;
390 /* Failed to query the window size. Perhaps we are on a serial terminal.
391 * Try to query the width by sending the cursor as far to the right
392 * and reading back the cursor position.
393 * Note that this is only done once per call to linenoise rather than
394 * every time the line is refreshed for efficiency reasons.
396 if (current->cols == 0) {
399 /* Move cursor far right and report cursor position, then back to the left */
400 fd_printf(current->fd, "\x1b[999C" "\x1b[6n");
402 /* Parse the response: ESC [ rows ; cols R */
403 if (fd_read_char(current->fd, 100) == 0x1b && fd_read_char(current->fd, 100) == '[') {
406 int ch = fd_read_char(current->fd, 100);
411 else if (ch == 'R') {
413 if (n != 0 && n < 1000) {
418 else if (ch >= 0 && ch <= '9') {
419 n = n * 10 + ch - '0';
431 * If escape (27) was received, reads subsequent
432 * chars to determine if this is a known special key.
434 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
436 * If no additional char is received within a short time,
439 static int check_special(int fd)
441 int c = fd_read_char(fd, 50);
448 c2 = fd_read_char(fd, 50);
452 if (c == '[' || c == 'O') {
453 /* Potential arrow key */
460 return SPECIAL_RIGHT;
469 if (c == '[' && c2 >= '1' && c2 <= '8') {
470 /* extended escape */
471 c = fd_read_char(fd, 50);
475 return SPECIAL_DELETE;
482 while (c != -1 && c != '~') {
483 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
484 c = fd_read_char(fd, 50);
490 #elif defined(USE_WINCONSOLE)
492 static DWORD orig_consolemode = 0;
494 static int enableRawMode(struct current *current) {
498 current->outh = GetStdHandle(STD_OUTPUT_HANDLE);
499 current->inh = GetStdHandle(STD_INPUT_HANDLE);
501 if (!PeekConsoleInput(current->inh, &irec, 1, &n)) {
504 if (getWindowSize(current) != 0) {
507 if (GetConsoleMode(current->inh, &orig_consolemode)) {
508 SetConsoleMode(current->inh, ENABLE_PROCESSED_INPUT);
513 static void disableRawMode(struct current *current)
515 SetConsoleMode(current->inh, orig_consolemode);
518 static void clearScreen(struct current *current)
520 COORD topleft = { 0, 0 };
523 FillConsoleOutputCharacter(current->outh, ' ',
524 current->cols * current->rows, topleft, &n);
525 FillConsoleOutputAttribute(current->outh,
526 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN,
527 current->cols * current->rows, topleft, &n);
528 SetConsoleCursorPosition(current->outh, topleft);
531 static void cursorToLeft(struct current *current)
533 COORD pos = { 0, (SHORT)current->y };
536 FillConsoleOutputAttribute(current->outh,
537 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, current->cols, pos, &n);
541 static int outputChars(struct current *current, const char *buf, int len)
543 COORD pos = { (SHORT)current->x, (SHORT)current->y };
546 WriteConsoleOutputCharacter(current->outh, buf, len, pos, &n);
551 static void outputControlChar(struct current *current, char ch)
553 COORD pos = { (SHORT)current->x, (SHORT)current->y };
556 FillConsoleOutputAttribute(current->outh, BACKGROUND_INTENSITY, 2, pos, &n);
557 outputChars(current, "^", 1);
558 outputChars(current, &ch, 1);
561 static void eraseEol(struct current *current)
563 COORD pos = { (SHORT)current->x, (SHORT)current->y };
566 FillConsoleOutputCharacter(current->outh, ' ', current->cols - current->x, pos, &n);
569 static void setCursorPos(struct current *current, int x)
571 COORD pos = { (SHORT)x, (SHORT)current->y };
573 SetConsoleCursorPosition(current->outh, pos);
577 static int fd_read(struct current *current)
582 if (WaitForSingleObject(current->inh, INFINITE) != WAIT_OBJECT_0) {
585 if (!ReadConsoleInput (current->inh, &irec, 1, &n)) {
588 if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown) {
589 KEY_EVENT_RECORD *k = &irec.Event.KeyEvent;
590 if (k->dwControlKeyState & ENHANCED_KEY) {
591 switch (k->wVirtualKeyCode) {
595 return SPECIAL_RIGHT;
601 return SPECIAL_DELETE;
608 /* Note that control characters are already translated in AsciiChar */
611 return k->uChar.UnicodeChar;
613 return k->uChar.AsciiChar;
621 static int getWindowSize(struct current *current)
623 CONSOLE_SCREEN_BUFFER_INFO info;
624 if (!GetConsoleScreenBufferInfo(current->outh, &info)) {
627 current->cols = info.dwSize.X;
628 current->rows = info.dwSize.Y;
629 if (current->cols <= 0 || current->rows <= 0) {
633 current->y = info.dwCursorPosition.Y;
634 current->x = info.dwCursorPosition.X;
639 static int utf8_getchars(char *buf, int c)
642 return utf8_fromunicode(buf, c);
650 * Returns the unicode character at the given offset,
653 static int get_char(struct current *current, int pos)
655 if (pos >= 0 && pos < current->chars) {
657 int i = utf8_index(current->buf, pos);
658 (void)utf8_tounicode(current->buf + i, &c);
664 static void refreshLine(const char *prompt, struct current *current)
670 const char *buf = current->buf;
671 int chars = current->chars;
672 int pos = current->pos;
677 /* Should intercept SIGWINCH. For now, just get the size every time */
678 getWindowSize(current);
680 plen = strlen(prompt);
681 pchars = utf8_strlen(prompt, plen);
683 /* Account for a line which is too long to fit in the window.
684 * Note that control chars require an extra column
687 /* How many cols are required to the left of 'pos'?
688 * The prompt, plus one extra for each control char
690 n = pchars + utf8_strlen(buf, current->len);
692 for (i = 0; i < pos; i++) {
693 b += utf8_tounicode(buf + b, &ch);
699 /* If too many are need, strip chars off the front of 'buf'
700 * until it fits. Note that if the current char is a control character,
701 * we need one extra col.
703 if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
707 while (n >= current->cols && pos > 0) {
708 b = utf8_tounicode(buf, &ch);
718 /* Cursor to left edge, then the prompt */
719 cursorToLeft(current);
720 outputChars(current, prompt, plen);
722 /* Now the current buffer content */
724 /* Need special handling for control characters.
725 * If we hit 'cols', stop.
727 b = 0; /* unwritted bytes */
728 n = 0; /* How many control chars were written */
729 for (i = 0; i < chars; i++) {
731 int w = utf8_tounicode(buf + b, &ch);
735 if (pchars + i + n >= current->cols) {
739 /* A control character, so write the buffer so far */
740 outputChars(current, buf, b);
743 outputControlChar(current, ch + '@');
752 outputChars(current, buf, b);
754 /* Erase to right, move cursor to original position */
756 setCursorPos(current, pos + pchars + backup);
759 static void set_current(struct current *current, const char *str)
761 strncpy(current->buf, str, current->bufmax);
762 current->buf[current->bufmax - 1] = 0;
763 current->len = strlen(current->buf);
764 current->pos = current->chars = utf8_strlen(current->buf, current->len);
767 static int has_room(struct current *current, int bytes)
769 return current->len + bytes < current->bufmax - 1;
773 * Removes the char at 'pos'.
775 * Returns 1 if the line needs to be refreshed, 2 if not
776 * and 0 if nothing was removed
778 static int remove_char(struct current *current, int pos)
780 if (pos >= 0 && pos < current->chars) {
783 p1 = utf8_index(current->buf, pos);
784 p2 = p1 + utf8_index(current->buf + p1, 1);
787 /* optimise remove char in the case of removing the last char */
788 if (current->pos == pos + 1 && current->pos == current->chars) {
789 if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
791 fd_printf(current->fd, "\b \b");
796 /* Move the null char too */
797 memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
798 current->len -= (p2 - p1);
801 if (current->pos > pos) {
810 * Insert 'ch' at position 'pos'
812 * Returns 1 if the line needs to be refreshed, 2 if not
813 * and 0 if nothing was inserted (no room)
815 static int insert_char(struct current *current, int pos, int ch)
818 int n = utf8_getchars(buf, ch);
820 if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
823 p1 = utf8_index(current->buf, pos);
827 /* optimise the case where adding a single char to the end and no scrolling is needed */
828 if (current->pos == pos && current->chars == pos) {
829 if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
830 IGNORE_RC(write(current->fd, buf, n));
836 memmove(current->buf + p2, current->buf + p1, current->len - p1);
837 memcpy(current->buf + p1, buf, n);
841 if (current->pos >= pos) {
850 * Returns 0 if no chars were removed or non-zero otherwise.
852 static int remove_chars(struct current *current, int pos, int n)
855 while (n-- && remove_char(current, pos)) {
861 #ifndef NO_COMPLETION
862 static linenoiseCompletionCallback *completionCallback = NULL;
866 fprintf(stderr, "\x7");
871 static void freeCompletions(linenoiseCompletions *lc) {
873 for (i = 0; i < lc->len; i++)
878 static int completeLine(struct current *current) {
879 linenoiseCompletions lc = { 0, NULL };
882 completionCallback(current->buf,&lc);
886 size_t stop = 0, i = 0;
889 /* Show completion or original buffer */
891 struct current tmp = *current;
892 tmp.buf = lc.cvec[i];
893 tmp.pos = tmp.len = strlen(tmp.buf);
894 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
895 refreshLine(current->prompt, &tmp);
897 refreshLine(current->prompt, current);
900 c = fd_read(current);
907 i = (i+1) % (lc.len+1);
908 if (i == lc.len) beep();
910 case 27: /* escape */
911 /* Re-show original buffer */
913 refreshLine(current->prompt, current);
918 /* Update buffer and return */
920 set_current(current,lc.cvec[i]);
928 freeCompletions(&lc);
929 return c; /* Return last read character */
932 /* Register a callback function to be called for tab-completion. */
933 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
934 completionCallback = fn;
937 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
938 lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
939 lc->cvec[lc->len++] = strdup(str);
944 static int linenoisePrompt(struct current *current) {
945 int history_index = 0;
947 /* The latest history entry is always our current buffer, that
948 * initially is just an empty string. */
949 linenoiseHistoryAdd("");
951 set_current(current, "");
952 refreshLine(current->prompt, current);
956 int c = fd_read(current);
958 #ifndef NO_COMPLETION
959 /* Only autocomplete when the callback is set. It returns < 0 when
960 * there was an error reading from fd. Otherwise it will return the
961 * character that should be handled next. */
962 if (c == '\t' && current->pos == current->chars && completionCallback != NULL) {
963 c = completeLine(current);
964 /* Return on errors */
965 if (c < 0) return current->len;
966 /* Read next character when 0 */
967 if (c == 0) continue;
972 if (c == -1) return current->len;
974 if (c == 27) { /* escape sequence */
975 c = check_special(current->fd);
979 case '\r': /* enter */
981 free(history[history_len]);
983 case ctrl('C'): /* ctrl-c */
986 case 127: /* backspace */
988 if (remove_char(current, current->pos - 1) == 1) {
989 refreshLine(current->prompt, current);
992 case ctrl('D'): /* ctrl-d */
993 if (current->len == 0) {
994 /* Empty line, so EOF */
996 free(history[history_len]);
999 /* Otherwise fall through to delete char to right of cursor */
1000 case SPECIAL_DELETE:
1001 if (remove_char(current, current->pos) == 1) {
1002 refreshLine(current->prompt, current);
1005 case ctrl('W'): /* ctrl-w */
1006 /* eat any spaces on the left */
1008 int pos = current->pos;
1009 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1013 /* now eat any non-spaces on the left */
1014 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1018 if (remove_chars(current, pos, current->pos - pos)) {
1019 refreshLine(current->prompt, current);
1023 case ctrl('R'): /* ctrl-r */
1025 /* Display the reverse-i-search prompt and process chars */
1030 int searchpos = history_len - 1;
1035 const char *p = NULL;
1039 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1040 refreshLine(rprompt, current);
1041 c = fd_read(current);
1042 if (c == ctrl('H') || c == 127) {
1044 int p = utf8_index(rbuf, --rchars);
1046 rlen = strlen(rbuf);
1052 c = check_special(current->fd);
1055 if (c == ctrl('P') || c == SPECIAL_UP) {
1056 /* Search for the previous (earlier) match */
1057 if (searchpos > 0) {
1062 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1063 /* Search for the next (later) match */
1064 if (searchpos < history_len) {
1070 else if (c >= ' ') {
1071 if (rlen >= (int)sizeof(rbuf) + 3) {
1075 n = utf8_getchars(rbuf + rlen, c);
1080 /* Adding a new char resets the search location */
1081 searchpos = history_len - 1;
1084 /* Exit from incremental search mode */
1088 /* Now search through the history for a match */
1089 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1090 p = strstr(history[searchpos], rbuf);
1093 if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
1094 /* But it is identical, so skip it */
1097 /* Copy the matching line and set the cursor position */
1098 set_current(current,history[searchpos]);
1099 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1104 /* No match, so don't add it */
1110 if (c == ctrl('G') || c == ctrl('C')) {
1111 /* ctrl-g terminates the search with no effect */
1112 set_current(current, "");
1115 else if (c == ctrl('J')) {
1116 /* ctrl-j terminates the search leaving the buffer in place */
1119 /* Go process the char normally */
1120 refreshLine(current->prompt, current);
1124 case ctrl('T'): /* ctrl-t */
1125 if (current->pos > 0 && current->pos < current->chars) {
1126 c = get_char(current, current->pos);
1127 remove_char(current, current->pos);
1128 insert_char(current, current->pos - 1, c);
1129 refreshLine(current->prompt, current);
1132 case ctrl('V'): /* ctrl-v */
1133 if (has_room(current, 3)) {
1134 /* Insert the ^V first */
1135 if (insert_char(current, current->pos, c)) {
1136 refreshLine(current->prompt, current);
1137 /* Now wait for the next char. Can insert anything except \0 */
1138 c = fd_read(current);
1140 /* Remove the ^V first */
1141 remove_char(current, current->pos - 1);
1143 /* Insert the actual char */
1144 insert_char(current, current->pos, c);
1146 refreshLine(current->prompt, current);
1152 if (current->pos > 0) {
1154 refreshLine(current->prompt, current);
1159 if (current->pos < current->chars) {
1161 refreshLine(current->prompt, current);
1169 if (history_len > 1) {
1170 /* Update the current history entry before to
1171 * overwrite it with tne next one. */
1172 free(history[history_len-1-history_index]);
1173 history[history_len-1-history_index] = strdup(current->buf);
1174 /* Show the new entry */
1175 history_index += dir;
1176 if (history_index < 0) {
1179 } else if (history_index >= history_len) {
1180 history_index = history_len-1;
1183 set_current(current, history[history_len-1-history_index]);
1184 refreshLine(current->prompt, current);
1187 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1190 refreshLine(current->prompt, current);
1192 case ctrl('E'): /* ctrl+e, go to the end of the line */
1194 current->pos = current->chars;
1195 refreshLine(current->prompt, current);
1197 case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
1198 if (remove_chars(current, 0, current->pos)) {
1199 refreshLine(current->prompt, current);
1202 case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
1203 if (remove_chars(current, current->pos, current->chars - current->pos)) {
1204 refreshLine(current->prompt, current);
1207 case ctrl('L'): /* Ctrl+L, clear screen */
1208 clearScreen(current);
1209 /* Force recalc of window size for serial terminals */
1211 refreshLine(current->prompt, current);
1214 /* Only tab is allowed without ^V */
1215 if (c == '\t' || c >= ' ') {
1216 if (insert_char(current, current->pos, c) == 1) {
1217 refreshLine(current->prompt, current);
1223 return current->len;
1226 char *linenoise(const char *prompt)
1229 struct current current;
1230 char buf[LINENOISE_MAX_LINE];
1232 if (enableRawMode(¤t) == -1) {
1233 printf("%s", prompt);
1235 if (fgets(buf, sizeof(buf), stdin) == NULL) {
1238 count = strlen(buf);
1239 if (count && buf[count-1] == '\n') {
1247 current.bufmax = sizeof(buf);
1251 current.prompt = prompt;
1253 count = linenoisePrompt(¤t);
1254 disableRawMode(¤t);
1263 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1264 int linenoiseHistoryAdd(const char *line) {
1267 if (history_max_len == 0) return 0;
1268 if (history == NULL) {
1269 history = (char **)malloc(sizeof(char*)*history_max_len);
1270 if (history == NULL) return 0;
1271 memset(history,0,(sizeof(char*)*history_max_len));
1274 /* do not insert duplicate lines into history */
1275 if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1279 linecopy = strdup(line);
1280 if (!linecopy) return 0;
1281 if (history_len == history_max_len) {
1283 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1286 history[history_len] = linecopy;
1291 int linenoiseHistoryGetMaxLen(void) {
1292 return history_max_len;
1295 int linenoiseHistorySetMaxLen(int len) {
1298 if (len < 1) return 0;
1300 int tocopy = history_len;
1302 newHistory = (char **)malloc(sizeof(char*)*len);
1303 if (newHistory == NULL) return 0;
1304 if (len < tocopy) tocopy = len;
1305 memcpy(newHistory,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
1307 history = newHistory;
1309 history_max_len = len;
1310 if (history_len > history_max_len)
1311 history_len = history_max_len;
1315 /* Save the history in the specified file. On success 0 is returned
1316 * otherwise -1 is returned. */
1317 int linenoiseHistorySave(const char *filename) {
1318 FILE *fp = fopen(filename,"w");
1321 if (fp == NULL) return -1;
1322 for (j = 0; j < history_len; j++) {
1323 const char *str = history[j];
1324 /* Need to encode backslash, nl and cr */
1329 else if (*str == '\n') {
1332 else if (*str == '\r') {
1347 /* Load the history from the specified file. If the file does not exist
1348 * zero is returned and no operation is performed.
1350 * If the file exists and the operation succeeded 0 is returned, otherwise
1351 * on error -1 is returned. */
1352 int linenoiseHistoryLoad(const char *filename) {
1353 FILE *fp = fopen(filename,"r");
1354 char buf[LINENOISE_MAX_LINE];
1356 if (fp == NULL) return -1;
1358 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1361 /* Decode backslash escaped values */
1362 for (src = dest = buf; *src; src++) {
1370 else if (*src == 'r') {
1378 /* Remove trailing newline */
1379 if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1384 linenoiseHistoryAdd(buf);
1390 /* Provide access to the history buffer.
1392 * If 'len' is not NULL, the length is stored in *len.
1394 char **linenoiseHistory(int *len) {