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 */
186 stringbuf *capture; /* capture buffer, or NULL for none. Always null terminated */
187 stringbuf *output; /* used only during refreshLine() - output accumulator */
188 #if defined(USE_TERMIOS)
189 int fd; /* Terminal fd */
190 #elif defined(USE_WINCONSOLE)
191 HANDLE outh; /* Console output handle */
192 HANDLE inh; /* Console input handle */
193 int rows; /* Screen rows */
194 int x; /* Current column during output */
195 int y; /* Current row */
197 #define UBUF_MAX_CHARS 132
198 WORD ubuf[UBUF_MAX_CHARS + 1]; /* Accumulates utf16 output - one extra for final surrogate pairs */
199 int ubuflen; /* length used in ubuf */
200 int ubufcols; /* how many columns are represented by the chars in ubuf? */
205 static int fd_read(struct current *current);
206 static int getWindowSize(struct current *current);
207 static void cursorDown(struct current *current, int n);
208 static void cursorUp(struct current *current, int n);
209 static void eraseEol(struct current *current);
210 static void refreshLine(struct current *current);
211 static void refreshLineAlt(struct current *current, const char *prompt, const char *buf, int cursor_pos);
212 static void setCursorPos(struct current *current, int x);
213 static void setOutputHighlight(struct current *current, const int *props, int nprops);
214 static void set_current(struct current *current, const char *str);
216 void linenoiseHistoryFree(void) {
220 for (j = 0; j < history_len; j++)
230 EP_START, /* looking for ESC */
231 EP_ESC, /* looking for [ */
232 EP_DIGITS, /* parsing digits */
233 EP_PROPS, /* parsing digits or semicolons */
235 EP_ERROR, /* error */
237 int props[5]; /* properties are stored here */
238 int maxprops; /* size of the props[] array */
239 int numprops; /* number of properties found */
240 int termchar; /* terminator char, or 0 for any alpha */
241 int current; /* current (partial) property value */
245 * Initialise the escape sequence parser at *parser.
247 * If termchar is 0 any alpha char terminates ok. Otherwise only the given
248 * char terminates successfully.
249 * Run the parser state machine with calls to parseEscapeSequence() for each char.
251 static void initParseEscapeSeq(struct esc_parser *parser, int termchar)
253 parser->state = EP_START;
254 parser->maxprops = sizeof(parser->props) / sizeof(*parser->props);
255 parser->numprops = 0;
257 parser->termchar = termchar;
261 * Pass character 'ch' into the state machine to parse:
262 * 'ESC' '[' <digits> (';' <digits>)* <termchar>
264 * The first character must be ESC.
265 * Returns the current state. The state machine is done when it returns either EP_END
268 * On EP_END, the "property/attribute" values can be read from parser->props[]
269 * of length parser->numprops.
271 static int parseEscapeSequence(struct esc_parser *parser, int ch)
273 switch (parser->state) {
275 parser->state = (ch == '\x1b') ? EP_ESC : EP_ERROR;
278 parser->state = (ch == '[') ? EP_DIGITS : EP_ERROR;
282 parser->state = EP_DIGITS;
284 if (parser->numprops + 1 < parser->maxprops) {
285 parser->props[parser->numprops++] = parser->current;
292 if (ch >= '0' && ch <= '9') {
293 parser->current = parser->current * 10 + (ch - '0');
294 parser->state = EP_PROPS;
297 /* must be terminator */
298 if (parser->termchar != ch) {
299 if (parser->termchar != 0 || !((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))) {
300 parser->state = EP_ERROR;
304 parser->state = EP_END;
307 parser->state = EP_ERROR;
312 return parser->state;
315 /*#define DEBUG_REFRESHLINE*/
317 #ifdef DEBUG_REFRESHLINE
318 #define DRL(ARGS...) fprintf(dfh, ARGS)
321 static void DRL_CHAR(int ch)
324 DRL("^%c", ch + '@');
333 static void DRL_STR(const char *str)
337 int n = utf8_tounicode(str, &ch);
348 #if defined(USE_WINCONSOLE)
349 #include "linenoise-win32.c"
352 #if defined(USE_TERMIOS)
353 static void linenoiseAtExit(void);
354 static struct termios orig_termios; /* in order to restore at exit */
355 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
356 static int atexit_registered = 0; /* register atexit just 1 time */
358 static const char *unsupported_term[] = {"dumb","cons25","emacs",NULL};
360 static int isUnsupportedTerm(void) {
361 char *term = getenv("TERM");
365 for (j = 0; unsupported_term[j]; j++) {
366 if (strcmp(term, unsupported_term[j]) == 0) {
374 static int enableRawMode(struct current *current) {
377 current->fd = STDIN_FILENO;
380 if (!isatty(current->fd) || isUnsupportedTerm() ||
381 tcgetattr(current->fd, &orig_termios) == -1) {
387 if (!atexit_registered) {
388 atexit(linenoiseAtExit);
389 atexit_registered = 1;
392 raw = orig_termios; /* modify the original mode */
393 /* input modes: no break, no CR to NL, no parity check, no strip char,
394 * no start/stop output control. */
395 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
396 /* output modes - actually, no need to disable post processing */
397 /*raw.c_oflag &= ~(OPOST);*/
398 /* control modes - set 8 bit chars */
399 raw.c_cflag |= (CS8);
400 /* local modes - choing off, canonical off, no extended functions,
401 * no signal chars (^Z,^C) */
402 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
403 /* control chars - set return condition: min number of bytes and timer.
404 * We want read to return every single byte, without timeout. */
405 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
407 /* put terminal in raw mode after flushing */
408 if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
415 static void disableRawMode(struct current *current) {
416 /* Don't even check the return value as it's too late. */
417 if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
421 /* At exit we'll try to fix the terminal to the initial conditions. */
422 static void linenoiseAtExit(void) {
424 tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
426 linenoiseHistoryFree();
429 /* gcc/glibc insists that we care about the return code of write!
430 * Clarification: This means that a void-cast like "(void) (EXPR)"
433 #define IGNORE_RC(EXPR) if (EXPR) {}
436 * Output bytes directly, or accumulate output (if current->output is set)
438 static void outputChars(struct current *current, const char *buf, int len)
443 if (current->output) {
444 sb_append_len(current->output, buf, len);
447 IGNORE_RC(write(current->fd, buf, len));
451 /* Like outputChars, but using printf-style formatting
453 static void outputFormatted(struct current *current, const char *format, ...)
459 va_start(args, format);
460 n = vsnprintf(buf, sizeof(buf), format, args);
461 /* This will never happen because we are sure to use outputFormatted() only for short sequences */
462 assert(n < (int)sizeof(buf));
464 outputChars(current, buf, n);
467 static void cursorToLeft(struct current *current)
469 outputChars(current, "\r", -1);
472 static void setOutputHighlight(struct current *current, const int *props, int nprops)
474 outputChars(current, "\x1b[", -1);
476 outputFormatted(current, "%d%c", *props, (nprops == 0) ? 'm' : ';');
481 static void eraseEol(struct current *current)
483 outputChars(current, "\x1b[0K", -1);
486 static void setCursorPos(struct current *current, int x)
489 cursorToLeft(current);
492 outputFormatted(current, "\r\x1b[%dC", x);
496 static void cursorUp(struct current *current, int n)
499 outputFormatted(current, "\x1b[%dA", n);
503 static void cursorDown(struct current *current, int n)
506 outputFormatted(current, "\x1b[%dB", n);
510 void linenoiseClearScreen(void)
512 write(STDOUT_FILENO, "\x1b[H\x1b[2J", 7);
516 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
518 * A timeout of -1 means to wait forever.
520 * Returns -1 if no char is received within the time or an error occurs.
522 static int fd_read_char(int fd, int timeout)
530 if (poll(&p, 1, timeout) == 0) {
534 if (read(fd, &c, 1) != 1) {
541 * Reads a complete utf-8 character
542 * and returns the unicode value, or -1 on error.
544 static int fd_read(struct current *current)
547 char buf[MAX_UTF8_LEN];
552 if (read(current->fd, &buf[0], 1) != 1) {
555 n = utf8_charlen(buf[0]);
559 for (i = 1; i < n; i++) {
560 if (read(current->fd, &buf[i], 1) != 1) {
564 /* decode and return the character */
565 utf8_tounicode(buf, &c);
568 return fd_read_char(current->fd, -1);
574 * Stores the current cursor column in '*cols'.
575 * Returns 1 if OK, or 0 if failed to determine cursor pos.
577 static int queryCursor(struct current *current, int* cols)
579 struct esc_parser parser;
582 /* Should not be buffering this output, it needs to go immediately */
583 assert(current->output == NULL);
585 /* control sequence - report cursor location */
586 outputChars(current, "\x1b[6n", -1);
588 /* Parse the response: ESC [ rows ; cols R */
589 initParseEscapeSeq(&parser, 'R');
590 while ((ch = fd_read_char(current->fd, 100)) > 0) {
591 switch (parseEscapeSequence(&parser, ch)) {
595 if (parser.numprops == 2 && parser.props[1] < 1000) {
596 *cols = parser.props[1];
610 * Updates current->cols with the current window size (width)
612 static int getWindowSize(struct current *current)
616 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
617 current->cols = ws.ws_col;
621 /* Failed to query the window size. Perhaps we are on a serial terminal.
622 * Try to query the width by sending the cursor as far to the right
623 * and reading back the cursor position.
624 * Note that this is only done once per call to linenoise rather than
625 * every time the line is refreshed for efficiency reasons.
627 * In more detail, we:
628 * (a) request current cursor position,
629 * (b) move cursor far right,
630 * (c) request cursor position again,
631 * (d) at last move back to the old position.
632 * This gives us the width without messing with the externally
633 * visible cursor position.
636 if (current->cols == 0) {
639 /* If anything fails => default 80 */
643 if (queryCursor (current, &here)) {
645 setCursorPos(current, 999);
647 /* (c). Note: If (a) succeeded, then (c) should as well.
648 * For paranoia we still check and have a fallback action
649 * for (d) in case of failure..
651 if (queryCursor (current, ¤t->cols)) {
652 /* (d) Reset the cursor back to the original location. */
653 if (current->cols > here) {
654 setCursorPos(current, here);
664 * If CHAR_ESCAPE was received, reads subsequent
665 * chars to determine if this is a known special key.
667 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
669 * If no additional char is received within a short time,
670 * CHAR_ESCAPE is returned.
672 static int check_special(int fd)
674 int c = fd_read_char(fd, 50);
681 c2 = fd_read_char(fd, 50);
685 if (c == '[' || c == 'O') {
686 /* Potential arrow key */
693 return SPECIAL_RIGHT;
702 if (c == '[' && c2 >= '1' && c2 <= '8') {
703 /* extended escape */
704 c = fd_read_char(fd, 50);
708 return SPECIAL_INSERT;
710 return SPECIAL_DELETE;
712 return SPECIAL_PAGE_UP;
714 return SPECIAL_PAGE_DOWN;
721 while (c != -1 && c != '~') {
722 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
723 c = fd_read_char(fd, 50);
731 static void clearOutputHighlight(struct current *current)
734 setOutputHighlight(current, &nohighlight, 1);
737 static void outputControlChar(struct current *current, char ch)
740 setOutputHighlight(current, &reverse, 1);
741 outputChars(current, "^", 1);
742 outputChars(current, &ch, 1);
743 clearOutputHighlight(current);
746 #ifndef utf8_getchars
747 static int utf8_getchars(char *buf, int c)
750 return utf8_fromunicode(buf, c);
759 * Returns the unicode character at the given offset,
762 static int get_char(struct current *current, int pos)
764 if (pos >= 0 && pos < sb_chars(current->buf)) {
766 int i = utf8_index(sb_str(current->buf), pos);
767 (void)utf8_tounicode(sb_str(current->buf) + i, &c);
773 static int char_display_width(int ch)
776 /* control chars take two positions */
780 return utf8_width(ch);
784 #ifndef NO_COMPLETION
785 static linenoiseCompletionCallback *completionCallback = NULL;
786 static void *completionUserdata = NULL;
787 static int showhints = 1;
788 static linenoiseHintsCallback *hintsCallback = NULL;
789 static linenoiseFreeHintsCallback *freeHintsCallback = NULL;
790 static void *hintsUserdata = NULL;
794 fprintf(stderr, "\x7");
799 static void freeCompletions(linenoiseCompletions *lc) {
801 for (i = 0; i < lc->len; i++)
806 static int completeLine(struct current *current) {
807 linenoiseCompletions lc = { 0, NULL };
810 completionCallback(sb_str(current->buf),&lc,completionUserdata);
814 size_t stop = 0, i = 0;
817 /* Show completion or original buffer */
819 int chars = utf8_strlen(lc.cvec[i], -1);
820 refreshLineAlt(current, current->prompt, lc.cvec[i], chars);
822 refreshLine(current);
825 c = fd_read(current);
832 i = (i+1) % (lc.len+1);
833 if (i == lc.len) beep();
835 case CHAR_ESCAPE: /* escape */
836 /* Re-show original buffer */
838 refreshLine(current);
843 /* Update buffer and return */
845 set_current(current,lc.cvec[i]);
853 freeCompletions(&lc);
854 return c; /* Return last read character */
857 /* Register a callback function to be called for tab-completion.
858 Returns the prior callback so that the caller may (if needed)
859 restore it when done. */
860 linenoiseCompletionCallback * linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn, void *userdata) {
861 linenoiseCompletionCallback * old = completionCallback;
862 completionCallback = fn;
863 completionUserdata = userdata;
867 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
868 lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
869 lc->cvec[lc->len++] = strdup(str);
872 void linenoiseSetHintsCallback(linenoiseHintsCallback *callback, void *userdata)
874 hintsCallback = callback;
875 hintsUserdata = userdata;
878 void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *callback)
880 freeHintsCallback = callback;
886 static const char *reduceSingleBuf(const char *buf, int availcols, int *cursor_pos)
888 /* We have availcols columns available.
889 * If necessary, strip chars off the front of buf until *cursor_pos
890 * fits within availcols
894 int new_cursor_pos = *cursor_pos;
895 const char *pt = buf;
897 DRL("reduceSingleBuf: availcols=%d, cursor_pos=%d\n", availcols, *cursor_pos);
901 int n = utf8_tounicode(pt, &ch);
904 needcols += char_display_width(ch);
906 /* If we need too many cols, strip
907 * chars off the front of buf to make it fit.
908 * We keep 3 extra cols to the right of the cursor.
909 * 2 for possible wide chars, 1 for the last column that
912 while (needcols >= availcols - 3) {
913 n = utf8_tounicode(buf, &ch);
915 needcols -= char_display_width(ch);
918 /* and adjust the apparent cursor position */
922 /* can't remove more than this */
927 if (pos++ == *cursor_pos) {
934 DRL("\nafter reduce, needcols=%d, new_cursor_pos=%d\n", needcols, new_cursor_pos);
936 /* Done, now new_cursor_pos contains the adjusted cursor position
937 * and buf points to he adjusted start
939 *cursor_pos = new_cursor_pos;
943 static int mlmode = 0;
945 void linenoiseSetMultiLine(int enableml)
950 /* Helper of refreshSingleLine() and refreshMultiLine() to show hints
951 * to the right of the prompt. */
952 static void refreshShowHints(struct current *current, const char *buf, int availcols) {
953 if (showhints && hintsCallback && availcols > 0) {
956 char *hint = hintsCallback(buf, &color, &bold, hintsUserdata);
959 if (bold == 1 && color == -1) color = 37;
960 if (bold || color > 0) {
961 int props[3] = { bold, color, 49 }; /* bold, color, fgnormal */
962 setOutputHighlight(current, props, 3);
964 DRL("<hint bold=%d,color=%d>", bold, color);
968 int n = utf8_tounicode(pt, &ch);
969 int width = char_display_width(ch);
971 if (width >= availcols) {
978 outputChars(current, pt, n);
981 if (bold || color > 0) {
982 clearOutputHighlight(current);
984 /* Call the function to free the hint returned. */
985 if (freeHintsCallback) freeHintsCallback(hint, hintsUserdata);
991 static void refreshStart(struct current *current)
993 /* We accumulate all output here */
994 assert(current->output == NULL);
995 current->output = sb_alloc();
998 static void refreshEnd(struct current *current)
1000 /* Output everything at once */
1001 IGNORE_RC(write(current->fd, sb_str(current->output), sb_len(current->output)));
1002 sb_free(current->output);
1003 current->output = NULL;
1006 static void refreshStartChars(struct current *current)
1010 static void refreshNewline(struct current *current)
1013 outputChars(current, "\n", 1);
1016 static void refreshEndChars(struct current *current)
1021 static void refreshLineAlt(struct current *current, const char *prompt, const char *buf, int cursor_pos)
1032 struct esc_parser parser;
1034 #ifdef DEBUG_REFRESHLINE
1035 dfh = fopen("linenoise.debuglog", "a");
1038 /* Should intercept SIGWINCH. For now, just get the size every time */
1039 getWindowSize(current);
1041 refreshStart(current);
1043 DRL("wincols=%d, cursor_pos=%d, nrows=%d, rpos=%d\n", current->cols, cursor_pos, current->nrows, current->rpos);
1045 /* Here is the plan:
1046 * (a) move the the bottom row, going down the appropriate number of lines
1047 * (b) move to beginning of line and erase the current line
1048 * (c) go up one line and do the same, until we have erased up to the first row
1049 * (d) output the prompt, counting cols and rows, taking into account escape sequences
1050 * (e) output the buffer, counting cols and rows
1051 * (e') when we hit the current pos, save the cursor position
1052 * (f) move the cursor to the saved cursor position
1053 * (g) save the current cursor row and number of rows
1056 /* (a) - The cursor is currently at row rpos */
1057 cursorDown(current, current->nrows - current->rpos - 1);
1058 DRL("<cud=%d>", current->nrows - current->rpos - 1);
1060 /* (b), (c) - Erase lines upwards until we get to the first row */
1061 for (i = 0; i < current->nrows; i++) {
1064 cursorUp(current, 1);
1067 cursorToLeft(current);
1072 /* (d) First output the prompt. control sequences don't take up display space */
1074 displaycol = 0; /* current display column */
1075 displayrow = 0; /* current display row */
1078 refreshStartChars(current);
1083 int n = utf8_tounicode(pt, &ch);
1085 if (visible && ch == CHAR_ESCAPE) {
1086 /* The start of an escape sequence, so not visible */
1088 initParseEscapeSeq(&parser, 'm');
1089 DRL("<esc-seq-start>");
1092 if (ch == '\n' || ch == '\r') {
1093 /* treat both CR and NL the same and force wrap */
1094 refreshNewline(current);
1099 width = visible * utf8_width(ch);
1101 displaycol += width;
1102 if (displaycol >= current->cols) {
1103 /* need to wrap to the next line because of newline or if it doesn't fit
1104 * XXX this is a problem in single line mode
1106 refreshNewline(current);
1112 #ifdef USE_WINCONSOLE
1114 outputChars(current, pt, n);
1117 outputChars(current, pt, n);
1123 switch (parseEscapeSequence(&parser, ch)) {
1126 setOutputHighlight(current, parser.props, parser.numprops);
1127 DRL("<esc-seq-end,numprops=%d>", parser.numprops);
1130 DRL("<esc-seq-err>");
1137 /* Now we are at the first line with all lines erased */
1138 DRL("\nafter prompt: displaycol=%d, displayrow=%d\n", displaycol, displayrow);
1141 /* (e) output the buffer, counting cols and rows */
1143 /* In this mode we may need to trim chars from the start of the buffer until the
1144 * cursor fits in the window.
1146 pt = reduceSingleBuf(buf, current->cols - displaycol, &cursor_pos);
1157 int n = utf8_tounicode(pt, &ch);
1158 int width = char_display_width(ch);
1160 if (currentpos == cursor_pos) {
1161 /* (e') wherever we output this character is where we want the cursor */
1165 if (displaycol + width >= current->cols) {
1167 /* In single line mode stop once we print as much as we can on one line */
1171 /* need to wrap to the next line since it doesn't fit */
1172 refreshNewline(current);
1177 if (notecursor == 1) {
1178 /* (e') Save this position as the current cursor position */
1179 cursorcol = displaycol;
1180 cursorrow = displayrow;
1185 displaycol += width;
1188 outputControlChar(current, ch + '@');
1191 outputChars(current, pt, n);
1195 DRL("<w=%d>", width);
1202 /* If we didn't see the cursor, it is at the current location */
1205 cursorcol = displaycol;
1206 cursorrow = displayrow;
1209 DRL("\nafter buf: displaycol=%d, displayrow=%d, cursorcol=%d, cursorrow=%d\n\n", displaycol, displayrow, cursorcol, cursorrow);
1211 /* (f) show hints */
1212 refreshShowHints(current, buf, current->cols - displaycol);
1214 refreshEndChars(current);
1216 /* (g) move the cursor to the correct place */
1217 cursorUp(current, displayrow - cursorrow);
1218 setCursorPos(current, cursorcol);
1220 /* (h) Update the number of rows if larger, but never reduce this */
1221 if (displayrow >= current->nrows) {
1222 current->nrows = displayrow + 1;
1224 /* And remember the row that the cursor is on */
1225 current->rpos = cursorrow;
1227 refreshEnd(current);
1229 #ifdef DEBUG_REFRESHLINE
1234 static void refreshLine(struct current *current)
1236 refreshLineAlt(current, current->prompt, sb_str(current->buf), current->pos);
1239 static void set_current(struct current *current, const char *str)
1241 sb_clear(current->buf);
1242 sb_append(current->buf, str);
1243 current->pos = sb_chars(current->buf);
1247 * Removes the char at 'pos'.
1249 * Returns 1 if the line needs to be refreshed, 2 if not
1250 * and 0 if nothing was removed
1252 static int remove_char(struct current *current, int pos)
1254 if (pos >= 0 && pos < sb_chars(current->buf)) {
1255 int offset = utf8_index(sb_str(current->buf), pos);
1256 int nbytes = utf8_index(sb_str(current->buf) + offset, 1);
1258 /* Note that we no longer try to optimise the remove-at-end case
1259 * since control characters and wide characters mess
1260 * up the simple count
1262 sb_delete(current->buf, offset, nbytes);
1264 if (current->pos > pos) {
1273 * Insert 'ch' at position 'pos'
1275 * Returns 1 if the line needs to be refreshed, 2 if not
1276 * and 0 if nothing was inserted (no room)
1278 static int insert_char(struct current *current, int pos, int ch)
1280 if (pos >= 0 && pos <= sb_chars(current->buf)) {
1281 char buf[MAX_UTF8_LEN + 1];
1282 int offset = utf8_index(sb_str(current->buf), pos);
1283 int n = utf8_getchars(buf, ch);
1285 /* null terminate since sb_insert() requires it */
1288 /* Optimisation removed - see reason in remove_char() */
1290 sb_insert(current->buf, offset, buf);
1291 if (current->pos >= pos) {
1300 * Captures up to 'n' characters starting at 'pos' for the cut buffer.
1302 * This replaces any existing characters in the cut buffer.
1304 static void capture_chars(struct current *current, int pos, int nchars)
1306 if (pos >= 0 && (pos + nchars - 1) < sb_chars(current->buf)) {
1307 int offset = utf8_index(sb_str(current->buf), pos);
1308 int nbytes = utf8_index(sb_str(current->buf) + offset, nchars);
1311 if (current->capture) {
1312 sb_clear(current->capture);
1315 current->capture = sb_alloc();
1317 sb_append_len(current->capture, sb_str(current->buf) + offset, nbytes);
1323 * Removes up to 'n' characters at cursor position 'pos'.
1325 * Returns 0 if no chars were removed or non-zero otherwise.
1327 static int remove_chars(struct current *current, int pos, int n)
1331 /* First save any chars which will be removed */
1332 capture_chars(current, pos, n);
1334 while (n-- && remove_char(current, pos)) {
1340 * Inserts the characters (string) 'chars' at the cursor position 'pos'.
1342 * Returns 0 if no chars were inserted or non-zero otherwise.
1344 static int insert_chars(struct current *current, int pos, const char *chars)
1350 int n = utf8_tounicode(chars, &ch);
1351 if (insert_char(current, pos, ch) == 0) {
1362 * Returns the keycode to process, or 0 if none.
1364 static int reverseIncrementalSearch(struct current *current)
1366 /* Display the reverse-i-search prompt and process chars */
1371 int searchpos = history_len - 1;
1377 const char *p = NULL;
1381 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1382 refreshLineAlt(current, rprompt, sb_str(current->buf), current->pos);
1383 c = fd_read(current);
1384 if (c == ctrl('H') || c == CHAR_DELETE) {
1386 int p = utf8_index(rbuf, --rchars);
1388 rlen = strlen(rbuf);
1393 if (c == CHAR_ESCAPE) {
1394 c = check_special(current->fd);
1397 if (c == ctrl('P') || c == SPECIAL_UP) {
1398 /* Search for the previous (earlier) match */
1399 if (searchpos > 0) {
1404 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1405 /* Search for the next (later) match */
1406 if (searchpos < history_len) {
1412 else if (c >= ' ') {
1413 /* >= here to allow for null terminator */
1414 if (rlen >= (int)sizeof(rbuf) - MAX_UTF8_LEN) {
1418 n = utf8_getchars(rbuf + rlen, c);
1423 /* Adding a new char resets the search location */
1424 searchpos = history_len - 1;
1427 /* Exit from incremental search mode */
1431 /* Now search through the history for a match */
1432 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1433 p = strstr(history[searchpos], rbuf);
1436 if (skipsame && strcmp(history[searchpos], sb_str(current->buf)) == 0) {
1437 /* But it is identical, so skip it */
1440 /* Copy the matching line and set the cursor position */
1441 set_current(current,history[searchpos]);
1442 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1447 /* No match, so don't add it */
1453 if (c == ctrl('G') || c == ctrl('C')) {
1454 /* ctrl-g terminates the search with no effect */
1455 set_current(current, "");
1458 else if (c == ctrl('J')) {
1459 /* ctrl-j terminates the search leaving the buffer in place */
1463 /* Go process the char normally */
1464 refreshLine(current);
1468 static int linenoiseEdit(struct current *current) {
1469 int history_index = 0;
1471 /* The latest history entry is always our current buffer, that
1472 * initially is just an empty string. */
1473 linenoiseHistoryAdd("");
1475 set_current(current, "");
1476 refreshLine(current);
1480 int c = fd_read(current);
1482 #ifndef NO_COMPLETION
1483 /* Only autocomplete when the callback is set. It returns < 0 when
1484 * there was an error reading from fd. Otherwise it will return the
1485 * character that should be handled next. */
1486 if (c == '\t' && current->pos == sb_chars(current->buf) && completionCallback != NULL) {
1487 c = completeLine(current);
1490 if (c == ctrl('R')) {
1491 /* reverse incremental search will provide an alternative keycode or 0 for none */
1492 c = reverseIncrementalSearch(current);
1493 /* go on to process the returned char normally */
1497 if (c == CHAR_ESCAPE) { /* escape sequence */
1498 c = check_special(current->fd);
1502 /* Return on errors */
1503 return sb_len(current->buf);
1509 case '\r': /* enter */
1511 free(history[history_len]);
1512 current->pos = sb_chars(current->buf);
1513 if (mlmode || hintsCallback) {
1515 refreshLine(current);
1518 return sb_len(current->buf);
1519 case ctrl('C'): /* ctrl-c */
1522 case ctrl('Z'): /* ctrl-z */
1524 /* send ourselves SIGSUSP */
1525 disableRawMode(current);
1528 enableRawMode(current);
1529 refreshLine(current);
1532 case CHAR_DELETE: /* backspace */
1534 if (remove_char(current, current->pos - 1) == 1) {
1535 refreshLine(current);
1538 case ctrl('D'): /* ctrl-d */
1539 if (sb_len(current->buf) == 0) {
1540 /* Empty line, so EOF */
1542 free(history[history_len]);
1545 /* Otherwise fall through to delete char to right of cursor */
1546 case SPECIAL_DELETE:
1547 if (remove_char(current, current->pos) == 1) {
1548 refreshLine(current);
1551 case SPECIAL_INSERT:
1552 /* Ignore. Expansion Hook.
1553 * Future possibility: Toggle Insert/Overwrite Modes
1556 case ctrl('W'): /* ctrl-w, delete word at left. save deleted chars */
1557 /* eat any spaces on the left */
1559 int pos = current->pos;
1560 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1564 /* now eat any non-spaces on the left */
1565 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1569 if (remove_chars(current, pos, current->pos - pos)) {
1570 refreshLine(current);
1574 case ctrl('T'): /* ctrl-t */
1575 if (current->pos > 0 && current->pos <= sb_chars(current->buf)) {
1576 /* If cursor is at end, transpose the previous two chars */
1577 int fixer = (current->pos == sb_chars(current->buf));
1578 c = get_char(current, current->pos - fixer);
1579 remove_char(current, current->pos - fixer);
1580 insert_char(current, current->pos - 1, c);
1581 refreshLine(current);
1584 case ctrl('V'): /* ctrl-v */
1585 /* Insert the ^V first */
1586 if (insert_char(current, current->pos, c)) {
1587 refreshLine(current);
1588 /* Now wait for the next char. Can insert anything except \0 */
1589 c = fd_read(current);
1591 /* Remove the ^V first */
1592 remove_char(current, current->pos - 1);
1594 /* Insert the actual char, can't be error or null */
1595 insert_char(current, current->pos, c);
1597 refreshLine(current);
1602 if (current->pos > 0) {
1604 refreshLine(current);
1609 if (current->pos < sb_chars(current->buf)) {
1611 refreshLine(current);
1614 case SPECIAL_PAGE_UP:
1615 dir = history_len - history_index - 1; /* move to start of history */
1616 goto history_navigation;
1617 case SPECIAL_PAGE_DOWN:
1618 dir = -history_index; /* move to 0 == end of history, i.e. current */
1619 goto history_navigation;
1623 goto history_navigation;
1627 if (history_len > 1) {
1628 /* Update the current history entry before to
1629 * overwrite it with tne next one. */
1630 free(history[history_len - 1 - history_index]);
1631 history[history_len - 1 - history_index] = strdup(sb_str(current->buf));
1632 /* Show the new entry */
1633 history_index += dir;
1634 if (history_index < 0) {
1637 } else if (history_index >= history_len) {
1638 history_index = history_len - 1;
1641 set_current(current, history[history_len - 1 - history_index]);
1642 refreshLine(current);
1645 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1648 refreshLine(current);
1650 case ctrl('E'): /* ctrl+e, go to the end of the line */
1652 current->pos = sb_chars(current->buf);
1653 refreshLine(current);
1655 case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */
1656 if (remove_chars(current, 0, current->pos)) {
1657 refreshLine(current);
1660 case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */
1661 if (remove_chars(current, current->pos, sb_chars(current->buf) - current->pos)) {
1662 refreshLine(current);
1665 case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */
1666 if (current->capture && insert_chars(current, current->pos, sb_str(current->capture))) {
1667 refreshLine(current);
1670 case ctrl('L'): /* Ctrl+L, clear screen */
1671 linenoiseClearScreen();
1672 /* Force recalc of window size for serial terminals */
1675 refreshLine(current);
1678 /* Only tab is allowed without ^V */
1679 if (c == '\t' || c >= ' ') {
1680 if (insert_char(current, current->pos, c) == 1) {
1681 refreshLine(current);
1687 return sb_len(current->buf);
1690 int linenoiseColumns(void)
1692 struct current current;
1693 enableRawMode (¤t);
1694 getWindowSize (¤t);
1695 disableRawMode (¤t);
1696 return current.cols;
1700 * Reads a line from the file handle (without the trailing NL or CRNL)
1701 * and returns it in a stringbuf.
1702 * Returns NULL if no characters are read before EOF or error.
1704 * Note that the character count will *not* be correct for lines containing
1705 * utf8 sequences. Do not rely on the character count.
1707 static stringbuf *sb_getline(FILE *fh)
1709 stringbuf *sb = sb_alloc();
1713 while ((c = getc(fh)) != EOF) {
1720 if (c == '\n' || c == '\r') {
1724 /* ignore the effect of character count for partial utf8 sequences */
1725 sb_append_len(sb, &ch, 1);
1734 char *linenoise(const char *prompt)
1737 struct current current;
1740 memset(¤t, 0, sizeof(current));
1742 if (enableRawMode(¤t) == -1) {
1743 printf("%s", prompt);
1745 sb = sb_getline(stdin);
1748 current.buf = sb_alloc();
1751 current.prompt = prompt;
1753 count = linenoiseEdit(¤t);
1755 disableRawMode(¤t);
1758 sb_free(current.capture);
1760 sb_free(current.buf);
1765 return sb ? sb_to_string(sb) : NULL;
1768 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1769 int linenoiseHistoryAddAllocated(char *line) {
1771 if (history_max_len == 0) {
1776 if (history == NULL) {
1777 history = (char **)calloc(sizeof(char*), history_max_len);
1780 /* do not insert duplicate lines into history */
1781 if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1785 if (history_len == history_max_len) {
1787 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1790 history[history_len] = line;
1795 int linenoiseHistoryAdd(const char *line) {
1796 return linenoiseHistoryAddAllocated(strdup(line));
1799 int linenoiseHistoryGetMaxLen(void) {
1800 return history_max_len;
1803 int linenoiseHistorySetMaxLen(int len) {
1806 if (len < 1) return 0;
1808 int tocopy = history_len;
1810 newHistory = (char **)calloc(sizeof(char*), len);
1812 /* If we can't copy everything, free the elements we'll not use. */
1816 for (j = 0; j < tocopy-len; j++) free(history[j]);
1819 memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy);
1821 history = newHistory;
1823 history_max_len = len;
1824 if (history_len > history_max_len)
1825 history_len = history_max_len;
1829 /* Save the history in the specified file. On success 0 is returned
1830 * otherwise -1 is returned. */
1831 int linenoiseHistorySave(const char *filename) {
1832 FILE *fp = fopen(filename,"w");
1835 if (fp == NULL) return -1;
1836 for (j = 0; j < history_len; j++) {
1837 const char *str = history[j];
1838 /* Need to encode backslash, nl and cr */
1843 else if (*str == '\n') {
1846 else if (*str == '\r') {
1861 /* Load the history from the specified file.
1863 * If the file does not exist or can't be opened, no operation is performed
1864 * and -1 is returned.
1865 * Otherwise 0 is returned.
1867 int linenoiseHistoryLoad(const char *filename) {
1868 FILE *fp = fopen(filename,"r");
1871 if (fp == NULL) return -1;
1873 while ((sb = sb_getline(fp)) != NULL) {
1874 /* Take the stringbuf and decode backslash escaped values */
1875 char *buf = sb_to_string(sb);
1879 for (src = buf; *src; src++) {
1887 else if (*src == 'r') {
1897 linenoiseHistoryAddAllocated(buf);
1903 /* Provide access to the history buffer.
1905 * If 'len' is not NULL, the length is stored in *len.
1907 char **linenoiseHistory(int *len) {