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 char *capture; /* Allocated capture buffer, or NULL for none. Always null terminated */
172 #if defined(USE_TERMIOS)
173 int fd; /* Terminal fd */
174 #elif defined(USE_WINCONSOLE)
175 HANDLE outh; /* Console output handle */
176 HANDLE inh; /* Console input handle */
177 int rows; /* Screen rows */
178 int x; /* Current column during output */
179 int y; /* Current row */
183 static int fd_read(struct current *current);
184 static int getWindowSize(struct current *current);
186 void linenoiseHistoryFree(void) {
190 for (j = 0; j < history_len; j++)
198 #if defined(USE_TERMIOS)
199 static void linenoiseAtExit(void);
200 static struct termios orig_termios; /* in order to restore at exit */
201 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
202 static int atexit_registered = 0; /* register atexit just 1 time */
204 static const char *unsupported_term[] = {"dumb","cons25",NULL};
206 static int isUnsupportedTerm(void) {
207 char *term = getenv("TERM");
211 for (j = 0; unsupported_term[j]; j++) {
212 if (strcmp(term, unsupported_term[j]) == 0) {
220 static int enableRawMode(struct current *current) {
223 current->fd = STDIN_FILENO;
225 if (!isatty(current->fd) || isUnsupportedTerm() ||
226 tcgetattr(current->fd, &orig_termios) == -1) {
232 if (!atexit_registered) {
233 atexit(linenoiseAtExit);
234 atexit_registered = 1;
237 raw = orig_termios; /* modify the original mode */
238 /* input modes: no break, no CR to NL, no parity check, no strip char,
239 * no start/stop output control. */
240 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
241 /* output modes - disable post processing */
242 raw.c_oflag &= ~(OPOST);
243 /* control modes - set 8 bit chars */
244 raw.c_cflag |= (CS8);
245 /* local modes - choing off, canonical off, no extended functions,
246 * no signal chars (^Z,^C) */
247 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
248 /* control chars - set return condition: min number of bytes and timer.
249 * We want read to return every single byte, without timeout. */
250 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
252 /* put terminal in raw mode after flushing */
253 if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
262 static void disableRawMode(struct current *current) {
263 /* Don't even check the return value as it's too late. */
264 if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
268 /* At exit we'll try to fix the terminal to the initial conditions. */
269 static void linenoiseAtExit(void) {
271 tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
273 linenoiseHistoryFree();
276 /* gcc/glibc insists that we care about the return code of write!
277 * Clarification: This means that a void-cast like "(void) (EXPR)"
280 #define IGNORE_RC(EXPR) if (EXPR) {}
282 /* This is fdprintf() on some systems, but use a different
283 * name to avoid conflicts
285 static void fd_printf(int fd, const char *format, ...)
291 va_start(args, format);
292 n = vsnprintf(buf, sizeof(buf), format, args);
294 IGNORE_RC(write(fd, buf, n));
297 static void clearScreen(struct current *current)
299 fd_printf(current->fd, "\x1b[H\x1b[2J");
302 static void cursorToLeft(struct current *current)
304 fd_printf(current->fd, "\r");
307 static int outputChars(struct current *current, const char *buf, int len)
309 return write(current->fd, buf, len);
312 static void outputControlChar(struct current *current, char ch)
314 fd_printf(current->fd, "\x1b[7m^%c\x1b[0m", ch);
317 static void eraseEol(struct current *current)
319 fd_printf(current->fd, "\x1b[0K");
322 static void setCursorPos(struct current *current, int x)
324 fd_printf(current->fd, "\r\x1b[%dC", x);
328 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
330 * A timeout of -1 means to wait forever.
332 * Returns -1 if no char is received within the time or an error occurs.
334 static int fd_read_char(int fd, int timeout)
342 if (poll(&p, 1, timeout) == 0) {
346 if (read(fd, &c, 1) != 1) {
353 * Reads a complete utf-8 character
354 * and returns the unicode value, or -1 on error.
356 static int fd_read(struct current *current)
364 if (read(current->fd, &buf[0], 1) != 1) {
367 n = utf8_charlen(buf[0]);
368 if (n < 1 || n > 3) {
371 for (i = 1; i < n; i++) {
372 if (read(current->fd, &buf[i], 1) != 1) {
377 /* decode and return the character */
378 utf8_tounicode(buf, &c);
381 return fd_read_char(current->fd, -1);
385 static int countColorControlChars(const char* prompt)
387 /* ANSI color control sequences have the form:
388 * "\x1b" "[" [0-9;]* "m"
389 * We parse them with a simple state machine.
396 } state = search_esc;
397 int len = 0, found = 0;
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 while ((ch = *prompt++) != 0) {
408 state = expect_bracket;
413 state = expect_trail;
414 /* 3 for "\e[ ... m" */
421 if ((ch == ';') || ((ch >= '0' && ch <= '9'))) {
422 /* 0-9, or semicolon */
437 static int getWindowSize(struct current *current)
441 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
442 current->cols = ws.ws_col;
446 /* Failed to query the window size. Perhaps we are on a serial terminal.
447 * Try to query the width by sending the cursor as far to the right
448 * and reading back the cursor position.
449 * Note that this is only done once per call to linenoise rather than
450 * every time the line is refreshed for efficiency reasons.
452 if (current->cols == 0) {
455 /* Move cursor far right and report cursor position, then back to the left */
456 fd_printf(current->fd, "\x1b[999C" "\x1b[6n");
458 /* Parse the response: ESC [ rows ; cols R */
459 if (fd_read_char(current->fd, 100) == 0x1b && fd_read_char(current->fd, 100) == '[') {
462 int ch = fd_read_char(current->fd, 100);
467 else if (ch == 'R') {
469 if (n != 0 && n < 1000) {
474 else if (ch >= 0 && ch <= '9') {
475 n = n * 10 + ch - '0';
487 * If escape (27) was received, reads subsequent
488 * chars to determine if this is a known special key.
490 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
492 * If no additional char is received within a short time,
495 static int check_special(int fd)
497 int c = fd_read_char(fd, 50);
504 c2 = fd_read_char(fd, 50);
508 if (c == '[' || c == 'O') {
509 /* Potential arrow key */
516 return SPECIAL_RIGHT;
525 if (c == '[' && c2 >= '1' && c2 <= '8') {
526 /* extended escape */
527 c = fd_read_char(fd, 50);
531 return SPECIAL_INSERT;
533 return SPECIAL_DELETE;
535 return SPECIAL_PAGE_UP;
537 return SPECIAL_PAGE_DOWN;
544 while (c != -1 && c != '~') {
545 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
546 c = fd_read_char(fd, 50);
552 #elif defined(USE_WINCONSOLE)
554 static DWORD orig_consolemode = 0;
556 static int enableRawMode(struct current *current) {
560 current->outh = GetStdHandle(STD_OUTPUT_HANDLE);
561 current->inh = GetStdHandle(STD_INPUT_HANDLE);
563 if (!PeekConsoleInput(current->inh, &irec, 1, &n)) {
566 if (getWindowSize(current) != 0) {
569 if (GetConsoleMode(current->inh, &orig_consolemode)) {
570 SetConsoleMode(current->inh, ENABLE_PROCESSED_INPUT);
575 static void disableRawMode(struct current *current)
577 SetConsoleMode(current->inh, orig_consolemode);
580 static void clearScreen(struct current *current)
582 COORD topleft = { 0, 0 };
585 FillConsoleOutputCharacter(current->outh, ' ',
586 current->cols * current->rows, topleft, &n);
587 FillConsoleOutputAttribute(current->outh,
588 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN,
589 current->cols * current->rows, topleft, &n);
590 SetConsoleCursorPosition(current->outh, topleft);
593 static void cursorToLeft(struct current *current)
595 COORD pos = { 0, (SHORT)current->y };
598 FillConsoleOutputAttribute(current->outh,
599 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, current->cols, pos, &n);
603 static int outputChars(struct current *current, const char *buf, int len)
605 COORD pos = { (SHORT)current->x, (SHORT)current->y };
608 WriteConsoleOutputCharacter(current->outh, buf, len, pos, &n);
613 static void outputControlChar(struct current *current, char ch)
615 COORD pos = { (SHORT)current->x, (SHORT)current->y };
618 FillConsoleOutputAttribute(current->outh, BACKGROUND_INTENSITY, 2, pos, &n);
619 outputChars(current, "^", 1);
620 outputChars(current, &ch, 1);
623 static void eraseEol(struct current *current)
625 COORD pos = { (SHORT)current->x, (SHORT)current->y };
628 FillConsoleOutputCharacter(current->outh, ' ', current->cols - current->x, pos, &n);
631 static void setCursorPos(struct current *current, int x)
633 COORD pos = { (SHORT)x, (SHORT)current->y };
635 SetConsoleCursorPosition(current->outh, pos);
639 static int fd_read(struct current *current)
644 if (WaitForSingleObject(current->inh, INFINITE) != WAIT_OBJECT_0) {
647 if (!ReadConsoleInput (current->inh, &irec, 1, &n)) {
650 if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown) {
651 KEY_EVENT_RECORD *k = &irec.Event.KeyEvent;
652 if (k->dwControlKeyState & ENHANCED_KEY) {
653 switch (k->wVirtualKeyCode) {
657 return SPECIAL_RIGHT;
663 return SPECIAL_INSERT;
665 return SPECIAL_DELETE;
671 return SPECIAL_PAGE_UP;
673 return SPECIAL_PAGE_DOWN;
676 /* Note that control characters are already translated in AsciiChar */
679 return k->uChar.UnicodeChar;
681 return k->uChar.AsciiChar;
689 static int countColorControlChars(const char* prompt)
691 /* For windows we assume that there are no embedded ansi color
697 static int getWindowSize(struct current *current)
699 CONSOLE_SCREEN_BUFFER_INFO info;
700 if (!GetConsoleScreenBufferInfo(current->outh, &info)) {
703 current->cols = info.dwSize.X;
704 current->rows = info.dwSize.Y;
705 if (current->cols <= 0 || current->rows <= 0) {
709 current->y = info.dwCursorPosition.Y;
710 current->x = info.dwCursorPosition.X;
715 static int utf8_getchars(char *buf, int c)
718 return utf8_fromunicode(buf, c);
726 * Returns the unicode character at the given offset,
729 static int get_char(struct current *current, int pos)
731 if (pos >= 0 && pos < current->chars) {
733 int i = utf8_index(current->buf, pos);
734 (void)utf8_tounicode(current->buf + i, &c);
740 static void refreshLine(const char *prompt, struct current *current)
746 const char *buf = current->buf;
747 int chars = current->chars;
748 int pos = current->pos;
753 /* Should intercept SIGWINCH. For now, just get the size every time */
754 getWindowSize(current);
756 plen = strlen(prompt);
757 pchars = utf8_strlen(prompt, plen);
759 /* Scan the prompt for embedded ansi color control sequences and
760 * discount them as characters/columns.
762 pchars -= countColorControlChars(prompt);
764 /* Account for a line which is too long to fit in the window.
765 * Note that control chars require an extra column
768 /* How many cols are required to the left of 'pos'?
769 * The prompt, plus one extra for each control char
771 n = pchars + utf8_strlen(buf, current->len);
773 for (i = 0; i < pos; i++) {
774 b += utf8_tounicode(buf + b, &ch);
780 /* If too many are needed, strip chars off the front of 'buf'
781 * until it fits. Note that if the current char is a control character,
782 * we need one extra col.
784 if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
788 while (n >= current->cols && pos > 0) {
789 b = utf8_tounicode(buf, &ch);
799 /* Cursor to left edge, then the prompt */
800 cursorToLeft(current);
801 outputChars(current, prompt, plen);
803 /* Now the current buffer content */
805 /* Need special handling for control characters.
806 * If we hit 'cols', stop.
808 b = 0; /* unwritted bytes */
809 n = 0; /* How many control chars were written */
810 for (i = 0; i < chars; i++) {
812 int w = utf8_tounicode(buf + b, &ch);
816 if (pchars + i + n >= current->cols) {
820 /* A control character, so write the buffer so far */
821 outputChars(current, buf, b);
824 outputControlChar(current, ch + '@');
833 outputChars(current, buf, b);
835 /* Erase to right, move cursor to original position */
837 setCursorPos(current, pos + pchars + backup);
840 static void set_current(struct current *current, const char *str)
842 strncpy(current->buf, str, current->bufmax);
843 current->buf[current->bufmax - 1] = 0;
844 current->len = strlen(current->buf);
845 current->pos = current->chars = utf8_strlen(current->buf, current->len);
848 static int has_room(struct current *current, int bytes)
850 return current->len + bytes < current->bufmax - 1;
854 * Removes the char at 'pos'.
856 * Returns 1 if the line needs to be refreshed, 2 if not
857 * and 0 if nothing was removed
859 static int remove_char(struct current *current, int pos)
861 if (pos >= 0 && pos < current->chars) {
864 p1 = utf8_index(current->buf, pos);
865 p2 = p1 + utf8_index(current->buf + p1, 1);
868 /* optimise remove char in the case of removing the last char */
869 if (current->pos == pos + 1 && current->pos == current->chars) {
870 if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
872 fd_printf(current->fd, "\b \b");
877 /* Move the null char too */
878 memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
879 current->len -= (p2 - p1);
882 if (current->pos > pos) {
891 * Insert 'ch' at position 'pos'
893 * Returns 1 if the line needs to be refreshed, 2 if not
894 * and 0 if nothing was inserted (no room)
896 static int insert_char(struct current *current, int pos, int ch)
899 int n = utf8_getchars(buf, ch);
901 if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
904 p1 = utf8_index(current->buf, pos);
908 /* optimise the case where adding a single char to the end and no scrolling is needed */
909 if (current->pos == pos && current->chars == pos) {
910 if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
911 IGNORE_RC(write(current->fd, buf, n));
917 memmove(current->buf + p2, current->buf + p1, current->len - p1);
918 memcpy(current->buf + p1, buf, n);
922 if (current->pos >= pos) {
931 * Captures up to 'n' characters starting at 'pos' for the cut buffer.
933 * This replaces any existing characters in the cut buffer.
935 static void capture_chars(struct current *current, int pos, int n)
937 if (pos >= 0 && (pos + n - 1) < current->chars) {
938 int p1 = utf8_index(current->buf, pos);
939 int nbytes = utf8_index(current->buf + p1, n);
942 free(current->capture);
943 /* Include space for the null terminator */
944 current->capture = (char *)malloc(nbytes + 1);
945 memcpy(current->capture, current->buf + p1, nbytes);
946 current->capture[nbytes] = '\0';
952 * Removes up to 'n' characters at cursor position 'pos'.
954 * Returns 0 if no chars were removed or non-zero otherwise.
956 static int remove_chars(struct current *current, int pos, int n)
960 /* First save any chars which will be removed */
961 capture_chars(current, pos, n);
963 while (n-- && remove_char(current, pos)) {
969 * Inserts the characters (string) 'chars' at the cursor position 'pos'.
971 * Returns 0 if no chars were inserted or non-zero otherwise.
973 static int insert_chars(struct current *current, int pos, const char *chars)
979 int n = utf8_tounicode(chars, &ch);
980 if (insert_char(current, pos, ch) == 0) {
990 #ifndef NO_COMPLETION
991 static linenoiseCompletionCallback *completionCallback = NULL;
995 fprintf(stderr, "\x7");
1000 static void freeCompletions(linenoiseCompletions *lc) {
1002 for (i = 0; i < lc->len; i++)
1007 static int completeLine(struct current *current) {
1008 linenoiseCompletions lc = { 0, NULL };
1011 completionCallback(current->buf,&lc);
1015 size_t stop = 0, i = 0;
1018 /* Show completion or original buffer */
1020 struct current tmp = *current;
1021 tmp.buf = lc.cvec[i];
1022 tmp.pos = tmp.len = strlen(tmp.buf);
1023 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
1024 refreshLine(current->prompt, &tmp);
1026 refreshLine(current->prompt, current);
1029 c = fd_read(current);
1035 case '\t': /* tab */
1036 i = (i+1) % (lc.len+1);
1037 if (i == lc.len) beep();
1039 case 27: /* escape */
1040 /* Re-show original buffer */
1042 refreshLine(current->prompt, current);
1047 /* Update buffer and return */
1049 set_current(current,lc.cvec[i]);
1057 freeCompletions(&lc);
1058 return c; /* Return last read character */
1061 /* Register a callback function to be called for tab-completion. */
1062 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
1063 completionCallback = fn;
1066 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
1067 lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
1068 lc->cvec[lc->len++] = strdup(str);
1073 static int linenoiseEdit(struct current *current) {
1074 int history_index = 0;
1076 /* The latest history entry is always our current buffer, that
1077 * initially is just an empty string. */
1078 linenoiseHistoryAdd("");
1080 set_current(current, "");
1081 refreshLine(current->prompt, current);
1085 int c = fd_read(current);
1087 #ifndef NO_COMPLETION
1088 /* Only autocomplete when the callback is set. It returns < 0 when
1089 * there was an error reading from fd. Otherwise it will return the
1090 * character that should be handled next. */
1091 if (c == '\t' && current->pos == current->chars && completionCallback != NULL) {
1092 c = completeLine(current);
1093 /* Return on errors */
1094 if (c < 0) return current->len;
1095 /* Read next character when 0 */
1096 if (c == 0) continue;
1101 if (c == -1) return current->len;
1103 if (c == 27) { /* escape sequence */
1104 c = check_special(current->fd);
1108 case '\r': /* enter */
1110 free(history[history_len]);
1111 return current->len;
1112 case ctrl('C'): /* ctrl-c */
1115 case 127: /* backspace */
1117 if (remove_char(current, current->pos - 1) == 1) {
1118 refreshLine(current->prompt, current);
1121 case ctrl('D'): /* ctrl-d */
1122 if (current->len == 0) {
1123 /* Empty line, so EOF */
1125 free(history[history_len]);
1128 /* Otherwise fall through to delete char to right of cursor */
1129 case SPECIAL_DELETE:
1130 if (remove_char(current, current->pos) == 1) {
1131 refreshLine(current->prompt, current);
1134 case SPECIAL_INSERT:
1135 /* Ignore. Expansion Hook.
1136 * Future possibility: Toggle Insert/Overwrite Modes
1139 case ctrl('W'): /* ctrl-w, delete word at left. save deleted chars */
1140 /* eat any spaces on the left */
1142 int pos = current->pos;
1143 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1147 /* now eat any non-spaces on the left */
1148 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1152 if (remove_chars(current, pos, current->pos - pos)) {
1153 refreshLine(current->prompt, current);
1157 case ctrl('R'): /* ctrl-r */
1159 /* Display the reverse-i-search prompt and process chars */
1164 int searchpos = history_len - 1;
1169 const char *p = NULL;
1173 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1174 refreshLine(rprompt, current);
1175 c = fd_read(current);
1176 if (c == ctrl('H') || c == 127) {
1178 int p = utf8_index(rbuf, --rchars);
1180 rlen = strlen(rbuf);
1186 c = check_special(current->fd);
1189 if (c == ctrl('P') || c == SPECIAL_UP) {
1190 /* Search for the previous (earlier) match */
1191 if (searchpos > 0) {
1196 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1197 /* Search for the next (later) match */
1198 if (searchpos < history_len) {
1204 else if (c >= ' ') {
1205 if (rlen >= (int)sizeof(rbuf) + 3) {
1209 n = utf8_getchars(rbuf + rlen, c);
1214 /* Adding a new char resets the search location */
1215 searchpos = history_len - 1;
1218 /* Exit from incremental search mode */
1222 /* Now search through the history for a match */
1223 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1224 p = strstr(history[searchpos], rbuf);
1227 if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
1228 /* But it is identical, so skip it */
1231 /* Copy the matching line and set the cursor position */
1232 set_current(current,history[searchpos]);
1233 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1238 /* No match, so don't add it */
1244 if (c == ctrl('G') || c == ctrl('C')) {
1245 /* ctrl-g terminates the search with no effect */
1246 set_current(current, "");
1249 else if (c == ctrl('J')) {
1250 /* ctrl-j terminates the search leaving the buffer in place */
1253 /* Go process the char normally */
1254 refreshLine(current->prompt, current);
1258 case ctrl('T'): /* ctrl-t */
1259 if (current->pos > 0 && current->pos <= current->chars) {
1260 /* If cursor is at end, transpose the previous two chars */
1261 int fixer = (current->pos == current->chars);
1262 c = get_char(current, current->pos - fixer);
1263 remove_char(current, current->pos - fixer);
1264 insert_char(current, current->pos - 1, c);
1265 refreshLine(current->prompt, current);
1268 case ctrl('V'): /* ctrl-v */
1269 if (has_room(current, 3)) {
1270 /* Insert the ^V first */
1271 if (insert_char(current, current->pos, c)) {
1272 refreshLine(current->prompt, current);
1273 /* Now wait for the next char. Can insert anything except \0 */
1274 c = fd_read(current);
1276 /* Remove the ^V first */
1277 remove_char(current, current->pos - 1);
1279 /* Insert the actual char */
1280 insert_char(current, current->pos, c);
1282 refreshLine(current->prompt, current);
1288 if (current->pos > 0) {
1290 refreshLine(current->prompt, current);
1295 if (current->pos < current->chars) {
1297 refreshLine(current->prompt, current);
1300 case SPECIAL_PAGE_UP:
1301 dir = history_len - history_index - 1; /* move to start of history */
1302 goto history_navigation;
1303 case SPECIAL_PAGE_DOWN:
1304 dir = -history_index; /* move to 0 == end of history, i.e. current */
1305 goto history_navigation;
1309 goto history_navigation;
1313 if (history_len > 1) {
1314 /* Update the current history entry before to
1315 * overwrite it with tne next one. */
1316 free(history[history_len - 1 - history_index]);
1317 history[history_len - 1 - history_index] = strdup(current->buf);
1318 /* Show the new entry */
1319 history_index += dir;
1320 if (history_index < 0) {
1323 } else if (history_index >= history_len) {
1324 history_index = history_len - 1;
1327 set_current(current, history[history_len - 1 - history_index]);
1328 refreshLine(current->prompt, current);
1331 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1334 refreshLine(current->prompt, current);
1336 case ctrl('E'): /* ctrl+e, go to the end of the line */
1338 current->pos = current->chars;
1339 refreshLine(current->prompt, current);
1341 case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */
1342 if (remove_chars(current, 0, current->pos)) {
1343 refreshLine(current->prompt, current);
1346 case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */
1347 if (remove_chars(current, current->pos, current->chars - current->pos)) {
1348 refreshLine(current->prompt, current);
1351 case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */
1352 if (current->capture && insert_chars(current, current->pos, current->capture)) {
1353 refreshLine(current->prompt, current);
1356 case ctrl('L'): /* Ctrl+L, clear screen */
1357 clearScreen(current);
1358 /* Force recalc of window size for serial terminals */
1360 refreshLine(current->prompt, current);
1363 /* Only tab is allowed without ^V */
1364 if (c == '\t' || c >= ' ') {
1365 if (insert_char(current, current->pos, c) == 1) {
1366 refreshLine(current->prompt, current);
1372 return current->len;
1375 int linenoiseColumns(void)
1377 struct current current;
1378 enableRawMode (¤t);
1379 getWindowSize (¤t);
1380 disableRawMode (¤t);
1381 return current.cols;
1384 char *linenoise(const char *prompt)
1387 struct current current;
1388 char buf[LINENOISE_MAX_LINE];
1390 if (enableRawMode(¤t) == -1) {
1391 printf("%s", prompt);
1393 if (fgets(buf, sizeof(buf), stdin) == NULL) {
1396 count = strlen(buf);
1397 if (count && buf[count-1] == '\n') {
1405 current.bufmax = sizeof(buf);
1409 current.prompt = prompt;
1410 current.capture = NULL;
1412 count = linenoiseEdit(¤t);
1414 disableRawMode(¤t);
1417 free(current.capture);
1425 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1426 int linenoiseHistoryAdd(const char *line) {
1429 if (history_max_len == 0) return 0;
1430 if (history == NULL) {
1431 history = (char **)malloc(sizeof(char*)*history_max_len);
1432 if (history == NULL) return 0;
1433 memset(history,0,(sizeof(char*)*history_max_len));
1436 /* do not insert duplicate lines into history */
1437 if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1441 linecopy = strdup(line);
1442 if (!linecopy) return 0;
1443 if (history_len == history_max_len) {
1445 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1448 history[history_len] = linecopy;
1453 int linenoiseHistoryGetMaxLen(void) {
1454 return history_max_len;
1457 int linenoiseHistorySetMaxLen(int len) {
1460 if (len < 1) return 0;
1462 int tocopy = history_len;
1464 newHistory = (char **)malloc(sizeof(char*)*len);
1465 if (newHistory == NULL) return 0;
1467 /* If we can't copy everything, free the elements we'll not use. */
1471 for (j = 0; j < tocopy-len; j++) free(history[j]);
1474 memset(newHistory,0,sizeof(char*)*len);
1475 memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy);
1477 history = newHistory;
1479 history_max_len = len;
1480 if (history_len > history_max_len)
1481 history_len = history_max_len;
1485 /* Save the history in the specified file. On success 0 is returned
1486 * otherwise -1 is returned. */
1487 int linenoiseHistorySave(const char *filename) {
1488 FILE *fp = fopen(filename,"w");
1491 if (fp == NULL) return -1;
1492 for (j = 0; j < history_len; j++) {
1493 const char *str = history[j];
1494 /* Need to encode backslash, nl and cr */
1499 else if (*str == '\n') {
1502 else if (*str == '\r') {
1517 /* Load the history from the specified file. If the file does not exist
1518 * zero is returned and no operation is performed.
1520 * If the file exists and the operation succeeded 0 is returned, otherwise
1521 * on error -1 is returned. */
1522 int linenoiseHistoryLoad(const char *filename) {
1523 FILE *fp = fopen(filename,"r");
1524 char buf[LINENOISE_MAX_LINE];
1526 if (fp == NULL) return -1;
1528 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1531 /* Decode backslash escaped values */
1532 for (src = dest = buf; *src; src++) {
1540 else if (*src == 'r') {
1548 /* Remove trailing newline */
1549 if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1554 linenoiseHistoryAdd(buf);
1560 /* Provide access to the history buffer.
1562 * If 'len' is not NULL, the length is stored in *len.
1564 char **linenoiseHistory(int *len) {