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"
145 #include "stringbuf.h"
148 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
150 #define ctrl(C) ((C) - '@')
152 /* Use -ve numbers here to co-exist with normal unicode chars */
155 /* don't use -1 here since that indicates error */
160 SPECIAL_DELETE = -24,
163 SPECIAL_INSERT = -27,
164 SPECIAL_PAGE_UP = -28,
165 SPECIAL_PAGE_DOWN = -29,
167 /* Some handy names for other special keycodes */
172 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
173 static int history_len = 0;
174 static char **history = NULL;
176 /* Structure to contain the status of the current (being edited) line */
178 stringbuf *buf; /* Current buffer. Always null terminated */
179 int pos; /* Cursor position, measured in chars */
180 int cols; /* Size of the window, in chars */
181 int nrows; /* How many rows are being used in multiline mode (>= 1) */
182 int rpos; /* The current row containing the cursor - multiline mode only */
184 stringbuf *capture; /* capture buffer, or NULL for none. Always null terminated */
185 stringbuf *output; /* used only during refreshLine() - output accumulator */
186 #if defined(USE_TERMIOS)
187 int fd; /* Terminal fd */
188 #elif defined(USE_WINCONSOLE)
189 HANDLE outh; /* Console output handle */
190 HANDLE inh; /* Console input handle */
191 int rows; /* Screen rows */
192 int x; /* Current column during output */
193 int y; /* Current row */
195 #define UBUF_MAX_CHARS 132
196 WORD ubuf[UBUF_MAX_CHARS + 1]; /* Accumulates utf16 output - one extra for final surrogate pairs */
197 int ubuflen; /* length used in ubuf */
198 int ubufcols; /* how many columns are represented by the chars in ubuf? */
203 static int fd_read(struct current *current);
204 static int getWindowSize(struct current *current);
205 static void cursorDown(struct current *current, int n);
206 static void cursorUp(struct current *current, int n);
207 static void eraseEol(struct current *current);
208 static void refreshLine(struct current *current);
209 static void refreshLineAlt(struct current *current, const char *prompt, const char *buf, int cursor_pos);
210 static void setCursorPos(struct current *current, int x);
211 static void setOutputHighlight(struct current *current, const int *props, int nprops);
212 static void set_current(struct current *current, const char *str);
214 void linenoiseHistoryFree(void) {
218 for (j = 0; j < history_len; j++)
228 EP_START, /* looking for ESC */
229 EP_ESC, /* looking for [ */
230 EP_DIGITS, /* parsing digits */
231 EP_PROPS, /* parsing digits or semicolons */
233 EP_ERROR, /* error */
235 int props[5]; /* properties are stored here */
236 int maxprops; /* size of the props[] array */
237 int numprops; /* number of properties found */
238 int termchar; /* terminator char, or 0 for any alpha */
239 int current; /* current (partial) property value */
243 * Initialise the escape sequence parser at *parser.
245 * If termchar is 0 any alpha char terminates ok. Otherwise only the given
246 * char terminates successfully.
247 * Run the parser state machine with calls to parseEscapeSequence() for each char.
249 static void initParseEscapeSeq(struct esc_parser *parser, int termchar)
251 parser->state = EP_START;
252 parser->maxprops = sizeof(parser->props) / sizeof(*parser->props);
253 parser->numprops = 0;
255 parser->termchar = termchar;
259 * Pass character 'ch' into the state machine to parse:
260 * 'ESC' '[' <digits> (';' <digits>)* <termchar>
262 * The first character must be ESC.
263 * Returns the current state. The state machine is done when it returns either EP_END
266 * On EP_END, the "property/attribute" values can be read from parser->props[]
267 * of length parser->numprops.
269 static int parseEscapeSequence(struct esc_parser *parser, int ch)
271 switch (parser->state) {
273 parser->state = (ch == '\x1b') ? EP_ESC : EP_ERROR;
276 parser->state = (ch == '[') ? EP_DIGITS : EP_ERROR;
280 parser->state = EP_DIGITS;
282 if (parser->numprops + 1 < parser->maxprops) {
283 parser->props[parser->numprops++] = parser->current;
290 if (ch >= '0' && ch <= '9') {
291 parser->current = parser->current * 10 + (ch - '0');
292 parser->state = EP_PROPS;
295 /* must be terminator */
296 if (parser->termchar != ch) {
297 if (parser->termchar != 0 || !((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))) {
298 parser->state = EP_ERROR;
302 parser->state = EP_END;
305 parser->state = EP_ERROR;
310 return parser->state;
313 /*#define DEBUG_REFRESHLINE*/
315 #ifdef DEBUG_REFRESHLINE
316 #define DRL(ARGS...) fprintf(dfh, ARGS)
319 static void DRL_CHAR(int ch)
322 DRL("^%c", ch + '@');
331 static void DRL_STR(const char *str)
335 int n = utf8_tounicode(str, &ch);
346 #if defined(USE_WINCONSOLE)
347 #include "linenoise-win32.c"
350 #if defined(USE_TERMIOS)
351 static void linenoiseAtExit(void);
352 static struct termios orig_termios; /* in order to restore at exit */
353 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
354 static int atexit_registered = 0; /* register atexit just 1 time */
356 static const char *unsupported_term[] = {"dumb","cons25","emacs",NULL};
358 static int isUnsupportedTerm(void) {
359 char *term = getenv("TERM");
363 for (j = 0; unsupported_term[j]; j++) {
364 if (strcmp(term, unsupported_term[j]) == 0) {
372 static int enableRawMode(struct current *current) {
375 current->fd = STDIN_FILENO;
378 if (!isatty(current->fd) || isUnsupportedTerm() ||
379 tcgetattr(current->fd, &orig_termios) == -1) {
385 if (!atexit_registered) {
386 atexit(linenoiseAtExit);
387 atexit_registered = 1;
390 raw = orig_termios; /* modify the original mode */
391 /* input modes: no break, no CR to NL, no parity check, no strip char,
392 * no start/stop output control. */
393 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
394 /* output modes - actually, no need to disable post processing */
395 /*raw.c_oflag &= ~(OPOST);*/
396 /* control modes - set 8 bit chars */
397 raw.c_cflag |= (CS8);
398 /* local modes - choing off, canonical off, no extended functions,
399 * no signal chars (^Z,^C) */
400 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
401 /* control chars - set return condition: min number of bytes and timer.
402 * We want read to return every single byte, without timeout. */
403 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
405 /* put terminal in raw mode after flushing */
406 if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
413 static void disableRawMode(struct current *current) {
414 /* Don't even check the return value as it's too late. */
415 if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
419 /* At exit we'll try to fix the terminal to the initial conditions. */
420 static void linenoiseAtExit(void) {
422 tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
424 linenoiseHistoryFree();
427 /* gcc/glibc insists that we care about the return code of write!
428 * Clarification: This means that a void-cast like "(void) (EXPR)"
431 #define IGNORE_RC(EXPR) if (EXPR) {}
434 * Output bytes directly, or accumulate output (if current->output is set)
436 static void outputChars(struct current *current, const char *buf, int len)
441 if (current->output) {
442 sb_append_len(current->output, buf, len);
445 IGNORE_RC(write(current->fd, buf, len));
449 /* Like outputChars, but using printf-style formatting
451 static void outputFormatted(struct current *current, const char *format, ...)
457 va_start(args, format);
458 n = vsnprintf(buf, sizeof(buf), format, args);
459 /* This will never happen because we are sure to use outputFormatted() only for short sequences */
460 assert(n < (int)sizeof(buf));
462 outputChars(current, buf, n);
465 static void cursorToLeft(struct current *current)
467 outputChars(current, "\r", -1);
470 static void setOutputHighlight(struct current *current, const int *props, int nprops)
472 outputChars(current, "\x1b[", -1);
474 outputFormatted(current, "%d%c", *props, (nprops == 0) ? 'm' : ';');
479 static void eraseEol(struct current *current)
481 outputChars(current, "\x1b[0K", -1);
484 static void setCursorPos(struct current *current, int x)
487 cursorToLeft(current);
490 outputFormatted(current, "\r\x1b[%dC", x);
494 static void cursorUp(struct current *current, int n)
497 outputFormatted(current, "\x1b[%dA", n);
501 static void cursorDown(struct current *current, int n)
504 outputFormatted(current, "\x1b[%dB", n);
508 void linenoiseClearScreen(void)
510 write(STDOUT_FILENO, "\x1b[H\x1b[2J", 7);
514 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
516 * A timeout of -1 means to wait forever.
518 * Returns -1 if no char is received within the time or an error occurs.
520 static int fd_read_char(int fd, int timeout)
528 if (poll(&p, 1, timeout) == 0) {
532 if (read(fd, &c, 1) != 1) {
539 * Reads a complete utf-8 character
540 * and returns the unicode value, or -1 on error.
542 static int fd_read(struct current *current)
545 char buf[MAX_UTF8_LEN];
550 if (read(current->fd, &buf[0], 1) != 1) {
553 n = utf8_charlen(buf[0]);
557 for (i = 1; i < n; i++) {
558 if (read(current->fd, &buf[i], 1) != 1) {
562 /* decode and return the character */
563 utf8_tounicode(buf, &c);
566 return fd_read_char(current->fd, -1);
572 * Stores the current cursor column in '*cols'.
573 * Returns 1 if OK, or 0 if failed to determine cursor pos.
575 static int queryCursor(struct current *current, int* cols)
577 struct esc_parser parser;
580 /* Should not be buffering this output, it needs to go immediately */
581 assert(current->output == NULL);
583 /* control sequence - report cursor location */
584 outputChars(current, "\x1b[6n", -1);
586 /* Parse the response: ESC [ rows ; cols R */
587 initParseEscapeSeq(&parser, 'R');
588 while ((ch = fd_read_char(current->fd, 100)) > 0) {
589 switch (parseEscapeSequence(&parser, ch)) {
593 if (parser.numprops == 2 && parser.props[1] < 1000) {
594 *cols = parser.props[1];
608 * Updates current->cols with the current window size (width)
610 static int getWindowSize(struct current *current)
614 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
615 current->cols = ws.ws_col;
619 /* Failed to query the window size. Perhaps we are on a serial terminal.
620 * Try to query the width by sending the cursor as far to the right
621 * and reading back the cursor position.
622 * Note that this is only done once per call to linenoise rather than
623 * every time the line is refreshed for efficiency reasons.
625 * In more detail, we:
626 * (a) request current cursor position,
627 * (b) move cursor far right,
628 * (c) request cursor position again,
629 * (d) at last move back to the old position.
630 * This gives us the width without messing with the externally
631 * visible cursor position.
634 if (current->cols == 0) {
637 /* If anything fails => default 80 */
641 if (queryCursor (current, &here)) {
643 setCursorPos(current, 999);
645 /* (c). Note: If (a) succeeded, then (c) should as well.
646 * For paranoia we still check and have a fallback action
647 * for (d) in case of failure..
649 if (queryCursor (current, ¤t->cols)) {
650 /* (d) Reset the cursor back to the original location. */
651 if (current->cols > here) {
652 setCursorPos(current, here);
662 * If CHAR_ESCAPE was received, reads subsequent
663 * chars to determine if this is a known special key.
665 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
667 * If no additional char is received within a short time,
668 * CHAR_ESCAPE is returned.
670 static int check_special(int fd)
672 int c = fd_read_char(fd, 50);
679 c2 = fd_read_char(fd, 50);
683 if (c == '[' || c == 'O') {
684 /* Potential arrow key */
691 return SPECIAL_RIGHT;
700 if (c == '[' && c2 >= '1' && c2 <= '8') {
701 /* extended escape */
702 c = fd_read_char(fd, 50);
706 return SPECIAL_INSERT;
708 return SPECIAL_DELETE;
710 return SPECIAL_PAGE_UP;
712 return SPECIAL_PAGE_DOWN;
719 while (c != -1 && c != '~') {
720 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
721 c = fd_read_char(fd, 50);
729 static void clearOutputHighlight(struct current *current)
732 setOutputHighlight(current, &nohighlight, 1);
735 static void outputControlChar(struct current *current, char ch)
738 setOutputHighlight(current, &reverse, 1);
739 outputChars(current, "^", 1);
740 outputChars(current, &ch, 1);
741 clearOutputHighlight(current);
744 #ifndef utf8_getchars
745 static int utf8_getchars(char *buf, int c)
748 return utf8_fromunicode(buf, c);
757 * Returns the unicode character at the given offset,
760 static int get_char(struct current *current, int pos)
762 if (pos >= 0 && pos < sb_chars(current->buf)) {
764 int i = utf8_index(sb_str(current->buf), pos);
765 (void)utf8_tounicode(sb_str(current->buf) + i, &c);
771 static int char_display_width(int ch)
774 /* control chars take two positions */
778 return utf8_width(ch);
782 #ifndef NO_COMPLETION
783 static linenoiseCompletionCallback *completionCallback = NULL;
784 static void *completionUserdata = NULL;
785 static int showhints = 1;
786 static linenoiseHintsCallback *hintsCallback = NULL;
787 static linenoiseFreeHintsCallback *freeHintsCallback = NULL;
788 static void *hintsUserdata = NULL;
792 fprintf(stderr, "\x7");
797 static void freeCompletions(linenoiseCompletions *lc) {
799 for (i = 0; i < lc->len; i++)
804 static int completeLine(struct current *current) {
805 linenoiseCompletions lc = { 0, NULL };
808 completionCallback(sb_str(current->buf),&lc,completionUserdata);
812 size_t stop = 0, i = 0;
815 /* Show completion or original buffer */
817 int chars = utf8_strlen(lc.cvec[i], -1);
818 refreshLineAlt(current, current->prompt, lc.cvec[i], chars);
820 refreshLine(current);
823 c = fd_read(current);
830 i = (i+1) % (lc.len+1);
831 if (i == lc.len) beep();
833 case CHAR_ESCAPE: /* escape */
834 /* Re-show original buffer */
836 refreshLine(current);
841 /* Update buffer and return */
843 set_current(current,lc.cvec[i]);
851 freeCompletions(&lc);
852 return c; /* Return last read character */
855 /* Register a callback function to be called for tab-completion.
856 Returns the prior callback so that the caller may (if needed)
857 restore it when done. */
858 linenoiseCompletionCallback * linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn, void *userdata) {
859 linenoiseCompletionCallback * old = completionCallback;
860 completionCallback = fn;
861 completionUserdata = userdata;
865 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
866 lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
867 lc->cvec[lc->len++] = strdup(str);
870 void linenoiseSetHintsCallback(linenoiseHintsCallback *callback, void *userdata)
872 hintsCallback = callback;
873 hintsUserdata = userdata;
876 void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *callback)
878 freeHintsCallback = callback;
884 static const char *reduceSingleBuf(const char *buf, int availcols, int *cursor_pos)
886 /* We have availcols columns available.
887 * If necessary, strip chars off the front of buf until *cursor_pos
888 * fits within availcols
892 int new_cursor_pos = *cursor_pos;
893 const char *pt = buf;
895 DRL("reduceSingleBuf: availcols=%d, cursor_pos=%d\n", availcols, *cursor_pos);
899 int n = utf8_tounicode(pt, &ch);
902 needcols += char_display_width(ch);
904 /* If we need too many cols, strip
905 * chars off the front of buf to make it fit.
906 * We keep 3 extra cols to the right of the cursor.
907 * 2 for possible wide chars, 1 for the last column that
910 while (needcols >= availcols - 3) {
911 n = utf8_tounicode(buf, &ch);
913 needcols -= char_display_width(ch);
916 /* and adjust the apparent cursor position */
920 /* can't remove more than this */
925 if (pos++ == *cursor_pos) {
932 DRL("\nafter reduce, needcols=%d, new_cursor_pos=%d\n", needcols, new_cursor_pos);
934 /* Done, now new_cursor_pos contains the adjusted cursor position
935 * and buf points to he adjusted start
937 *cursor_pos = new_cursor_pos;
941 static int mlmode = 0;
943 void linenoiseSetMultiLine(int enableml)
948 /* Helper of refreshSingleLine() and refreshMultiLine() to show hints
949 * to the right of the prompt. */
950 static void refreshShowHints(struct current *current, const char *buf, int availcols) {
951 if (showhints && hintsCallback && availcols > 0) {
954 char *hint = hintsCallback(buf, &color, &bold, hintsUserdata);
957 if (bold == 1 && color == -1) color = 37;
958 if (bold || color > 0) {
959 int props[3] = { bold, color, 49 }; /* bold, color, fgnormal */
960 setOutputHighlight(current, props, 3);
962 DRL("<hint bold=%d,color=%d>", bold, color);
966 int n = utf8_tounicode(pt, &ch);
967 int width = char_display_width(ch);
969 if (width >= availcols) {
976 outputChars(current, pt, n);
979 if (bold || color > 0) {
980 clearOutputHighlight(current);
982 /* Call the function to free the hint returned. */
983 if (freeHintsCallback) freeHintsCallback(hint, hintsUserdata);
989 static void refreshStart(struct current *current)
991 /* We accumulate all output here */
992 assert(current->output == NULL);
993 current->output = sb_alloc();
996 static void refreshEnd(struct current *current)
998 /* Output everything at once */
999 IGNORE_RC(write(current->fd, sb_str(current->output), sb_len(current->output)));
1000 sb_free(current->output);
1001 current->output = NULL;
1004 static void refreshStartChars(struct current *current)
1008 static void refreshNewline(struct current *current)
1011 outputChars(current, "\n", 1);
1014 static void refreshEndChars(struct current *current)
1019 static void refreshLineAlt(struct current *current, const char *prompt, const char *buf, int cursor_pos)
1030 struct esc_parser parser;
1032 #ifdef DEBUG_REFRESHLINE
1033 dfh = fopen("linenoise.debuglog", "a");
1036 /* Should intercept SIGWINCH. For now, just get the size every time */
1037 getWindowSize(current);
1039 refreshStart(current);
1041 DRL("wincols=%d, cursor_pos=%d, nrows=%d, rpos=%d\n", current->cols, cursor_pos, current->nrows, current->rpos);
1043 /* Here is the plan:
1044 * (a) move the the bottom row, going down the appropriate number of lines
1045 * (b) move to beginning of line and erase the current line
1046 * (c) go up one line and do the same, until we have erased up to the first row
1047 * (d) output the prompt, counting cols and rows, taking into account escape sequences
1048 * (e) output the buffer, counting cols and rows
1049 * (e') when we hit the current pos, save the cursor position
1050 * (f) move the cursor to the saved cursor position
1051 * (g) save the current cursor row and number of rows
1054 /* (a) - The cursor is currently at row rpos */
1055 cursorDown(current, current->nrows - current->rpos - 1);
1056 DRL("<cud=%d>", current->nrows - current->rpos - 1);
1058 /* (b), (c) - Erase lines upwards until we get to the first row */
1059 for (i = 0; i < current->nrows; i++) {
1062 cursorUp(current, 1);
1065 cursorToLeft(current);
1070 /* (d) First output the prompt. control sequences don't take up display space */
1072 displaycol = 0; /* current display column */
1073 displayrow = 0; /* current display row */
1076 refreshStartChars(current);
1081 int n = utf8_tounicode(pt, &ch);
1083 if (visible && ch == CHAR_ESCAPE) {
1084 /* The start of an escape sequence, so not visible */
1086 initParseEscapeSeq(&parser, 'm');
1087 DRL("<esc-seq-start>");
1090 if (ch == '\n' || ch == '\r') {
1091 /* treat both CR and NL the same and force wrap */
1092 refreshNewline(current);
1097 width = visible * utf8_width(ch);
1099 displaycol += width;
1100 if (displaycol >= current->cols) {
1101 /* need to wrap to the next line because of newline or if it doesn't fit
1102 * XXX this is a problem in single line mode
1104 refreshNewline(current);
1110 #ifdef USE_WINCONSOLE
1112 outputChars(current, pt, n);
1115 outputChars(current, pt, n);
1121 switch (parseEscapeSequence(&parser, ch)) {
1124 setOutputHighlight(current, parser.props, parser.numprops);
1125 DRL("<esc-seq-end,numprops=%d>", parser.numprops);
1128 DRL("<esc-seq-err>");
1135 /* Now we are at the first line with all lines erased */
1136 DRL("\nafter prompt: displaycol=%d, displayrow=%d\n", displaycol, displayrow);
1139 /* (e) output the buffer, counting cols and rows */
1141 /* In this mode we may need to trim chars from the start of the buffer until the
1142 * cursor fits in the window.
1144 pt = reduceSingleBuf(buf, current->cols - displaycol, &cursor_pos);
1155 int n = utf8_tounicode(pt, &ch);
1156 int width = char_display_width(ch);
1158 if (currentpos == cursor_pos) {
1159 /* (e') wherever we output this character is where we want the cursor */
1163 if (displaycol + width >= current->cols) {
1165 /* In single line mode stop once we print as much as we can on one line */
1169 /* need to wrap to the next line since it doesn't fit */
1170 refreshNewline(current);
1175 if (notecursor == 1) {
1176 /* (e') Save this position as the current cursor position */
1177 cursorcol = displaycol;
1178 cursorrow = displayrow;
1183 displaycol += width;
1186 outputControlChar(current, ch + '@');
1189 outputChars(current, pt, n);
1193 DRL("<w=%d>", width);
1200 /* If we didn't see the cursor, it is at the current location */
1203 cursorcol = displaycol;
1204 cursorrow = displayrow;
1207 DRL("\nafter buf: displaycol=%d, displayrow=%d, cursorcol=%d, cursorrow=%d\n\n", displaycol, displayrow, cursorcol, cursorrow);
1209 /* (f) show hints */
1210 refreshShowHints(current, buf, current->cols - displaycol);
1212 refreshEndChars(current);
1214 /* (g) move the cursor to the correct place */
1215 cursorUp(current, displayrow - cursorrow);
1216 setCursorPos(current, cursorcol);
1218 /* (h) Update the number of rows if larger, but never reduce this */
1219 if (displayrow >= current->nrows) {
1220 current->nrows = displayrow + 1;
1222 /* And remember the row that the cursor is on */
1223 current->rpos = cursorrow;
1225 refreshEnd(current);
1227 #ifdef DEBUG_REFRESHLINE
1232 static void refreshLine(struct current *current)
1234 refreshLineAlt(current, current->prompt, sb_str(current->buf), current->pos);
1237 static void set_current(struct current *current, const char *str)
1239 sb_clear(current->buf);
1240 sb_append(current->buf, str);
1241 current->pos = sb_chars(current->buf);
1245 * Removes the char at 'pos'.
1247 * Returns 1 if the line needs to be refreshed, 2 if not
1248 * and 0 if nothing was removed
1250 static int remove_char(struct current *current, int pos)
1252 if (pos >= 0 && pos < sb_chars(current->buf)) {
1253 int offset = utf8_index(sb_str(current->buf), pos);
1254 int nbytes = utf8_index(sb_str(current->buf) + offset, 1);
1256 /* Note that we no longer try to optimise the remove-at-end case
1257 * since control characters and wide characters mess
1258 * up the simple count
1260 sb_delete(current->buf, offset, nbytes);
1262 if (current->pos > pos) {
1271 * Insert 'ch' at position 'pos'
1273 * Returns 1 if the line needs to be refreshed, 2 if not
1274 * and 0 if nothing was inserted (no room)
1276 static int insert_char(struct current *current, int pos, int ch)
1278 if (pos >= 0 && pos <= sb_chars(current->buf)) {
1279 char buf[MAX_UTF8_LEN + 1];
1280 int offset = utf8_index(sb_str(current->buf), pos);
1281 int n = utf8_getchars(buf, ch);
1283 /* null terminate since sb_insert() requires it */
1286 /* Optimisation removed - see reason in remove_char() */
1288 sb_insert(current->buf, offset, buf);
1289 if (current->pos >= pos) {
1298 * Captures up to 'n' characters starting at 'pos' for the cut buffer.
1300 * This replaces any existing characters in the cut buffer.
1302 static void capture_chars(struct current *current, int pos, int nchars)
1304 if (pos >= 0 && (pos + nchars - 1) < sb_chars(current->buf)) {
1305 int offset = utf8_index(sb_str(current->buf), pos);
1306 int nbytes = utf8_index(sb_str(current->buf) + offset, nchars);
1309 if (current->capture) {
1310 sb_clear(current->capture);
1313 current->capture = sb_alloc();
1315 sb_append_len(current->capture, sb_str(current->buf) + offset, nbytes);
1321 * Removes up to 'n' characters at cursor position 'pos'.
1323 * Returns 0 if no chars were removed or non-zero otherwise.
1325 static int remove_chars(struct current *current, int pos, int n)
1329 /* First save any chars which will be removed */
1330 capture_chars(current, pos, n);
1332 while (n-- && remove_char(current, pos)) {
1338 * Inserts the characters (string) 'chars' at the cursor position 'pos'.
1340 * Returns 0 if no chars were inserted or non-zero otherwise.
1342 static int insert_chars(struct current *current, int pos, const char *chars)
1348 int n = utf8_tounicode(chars, &ch);
1349 if (insert_char(current, pos, ch) == 0) {
1360 * Returns the keycode to process, or 0 if none.
1362 static int reverseIncrementalSearch(struct current *current)
1364 /* Display the reverse-i-search prompt and process chars */
1369 int searchpos = history_len - 1;
1375 const char *p = NULL;
1379 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1380 refreshLineAlt(current, rprompt, sb_str(current->buf), current->pos);
1381 c = fd_read(current);
1382 if (c == ctrl('H') || c == CHAR_DELETE) {
1384 int p = utf8_index(rbuf, --rchars);
1386 rlen = strlen(rbuf);
1391 if (c == CHAR_ESCAPE) {
1392 c = check_special(current->fd);
1395 if (c == ctrl('P') || c == SPECIAL_UP) {
1396 /* Search for the previous (earlier) match */
1397 if (searchpos > 0) {
1402 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1403 /* Search for the next (later) match */
1404 if (searchpos < history_len) {
1410 else if (c >= ' ') {
1411 /* >= here to allow for null terminator */
1412 if (rlen >= (int)sizeof(rbuf) - MAX_UTF8_LEN) {
1416 n = utf8_getchars(rbuf + rlen, c);
1421 /* Adding a new char resets the search location */
1422 searchpos = history_len - 1;
1425 /* Exit from incremental search mode */
1429 /* Now search through the history for a match */
1430 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1431 p = strstr(history[searchpos], rbuf);
1434 if (skipsame && strcmp(history[searchpos], sb_str(current->buf)) == 0) {
1435 /* But it is identical, so skip it */
1438 /* Copy the matching line and set the cursor position */
1439 set_current(current,history[searchpos]);
1440 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1445 /* No match, so don't add it */
1451 if (c == ctrl('G') || c == ctrl('C')) {
1452 /* ctrl-g terminates the search with no effect */
1453 set_current(current, "");
1456 else if (c == ctrl('J')) {
1457 /* ctrl-j terminates the search leaving the buffer in place */
1461 /* Go process the char normally */
1462 refreshLine(current);
1466 static int linenoiseEdit(struct current *current) {
1467 int history_index = 0;
1469 /* The latest history entry is always our current buffer, that
1470 * initially is just an empty string. */
1471 linenoiseHistoryAdd("");
1473 set_current(current, "");
1474 refreshLine(current);
1478 int c = fd_read(current);
1480 #ifndef NO_COMPLETION
1481 /* Only autocomplete when the callback is set. It returns < 0 when
1482 * there was an error reading from fd. Otherwise it will return the
1483 * character that should be handled next. */
1484 if (c == '\t' && current->pos == sb_chars(current->buf) && completionCallback != NULL) {
1485 c = completeLine(current);
1488 if (c == ctrl('R')) {
1489 /* reverse incremental search will provide an alternative keycode or 0 for none */
1490 c = reverseIncrementalSearch(current);
1491 /* go on to process the returned char normally */
1495 if (c == CHAR_ESCAPE) { /* escape sequence */
1496 c = check_special(current->fd);
1500 /* Return on errors */
1501 return sb_len(current->buf);
1507 case '\r': /* enter */
1509 free(history[history_len]);
1510 current->pos = sb_chars(current->buf);
1511 if (mlmode || hintsCallback) {
1513 refreshLine(current);
1516 return sb_len(current->buf);
1517 case ctrl('C'): /* ctrl-c */
1520 case ctrl('Z'): /* ctrl-z */
1522 /* send ourselves SIGSUSP */
1523 disableRawMode(current);
1526 enableRawMode(current);
1527 refreshLine(current);
1530 case CHAR_DELETE: /* backspace */
1532 if (remove_char(current, current->pos - 1) == 1) {
1533 refreshLine(current);
1536 case ctrl('D'): /* ctrl-d */
1537 if (sb_len(current->buf) == 0) {
1538 /* Empty line, so EOF */
1540 free(history[history_len]);
1543 /* Otherwise fall through to delete char to right of cursor */
1544 case SPECIAL_DELETE:
1545 if (remove_char(current, current->pos) == 1) {
1546 refreshLine(current);
1549 case SPECIAL_INSERT:
1550 /* Ignore. Expansion Hook.
1551 * Future possibility: Toggle Insert/Overwrite Modes
1554 case ctrl('W'): /* ctrl-w, delete word at left. save deleted chars */
1555 /* eat any spaces on the left */
1557 int pos = current->pos;
1558 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1562 /* now eat any non-spaces on the left */
1563 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1567 if (remove_chars(current, pos, current->pos - pos)) {
1568 refreshLine(current);
1572 case ctrl('T'): /* ctrl-t */
1573 if (current->pos > 0 && current->pos <= sb_chars(current->buf)) {
1574 /* If cursor is at end, transpose the previous two chars */
1575 int fixer = (current->pos == sb_chars(current->buf));
1576 c = get_char(current, current->pos - fixer);
1577 remove_char(current, current->pos - fixer);
1578 insert_char(current, current->pos - 1, c);
1579 refreshLine(current);
1582 case ctrl('V'): /* ctrl-v */
1583 /* Insert the ^V first */
1584 if (insert_char(current, current->pos, c)) {
1585 refreshLine(current);
1586 /* Now wait for the next char. Can insert anything except \0 */
1587 c = fd_read(current);
1589 /* Remove the ^V first */
1590 remove_char(current, current->pos - 1);
1592 /* Insert the actual char, can't be error or null */
1593 insert_char(current, current->pos, c);
1595 refreshLine(current);
1600 if (current->pos > 0) {
1602 refreshLine(current);
1607 if (current->pos < sb_chars(current->buf)) {
1609 refreshLine(current);
1612 case SPECIAL_PAGE_UP:
1613 dir = history_len - history_index - 1; /* move to start of history */
1614 goto history_navigation;
1615 case SPECIAL_PAGE_DOWN:
1616 dir = -history_index; /* move to 0 == end of history, i.e. current */
1617 goto history_navigation;
1621 goto history_navigation;
1625 if (history_len > 1) {
1626 /* Update the current history entry before to
1627 * overwrite it with tne next one. */
1628 free(history[history_len - 1 - history_index]);
1629 history[history_len - 1 - history_index] = strdup(sb_str(current->buf));
1630 /* Show the new entry */
1631 history_index += dir;
1632 if (history_index < 0) {
1635 } else if (history_index >= history_len) {
1636 history_index = history_len - 1;
1639 set_current(current, history[history_len - 1 - history_index]);
1640 refreshLine(current);
1643 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1646 refreshLine(current);
1648 case ctrl('E'): /* ctrl+e, go to the end of the line */
1650 current->pos = sb_chars(current->buf);
1651 refreshLine(current);
1653 case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */
1654 if (remove_chars(current, 0, current->pos)) {
1655 refreshLine(current);
1658 case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */
1659 if (remove_chars(current, current->pos, sb_chars(current->buf) - current->pos)) {
1660 refreshLine(current);
1663 case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */
1664 if (current->capture && insert_chars(current, current->pos, sb_str(current->capture))) {
1665 refreshLine(current);
1668 case ctrl('L'): /* Ctrl+L, clear screen */
1669 linenoiseClearScreen();
1670 /* Force recalc of window size for serial terminals */
1673 refreshLine(current);
1676 /* Only tab is allowed without ^V */
1677 if (c == '\t' || c >= ' ') {
1678 if (insert_char(current, current->pos, c) == 1) {
1679 refreshLine(current);
1685 return sb_len(current->buf);
1688 int linenoiseColumns(void)
1690 struct current current;
1691 enableRawMode (¤t);
1692 getWindowSize (¤t);
1693 disableRawMode (¤t);
1694 return current.cols;
1698 * Reads a line from the file handle (without the trailing NL or CRNL)
1699 * and returns it in a stringbuf.
1700 * Returns NULL if no characters are read before EOF or error.
1702 * Note that the character count will *not* be correct for lines containing
1703 * utf8 sequences. Do not rely on the character count.
1705 static stringbuf *sb_getline(FILE *fh)
1707 stringbuf *sb = sb_alloc();
1711 while ((c = getc(fh)) != EOF) {
1718 if (c == '\n' || c == '\r') {
1722 /* ignore the effect of character count for partial utf8 sequences */
1723 sb_append_len(sb, &ch, 1);
1732 char *linenoise(const char *prompt)
1735 struct current current;
1738 memset(¤t, 0, sizeof(current));
1740 if (enableRawMode(¤t) == -1) {
1741 printf("%s", prompt);
1743 sb = sb_getline(stdin);
1746 current.buf = sb_alloc();
1749 current.prompt = prompt;
1751 count = linenoiseEdit(¤t);
1753 disableRawMode(¤t);
1756 sb_free(current.capture);
1758 sb_free(current.buf);
1763 return sb ? sb_to_string(sb) : NULL;
1766 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1767 int linenoiseHistoryAddAllocated(char *line) {
1769 if (history_max_len == 0) {
1774 if (history == NULL) {
1775 history = (char **)calloc(sizeof(char*), history_max_len);
1778 /* do not insert duplicate lines into history */
1779 if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1783 if (history_len == history_max_len) {
1785 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1788 history[history_len] = line;
1793 int linenoiseHistoryAdd(const char *line) {
1794 return linenoiseHistoryAddAllocated(strdup(line));
1797 int linenoiseHistoryGetMaxLen(void) {
1798 return history_max_len;
1801 int linenoiseHistorySetMaxLen(int len) {
1804 if (len < 1) return 0;
1806 int tocopy = history_len;
1808 newHistory = (char **)calloc(sizeof(char*), len);
1810 /* If we can't copy everything, free the elements we'll not use. */
1814 for (j = 0; j < tocopy-len; j++) free(history[j]);
1817 memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy);
1819 history = newHistory;
1821 history_max_len = len;
1822 if (history_len > history_max_len)
1823 history_len = history_max_len;
1827 /* Save the history in the specified file. On success 0 is returned
1828 * otherwise -1 is returned. */
1829 int linenoiseHistorySave(const char *filename) {
1830 FILE *fp = fopen(filename,"w");
1833 if (fp == NULL) return -1;
1834 for (j = 0; j < history_len; j++) {
1835 const char *str = history[j];
1836 /* Need to encode backslash, nl and cr */
1841 else if (*str == '\n') {
1844 else if (*str == '\r') {
1859 /* Load the history from the specified file.
1861 * If the file does not exist or can't be opened, no operation is performed
1862 * and -1 is returned.
1863 * Otherwise 0 is returned.
1865 int linenoiseHistoryLoad(const char *filename) {
1866 FILE *fp = fopen(filename,"r");
1869 if (fp == NULL) return -1;
1871 while ((sb = sb_getline(fp)) != NULL) {
1872 /* Take the stringbuf and decode backslash escaped values */
1873 char *buf = sb_to_string(sb);
1877 for (src = buf; *src; src++) {
1885 else if (*src == 'r') {
1895 linenoiseHistoryAddAllocated(buf);
1901 /* Provide access to the history buffer.
1903 * If 'len' is not NULL, the length is stored in *len.
1905 char **linenoiseHistory(int *len) {