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,
153 SPECIAL_INSERT = -27,
154 SPECIAL_PAGE_UP = -28,
155 SPECIAL_PAGE_DOWN = -29
158 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
159 static int history_len = 0;
160 static char **history = NULL;
162 /* Structure to contain the status of the current (being edited) line */
164 char *buf; /* Current buffer. Always null terminated */
165 int bufmax; /* Size of the buffer, including space for the null termination */
166 int len; /* Number of bytes in 'buf' */
167 int chars; /* Number of chars in 'buf' (utf-8 chars) */
168 int pos; /* Cursor position, measured in chars */
169 int cols; /* Size of the window, in chars */
171 #if defined(USE_TERMIOS)
172 int fd; /* Terminal fd */
173 #elif defined(USE_WINCONSOLE)
174 HANDLE outh; /* Console output handle */
175 HANDLE inh; /* Console input handle */
176 int rows; /* Screen rows */
177 int x; /* Current column during output */
178 int y; /* Current row */
182 static int fd_read(struct current *current);
183 static int getWindowSize(struct current *current);
185 void linenoiseHistoryFree(void) {
189 for (j = 0; j < history_len; j++)
197 #if defined(USE_TERMIOS)
198 static void linenoiseAtExit(void);
199 static struct termios orig_termios; /* in order to restore at exit */
200 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
201 static int atexit_registered = 0; /* register atexit just 1 time */
203 static const char *unsupported_term[] = {"dumb","cons25",NULL};
205 static int isUnsupportedTerm(void) {
206 char *term = getenv("TERM");
210 for (j = 0; unsupported_term[j]; j++) {
211 if (strcasecmp(term, unsupported_term[j]) == 0) {
219 static int enableRawMode(struct current *current) {
222 current->fd = STDIN_FILENO;
224 if (!isatty(current->fd) || isUnsupportedTerm() ||
225 tcgetattr(current->fd, &orig_termios) == -1) {
231 if (!atexit_registered) {
232 atexit(linenoiseAtExit);
233 atexit_registered = 1;
236 raw = orig_termios; /* modify the original mode */
237 /* input modes: no break, no CR to NL, no parity check, no strip char,
238 * no start/stop output control. */
239 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
240 /* output modes - disable post processing */
241 raw.c_oflag &= ~(OPOST);
242 /* control modes - set 8 bit chars */
243 raw.c_cflag |= (CS8);
244 /* local modes - choing off, canonical off, no extended functions,
245 * no signal chars (^Z,^C) */
246 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
247 /* control chars - set return condition: min number of bytes and timer.
248 * We want read to return every single byte, without timeout. */
249 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
251 /* put terminal in raw mode after flushing */
252 if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
261 static void disableRawMode(struct current *current) {
262 /* Don't even check the return value as it's too late. */
263 if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
267 /* At exit we'll try to fix the terminal to the initial conditions. */
268 static void linenoiseAtExit(void) {
270 tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
272 linenoiseHistoryFree();
275 /* gcc/glibc insists that we care about the return code of write!
276 * Clarification: This means that a void-cast like "(void) (EXPR)"
279 #define IGNORE_RC(EXPR) if (EXPR) {}
281 /* This is fdprintf() on some systems, but use a different
282 * name to avoid conflicts
284 static void fd_printf(int fd, const char *format, ...)
290 va_start(args, format);
291 n = vsnprintf(buf, sizeof(buf), format, args);
293 IGNORE_RC(write(fd, buf, n));
296 static void clearScreen(struct current *current)
298 fd_printf(current->fd, "\x1b[H\x1b[2J");
301 static void cursorToLeft(struct current *current)
303 fd_printf(current->fd, "\r");
306 static int outputChars(struct current *current, const char *buf, int len)
308 return write(current->fd, buf, len);
311 static void outputControlChar(struct current *current, char ch)
313 fd_printf(current->fd, "\x1b[7m^%c\x1b[0m", ch);
316 static void eraseEol(struct current *current)
318 fd_printf(current->fd, "\x1b[0K");
321 static void setCursorPos(struct current *current, int x)
323 fd_printf(current->fd, "\r\x1b[%dC", x);
327 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
329 * A timeout of -1 means to wait forever.
331 * Returns -1 if no char is received within the time or an error occurs.
333 static int fd_read_char(int fd, int timeout)
341 if (poll(&p, 1, timeout) == 0) {
345 if (read(fd, &c, 1) != 1) {
352 * Reads a complete utf-8 character
353 * and returns the unicode value, or -1 on error.
355 static int fd_read(struct current *current)
363 if (read(current->fd, &buf[0], 1) != 1) {
366 n = utf8_charlen(buf[0]);
367 if (n < 1 || n > 3) {
370 for (i = 1; i < n; i++) {
371 if (read(current->fd, &buf[i], 1) != 1) {
376 /* decode and return the character */
377 utf8_tounicode(buf, &c);
380 return fd_read_char(current->fd, -1);
384 static int countColorControlChars(const char* prompt, int plen)
386 /* ANSI color control sequences have the form:
387 * "\x1b" "[" [0-9;]+ "m"
388 * We parse them with a simple state machine.
396 } state = search_esc;
400 /* XXX: Strictly we should be checking utf8 chars rather than
401 * bytes in case of the extremely unlikely scenario where
402 * an ANSI sequence is part of a utf8 sequence.
404 for (; plen ; plen--, prompt++) {
411 state = expect_bracket;
417 state = expect_inner;
424 if (ch >= '0' && ch <= '9') {
426 state = expect_trail;
436 } else if ((ch != ';') && ((ch < '0') || (ch > '9'))) {
439 /* 0-9, or semicolon */
448 static int getWindowSize(struct current *current)
452 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
453 current->cols = ws.ws_col;
457 /* Failed to query the window size. Perhaps we are on a serial terminal.
458 * Try to query the width by sending the cursor as far to the right
459 * and reading back the cursor position.
460 * Note that this is only done once per call to linenoise rather than
461 * every time the line is refreshed for efficiency reasons.
463 if (current->cols == 0) {
466 /* Move cursor far right and report cursor position, then back to the left */
467 fd_printf(current->fd, "\x1b[999C" "\x1b[6n");
469 /* Parse the response: ESC [ rows ; cols R */
470 if (fd_read_char(current->fd, 100) == 0x1b && fd_read_char(current->fd, 100) == '[') {
473 int ch = fd_read_char(current->fd, 100);
478 else if (ch == 'R') {
480 if (n != 0 && n < 1000) {
485 else if (ch >= 0 && ch <= '9') {
486 n = n * 10 + ch - '0';
498 * If escape (27) was received, reads subsequent
499 * chars to determine if this is a known special key.
501 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
503 * If no additional char is received within a short time,
506 static int check_special(int fd)
508 int c = fd_read_char(fd, 50);
515 c2 = fd_read_char(fd, 50);
519 if (c == '[' || c == 'O') {
520 /* Potential arrow key */
527 return SPECIAL_RIGHT;
536 if (c == '[' && c2 >= '1' && c2 <= '8') {
537 /* extended escape */
538 c = fd_read_char(fd, 50);
542 return SPECIAL_INSERT;
544 return SPECIAL_DELETE;
546 return SPECIAL_PAGE_UP;
548 return SPECIAL_PAGE_DOWN;
555 while (c != -1 && c != '~') {
556 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
557 c = fd_read_char(fd, 50);
563 #elif defined(USE_WINCONSOLE)
565 static DWORD orig_consolemode = 0;
567 static int enableRawMode(struct current *current) {
571 current->outh = GetStdHandle(STD_OUTPUT_HANDLE);
572 current->inh = GetStdHandle(STD_INPUT_HANDLE);
574 if (!PeekConsoleInput(current->inh, &irec, 1, &n)) {
577 if (getWindowSize(current) != 0) {
580 if (GetConsoleMode(current->inh, &orig_consolemode)) {
581 SetConsoleMode(current->inh, ENABLE_PROCESSED_INPUT);
586 static void disableRawMode(struct current *current)
588 SetConsoleMode(current->inh, orig_consolemode);
591 static void clearScreen(struct current *current)
593 COORD topleft = { 0, 0 };
596 FillConsoleOutputCharacter(current->outh, ' ',
597 current->cols * current->rows, topleft, &n);
598 FillConsoleOutputAttribute(current->outh,
599 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN,
600 current->cols * current->rows, topleft, &n);
601 SetConsoleCursorPosition(current->outh, topleft);
604 static void cursorToLeft(struct current *current)
606 COORD pos = { 0, (SHORT)current->y };
609 FillConsoleOutputAttribute(current->outh,
610 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, current->cols, pos, &n);
614 static int outputChars(struct current *current, const char *buf, int len)
616 COORD pos = { (SHORT)current->x, (SHORT)current->y };
619 WriteConsoleOutputCharacter(current->outh, buf, len, pos, &n);
624 static void outputControlChar(struct current *current, char ch)
626 COORD pos = { (SHORT)current->x, (SHORT)current->y };
629 FillConsoleOutputAttribute(current->outh, BACKGROUND_INTENSITY, 2, pos, &n);
630 outputChars(current, "^", 1);
631 outputChars(current, &ch, 1);
634 static void eraseEol(struct current *current)
636 COORD pos = { (SHORT)current->x, (SHORT)current->y };
639 FillConsoleOutputCharacter(current->outh, ' ', current->cols - current->x, pos, &n);
642 static void setCursorPos(struct current *current, int x)
644 COORD pos = { (SHORT)x, (SHORT)current->y };
646 SetConsoleCursorPosition(current->outh, pos);
650 static int fd_read(struct current *current)
655 if (WaitForSingleObject(current->inh, INFINITE) != WAIT_OBJECT_0) {
658 if (!ReadConsoleInput (current->inh, &irec, 1, &n)) {
661 if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown) {
662 KEY_EVENT_RECORD *k = &irec.Event.KeyEvent;
663 if (k->dwControlKeyState & ENHANCED_KEY) {
664 switch (k->wVirtualKeyCode) {
668 return SPECIAL_RIGHT;
674 return SPECIAL_INSERT;
676 return SPECIAL_DELETE;
682 return SPECIAL_PAGE_UP;
684 return SPECIAL_PAGE_DOWN;
687 /* Note that control characters are already translated in AsciiChar */
690 return k->uChar.UnicodeChar;
692 return k->uChar.AsciiChar;
700 static int countColorControlChars(char* prompt, int plen)
702 /* For windows we assume that there are no embedded ansi color
708 static int getWindowSize(struct current *current)
710 CONSOLE_SCREEN_BUFFER_INFO info;
711 if (!GetConsoleScreenBufferInfo(current->outh, &info)) {
714 current->cols = info.dwSize.X;
715 current->rows = info.dwSize.Y;
716 if (current->cols <= 0 || current->rows <= 0) {
720 current->y = info.dwCursorPosition.Y;
721 current->x = info.dwCursorPosition.X;
726 static int utf8_getchars(char *buf, int c)
729 return utf8_fromunicode(buf, c);
737 * Returns the unicode character at the given offset,
740 static int get_char(struct current *current, int pos)
742 if (pos >= 0 && pos < current->chars) {
744 int i = utf8_index(current->buf, pos);
745 (void)utf8_tounicode(current->buf + i, &c);
751 static void refreshLine(const char *prompt, struct current *current)
757 const char *buf = current->buf;
758 int chars = current->chars;
759 int pos = current->pos;
764 /* Should intercept SIGWINCH. For now, just get the size every time */
765 getWindowSize(current);
767 plen = strlen(prompt);
768 pchars = utf8_strlen(prompt, plen);
770 /* Scan the prompt for embedded ansi color control sequences and
771 * discount them as characters/columns.
773 pchars -= countColorControlChars(prompt, plen);
775 /* Account for a line which is too long to fit in the window.
776 * Note that control chars require an extra column
779 /* How many cols are required to the left of 'pos'?
780 * The prompt, plus one extra for each control char
782 n = pchars + utf8_strlen(buf, current->len);
784 for (i = 0; i < pos; i++) {
785 b += utf8_tounicode(buf + b, &ch);
791 /* If too many are needed, strip chars off the front of 'buf'
792 * until it fits. Note that if the current char is a control character,
793 * we need one extra col.
795 if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
799 while (n >= current->cols && pos > 0) {
800 b = utf8_tounicode(buf, &ch);
810 /* Cursor to left edge, then the prompt */
811 cursorToLeft(current);
812 outputChars(current, prompt, plen);
814 /* Now the current buffer content */
816 /* Need special handling for control characters.
817 * If we hit 'cols', stop.
819 b = 0; /* unwritted bytes */
820 n = 0; /* How many control chars were written */
821 for (i = 0; i < chars; i++) {
823 int w = utf8_tounicode(buf + b, &ch);
827 if (pchars + i + n >= current->cols) {
831 /* A control character, so write the buffer so far */
832 outputChars(current, buf, b);
835 outputControlChar(current, ch + '@');
844 outputChars(current, buf, b);
846 /* Erase to right, move cursor to original position */
848 setCursorPos(current, pos + pchars + backup);
851 static void set_current(struct current *current, const char *str)
853 strncpy(current->buf, str, current->bufmax);
854 current->buf[current->bufmax - 1] = 0;
855 current->len = strlen(current->buf);
856 current->pos = current->chars = utf8_strlen(current->buf, current->len);
859 static int has_room(struct current *current, int bytes)
861 return current->len + bytes < current->bufmax - 1;
865 * Removes the char at 'pos'.
867 * Returns 1 if the line needs to be refreshed, 2 if not
868 * and 0 if nothing was removed
870 static int remove_char(struct current *current, int pos)
872 if (pos >= 0 && pos < current->chars) {
875 p1 = utf8_index(current->buf, pos);
876 p2 = p1 + utf8_index(current->buf + p1, 1);
879 /* optimise remove char in the case of removing the last char */
880 if (current->pos == pos + 1 && current->pos == current->chars) {
881 if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
883 fd_printf(current->fd, "\b \b");
888 /* Move the null char too */
889 memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
890 current->len -= (p2 - p1);
893 if (current->pos > pos) {
902 * Insert 'ch' at position 'pos'
904 * Returns 1 if the line needs to be refreshed, 2 if not
905 * and 0 if nothing was inserted (no room)
907 static int insert_char(struct current *current, int pos, int ch)
910 int n = utf8_getchars(buf, ch);
912 if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
915 p1 = utf8_index(current->buf, pos);
919 /* optimise the case where adding a single char to the end and no scrolling is needed */
920 if (current->pos == pos && current->chars == pos) {
921 if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
922 IGNORE_RC(write(current->fd, buf, n));
928 memmove(current->buf + p2, current->buf + p1, current->len - p1);
929 memcpy(current->buf + p1, buf, n);
933 if (current->pos >= pos) {
942 * Returns 0 if no chars were removed or non-zero otherwise.
944 static int remove_chars(struct current *current, int pos, int n)
947 while (n-- && remove_char(current, pos)) {
953 #ifndef NO_COMPLETION
954 static linenoiseCompletionCallback *completionCallback = NULL;
958 fprintf(stderr, "\x7");
963 static void freeCompletions(linenoiseCompletions *lc) {
965 for (i = 0; i < lc->len; i++)
970 static int completeLine(struct current *current) {
971 linenoiseCompletions lc = { 0, NULL };
974 completionCallback(current->buf,&lc);
978 size_t stop = 0, i = 0;
981 /* Show completion or original buffer */
983 struct current tmp = *current;
984 tmp.buf = lc.cvec[i];
985 tmp.pos = tmp.len = strlen(tmp.buf);
986 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
987 refreshLine(current->prompt, &tmp);
989 refreshLine(current->prompt, current);
992 c = fd_read(current);
999 i = (i+1) % (lc.len+1);
1000 if (i == lc.len) beep();
1002 case 27: /* escape */
1003 /* Re-show original buffer */
1005 refreshLine(current->prompt, current);
1010 /* Update buffer and return */
1012 set_current(current,lc.cvec[i]);
1020 freeCompletions(&lc);
1021 return c; /* Return last read character */
1024 /* Register a callback function to be called for tab-completion. */
1025 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
1026 completionCallback = fn;
1029 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
1030 lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
1031 lc->cvec[lc->len++] = strdup(str);
1036 static int linenoisePrompt(struct current *current) {
1037 int history_index = 0;
1039 /* The latest history entry is always our current buffer, that
1040 * initially is just an empty string. */
1041 linenoiseHistoryAdd("");
1043 set_current(current, "");
1044 refreshLine(current->prompt, current);
1048 int c = fd_read(current);
1050 #ifndef NO_COMPLETION
1051 /* Only autocomplete when the callback is set. It returns < 0 when
1052 * there was an error reading from fd. Otherwise it will return the
1053 * character that should be handled next. */
1054 if (c == '\t' && current->pos == current->chars && completionCallback != NULL) {
1055 c = completeLine(current);
1056 /* Return on errors */
1057 if (c < 0) return current->len;
1058 /* Read next character when 0 */
1059 if (c == 0) continue;
1064 if (c == -1) return current->len;
1066 if (c == 27) { /* escape sequence */
1067 c = check_special(current->fd);
1071 case '\r': /* enter */
1073 free(history[history_len]);
1074 return current->len;
1075 case ctrl('C'): /* ctrl-c */
1078 case 127: /* backspace */
1080 if (remove_char(current, current->pos - 1) == 1) {
1081 refreshLine(current->prompt, current);
1084 case ctrl('D'): /* ctrl-d */
1085 if (current->len == 0) {
1086 /* Empty line, so EOF */
1088 free(history[history_len]);
1091 /* Otherwise fall through to delete char to right of cursor */
1092 case SPECIAL_DELETE:
1093 if (remove_char(current, current->pos) == 1) {
1094 refreshLine(current->prompt, current);
1097 case SPECIAL_INSERT:
1098 /* Ignore. Expansion Hook.
1099 * Future possibility: Toggle Insert/Overwrite Modes
1102 case ctrl('W'): /* ctrl-w */
1103 /* eat any spaces on the left */
1105 int pos = current->pos;
1106 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1110 /* now eat any non-spaces on the left */
1111 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1115 if (remove_chars(current, pos, current->pos - pos)) {
1116 refreshLine(current->prompt, current);
1120 case ctrl('R'): /* ctrl-r */
1122 /* Display the reverse-i-search prompt and process chars */
1127 int searchpos = history_len - 1;
1132 const char *p = NULL;
1136 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1137 refreshLine(rprompt, current);
1138 c = fd_read(current);
1139 if (c == ctrl('H') || c == 127) {
1141 int p = utf8_index(rbuf, --rchars);
1143 rlen = strlen(rbuf);
1149 c = check_special(current->fd);
1152 if (c == ctrl('P') || c == SPECIAL_UP) {
1153 /* Search for the previous (earlier) match */
1154 if (searchpos > 0) {
1159 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1160 /* Search for the next (later) match */
1161 if (searchpos < history_len) {
1167 else if (c >= ' ') {
1168 if (rlen >= (int)sizeof(rbuf) + 3) {
1172 n = utf8_getchars(rbuf + rlen, c);
1177 /* Adding a new char resets the search location */
1178 searchpos = history_len - 1;
1181 /* Exit from incremental search mode */
1185 /* Now search through the history for a match */
1186 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1187 p = strstr(history[searchpos], rbuf);
1190 if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
1191 /* But it is identical, so skip it */
1194 /* Copy the matching line and set the cursor position */
1195 set_current(current,history[searchpos]);
1196 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1201 /* No match, so don't add it */
1207 if (c == ctrl('G') || c == ctrl('C')) {
1208 /* ctrl-g terminates the search with no effect */
1209 set_current(current, "");
1212 else if (c == ctrl('J')) {
1213 /* ctrl-j terminates the search leaving the buffer in place */
1216 /* Go process the char normally */
1217 refreshLine(current->prompt, current);
1221 case ctrl('T'): /* ctrl-t */
1222 if (current->pos > 0 && current->pos <= current->chars) {
1223 /* If cursor is at end, transpose the previous two chars */
1224 int fixer = (current->pos == current->chars);
1225 c = get_char(current, current->pos - fixer);
1226 remove_char(current, current->pos - fixer);
1227 insert_char(current, current->pos - 1, c);
1228 refreshLine(current->prompt, current);
1231 case ctrl('V'): /* ctrl-v */
1232 if (has_room(current, 3)) {
1233 /* Insert the ^V first */
1234 if (insert_char(current, current->pos, c)) {
1235 refreshLine(current->prompt, current);
1236 /* Now wait for the next char. Can insert anything except \0 */
1237 c = fd_read(current);
1239 /* Remove the ^V first */
1240 remove_char(current, current->pos - 1);
1242 /* Insert the actual char */
1243 insert_char(current, current->pos, c);
1245 refreshLine(current->prompt, current);
1251 if (current->pos > 0) {
1253 refreshLine(current->prompt, current);
1258 if (current->pos < current->chars) {
1260 refreshLine(current->prompt, current);
1263 case SPECIAL_PAGE_UP:
1264 dir = history_len - history_index - 1; /* move to start of history */
1265 goto history_navigation;
1266 case SPECIAL_PAGE_DOWN:
1267 dir = -history_index; /* move to 0 == end of history, i.e. current */
1268 goto history_navigation;
1272 goto history_navigation;
1276 if (history_len > 1) {
1277 /* Update the current history entry before to
1278 * overwrite it with tne next one. */
1279 free(history[history_len - 1 - history_index]);
1280 history[history_len - 1 - history_index] = strdup(current->buf);
1281 /* Show the new entry */
1282 history_index += dir;
1283 if (history_index < 0) {
1286 } else if (history_index >= history_len) {
1287 history_index = history_len - 1;
1290 set_current(current, history[history_len - 1 - history_index]);
1291 refreshLine(current->prompt, current);
1294 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1297 refreshLine(current->prompt, current);
1299 case ctrl('E'): /* ctrl+e, go to the end of the line */
1301 current->pos = current->chars;
1302 refreshLine(current->prompt, current);
1304 case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
1305 if (remove_chars(current, 0, current->pos)) {
1306 refreshLine(current->prompt, current);
1309 case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
1310 if (remove_chars(current, current->pos, current->chars - current->pos)) {
1311 refreshLine(current->prompt, current);
1314 case ctrl('L'): /* Ctrl+L, clear screen */
1315 clearScreen(current);
1316 /* Force recalc of window size for serial terminals */
1318 refreshLine(current->prompt, current);
1321 /* Only tab is allowed without ^V */
1322 if (c == '\t' || c >= ' ') {
1323 if (insert_char(current, current->pos, c) == 1) {
1324 refreshLine(current->prompt, current);
1330 return current->len;
1333 int linenoiseColumns(void)
1335 struct current current;
1336 enableRawMode (¤t);
1337 getWindowSize (¤t);
1338 disableRawMode (¤t);
1339 return current.cols;
1342 char *linenoise(const char *prompt)
1345 struct current current;
1346 char buf[LINENOISE_MAX_LINE];
1348 if (enableRawMode(¤t) == -1) {
1349 printf("%s", prompt);
1351 if (fgets(buf, sizeof(buf), stdin) == NULL) {
1354 count = strlen(buf);
1355 if (count && buf[count-1] == '\n') {
1363 current.bufmax = sizeof(buf);
1367 current.prompt = prompt;
1369 count = linenoisePrompt(¤t);
1370 disableRawMode(¤t);
1379 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1380 int linenoiseHistoryAdd(const char *line) {
1383 if (history_max_len == 0) return 0;
1384 if (history == NULL) {
1385 history = (char **)malloc(sizeof(char*)*history_max_len);
1386 if (history == NULL) return 0;
1387 memset(history,0,(sizeof(char*)*history_max_len));
1390 /* do not insert duplicate lines into history */
1391 if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1395 linecopy = strdup(line);
1396 if (!linecopy) return 0;
1397 if (history_len == history_max_len) {
1399 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1402 history[history_len] = linecopy;
1407 int linenoiseHistoryGetMaxLen(void) {
1408 return history_max_len;
1411 int linenoiseHistorySetMaxLen(int len) {
1414 if (len < 1) return 0;
1416 int tocopy = history_len;
1418 newHistory = (char **)malloc(sizeof(char*)*len);
1419 if (newHistory == NULL) return 0;
1420 if (len < tocopy) tocopy = len;
1421 memcpy(newHistory,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
1423 history = newHistory;
1425 history_max_len = len;
1426 if (history_len > history_max_len)
1427 history_len = history_max_len;
1431 /* Save the history in the specified file. On success 0 is returned
1432 * otherwise -1 is returned. */
1433 int linenoiseHistorySave(const char *filename) {
1434 FILE *fp = fopen(filename,"w");
1437 if (fp == NULL) return -1;
1438 for (j = 0; j < history_len; j++) {
1439 const char *str = history[j];
1440 /* Need to encode backslash, nl and cr */
1445 else if (*str == '\n') {
1448 else if (*str == '\r') {
1463 /* Load the history from the specified file. If the file does not exist
1464 * zero is returned and no operation is performed.
1466 * If the file exists and the operation succeeded 0 is returned, otherwise
1467 * on error -1 is returned. */
1468 int linenoiseHistoryLoad(const char *filename) {
1469 FILE *fp = fopen(filename,"r");
1470 char buf[LINENOISE_MAX_LINE];
1472 if (fp == NULL) return -1;
1474 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1477 /* Decode backslash escaped values */
1478 for (src = dest = buf; *src; src++) {
1486 else if (*src == 'r') {
1494 /* Remove trailing newline */
1495 if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1500 linenoiseHistoryAdd(buf);
1506 /* Provide access to the history buffer.
1508 * If 'len' is not NULL, the length is stored in *len.
1510 char **linenoiseHistory(int *len) {