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>
121 #define HAVE_UNISTD_H
135 #include <sys/types.h>
137 #include "linenoise.h"
140 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
141 #define LINENOISE_MAX_LINE 4096
143 #define ctrl(C) ((C) - '@')
145 /* Use -ve numbers here to co-exist with normal unicode chars */
152 SPECIAL_DELETE = -24,
155 SPECIAL_INSERT = -27,
156 SPECIAL_PAGE_UP = -28,
157 SPECIAL_PAGE_DOWN = -29
160 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
161 static int history_len = 0;
162 static char **history = NULL;
164 /* Structure to contain the status of the current (being edited) line */
166 char *buf; /* Current buffer. Always null terminated */
167 int bufmax; /* Size of the buffer, including space for the null termination */
168 int len; /* Number of bytes in 'buf' */
169 int chars; /* Number of chars in 'buf' (utf-8 chars) */
170 int pos; /* Cursor position, measured in chars */
171 int cols; /* Size of the window, in chars */
173 char *capture; /* Allocated capture buffer, or NULL for none. Always null terminated */
174 #if defined(USE_TERMIOS)
175 int fd; /* Terminal fd */
176 #elif defined(USE_WINCONSOLE)
177 HANDLE outh; /* Console output handle */
178 HANDLE inh; /* Console input handle */
179 int rows; /* Screen rows */
180 int x; /* Current column during output */
181 int y; /* Current row */
185 static int fd_read(struct current *current);
186 static int getWindowSize(struct current *current);
188 void linenoiseHistoryFree(void) {
192 for (j = 0; j < history_len; j++)
200 #if defined(USE_TERMIOS)
201 static void linenoiseAtExit(void);
202 static struct termios orig_termios; /* in order to restore at exit */
203 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
204 static int atexit_registered = 0; /* register atexit just 1 time */
206 static const char *unsupported_term[] = {"dumb","cons25",NULL};
208 static int isUnsupportedTerm(void) {
209 char *term = getenv("TERM");
213 for (j = 0; unsupported_term[j]; j++) {
214 if (strcmp(term, unsupported_term[j]) == 0) {
222 static int enableRawMode(struct current *current) {
225 current->fd = STDIN_FILENO;
228 if (!isatty(current->fd) || isUnsupportedTerm() ||
229 tcgetattr(current->fd, &orig_termios) == -1) {
235 if (!atexit_registered) {
236 atexit(linenoiseAtExit);
237 atexit_registered = 1;
240 raw = orig_termios; /* modify the original mode */
241 /* input modes: no break, no CR to NL, no parity check, no strip char,
242 * no start/stop output control. */
243 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
244 /* output modes - actually, no need to disable post processing */
245 /*raw.c_oflag &= ~(OPOST);*/
246 /* control modes - set 8 bit chars */
247 raw.c_cflag |= (CS8);
248 /* local modes - choing off, canonical off, no extended functions,
249 * no signal chars (^Z,^C) */
250 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
251 /* control chars - set return condition: min number of bytes and timer.
252 * We want read to return every single byte, without timeout. */
253 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
255 /* put terminal in raw mode after flushing */
256 if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
263 static void disableRawMode(struct current *current) {
264 /* Don't even check the return value as it's too late. */
265 if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
269 /* At exit we'll try to fix the terminal to the initial conditions. */
270 static void linenoiseAtExit(void) {
272 tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
274 linenoiseHistoryFree();
277 /* gcc/glibc insists that we care about the return code of write!
278 * Clarification: This means that a void-cast like "(void) (EXPR)"
281 #define IGNORE_RC(EXPR) if (EXPR) {}
283 /* This is fdprintf() on some systems, but use a different
284 * name to avoid conflicts
286 static void fd_printf(int fd, const char *format, ...)
292 va_start(args, format);
293 n = vsnprintf(buf, sizeof(buf), format, args);
294 /* This will never happen because we are sure to use fd_printf() for short sequences */
295 assert(n < sizeof(buf));
297 IGNORE_RC(write(fd, buf, n));
300 void linenoiseClearScreen(void)
302 fd_printf(STDOUT_FILENO, "\x1b[H\x1b[2J");
305 static void cursorToLeft(struct current *current)
307 fd_printf(current->fd, "\r");
310 static int outputChars(struct current *current, const char *buf, int len)
312 return write(current->fd, buf, len);
315 static void outputControlChar(struct current *current, char ch)
317 fd_printf(current->fd, "\x1b[7m^%c\x1b[0m", ch);
320 static void eraseEol(struct current *current)
322 fd_printf(current->fd, "\x1b[0K");
325 static void setCursorPos(struct current *current, int x)
328 cursorToLeft(current);
331 fd_printf(current->fd, "\r\x1b[%dC", x);
336 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
338 * A timeout of -1 means to wait forever.
340 * Returns -1 if no char is received within the time or an error occurs.
342 static int fd_read_char(int fd, int timeout)
350 if (poll(&p, 1, timeout) == 0) {
354 if (read(fd, &c, 1) != 1) {
361 * Reads a complete utf-8 character
362 * and returns the unicode value, or -1 on error.
364 static int fd_read(struct current *current)
367 char buf[MAX_UTF8_LEN];
372 if (read(current->fd, &buf[0], 1) != 1) {
375 n = utf8_charlen(buf[0]);
379 for (i = 1; i < n; i++) {
380 if (read(current->fd, &buf[i], 1) != 1) {
384 /* decode and return the character */
385 utf8_tounicode(buf, &c);
388 return fd_read_char(current->fd, -1);
392 static int countColorControlChars(const char* prompt)
394 /* ANSI color control sequences have the form:
395 * "\x1b" "[" [0-9;]* "m"
396 * We parse them with a simple state machine.
403 } state = search_esc;
404 int len = 0, found = 0;
407 /* XXX: Strictly we should be checking utf8 chars rather than
408 * bytes in case of the extremely unlikely scenario where
409 * an ANSI sequence is part of a utf8 sequence.
411 while ((ch = *prompt++) != 0) {
415 state = expect_bracket;
420 state = expect_trail;
421 /* 3 for "\e[ ... m" */
428 if ((ch == ';') || ((ch >= '0' && ch <= '9'))) {
429 /* 0-9, or semicolon */
445 * Stores the current cursor column in '*cols'.
446 * Returns 1 if OK, or 0 if failed to determine cursor pos.
448 static int queryCursor(int fd, int* cols)
450 /* control sequence - report cursor location */
451 fd_printf(fd, "\x1b[6n");
453 /* Parse the response: ESC [ rows ; cols R */
454 if (fd_read_char(fd, 100) == 0x1b &&
455 fd_read_char(fd, 100) == '[') {
459 int ch = fd_read_char(fd, 100);
464 else if (ch == 'R') {
466 if (n != 0 && n < 1000) {
471 else if (ch >= 0 && ch <= '9') {
472 n = n * 10 + ch - '0';
485 * Updates current->cols with the current window size (width)
487 static int getWindowSize(struct current *current)
491 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
492 current->cols = ws.ws_col;
496 /* Failed to query the window size. Perhaps we are on a serial terminal.
497 * Try to query the width by sending the cursor as far to the right
498 * and reading back the cursor position.
499 * Note that this is only done once per call to linenoise rather than
500 * every time the line is refreshed for efficiency reasons.
502 * In more detail, we:
503 * (a) request current cursor position,
504 * (b) move cursor far right,
505 * (c) request cursor position again,
506 * (d) at last move back to the old position.
507 * This gives us the width without messing with the externally
508 * visible cursor position.
511 if (current->cols == 0) {
517 if (queryCursor (current->fd, &here)) {
519 fd_printf(current->fd, "\x1b[999C");
521 /* (c). Note: If (a) succeeded, then (c) should as well.
522 * For paranoia we still check and have a fallback action
523 * for (d) in case of failure..
525 if (!queryCursor (current->fd, ¤t->cols)) {
526 /* (d') Unable to get accurate position data, reset
527 * the cursor to the far left. While this may not
528 * restore the exact original position it should not
531 fd_printf(current->fd, "\r");
533 /* (d) Reset the cursor back to the original location. */
534 if (current->cols > here) {
535 fd_printf(current->fd, "\x1b[%dD", current->cols - here);
538 } /* 1st query failed, doing nothing => default 80 */
545 * If escape (27) was received, reads subsequent
546 * chars to determine if this is a known special key.
548 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
550 * If no additional char is received within a short time,
553 static int check_special(int fd)
555 int c = fd_read_char(fd, 50);
562 c2 = fd_read_char(fd, 50);
566 if (c == '[' || c == 'O') {
567 /* Potential arrow key */
574 return SPECIAL_RIGHT;
583 if (c == '[' && c2 >= '1' && c2 <= '8') {
584 /* extended escape */
585 c = fd_read_char(fd, 50);
589 return SPECIAL_INSERT;
591 return SPECIAL_DELETE;
593 return SPECIAL_PAGE_UP;
595 return SPECIAL_PAGE_DOWN;
602 while (c != -1 && c != '~') {
603 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
604 c = fd_read_char(fd, 50);
610 #elif defined(USE_WINCONSOLE)
612 static DWORD orig_consolemode = 0;
614 static int enableRawMode(struct current *current) {
618 current->outh = GetStdHandle(STD_OUTPUT_HANDLE);
619 current->inh = GetStdHandle(STD_INPUT_HANDLE);
621 if (!PeekConsoleInput(current->inh, &irec, 1, &n)) {
624 if (getWindowSize(current) != 0) {
627 if (GetConsoleMode(current->inh, &orig_consolemode)) {
628 SetConsoleMode(current->inh, ENABLE_PROCESSED_INPUT);
633 static void disableRawMode(struct current *current)
635 SetConsoleMode(current->inh, orig_consolemode);
638 void linenoiseClearScreen(void)
640 /* XXX: This is ugly. Should just have the caller pass a handle */
641 struct current current;
643 current.outh = GetStdHandle(STD_OUTPUT_HANDLE);
645 if (getWindowSize(¤t) == 0) {
646 COORD topleft = { 0, 0 };
649 FillConsoleOutputCharacter(current.outh, ' ',
650 current.cols * current.rows, topleft, &n);
651 FillConsoleOutputAttribute(current.outh,
652 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN,
653 current.cols * current.rows, topleft, &n);
654 SetConsoleCursorPosition(current.outh, topleft);
658 static void cursorToLeft(struct current *current)
664 pos.Y = (SHORT)current->y;
666 FillConsoleOutputAttribute(current->outh,
667 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, current->cols, pos, &n);
671 static int outputChars(struct current *current, const char *buf, int len)
676 pos.Y = (SHORT)current->y;
683 s = utf8_tounicode(buf, &c);
690 pos.X = (SHORT)current->x;
692 /* fixed display utf8 character */
693 WriteConsoleOutputCharacterW(current->outh, &wc, 1, pos, &n);
695 current->x += utf8_width(c);
698 pos.X = (SHORT)current->x;
700 WriteConsoleOutputCharacterA(current->outh, buf, len, pos, &n);
707 static void outputControlChar(struct current *current, char ch)
712 pos.X = (SHORT) current->x;
713 pos.Y = (SHORT) current->y;
715 FillConsoleOutputAttribute(current->outh, BACKGROUND_INTENSITY, 2, pos, &n);
716 outputChars(current, "^", 1);
717 outputChars(current, &ch, 1);
720 static void eraseEol(struct current *current)
725 pos.X = (SHORT) current->x;
726 pos.Y = (SHORT) current->y;
728 FillConsoleOutputCharacter(current->outh, ' ', current->cols - current->x, pos, &n);
731 static void setCursorPos(struct current *current, int x)
736 pos.Y = (SHORT) current->y;
738 SetConsoleCursorPosition(current->outh, pos);
742 static int fd_read(struct current *current)
747 if (WaitForSingleObject(current->inh, INFINITE) != WAIT_OBJECT_0) {
750 if (!ReadConsoleInput (current->inh, &irec, 1, &n)) {
753 if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown) {
754 KEY_EVENT_RECORD *k = &irec.Event.KeyEvent;
755 if (k->dwControlKeyState & ENHANCED_KEY) {
756 switch (k->wVirtualKeyCode) {
760 return SPECIAL_RIGHT;
766 return SPECIAL_INSERT;
768 return SPECIAL_DELETE;
774 return SPECIAL_PAGE_UP;
776 return SPECIAL_PAGE_DOWN;
779 /* Note that control characters are already translated in AsciiChar */
780 else if (k->wVirtualKeyCode == VK_CONTROL)
784 return k->uChar.UnicodeChar;
786 return k->uChar.AsciiChar;
794 static int countColorControlChars(const char* prompt)
796 /* For windows we assume that there are no embedded ansi color
802 static int getWindowSize(struct current *current)
804 CONSOLE_SCREEN_BUFFER_INFO info;
805 if (!GetConsoleScreenBufferInfo(current->outh, &info)) {
808 current->cols = info.dwSize.X;
809 current->rows = info.dwSize.Y;
810 if (current->cols <= 0 || current->rows <= 0) {
814 current->y = info.dwCursorPosition.Y;
815 current->x = info.dwCursorPosition.X;
820 #ifndef utf8_getchars
821 static int utf8_getchars(char *buf, int c)
824 return utf8_fromunicode(buf, c);
833 * Returns the unicode character at the given offset,
836 static int get_char(struct current *current, int pos)
838 if (pos >= 0 && pos < current->chars) {
840 int i = utf8_index(current->buf, pos);
841 (void)utf8_tounicode(current->buf + i, &c);
847 static void refreshLine(const char *prompt, struct current *current)
853 const char *buf = current->buf;
854 int chars = current->chars;
855 int pos = current->pos;
862 /* Should intercept SIGWINCH. For now, just get the size every time */
863 getWindowSize(current);
865 plen = strlen(prompt);
866 pchars = utf8_strwidth(prompt, utf8_strlen(prompt, plen));
868 /* Scan the prompt for embedded ansi color control sequences and
869 * discount them as characters/columns.
871 pchars -= countColorControlChars(prompt);
873 /* Account for a line which is too long to fit in the window.
874 * Note that control chars require an extra column
877 /* How many cols are required to the left of 'pos'?
878 * The prompt, plus one extra for each control char
880 n = pchars + utf8_strwidth(buf, utf8_strlen(buf, current->len));
882 for (i = 0; i < pos; i++) {
883 b += utf8_tounicode(buf + b, &ch);
889 /* Pluse one if the current char is a control character */
890 if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
894 /* If too many are needed, strip chars off the front of 'buf'
895 * until it fits. Note that if the current char is a control character,
896 * we need one extra col.
898 while (n >= current->cols && pos > 0) {
899 b = utf8_tounicode(buf, &ch);
909 /* Cursor to left edge, then the prompt */
910 cursorToLeft(current);
911 outputChars(current, prompt, plen);
913 /* Now the current buffer content */
915 /* Need special handling for control characters.
916 * If we hit 'cols', stop.
918 b = 0; /* unwritted bytes */
919 n = 0; /* How many control chars were written */
920 width = 0; /* current display width */
921 bufwidth = utf8_strwidth(buf, pos);
923 for (i = 0; i < chars; i++) {
925 int w = utf8_tounicode(buf + b, &ch);
930 width += utf8_width(ch);
932 if (pchars + width + n >= current->cols) {
936 /* A control character, so write the buffer so far */
937 outputChars(current, buf, b);
940 outputControlChar(current, ch + '@');
949 outputChars(current, buf, b);
951 /* Erase to right, move cursor to original position */
953 setCursorPos(current, bufwidth + pchars + backup);
956 static void set_current(struct current *current, const char *str)
958 strncpy(current->buf, str, current->bufmax);
959 current->buf[current->bufmax - 1] = 0;
960 current->len = strlen(current->buf);
961 current->pos = current->chars = utf8_strlen(current->buf, current->len);
964 static int has_room(struct current *current, int bytes)
966 return current->len + bytes < current->bufmax - 1;
970 * Removes the char at 'pos'.
972 * Returns 1 if the line needs to be refreshed, 2 if not
973 * and 0 if nothing was removed
975 static int remove_char(struct current *current, int pos)
977 if (pos >= 0 && pos < current->chars) {
980 p1 = utf8_index(current->buf, pos);
981 p2 = p1 + utf8_index(current->buf + p1, 1);
984 /* optimise remove char in the case of removing the last char */
985 if (current->pos == pos + 1 && current->pos == current->chars) {
986 if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
988 fd_printf(current->fd, "\b \b");
993 /* Move the null char too */
994 memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
995 current->len -= (p2 - p1);
998 if (current->pos > pos) {
1007 * Insert 'ch' at position 'pos'
1009 * Returns 1 if the line needs to be refreshed, 2 if not
1010 * and 0 if nothing was inserted (no room)
1012 static int insert_char(struct current *current, int pos, int ch)
1014 char buf[MAX_UTF8_LEN];
1015 int n = utf8_getchars(buf, ch);
1017 if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
1020 p1 = utf8_index(current->buf, pos);
1024 /* optimise the case where adding a single char to the end and no scrolling is needed */
1025 if (current->pos == pos && current->chars == pos) {
1026 if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
1027 IGNORE_RC(write(current->fd, buf, n));
1033 memmove(current->buf + p2, current->buf + p1, current->len - p1);
1034 memcpy(current->buf + p1, buf, n);
1038 if (current->pos >= pos) {
1047 * Captures up to 'n' characters starting at 'pos' for the cut buffer.
1049 * This replaces any existing characters in the cut buffer.
1051 static void capture_chars(struct current *current, int pos, int n)
1053 if (pos >= 0 && (pos + n - 1) < current->chars) {
1054 int p1 = utf8_index(current->buf, pos);
1055 int nbytes = utf8_index(current->buf + p1, n);
1058 free(current->capture);
1059 /* Include space for the null terminator */
1060 current->capture = (char *)malloc(nbytes + 1);
1061 memcpy(current->capture, current->buf + p1, nbytes);
1062 current->capture[nbytes] = '\0';
1068 * Removes up to 'n' characters at cursor position 'pos'.
1070 * Returns 0 if no chars were removed or non-zero otherwise.
1072 static int remove_chars(struct current *current, int pos, int n)
1076 /* First save any chars which will be removed */
1077 capture_chars(current, pos, n);
1079 while (n-- && remove_char(current, pos)) {
1085 * Inserts the characters (string) 'chars' at the cursor position 'pos'.
1087 * Returns 0 if no chars were inserted or non-zero otherwise.
1089 static int insert_chars(struct current *current, int pos, const char *chars)
1095 int n = utf8_tounicode(chars, &ch);
1096 if (insert_char(current, pos, ch) == 0) {
1106 #ifndef NO_COMPLETION
1107 static linenoiseCompletionCallback *completionCallback = NULL;
1108 static void *completionUserdata = NULL;
1110 static void beep() {
1112 fprintf(stderr, "\x7");
1117 static void freeCompletions(linenoiseCompletions *lc) {
1119 for (i = 0; i < lc->len; i++)
1124 static int completeLine(struct current *current) {
1125 linenoiseCompletions lc = { 0, NULL };
1128 completionCallback(current->buf,&lc,completionUserdata);
1132 size_t stop = 0, i = 0;
1135 /* Show completion or original buffer */
1137 struct current tmp = *current;
1138 tmp.buf = lc.cvec[i];
1139 tmp.pos = tmp.len = strlen(tmp.buf);
1140 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
1141 refreshLine(current->prompt, &tmp);
1143 refreshLine(current->prompt, current);
1146 c = fd_read(current);
1152 case '\t': /* tab */
1153 i = (i+1) % (lc.len+1);
1154 if (i == lc.len) beep();
1156 case 27: /* escape */
1157 /* Re-show original buffer */
1159 refreshLine(current->prompt, current);
1164 /* Update buffer and return */
1166 set_current(current,lc.cvec[i]);
1174 freeCompletions(&lc);
1175 return c; /* Return last read character */
1178 /* Register a callback function to be called for tab-completion.
1179 Returns the prior callback so that the caller may (if needed)
1180 restore it when done. */
1181 linenoiseCompletionCallback * linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn, void *userdata) {
1182 linenoiseCompletionCallback * old = completionCallback;
1183 completionCallback = fn;
1184 completionUserdata = userdata;
1188 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
1189 lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
1190 lc->cvec[lc->len++] = strdup(str);
1195 static int linenoiseEdit(struct current *current) {
1196 int history_index = 0;
1198 /* The latest history entry is always our current buffer, that
1199 * initially is just an empty string. */
1200 linenoiseHistoryAdd("");
1202 set_current(current, "");
1203 refreshLine(current->prompt, current);
1207 int c = fd_read(current);
1209 #ifndef NO_COMPLETION
1210 /* Only autocomplete when the callback is set. It returns < 0 when
1211 * there was an error reading from fd. Otherwise it will return the
1212 * character that should be handled next. */
1213 if (c == '\t' && current->pos == current->chars && completionCallback != NULL) {
1214 c = completeLine(current);
1215 /* Return on errors */
1216 if (c < 0) return current->len;
1217 /* Read next character when 0 */
1218 if (c == 0) continue;
1223 if (c == -1) return current->len;
1225 if (c == 27) { /* escape sequence */
1226 c = check_special(current->fd);
1230 case '\r': /* enter */
1232 free(history[history_len]);
1233 return current->len;
1234 case ctrl('C'): /* ctrl-c */
1237 case ctrl('Z'): /* ctrl-z */
1239 /* send ourselves SIGSUSP */
1240 disableRawMode(current);
1243 enableRawMode(current);
1244 refreshLine(current->prompt, current);
1247 case 127: /* backspace */
1249 if (remove_char(current, current->pos - 1) == 1) {
1250 refreshLine(current->prompt, current);
1253 case ctrl('D'): /* ctrl-d */
1254 if (current->len == 0) {
1255 /* Empty line, so EOF */
1257 free(history[history_len]);
1260 /* Otherwise fall through to delete char to right of cursor */
1261 case SPECIAL_DELETE:
1262 if (remove_char(current, current->pos) == 1) {
1263 refreshLine(current->prompt, current);
1266 case SPECIAL_INSERT:
1267 /* Ignore. Expansion Hook.
1268 * Future possibility: Toggle Insert/Overwrite Modes
1271 case ctrl('W'): /* ctrl-w, delete word at left. save deleted chars */
1272 /* eat any spaces on the left */
1274 int pos = current->pos;
1275 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1279 /* now eat any non-spaces on the left */
1280 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1284 if (remove_chars(current, pos, current->pos - pos)) {
1285 refreshLine(current->prompt, current);
1289 case ctrl('R'): /* ctrl-r */
1291 /* Display the reverse-i-search prompt and process chars */
1296 int searchpos = history_len - 1;
1301 const char *p = NULL;
1305 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1306 refreshLine(rprompt, current);
1307 c = fd_read(current);
1308 if (c == ctrl('H') || c == 127) {
1310 int p = utf8_index(rbuf, --rchars);
1312 rlen = strlen(rbuf);
1318 c = check_special(current->fd);
1321 if (c == ctrl('P') || c == SPECIAL_UP) {
1322 /* Search for the previous (earlier) match */
1323 if (searchpos > 0) {
1328 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1329 /* Search for the next (later) match */
1330 if (searchpos < history_len) {
1336 else if (c >= ' ') {
1337 /* >= here to allow for null terminator */
1338 if (rlen >= (int)sizeof(rbuf) - MAX_UTF8_LEN) {
1342 n = utf8_getchars(rbuf + rlen, c);
1347 /* Adding a new char resets the search location */
1348 searchpos = history_len - 1;
1351 /* Exit from incremental search mode */
1355 /* Now search through the history for a match */
1356 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1357 p = strstr(history[searchpos], rbuf);
1360 if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
1361 /* But it is identical, so skip it */
1364 /* Copy the matching line and set the cursor position */
1365 set_current(current,history[searchpos]);
1366 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1371 /* No match, so don't add it */
1377 if (c == ctrl('G') || c == ctrl('C')) {
1378 /* ctrl-g terminates the search with no effect */
1379 set_current(current, "");
1382 else if (c == ctrl('J')) {
1383 /* ctrl-j terminates the search leaving the buffer in place */
1386 /* Go process the char normally */
1387 refreshLine(current->prompt, current);
1391 case ctrl('T'): /* ctrl-t */
1392 if (current->pos > 0 && current->pos <= current->chars) {
1393 /* If cursor is at end, transpose the previous two chars */
1394 int fixer = (current->pos == current->chars);
1395 c = get_char(current, current->pos - fixer);
1396 remove_char(current, current->pos - fixer);
1397 insert_char(current, current->pos - 1, c);
1398 refreshLine(current->prompt, current);
1401 case ctrl('V'): /* ctrl-v */
1402 if (has_room(current, MAX_UTF8_LEN)) {
1403 /* Insert the ^V first */
1404 if (insert_char(current, current->pos, c)) {
1405 refreshLine(current->prompt, current);
1406 /* Now wait for the next char. Can insert anything except \0 */
1407 c = fd_read(current);
1409 /* Remove the ^V first */
1410 remove_char(current, current->pos - 1);
1412 /* Insert the actual char */
1413 insert_char(current, current->pos, c);
1415 refreshLine(current->prompt, current);
1421 if (current->pos > 0) {
1423 refreshLine(current->prompt, current);
1428 if (current->pos < current->chars) {
1430 refreshLine(current->prompt, current);
1433 case SPECIAL_PAGE_UP:
1434 dir = history_len - history_index - 1; /* move to start of history */
1435 goto history_navigation;
1436 case SPECIAL_PAGE_DOWN:
1437 dir = -history_index; /* move to 0 == end of history, i.e. current */
1438 goto history_navigation;
1442 goto history_navigation;
1446 if (history_len > 1) {
1447 /* Update the current history entry before to
1448 * overwrite it with tne next one. */
1449 free(history[history_len - 1 - history_index]);
1450 history[history_len - 1 - history_index] = strdup(current->buf);
1451 /* Show the new entry */
1452 history_index += dir;
1453 if (history_index < 0) {
1456 } else if (history_index >= history_len) {
1457 history_index = history_len - 1;
1460 set_current(current, history[history_len - 1 - history_index]);
1461 refreshLine(current->prompt, current);
1464 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1467 refreshLine(current->prompt, current);
1469 case ctrl('E'): /* ctrl+e, go to the end of the line */
1471 current->pos = current->chars;
1472 refreshLine(current->prompt, current);
1474 case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */
1475 if (remove_chars(current, 0, current->pos)) {
1476 refreshLine(current->prompt, current);
1479 case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */
1480 if (remove_chars(current, current->pos, current->chars - current->pos)) {
1481 refreshLine(current->prompt, current);
1484 case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */
1485 if (current->capture && insert_chars(current, current->pos, current->capture)) {
1486 refreshLine(current->prompt, current);
1489 case ctrl('L'): /* Ctrl+L, clear screen */
1490 linenoiseClearScreen();
1491 /* Force recalc of window size for serial terminals */
1493 refreshLine(current->prompt, current);
1496 /* Only tab is allowed without ^V */
1497 if (c == '\t' || c >= ' ') {
1498 if (insert_char(current, current->pos, c) == 1) {
1499 refreshLine(current->prompt, current);
1505 return current->len;
1508 int linenoiseColumns(void)
1510 struct current current;
1511 enableRawMode (¤t);
1512 getWindowSize (¤t);
1513 disableRawMode (¤t);
1514 return current.cols;
1517 char *linenoise(const char *prompt)
1520 struct current current;
1521 char buf[LINENOISE_MAX_LINE];
1523 if (enableRawMode(¤t) == -1) {
1524 printf("%s", prompt);
1526 if (fgets(buf, sizeof(buf), stdin) == NULL) {
1529 count = strlen(buf);
1530 if (count && buf[count-1] == '\n') {
1538 current.bufmax = sizeof(buf);
1542 current.prompt = prompt;
1543 current.capture = NULL;
1545 count = linenoiseEdit(¤t);
1547 disableRawMode(¤t);
1550 free(current.capture);
1558 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1559 int linenoiseHistoryAdd(const char *line) {
1562 if (history_max_len == 0) return 0;
1563 if (history == NULL) {
1564 history = (char **)malloc(sizeof(char*)*history_max_len);
1565 if (history == NULL) return 0;
1566 memset(history,0,(sizeof(char*)*history_max_len));
1569 /* do not insert duplicate lines into history */
1570 if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1574 linecopy = strdup(line);
1575 if (!linecopy) return 0;
1576 if (history_len == history_max_len) {
1578 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1581 history[history_len] = linecopy;
1586 int linenoiseHistoryGetMaxLen(void) {
1587 return history_max_len;
1590 int linenoiseHistorySetMaxLen(int len) {
1593 if (len < 1) return 0;
1595 int tocopy = history_len;
1597 newHistory = (char **)malloc(sizeof(char*)*len);
1598 if (newHistory == NULL) return 0;
1600 /* If we can't copy everything, free the elements we'll not use. */
1604 for (j = 0; j < tocopy-len; j++) free(history[j]);
1607 memset(newHistory,0,sizeof(char*)*len);
1608 memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy);
1610 history = newHistory;
1612 history_max_len = len;
1613 if (history_len > history_max_len)
1614 history_len = history_max_len;
1618 /* Save the history in the specified file. On success 0 is returned
1619 * otherwise -1 is returned. */
1620 int linenoiseHistorySave(const char *filename) {
1621 FILE *fp = fopen(filename,"w");
1624 if (fp == NULL) return -1;
1625 for (j = 0; j < history_len; j++) {
1626 const char *str = history[j];
1627 /* Need to encode backslash, nl and cr */
1632 else if (*str == '\n') {
1635 else if (*str == '\r') {
1650 /* Load the history from the specified file. If the file does not exist
1651 * zero is returned and no operation is performed.
1653 * If the file exists and the operation succeeded 0 is returned, otherwise
1654 * on error -1 is returned. */
1655 int linenoiseHistoryLoad(const char *filename) {
1656 FILE *fp = fopen(filename,"r");
1657 char buf[LINENOISE_MAX_LINE];
1659 if (fp == NULL) return -1;
1661 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1664 /* Decode backslash escaped values */
1665 for (src = dest = buf; *src; src++) {
1673 else if (*src == 'r') {
1681 /* Remove trailing newline */
1682 if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1687 linenoiseHistoryAdd(buf);
1693 /* Provide access to the history buffer.
1695 * If 'len' is not NULL, the length is stored in *len.
1697 char **linenoiseHistory(int *len) {