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: clear from cursor to end of line
63 * CUF (CUrsor Forward)
65 * Effect: moves cursor forward n chars
67 * CR (Carriage Return)
69 * Effect: moves cursor to column 1
71 * The following are used to clear the screen: ESC [ H ESC [ 2 J
72 * This is actually composed of two sequences:
76 * Effect: moves the cursor to upper left corner
78 * ED2 (Clear entire screen)
80 * Effect: clear the whole screen
82 * == For highlighting control characters, we also use the following two ==
85 * Effect: Uses some standout mode such as reverse video
89 * Effect: Exit standout mode
91 * == Only used if TIOCGWINSZ fails ==
92 * DSR/CPR (Report cursor position)
94 * Effect: reports current cursor position as ESC [ NNN ; MMM R
96 * == Only used in multiline mode ==
99 * Effect: moves cursor up n chars.
102 * Sequence: ESC [ n B
103 * Effect: moves cursor down n chars.
107 * If __MINGW32__ is defined, the win32 console API is used.
108 * This could probably be made to work for the msvc compiler too.
109 * This support based in part on work by Jon Griffiths.
112 #ifdef _WIN32 /* Windows platform, either MinGW or Visual Studio (MSVC) */
115 #define USE_WINCONSOLE
117 #define HAVE_UNISTD_H
119 /* Microsoft headers don't like old POSIX names */
120 #define strdup _strdup
121 #define snprintf _snprintf
125 #include <sys/ioctl.h>
128 #define HAVE_UNISTD_H
142 #include <sys/types.h>
144 #include "linenoise.h"
146 #include "stringbuf.h"
150 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
152 #define ctrl(C) ((C) - '@')
154 /* Use -ve numbers here to co-exist with normal unicode chars */
157 /* don't use -1 here since that indicates error */
162 SPECIAL_DELETE = -24,
165 SPECIAL_INSERT = -27,
166 SPECIAL_PAGE_UP = -28,
167 SPECIAL_PAGE_DOWN = -29,
169 /* Some handy names for other special keycodes */
174 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
175 static int history_len = 0;
176 static char **history = NULL;
178 /* Structure to contain the status of the current (being edited) line */
180 stringbuf *buf; /* Current buffer. Always null terminated */
181 int pos; /* Cursor position, measured in chars */
182 int cols; /* Size of the window, in chars */
183 int nrows; /* How many rows are being used in multiline mode (>= 1) */
184 int rpos; /* The current row containing the cursor - multiline mode only */
185 int colsright; /* refreshLine() cached cols for insert_char() optimisation */
186 int colsleft; /* refreshLine() cached cols for remove_char() optimisation */
188 stringbuf *capture; /* capture buffer, or NULL for none. Always null terminated */
189 stringbuf *output; /* used only during refreshLine() - output accumulator */
190 #if defined(USE_TERMIOS)
191 int fd; /* Terminal fd */
192 #elif defined(USE_WINCONSOLE)
193 HANDLE outh; /* Console output handle */
194 HANDLE inh; /* Console input handle */
195 int rows; /* Screen rows */
196 int x; /* Current column during output */
197 int y; /* Current row */
199 #define UBUF_MAX_CHARS 132
200 WORD ubuf[UBUF_MAX_CHARS + 1]; /* Accumulates utf16 output - one extra for final surrogate pairs */
201 int ubuflen; /* length used in ubuf */
202 int ubufcols; /* how many columns are represented by the chars in ubuf? */
207 static int fd_read(struct current *current);
208 static int getWindowSize(struct current *current);
209 static void cursorDown(struct current *current, int n);
210 static void cursorUp(struct current *current, int n);
211 static void eraseEol(struct current *current);
212 static void refreshLine(struct current *current);
213 static void refreshLineAlt(struct current *current, const char *prompt, const char *buf, int cursor_pos);
214 static void setCursorPos(struct current *current, int x);
215 static void setOutputHighlight(struct current *current, const int *props, int nprops);
216 static void set_current(struct current *current, const char *str);
218 void linenoiseHistoryFree(void) {
222 for (j = 0; j < history_len; j++)
231 EP_START, /* looking for ESC */
232 EP_ESC, /* looking for [ */
233 EP_DIGITS, /* parsing digits */
234 EP_PROPS, /* parsing digits or semicolons */
236 EP_ERROR, /* error */
241 int props[5]; /* properties are stored here */
242 int maxprops; /* size of the props[] array */
243 int numprops; /* number of properties found */
244 int termchar; /* terminator char, or 0 for any alpha */
245 int current; /* current (partial) property value */
249 * Initialise the escape sequence parser at *parser.
251 * If termchar is 0 any alpha char terminates ok. Otherwise only the given
252 * char terminates successfully.
253 * Run the parser state machine with calls to parseEscapeSequence() for each char.
255 static void initParseEscapeSeq(struct esc_parser *parser, int termchar)
257 parser->state = EP_START;
258 parser->maxprops = sizeof(parser->props) / sizeof(*parser->props);
259 parser->numprops = 0;
261 parser->termchar = termchar;
265 * Pass character 'ch' into the state machine to parse:
266 * 'ESC' '[' <digits> (';' <digits>)* <termchar>
268 * The first character must be ESC.
269 * Returns the current state. The state machine is done when it returns either EP_END
272 * On EP_END, the "property/attribute" values can be read from parser->props[]
273 * of length parser->numprops.
275 static int parseEscapeSequence(struct esc_parser *parser, int ch)
277 switch (parser->state) {
279 parser->state = (ch == '\x1b') ? EP_ESC : EP_ERROR;
282 parser->state = (ch == '[') ? EP_DIGITS : EP_ERROR;
286 parser->state = EP_DIGITS;
288 if (parser->numprops + 1 < parser->maxprops) {
289 parser->props[parser->numprops++] = parser->current;
296 if (ch >= '0' && ch <= '9') {
297 parser->current = parser->current * 10 + (ch - '0');
298 parser->state = EP_PROPS;
301 /* must be terminator */
302 if (parser->termchar != ch) {
303 if (parser->termchar != 0 || !((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))) {
304 parser->state = EP_ERROR;
308 parser->state = EP_END;
311 parser->state = EP_ERROR;
316 return parser->state;
319 /*#define DEBUG_REFRESHLINE*/
321 #ifdef DEBUG_REFRESHLINE
322 #define DRL(ARGS...) fprintf(dfh, ARGS)
325 static void DRL_CHAR(int ch)
328 DRL("^%c", ch + '@');
337 static void DRL_STR(const char *str)
341 int n = utf8_tounicode(str, &ch);
352 #if defined(USE_WINCONSOLE)
353 #include "linenoise-win32.c"
356 #if defined(USE_TERMIOS)
357 static void linenoiseAtExit(void);
358 static struct termios orig_termios; /* in order to restore at exit */
359 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
360 static int atexit_registered = 0; /* register atexit just 1 time */
362 static const char *unsupported_term[] = {"dumb","cons25","emacs",NULL};
364 static int isUnsupportedTerm(void) {
365 char *term = getenv("TERM");
369 for (j = 0; unsupported_term[j]; j++) {
370 if (strcmp(term, unsupported_term[j]) == 0) {
378 static int enableRawMode(struct current *current) {
381 current->fd = STDIN_FILENO;
384 if (!isatty(current->fd) || isUnsupportedTerm() ||
385 tcgetattr(current->fd, &orig_termios) == -1) {
391 if (!atexit_registered) {
392 atexit(linenoiseAtExit);
393 atexit_registered = 1;
396 raw = orig_termios; /* modify the original mode */
397 /* input modes: no break, no CR to NL, no parity check, no strip char,
398 * no start/stop output control. */
399 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
400 /* output modes - actually, no need to disable post processing */
401 /*raw.c_oflag &= ~(OPOST);*/
402 /* control modes - set 8 bit chars */
403 raw.c_cflag |= (CS8);
404 /* local modes - choing off, canonical off, no extended functions,
405 * no signal chars (^Z,^C) */
406 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
407 /* control chars - set return condition: min number of bytes and timer.
408 * We want read to return every single byte, without timeout. */
409 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
411 /* put terminal in raw mode after flushing */
412 if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
419 static void disableRawMode(struct current *current) {
420 /* Don't even check the return value as it's too late. */
421 if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
425 /* At exit we'll try to fix the terminal to the initial conditions. */
426 static void linenoiseAtExit(void) {
428 tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
430 linenoiseHistoryFree();
433 /* gcc/glibc insists that we care about the return code of write!
434 * Clarification: This means that a void-cast like "(void) (EXPR)"
437 #define IGNORE_RC(EXPR) if (EXPR) {}
440 * Output bytes directly, or accumulate output (if current->output is set)
442 static void outputChars(struct current *current, const char *buf, int len)
447 if (current->output) {
448 sb_append_len(current->output, buf, len);
451 IGNORE_RC(write(current->fd, buf, len));
455 /* Like outputChars, but using printf-style formatting
457 static void outputFormatted(struct current *current, const char *format, ...)
463 va_start(args, format);
464 n = vsnprintf(buf, sizeof(buf), format, args);
465 /* This will never happen because we are sure to use outputFormatted() only for short sequences */
466 assert(n < (int)sizeof(buf));
468 outputChars(current, buf, n);
471 static void cursorToLeft(struct current *current)
473 outputChars(current, "\r", -1);
476 static void setOutputHighlight(struct current *current, const int *props, int nprops)
478 outputChars(current, "\x1b[", -1);
480 outputFormatted(current, "%d%c", *props, (nprops == 0) ? 'm' : ';');
485 static void eraseEol(struct current *current)
487 outputChars(current, "\x1b[0K", -1);
490 static void setCursorPos(struct current *current, int x)
493 cursorToLeft(current);
496 outputFormatted(current, "\r\x1b[%dC", x);
500 static void cursorUp(struct current *current, int n)
503 outputFormatted(current, "\x1b[%dA", n);
507 static void cursorDown(struct current *current, int n)
510 outputFormatted(current, "\x1b[%dB", n);
514 void linenoiseClearScreen(void)
516 IGNORE_RC(write(STDOUT_FILENO, "\x1b[H\x1b[2J", 7));
520 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
522 * A timeout of -1 means to wait forever.
524 * Returns -1 if no char is received within the time or an error occurs.
526 static int fd_read_char(int fd, int timeout)
534 if (poll(&p, 1, timeout) == 0) {
538 if (read(fd, &c, 1) != 1) {
545 * Reads a complete utf-8 character
546 * and returns the unicode value, or -1 on error.
548 static int fd_read(struct current *current)
551 char buf[MAX_UTF8_LEN];
556 if (read(current->fd, &buf[0], 1) != 1) {
559 n = utf8_charlen(buf[0]);
563 for (i = 1; i < n; i++) {
564 if (read(current->fd, &buf[i], 1) != 1) {
568 /* decode and return the character */
569 utf8_tounicode(buf, &c);
572 return fd_read_char(current->fd, -1);
578 * Stores the current cursor column in '*cols'.
579 * Returns 1 if OK, or 0 if failed to determine cursor pos.
581 static int queryCursor(struct current *current, int* cols)
583 struct esc_parser parser;
586 /* Should not be buffering this output, it needs to go immediately */
587 assert(current->output == NULL);
589 /* control sequence - report cursor location */
590 outputChars(current, "\x1b[6n", -1);
592 /* Parse the response: ESC [ rows ; cols R */
593 initParseEscapeSeq(&parser, 'R');
594 while ((ch = fd_read_char(current->fd, 100)) > 0) {
595 switch (parseEscapeSequence(&parser, ch)) {
599 if (parser.numprops == 2 && parser.props[1] < 1000) {
600 *cols = parser.props[1];
614 * Updates current->cols with the current window size (width)
616 static int getWindowSize(struct current *current)
620 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
621 current->cols = ws.ws_col;
625 /* Failed to query the window size. Perhaps we are on a serial terminal.
626 * Try to query the width by sending the cursor as far to the right
627 * and reading back the cursor position.
628 * Note that this is only done once per call to linenoise rather than
629 * every time the line is refreshed for efficiency reasons.
631 * In more detail, we:
632 * (a) request current cursor position,
633 * (b) move cursor far right,
634 * (c) request cursor position again,
635 * (d) at last move back to the old position.
636 * This gives us the width without messing with the externally
637 * visible cursor position.
640 if (current->cols == 0) {
643 /* If anything fails => default 80 */
647 if (queryCursor (current, &here)) {
649 setCursorPos(current, 999);
651 /* (c). Note: If (a) succeeded, then (c) should as well.
652 * For paranoia we still check and have a fallback action
653 * for (d) in case of failure..
655 if (queryCursor (current, ¤t->cols)) {
656 /* (d) Reset the cursor back to the original location. */
657 if (current->cols > here) {
658 setCursorPos(current, here);
668 * If CHAR_ESCAPE was received, reads subsequent
669 * chars to determine if this is a known special key.
671 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
673 * If no additional char is received within a short time,
674 * CHAR_ESCAPE is returned.
676 static int check_special(int fd)
678 int c = fd_read_char(fd, 50);
685 c2 = fd_read_char(fd, 50);
689 if (c == '[' || c == 'O') {
690 /* Potential arrow key */
697 return SPECIAL_RIGHT;
706 if (c == '[' && c2 >= '1' && c2 <= '8') {
707 /* extended escape */
708 c = fd_read_char(fd, 50);
712 return SPECIAL_INSERT;
714 return SPECIAL_DELETE;
716 return SPECIAL_PAGE_UP;
718 return SPECIAL_PAGE_DOWN;
725 while (c != -1 && c != '~') {
726 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
727 c = fd_read_char(fd, 50);
735 static void clearOutputHighlight(struct current *current)
738 setOutputHighlight(current, &nohighlight, 1);
741 static void outputControlChar(struct current *current, char ch)
744 setOutputHighlight(current, &reverse, 1);
745 outputChars(current, "^", 1);
746 outputChars(current, &ch, 1);
747 clearOutputHighlight(current);
750 #ifndef utf8_getchars
751 static int utf8_getchars(char *buf, int c)
754 return utf8_fromunicode(buf, c);
763 * Returns the unicode character at the given offset,
766 static int get_char(struct current *current, int pos)
768 if (pos >= 0 && pos < sb_chars(current->buf)) {
770 int i = utf8_index(sb_str(current->buf), pos);
771 (void)utf8_tounicode(sb_str(current->buf) + i, &c);
777 static int char_display_width(int ch)
780 /* control chars take two positions */
784 return utf8_width(ch);
788 #ifndef NO_COMPLETION
789 static linenoiseCompletionCallback *completionCallback = NULL;
790 static void *completionUserdata = NULL;
791 static int showhints = 1;
792 static linenoiseHintsCallback *hintsCallback = NULL;
793 static linenoiseFreeHintsCallback *freeHintsCallback = NULL;
794 static void *hintsUserdata = NULL;
798 fprintf(stderr, "\x7");
803 static void freeCompletions(linenoiseCompletions *lc) {
805 for (i = 0; i < lc->len; i++)
810 static int completeLine(struct current *current) {
811 linenoiseCompletions lc = { 0, NULL };
814 completionCallback(sb_str(current->buf),&lc,completionUserdata);
818 size_t stop = 0, i = 0;
821 /* Show completion or original buffer */
823 int chars = utf8_strlen(lc.cvec[i], -1);
824 refreshLineAlt(current, current->prompt, lc.cvec[i], chars);
826 refreshLine(current);
829 c = fd_read(current);
836 i = (i+1) % (lc.len+1);
837 if (i == lc.len) beep();
839 case CHAR_ESCAPE: /* escape */
840 /* Re-show original buffer */
842 refreshLine(current);
847 /* Update buffer and return */
849 set_current(current,lc.cvec[i]);
857 freeCompletions(&lc);
858 return c; /* Return last read character */
861 /* Register a callback function to be called for tab-completion.
862 Returns the prior callback so that the caller may (if needed)
863 restore it when done. */
864 linenoiseCompletionCallback * linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn, void *userdata) {
865 linenoiseCompletionCallback * old = completionCallback;
866 completionCallback = fn;
867 completionUserdata = userdata;
871 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
872 lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
873 lc->cvec[lc->len++] = strdup(str);
876 void linenoiseSetHintsCallback(linenoiseHintsCallback *callback, void *userdata)
878 hintsCallback = callback;
879 hintsUserdata = userdata;
882 void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *callback)
884 freeHintsCallback = callback;
890 static const char *reduceSingleBuf(const char *buf, int availcols, int *cursor_pos)
892 /* We have availcols columns available.
893 * If necessary, strip chars off the front of buf until *cursor_pos
894 * fits within availcols
898 int new_cursor_pos = *cursor_pos;
899 const char *pt = buf;
901 DRL("reduceSingleBuf: availcols=%d, cursor_pos=%d\n", availcols, *cursor_pos);
905 int n = utf8_tounicode(pt, &ch);
908 needcols += char_display_width(ch);
910 /* If we need too many cols, strip
911 * chars off the front of buf to make it fit.
912 * We keep 3 extra cols to the right of the cursor.
913 * 2 for possible wide chars, 1 for the last column that
916 while (needcols >= availcols - 3) {
917 n = utf8_tounicode(buf, &ch);
919 needcols -= char_display_width(ch);
922 /* and adjust the apparent cursor position */
926 /* can't remove more than this */
931 if (pos++ == *cursor_pos) {
938 DRL("\nafter reduce, needcols=%d, new_cursor_pos=%d\n", needcols, new_cursor_pos);
940 /* Done, now new_cursor_pos contains the adjusted cursor position
941 * and buf points to he adjusted start
943 *cursor_pos = new_cursor_pos;
947 static int mlmode = 0;
949 void linenoiseSetMultiLine(int enableml)
954 /* Helper of refreshSingleLine() and refreshMultiLine() to show hints
955 * to the right of the prompt.
956 * Returns 1 if a hint was shown, or 0 if not
957 * If 'display' is 0, does no output. Just returns the appropriate return code.
959 static int refreshShowHints(struct current *current, const char *buf, int availcols, int display)
962 if (showhints && hintsCallback && availcols > 0) {
965 char *hint = hintsCallback(buf, &color, &bold, hintsUserdata);
970 if (bold == 1 && color == -1) color = 37;
971 if (bold || color > 0) {
972 int props[3] = { bold, color, 49 }; /* bold, color, fgnormal */
973 setOutputHighlight(current, props, 3);
975 DRL("<hint bold=%d,color=%d>", bold, color);
979 int n = utf8_tounicode(pt, &ch);
980 int width = char_display_width(ch);
982 if (width >= availcols) {
989 outputChars(current, pt, n);
992 if (bold || color > 0) {
993 clearOutputHighlight(current);
995 /* Call the function to free the hint returned. */
996 if (freeHintsCallback) freeHintsCallback(hint, hintsUserdata);
1004 static void refreshStart(struct current *current)
1006 /* We accumulate all output here */
1007 assert(current->output == NULL);
1008 current->output = sb_alloc();
1011 static void refreshEnd(struct current *current)
1013 /* Output everything at once */
1014 IGNORE_RC(write(current->fd, sb_str(current->output), sb_len(current->output)));
1015 sb_free(current->output);
1016 current->output = NULL;
1019 static void refreshStartChars(struct current *current)
1024 static void refreshNewline(struct current *current)
1027 outputChars(current, "\n", 1);
1030 static void refreshEndChars(struct current *current)
1036 static void refreshLineAlt(struct current *current, const char *prompt, const char *buf, int cursor_pos)
1048 struct esc_parser parser;
1050 #ifdef DEBUG_REFRESHLINE
1051 dfh = fopen("linenoise.debuglog", "a");
1054 /* Should intercept SIGWINCH. For now, just get the size every time */
1055 getWindowSize(current);
1057 refreshStart(current);
1059 DRL("wincols=%d, cursor_pos=%d, nrows=%d, rpos=%d\n", current->cols, cursor_pos, current->nrows, current->rpos);
1061 /* Here is the plan:
1062 * (a) move the the bottom row, going down the appropriate number of lines
1063 * (b) move to beginning of line and erase the current line
1064 * (c) go up one line and do the same, until we have erased up to the first row
1065 * (d) output the prompt, counting cols and rows, taking into account escape sequences
1066 * (e) output the buffer, counting cols and rows
1067 * (e') when we hit the current pos, save the cursor position
1068 * (f) move the cursor to the saved cursor position
1069 * (g) save the current cursor row and number of rows
1072 /* (a) - The cursor is currently at row rpos */
1073 cursorDown(current, current->nrows - current->rpos - 1);
1074 DRL("<cud=%d>", current->nrows - current->rpos - 1);
1076 /* (b), (c) - Erase lines upwards until we get to the first row */
1077 for (i = 0; i < current->nrows; i++) {
1080 cursorUp(current, 1);
1083 cursorToLeft(current);
1088 /* (d) First output the prompt. control sequences don't take up display space */
1090 displaycol = 0; /* current display column */
1091 displayrow = 0; /* current display row */
1094 refreshStartChars(current);
1099 int n = utf8_tounicode(pt, &ch);
1101 if (visible && ch == CHAR_ESCAPE) {
1102 /* The start of an escape sequence, so not visible */
1104 initParseEscapeSeq(&parser, 'm');
1105 DRL("<esc-seq-start>");
1108 if (ch == '\n' || ch == '\r') {
1109 /* treat both CR and NL the same and force wrap */
1110 refreshNewline(current);
1115 width = visible * utf8_width(ch);
1117 displaycol += width;
1118 if (displaycol >= current->cols) {
1119 /* need to wrap to the next line because of newline or if it doesn't fit
1120 * XXX this is a problem in single line mode
1122 refreshNewline(current);
1128 #ifdef USE_WINCONSOLE
1130 outputChars(current, pt, n);
1133 outputChars(current, pt, n);
1139 switch (parseEscapeSequence(&parser, ch)) {
1142 setOutputHighlight(current, parser.props, parser.numprops);
1143 DRL("<esc-seq-end,numprops=%d>", parser.numprops);
1146 DRL("<esc-seq-err>");
1153 /* Now we are at the first line with all lines erased */
1154 DRL("\nafter prompt: displaycol=%d, displayrow=%d\n", displaycol, displayrow);
1157 /* (e) output the buffer, counting cols and rows */
1159 /* In this mode we may need to trim chars from the start of the buffer until the
1160 * cursor fits in the window.
1162 pt = reduceSingleBuf(buf, current->cols - displaycol, &cursor_pos);
1173 int n = utf8_tounicode(pt, &ch);
1174 int width = char_display_width(ch);
1176 if (currentpos == cursor_pos) {
1177 /* (e') wherever we output this character is where we want the cursor */
1181 if (displaycol + width >= current->cols) {
1183 /* In single line mode stop once we print as much as we can on one line */
1187 /* need to wrap to the next line since it doesn't fit */
1188 refreshNewline(current);
1193 if (notecursor == 1) {
1194 /* (e') Save this position as the current cursor position */
1195 cursorcol = displaycol;
1196 cursorrow = displayrow;
1201 displaycol += width;
1204 outputControlChar(current, ch + '@');
1207 outputChars(current, pt, n);
1211 DRL("<w=%d>", width);
1218 /* If we didn't see the cursor, it is at the current location */
1221 cursorcol = displaycol;
1222 cursorrow = displayrow;
1225 DRL("\nafter buf: displaycol=%d, displayrow=%d, cursorcol=%d, cursorrow=%d\n", displaycol, displayrow, cursorcol, cursorrow);
1227 /* (f) show hints */
1228 hint = refreshShowHints(current, buf, current->cols - displaycol, 1);
1230 /* Remember how many many cols are available for insert optimisation */
1231 if (prompt == current->prompt && hint == 0) {
1232 current->colsright = current->cols - displaycol;
1233 current->colsleft = displaycol;
1236 /* Can't optimise */
1237 current->colsright = 0;
1238 current->colsleft = 0;
1240 DRL("\nafter hints: colsleft=%d, colsright=%d\n\n", current->colsleft, current->colsright);
1242 refreshEndChars(current);
1244 /* (g) move the cursor to the correct place */
1245 cursorUp(current, displayrow - cursorrow);
1246 setCursorPos(current, cursorcol);
1248 /* (h) Update the number of rows if larger, but never reduce this */
1249 if (displayrow >= current->nrows) {
1250 current->nrows = displayrow + 1;
1252 /* And remember the row that the cursor is on */
1253 current->rpos = cursorrow;
1255 refreshEnd(current);
1257 #ifdef DEBUG_REFRESHLINE
1262 static void refreshLine(struct current *current)
1264 refreshLineAlt(current, current->prompt, sb_str(current->buf), current->pos);
1267 static void set_current(struct current *current, const char *str)
1269 sb_clear(current->buf);
1270 sb_append(current->buf, str);
1271 current->pos = sb_chars(current->buf);
1275 * Removes the char at 'pos'.
1277 * Returns 1 if the line needs to be refreshed, 2 if not
1278 * and 0 if nothing was removed
1280 static int remove_char(struct current *current, int pos)
1282 if (pos >= 0 && pos < sb_chars(current->buf)) {
1283 int offset = utf8_index(sb_str(current->buf), pos);
1284 int nbytes = utf8_index(sb_str(current->buf) + offset, 1);
1287 /* Now we try to optimise in the simple but very common case that:
1288 * - outputChars() can be used directly (not win32)
1289 * - we are removing the char at EOL
1290 * - the buffer is not empty
1291 * - there are columns available to the left
1292 * - the char being deleted is not a wide or utf-8 character
1293 * - no hints are being shown
1295 if (current->output && current->pos == pos + 1 && current->pos == sb_chars(current->buf) && pos > 0) {
1297 /* Could implement utf8_prev_len() but simplest just to not optimise this case */
1298 char last = sb_str(current->buf)[offset];
1302 if (current->colsleft > 0 && (last & 0x80) == 0) {
1303 /* Have cols on the left and not a UTF-8 char or continuation */
1304 /* Yes, can optimise */
1305 current->colsleft--;
1306 current->colsright++;
1311 sb_delete(current->buf, offset, nbytes);
1313 if (current->pos > pos) {
1317 if (refreshShowHints(current, sb_str(current->buf), current->colsright, 0)) {
1318 /* A hint needs to be shown, so can't optimise after all */
1322 /* optimised output */
1323 outputChars(current, "\b \b", 3);
1333 * Insert 'ch' at position 'pos'
1335 * Returns 1 if the line needs to be refreshed, 2 if not
1336 * and 0 if nothing was inserted (no room)
1338 static int insert_char(struct current *current, int pos, int ch)
1340 if (pos >= 0 && pos <= sb_chars(current->buf)) {
1341 char buf[MAX_UTF8_LEN + 1];
1342 int offset = utf8_index(sb_str(current->buf), pos);
1343 int n = utf8_getchars(buf, ch);
1346 /* null terminate since sb_insert() requires it */
1349 /* Now we try to optimise in the simple but very common case that:
1350 * - outputChars() can be used directly (not win32)
1351 * - we are inserting at EOL
1352 * - there are enough columns available
1353 * - no hints are being shown
1355 if (current->output && pos == current->pos && pos == sb_chars(current->buf)) {
1356 int width = char_display_width(ch);
1357 if (current->colsright > width) {
1358 /* Yes, can optimise */
1359 current->colsright -= width;
1360 current->colsleft -= width;
1364 sb_insert(current->buf, offset, buf);
1365 if (current->pos >= pos) {
1369 if (refreshShowHints(current, sb_str(current->buf), current->colsright, 0)) {
1370 /* A hint needs to be shown, so can't optimise after all */
1374 /* optimised output */
1375 outputChars(current, buf, n);
1384 * Captures up to 'n' characters starting at 'pos' for the cut buffer.
1386 * This replaces any existing characters in the cut buffer.
1388 static void capture_chars(struct current *current, int pos, int nchars)
1390 if (pos >= 0 && (pos + nchars - 1) < sb_chars(current->buf)) {
1391 int offset = utf8_index(sb_str(current->buf), pos);
1392 int nbytes = utf8_index(sb_str(current->buf) + offset, nchars);
1395 if (current->capture) {
1396 sb_clear(current->capture);
1399 current->capture = sb_alloc();
1401 sb_append_len(current->capture, sb_str(current->buf) + offset, nbytes);
1407 * Removes up to 'n' characters at cursor position 'pos'.
1409 * Returns 0 if no chars were removed or non-zero otherwise.
1411 static int remove_chars(struct current *current, int pos, int n)
1415 /* First save any chars which will be removed */
1416 capture_chars(current, pos, n);
1418 while (n-- && remove_char(current, pos)) {
1424 * Inserts the characters (string) 'chars' at the cursor position 'pos'.
1426 * Returns 0 if no chars were inserted or non-zero otherwise.
1428 static int insert_chars(struct current *current, int pos, const char *chars)
1434 int n = utf8_tounicode(chars, &ch);
1435 if (insert_char(current, pos, ch) == 0) {
1446 * Returns the keycode to process, or 0 if none.
1448 static int reverseIncrementalSearch(struct current *current)
1450 /* Display the reverse-i-search prompt and process chars */
1455 int searchpos = history_len - 1;
1461 const char *p = NULL;
1465 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1466 refreshLineAlt(current, rprompt, sb_str(current->buf), current->pos);
1467 c = fd_read(current);
1468 if (c == ctrl('H') || c == CHAR_DELETE) {
1470 int p_ind = utf8_index(rbuf, --rchars);
1472 rlen = strlen(rbuf);
1477 if (c == CHAR_ESCAPE) {
1478 c = check_special(current->fd);
1481 if (c == ctrl('P') || c == SPECIAL_UP) {
1482 /* Search for the previous (earlier) match */
1483 if (searchpos > 0) {
1488 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1489 /* Search for the next (later) match */
1490 if (searchpos < history_len) {
1496 else if (c >= ' ') {
1497 /* >= here to allow for null terminator */
1498 if (rlen >= (int)sizeof(rbuf) - MAX_UTF8_LEN) {
1502 n = utf8_getchars(rbuf + rlen, c);
1507 /* Adding a new char resets the search location */
1508 searchpos = history_len - 1;
1511 /* Exit from incremental search mode */
1515 /* Now search through the history for a match */
1516 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1517 p = strstr(history[searchpos], rbuf);
1520 if (skipsame && strcmp(history[searchpos], sb_str(current->buf)) == 0) {
1521 /* But it is identical, so skip it */
1524 /* Copy the matching line and set the cursor position */
1525 set_current(current,history[searchpos]);
1526 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1531 /* No match, so don't add it */
1537 if (c == ctrl('G') || c == ctrl('C')) {
1538 /* ctrl-g terminates the search with no effect */
1539 set_current(current, "");
1542 else if (c == ctrl('J')) {
1543 /* ctrl-j terminates the search leaving the buffer in place */
1547 /* Go process the char normally */
1548 refreshLine(current);
1552 static int linenoiseEdit(struct current *current) {
1553 int history_index = 0;
1555 /* The latest history entry is always our current buffer, that
1556 * initially is just an empty string. */
1557 linenoiseHistoryAdd("");
1559 set_current(current, "");
1560 refreshLine(current);
1564 int c = fd_read(current);
1566 #ifndef NO_COMPLETION
1567 /* Only autocomplete when the callback is set. It returns < 0 when
1568 * there was an error reading from fd. Otherwise it will return the
1569 * character that should be handled next. */
1570 if (c == '\t' && current->pos == sb_chars(current->buf) && completionCallback != NULL) {
1571 c = completeLine(current);
1574 if (c == ctrl('R')) {
1575 /* reverse incremental search will provide an alternative keycode or 0 for none */
1576 c = reverseIncrementalSearch(current);
1577 /* go on to process the returned char normally */
1581 if (c == CHAR_ESCAPE) { /* escape sequence */
1582 c = check_special(current->fd);
1586 /* Return on errors */
1587 return sb_len(current->buf);
1593 case '\r': /* enter/CR */
1596 free(history[history_len]);
1597 current->pos = sb_chars(current->buf);
1598 if (mlmode || hintsCallback) {
1600 refreshLine(current);
1603 return sb_len(current->buf);
1604 case ctrl('C'): /* ctrl-c */
1607 case ctrl('Z'): /* ctrl-z */
1609 /* send ourselves SIGSUSP */
1610 disableRawMode(current);
1613 enableRawMode(current);
1614 refreshLine(current);
1617 case CHAR_DELETE: /* backspace */
1619 if (remove_char(current, current->pos - 1) == 1) {
1620 refreshLine(current);
1623 case ctrl('D'): /* ctrl-d */
1624 if (sb_len(current->buf) == 0) {
1625 /* Empty line, so EOF */
1627 free(history[history_len]);
1630 /* Otherwise fall through to delete char to right of cursor */
1631 case SPECIAL_DELETE:
1632 if (remove_char(current, current->pos) == 1) {
1633 refreshLine(current);
1636 case SPECIAL_INSERT:
1637 /* Ignore. Expansion Hook.
1638 * Future possibility: Toggle Insert/Overwrite Modes
1641 case ctrl('W'): /* ctrl-w, delete word at left. save deleted chars */
1642 /* eat any spaces on the left */
1644 int pos = current->pos;
1645 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1649 /* now eat any non-spaces on the left */
1650 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1654 if (remove_chars(current, pos, current->pos - pos)) {
1655 refreshLine(current);
1659 case ctrl('T'): /* ctrl-t */
1660 if (current->pos > 0 && current->pos <= sb_chars(current->buf)) {
1661 /* If cursor is at end, transpose the previous two chars */
1662 int fixer = (current->pos == sb_chars(current->buf));
1663 c = get_char(current, current->pos - fixer);
1664 remove_char(current, current->pos - fixer);
1665 insert_char(current, current->pos - 1, c);
1666 refreshLine(current);
1669 case ctrl('V'): /* ctrl-v */
1670 /* Insert the ^V first */
1671 if (insert_char(current, current->pos, c)) {
1672 refreshLine(current);
1673 /* Now wait for the next char. Can insert anything except \0 */
1674 c = fd_read(current);
1676 /* Remove the ^V first */
1677 remove_char(current, current->pos - 1);
1679 /* Insert the actual char, can't be error or null */
1680 insert_char(current, current->pos, c);
1682 refreshLine(current);
1687 if (current->pos > 0) {
1689 refreshLine(current);
1694 if (current->pos < sb_chars(current->buf)) {
1696 refreshLine(current);
1699 case SPECIAL_PAGE_UP:
1700 dir = history_len - history_index - 1; /* move to start of history */
1701 goto history_navigation;
1702 case SPECIAL_PAGE_DOWN:
1703 dir = -history_index; /* move to 0 == end of history, i.e. current */
1704 goto history_navigation;
1708 goto history_navigation;
1712 if (history_len > 1) {
1713 /* Update the current history entry before to
1714 * overwrite it with tne next one. */
1715 free(history[history_len - 1 - history_index]);
1716 history[history_len - 1 - history_index] = strdup(sb_str(current->buf));
1717 /* Show the new entry */
1718 history_index += dir;
1719 if (history_index < 0) {
1722 } else if (history_index >= history_len) {
1723 history_index = history_len - 1;
1726 set_current(current, history[history_len - 1 - history_index]);
1727 refreshLine(current);
1730 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1733 refreshLine(current);
1735 case ctrl('E'): /* ctrl+e, go to the end of the line */
1737 current->pos = sb_chars(current->buf);
1738 refreshLine(current);
1740 case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */
1741 if (remove_chars(current, 0, current->pos)) {
1742 refreshLine(current);
1745 case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */
1746 if (remove_chars(current, current->pos, sb_chars(current->buf) - current->pos)) {
1747 refreshLine(current);
1750 case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */
1751 if (current->capture && insert_chars(current, current->pos, sb_str(current->capture))) {
1752 refreshLine(current);
1755 case ctrl('L'): /* Ctrl+L, clear screen */
1756 linenoiseClearScreen();
1757 /* Force recalc of window size for serial terminals */
1760 refreshLine(current);
1763 /* Only tab is allowed without ^V */
1764 if (c == '\t' || c >= ' ') {
1765 if (insert_char(current, current->pos, c) == 1) {
1766 refreshLine(current);
1772 return sb_len(current->buf);
1775 int linenoiseColumns(void)
1777 struct current current;
1778 current.output = NULL;
1779 enableRawMode (¤t);
1780 getWindowSize (¤t);
1781 disableRawMode (¤t);
1782 return current.cols;
1786 * Reads a line from the file handle (without the trailing NL or CRNL)
1787 * and returns it in a stringbuf.
1788 * Returns NULL if no characters are read before EOF or error.
1790 * Note that the character count will *not* be correct for lines containing
1791 * utf8 sequences. Do not rely on the character count.
1793 static stringbuf *sb_getline(FILE *fh)
1795 stringbuf *sb = sb_alloc();
1799 while ((c = getc(fh)) != EOF) {
1806 if (c == '\n' || c == '\r') {
1810 /* ignore the effect of character count for partial utf8 sequences */
1811 sb_append_len(sb, &ch, 1);
1820 char *linenoise(const char *prompt)
1823 struct current current;
1826 memset(¤t, 0, sizeof(current));
1828 if (enableRawMode(¤t) == -1) {
1829 printf("%s", prompt);
1831 sb = sb_getline(stdin);
1834 current.buf = sb_alloc();
1837 current.prompt = prompt;
1839 count = linenoiseEdit(¤t);
1841 disableRawMode(¤t);
1844 sb_free(current.capture);
1846 sb_free(current.buf);
1851 return sb ? sb_to_string(sb) : NULL;
1854 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1855 int linenoiseHistoryAddAllocated(char *line) {
1857 if (history_max_len == 0) {
1862 if (history == NULL) {
1863 history = (char **)calloc(sizeof(char*), history_max_len);
1866 /* do not insert duplicate lines into history */
1867 if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1871 if (history_len == history_max_len) {
1873 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1876 history[history_len] = line;
1881 int linenoiseHistoryAdd(const char *line) {
1882 return linenoiseHistoryAddAllocated(strdup(line));
1885 int linenoiseHistoryGetMaxLen(void) {
1886 return history_max_len;
1889 int linenoiseHistorySetMaxLen(int len) {
1892 if (len < 1) return 0;
1894 int tocopy = history_len;
1896 newHistory = (char **)calloc(sizeof(char*), len);
1898 /* If we can't copy everything, free the elements we'll not use. */
1902 for (j = 0; j < tocopy-len; j++) free(history[j]);
1905 memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy);
1907 history = newHistory;
1909 history_max_len = len;
1910 if (history_len > history_max_len)
1911 history_len = history_max_len;
1915 /* Save the history in the specified file. On success 0 is returned
1916 * otherwise -1 is returned. */
1917 int linenoiseHistorySave(const char *filename) {
1918 FILE *fp = fopen(filename,"w");
1921 if (fp == NULL) return -1;
1922 for (j = 0; j < history_len; j++) {
1923 const char *str = history[j];
1924 /* Need to encode backslash, nl and cr */
1929 else if (*str == '\n') {
1932 else if (*str == '\r') {
1947 /* Load the history from the specified file.
1949 * If the file does not exist or can't be opened, no operation is performed
1950 * and -1 is returned.
1951 * Otherwise 0 is returned.
1953 int linenoiseHistoryLoad(const char *filename) {
1954 FILE *fp = fopen(filename,"r");
1957 if (fp == NULL) return -1;
1959 while ((sb = sb_getline(fp)) != NULL) {
1960 /* Take the stringbuf and decode backslash escaped values */
1961 char *buf = sb_to_string(sb);
1965 for (src = buf; *src; src++) {
1973 else if (*src == 'r') {
1983 linenoiseHistoryAddAllocated(buf);
1989 /* Provide access to the history buffer.
1991 * If 'len' is not NULL, the length is stored in *len.
1993 char **linenoiseHistory(int *len) {