]> git.lizzy.rs Git - linenoise.git/blob - linenoise.c
Can't use insert/delete char optimisation on win32
[linenoise.git] / linenoise.c
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.
3  *
4  * You can find the latest source code at:
5  *
6  *   http://github.com/msteveb/linenoise
7  *   (forked from http://github.com/antirez/linenoise)
8  *
9  * Does a number of crazy assumptions that happen to be true in 99.9999% of
10  * the 2010 UNIX computers around.
11  *
12  * ------------------------------------------------------------------------
13  *
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>
17  *
18  * All rights reserved.
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions are
22  * met:
23  *
24  *  *  Redistributions of source code must retain the above copyright
25  *     notice, this list of conditions and the following disclaimer.
26  *
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.
30  *
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.
42  *
43  * ------------------------------------------------------------------------
44  *
45  * References:
46  * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
47  * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
48  *
49  * Bloat:
50  * - Completion?
51  *
52  * Unix/termios
53  * ------------
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.
58  *
59  * EL (Erase Line)
60  *    Sequence: ESC [ 0 K
61  *    Effect: clear from cursor to end of line
62  *
63  * CUF (CUrsor Forward)
64  *    Sequence: ESC [ n C
65  *    Effect: moves cursor forward n chars
66  *
67  * CR (Carriage Return)
68  *    Sequence: \r
69  *    Effect: moves cursor to column 1
70  *
71  * The following are used to clear the screen: ESC [ H ESC [ 2 J
72  * This is actually composed of two sequences:
73  *
74  * cursorhome
75  *    Sequence: ESC [ H
76  *    Effect: moves the cursor to upper left corner
77  *
78  * ED2 (Clear entire screen)
79  *    Sequence: ESC [ 2 J
80  *    Effect: clear the whole screen
81  *
82  * == For highlighting control characters, we also use the following two ==
83  * SO (enter StandOut)
84  *    Sequence: ESC [ 7 m
85  *    Effect: Uses some standout mode such as reverse video
86  *
87  * SE (Standout End)
88  *    Sequence: ESC [ 0 m
89  *    Effect: Exit standout mode
90  *
91  * == Only used if TIOCGWINSZ fails ==
92  * DSR/CPR (Report cursor position)
93  *    Sequence: ESC [ 6 n
94  *    Effect: reports current cursor position as ESC [ NNN ; MMM R
95  *
96  * == Only used in multiline mode ==
97  * CUU (Cursor Up)
98  *    Sequence: ESC [ n A
99  *    Effect: moves cursor up n chars.
100  *
101  * CUD (Cursor Down)
102  *    Sequence: ESC [ n B
103  *    Effect: moves cursor down n chars.
104  *
105  * win32/console
106  * -------------
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.
110  */
111
112 #ifdef _WIN32 /* Windows platform, either MinGW or Visual Studio (MSVC) */
113 #include <windows.h>
114 #include <fcntl.h>
115 #define USE_WINCONSOLE
116 #ifdef __MINGW32__
117 #define HAVE_UNISTD_H
118 #else
119 /* Microsoft headers don't like old POSIX names */
120 #define strdup _strdup
121 #define snprintf _snprintf
122 #endif
123 #else
124 #include <termios.h>
125 #include <sys/ioctl.h>
126 #include <poll.h>
127 #define USE_TERMIOS
128 #define HAVE_UNISTD_H
129 #endif
130
131 #ifdef HAVE_UNISTD_H
132 #include <unistd.h>
133 #endif
134 #include <stdlib.h>
135 #include <stdarg.h>
136 #include <stdio.h>
137 #include <assert.h>
138 #include <errno.h>
139 #include <string.h>
140 #include <signal.h>
141 #include <stdlib.h>
142 #include <sys/types.h>
143
144 #include "linenoise.h"
145 #ifndef STRINGBUF_H
146 #include "stringbuf.h"
147 #endif
148 #include "utf8.h"
149
150 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
151
152 #define ctrl(C) ((C) - '@')
153
154 /* Use -ve numbers here to co-exist with normal unicode chars */
155 enum {
156     SPECIAL_NONE,
157     /* don't use -1 here since that indicates error */
158     SPECIAL_UP = -20,
159     SPECIAL_DOWN = -21,
160     SPECIAL_LEFT = -22,
161     SPECIAL_RIGHT = -23,
162     SPECIAL_DELETE = -24,
163     SPECIAL_HOME = -25,
164     SPECIAL_END = -26,
165     SPECIAL_INSERT = -27,
166     SPECIAL_PAGE_UP = -28,
167     SPECIAL_PAGE_DOWN = -29,
168
169     /* Some handy names for other special keycodes */
170     CHAR_ESCAPE = 27,
171     CHAR_DELETE = 127,
172 };
173
174 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
175 static int history_len = 0;
176 static char **history = NULL;
177
178 /* Structure to contain the status of the current (being edited) line */
179 struct current {
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 */
187     const char *prompt;
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 */
198 #ifdef USE_UTF8
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? */
203 #endif
204 #endif
205 };
206
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);
217
218 void linenoiseHistoryFree(void) {
219     if (history) {
220         int j;
221
222         for (j = 0; j < history_len; j++)
223             free(history[j]);
224         free(history);
225         history = NULL;
226         history_len = 0;
227     }
228 }
229
230 struct esc_parser {
231     enum {
232         EP_START,   /* looking for ESC */
233         EP_ESC,     /* looking for [ */
234         EP_DIGITS,  /* parsing digits */
235         EP_PROPS,   /* parsing digits or semicolons */
236         EP_END,     /* ok */
237         EP_ERROR,   /* error */
238     } state;
239     int props[5];   /* properties are stored here */
240     int maxprops;   /* size of the props[] array */
241     int numprops;   /* number of properties found */
242     int termchar;   /* terminator char, or 0 for any alpha */
243     int current;    /* current (partial) property value */
244 };
245
246 /**
247  * Initialise the escape sequence parser at *parser.
248  *
249  * If termchar is 0 any alpha char terminates ok. Otherwise only the given
250  * char terminates successfully.
251  * Run the parser state machine with calls to parseEscapeSequence() for each char.
252  */
253 static void initParseEscapeSeq(struct esc_parser *parser, int termchar)
254 {
255     parser->state = EP_START;
256     parser->maxprops = sizeof(parser->props) / sizeof(*parser->props);
257     parser->numprops = 0;
258     parser->current = 0;
259     parser->termchar = termchar;
260 }
261
262 /**
263  * Pass character 'ch' into the state machine to parse:
264  *   'ESC' '[' <digits> (';' <digits>)* <termchar>
265  *
266  * The first character must be ESC.
267  * Returns the current state. The state machine is done when it returns either EP_END
268  * or EP_ERROR.
269  *
270  * On EP_END, the "property/attribute" values can be read from parser->props[]
271  * of length parser->numprops.
272  */
273 static int parseEscapeSequence(struct esc_parser *parser, int ch)
274 {
275     switch (parser->state) {
276         case EP_START:
277             parser->state = (ch == '\x1b') ? EP_ESC : EP_ERROR;
278             break;
279         case EP_ESC:
280             parser->state = (ch == '[') ? EP_DIGITS : EP_ERROR;
281             break;
282         case EP_PROPS:
283             if (ch == ';') {
284                 parser->state = EP_DIGITS;
285 donedigits:
286                 if (parser->numprops + 1 < parser->maxprops) {
287                     parser->props[parser->numprops++] = parser->current;
288                     parser->current = 0;
289                 }
290                 break;
291             }
292             /* fall through */
293         case EP_DIGITS:
294             if (ch >= '0' && ch <= '9') {
295                 parser->current = parser->current * 10 + (ch - '0');
296                 parser->state = EP_PROPS;
297                 break;
298             }
299             /* must be terminator */
300             if (parser->termchar != ch) {
301                 if (parser->termchar != 0 || !((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))) {
302                     parser->state = EP_ERROR;
303                     break;
304                 }
305             }
306             parser->state = EP_END;
307             goto donedigits;
308         case EP_END:
309             parser->state = EP_ERROR;
310             break;
311         case EP_ERROR:
312             break;
313     }
314     return parser->state;
315 }
316
317 /*#define DEBUG_REFRESHLINE*/
318
319 #ifdef DEBUG_REFRESHLINE
320 #define DRL(ARGS...) fprintf(dfh, ARGS)
321 static FILE *dfh;
322
323 static void DRL_CHAR(int ch)
324 {
325     if (ch < ' ') {
326         DRL("^%c", ch + '@');
327     }
328     else if (ch > 127) {
329         DRL("\\u%04x", ch);
330     }
331     else {
332         DRL("%c", ch);
333     }
334 }
335 static void DRL_STR(const char *str)
336 {
337     while (*str) {
338         int ch;
339         int n = utf8_tounicode(str, &ch);
340         str += n;
341         DRL_CHAR(ch);
342     }
343 }
344 #else
345 #define DRL(ARGS...)
346 #define DRL_CHAR(ch)
347 #define DRL_STR(str)
348 #endif
349
350 #if defined(USE_WINCONSOLE)
351 #include "linenoise-win32.c"
352 #endif
353
354 #if defined(USE_TERMIOS)
355 static void linenoiseAtExit(void);
356 static struct termios orig_termios; /* in order to restore at exit */
357 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
358 static int atexit_registered = 0; /* register atexit just 1 time */
359
360 static const char *unsupported_term[] = {"dumb","cons25","emacs",NULL};
361
362 static int isUnsupportedTerm(void) {
363     char *term = getenv("TERM");
364
365     if (term) {
366         int j;
367         for (j = 0; unsupported_term[j]; j++) {
368             if (strcmp(term, unsupported_term[j]) == 0) {
369                 return 1;
370             }
371         }
372     }
373     return 0;
374 }
375
376 static int enableRawMode(struct current *current) {
377     struct termios raw;
378
379     current->fd = STDIN_FILENO;
380     current->cols = 0;
381
382     if (!isatty(current->fd) || isUnsupportedTerm() ||
383         tcgetattr(current->fd, &orig_termios) == -1) {
384 fatal:
385         errno = ENOTTY;
386         return -1;
387     }
388
389     if (!atexit_registered) {
390         atexit(linenoiseAtExit);
391         atexit_registered = 1;
392     }
393
394     raw = orig_termios;  /* modify the original mode */
395     /* input modes: no break, no CR to NL, no parity check, no strip char,
396      * no start/stop output control. */
397     raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
398     /* output modes - actually, no need to disable post processing */
399     /*raw.c_oflag &= ~(OPOST);*/
400     /* control modes - set 8 bit chars */
401     raw.c_cflag |= (CS8);
402     /* local modes - choing off, canonical off, no extended functions,
403      * no signal chars (^Z,^C) */
404     raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
405     /* control chars - set return condition: min number of bytes and timer.
406      * We want read to return every single byte, without timeout. */
407     raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
408
409     /* put terminal in raw mode after flushing */
410     if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
411         goto fatal;
412     }
413     rawmode = 1;
414     return 0;
415 }
416
417 static void disableRawMode(struct current *current) {
418     /* Don't even check the return value as it's too late. */
419     if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
420         rawmode = 0;
421 }
422
423 /* At exit we'll try to fix the terminal to the initial conditions. */
424 static void linenoiseAtExit(void) {
425     if (rawmode) {
426         tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
427     }
428     linenoiseHistoryFree();
429 }
430
431 /* gcc/glibc insists that we care about the return code of write!
432  * Clarification: This means that a void-cast like "(void) (EXPR)"
433  * does not work.
434  */
435 #define IGNORE_RC(EXPR) if (EXPR) {}
436
437 /**
438  * Output bytes directly, or accumulate output (if current->output is set)
439  */
440 static void outputChars(struct current *current, const char *buf, int len)
441 {
442     if (len < 0) {
443         len = strlen(buf);
444     }
445     if (current->output) {
446         sb_append_len(current->output, buf, len);
447     }
448     else {
449         IGNORE_RC(write(current->fd, buf, len));
450     }
451 }
452
453 /* Like outputChars, but using printf-style formatting
454  */
455 static void outputFormatted(struct current *current, const char *format, ...)
456 {
457     va_list args;
458     char buf[64];
459     int n;
460
461     va_start(args, format);
462     n = vsnprintf(buf, sizeof(buf), format, args);
463     /* This will never happen because we are sure to use outputFormatted() only for short sequences */
464     assert(n < (int)sizeof(buf));
465     va_end(args);
466     outputChars(current, buf, n);
467 }
468
469 static void cursorToLeft(struct current *current)
470 {
471     outputChars(current, "\r", -1);
472 }
473
474 static void setOutputHighlight(struct current *current, const int *props, int nprops)
475 {
476     outputChars(current, "\x1b[", -1);
477     while (nprops--) {
478         outputFormatted(current, "%d%c", *props, (nprops == 0) ? 'm' : ';');
479         props++;
480     }
481 }
482
483 static void eraseEol(struct current *current)
484 {
485     outputChars(current, "\x1b[0K", -1);
486 }
487
488 static void setCursorPos(struct current *current, int x)
489 {
490     if (x == 0) {
491         cursorToLeft(current);
492     }
493     else {
494         outputFormatted(current, "\r\x1b[%dC", x);
495     }
496 }
497
498 static void cursorUp(struct current *current, int n)
499 {
500     if (n) {
501         outputFormatted(current, "\x1b[%dA", n);
502     }
503 }
504
505 static void cursorDown(struct current *current, int n)
506 {
507     if (n) {
508         outputFormatted(current, "\x1b[%dB", n);
509     }
510 }
511
512 void linenoiseClearScreen(void)
513 {
514     IGNORE_RC(write(STDOUT_FILENO, "\x1b[H\x1b[2J", 7));
515 }
516
517 /**
518  * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
519  *
520  * A timeout of -1 means to wait forever.
521  *
522  * Returns -1 if no char is received within the time or an error occurs.
523  */
524 static int fd_read_char(int fd, int timeout)
525 {
526     struct pollfd p;
527     unsigned char c;
528
529     p.fd = fd;
530     p.events = POLLIN;
531
532     if (poll(&p, 1, timeout) == 0) {
533         /* timeout */
534         return -1;
535     }
536     if (read(fd, &c, 1) != 1) {
537         return -1;
538     }
539     return c;
540 }
541
542 /**
543  * Reads a complete utf-8 character
544  * and returns the unicode value, or -1 on error.
545  */
546 static int fd_read(struct current *current)
547 {
548 #ifdef USE_UTF8
549     char buf[MAX_UTF8_LEN];
550     int n;
551     int i;
552     int c;
553
554     if (read(current->fd, &buf[0], 1) != 1) {
555         return -1;
556     }
557     n = utf8_charlen(buf[0]);
558     if (n < 1) {
559         return -1;
560     }
561     for (i = 1; i < n; i++) {
562         if (read(current->fd, &buf[i], 1) != 1) {
563             return -1;
564         }
565     }
566     /* decode and return the character */
567     utf8_tounicode(buf, &c);
568     return c;
569 #else
570     return fd_read_char(current->fd, -1);
571 #endif
572 }
573
574
575 /**
576  * Stores the current cursor column in '*cols'.
577  * Returns 1 if OK, or 0 if failed to determine cursor pos.
578  */
579 static int queryCursor(struct current *current, int* cols)
580 {
581     struct esc_parser parser;
582     int ch;
583
584     /* Should not be buffering this output, it needs to go immediately */
585     assert(current->output == NULL);
586
587     /* control sequence - report cursor location */
588     outputChars(current, "\x1b[6n", -1);
589
590     /* Parse the response: ESC [ rows ; cols R */
591     initParseEscapeSeq(&parser, 'R');
592     while ((ch = fd_read_char(current->fd, 100)) > 0) {
593         switch (parseEscapeSequence(&parser, ch)) {
594             default:
595                 continue;
596             case EP_END:
597                 if (parser.numprops == 2 && parser.props[1] < 1000) {
598                     *cols = parser.props[1];
599                     return 1;
600                 }
601                 break;
602             case EP_ERROR:
603                 break;
604         }
605         /* failed */
606         break;
607     }
608     return 0;
609 }
610
611 /**
612  * Updates current->cols with the current window size (width)
613  */
614 static int getWindowSize(struct current *current)
615 {
616     struct winsize ws;
617
618     if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
619         current->cols = ws.ws_col;
620         return 0;
621     }
622
623     /* Failed to query the window size. Perhaps we are on a serial terminal.
624      * Try to query the width by sending the cursor as far to the right
625      * and reading back the cursor position.
626      * Note that this is only done once per call to linenoise rather than
627      * every time the line is refreshed for efficiency reasons.
628      *
629      * In more detail, we:
630      * (a) request current cursor position,
631      * (b) move cursor far right,
632      * (c) request cursor position again,
633      * (d) at last move back to the old position.
634      * This gives us the width without messing with the externally
635      * visible cursor position.
636      */
637
638     if (current->cols == 0) {
639         int here;
640
641         /* If anything fails => default 80 */
642         current->cols = 80;
643
644         /* (a) */
645         if (queryCursor (current, &here)) {
646             /* (b) */
647             setCursorPos(current, 999);
648
649             /* (c). Note: If (a) succeeded, then (c) should as well.
650              * For paranoia we still check and have a fallback action
651              * for (d) in case of failure..
652              */
653             if (queryCursor (current, &current->cols)) {
654                 /* (d) Reset the cursor back to the original location. */
655                 if (current->cols > here) {
656                     setCursorPos(current, here);
657                 }
658             }
659         }
660     }
661
662     return 0;
663 }
664
665 /**
666  * If CHAR_ESCAPE was received, reads subsequent
667  * chars to determine if this is a known special key.
668  *
669  * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
670  *
671  * If no additional char is received within a short time,
672  * CHAR_ESCAPE is returned.
673  */
674 static int check_special(int fd)
675 {
676     int c = fd_read_char(fd, 50);
677     int c2;
678
679     if (c < 0) {
680         return CHAR_ESCAPE;
681     }
682
683     c2 = fd_read_char(fd, 50);
684     if (c2 < 0) {
685         return c2;
686     }
687     if (c == '[' || c == 'O') {
688         /* Potential arrow key */
689         switch (c2) {
690             case 'A':
691                 return SPECIAL_UP;
692             case 'B':
693                 return SPECIAL_DOWN;
694             case 'C':
695                 return SPECIAL_RIGHT;
696             case 'D':
697                 return SPECIAL_LEFT;
698             case 'F':
699                 return SPECIAL_END;
700             case 'H':
701                 return SPECIAL_HOME;
702         }
703     }
704     if (c == '[' && c2 >= '1' && c2 <= '8') {
705         /* extended escape */
706         c = fd_read_char(fd, 50);
707         if (c == '~') {
708             switch (c2) {
709                 case '2':
710                     return SPECIAL_INSERT;
711                 case '3':
712                     return SPECIAL_DELETE;
713                 case '5':
714                     return SPECIAL_PAGE_UP;
715                 case '6':
716                     return SPECIAL_PAGE_DOWN;
717                 case '7':
718                     return SPECIAL_HOME;
719                 case '8':
720                     return SPECIAL_END;
721             }
722         }
723         while (c != -1 && c != '~') {
724             /* .e.g \e[12~ or '\e[11;2~   discard the complete sequence */
725             c = fd_read_char(fd, 50);
726         }
727     }
728
729     return SPECIAL_NONE;
730 }
731 #endif
732
733 static void clearOutputHighlight(struct current *current)
734 {
735     int nohighlight = 0;
736     setOutputHighlight(current, &nohighlight, 1);
737 }
738
739 static void outputControlChar(struct current *current, char ch)
740 {
741     int reverse = 7;
742     setOutputHighlight(current, &reverse, 1);
743     outputChars(current, "^", 1);
744     outputChars(current, &ch, 1);
745     clearOutputHighlight(current);
746 }
747
748 #ifndef utf8_getchars
749 static int utf8_getchars(char *buf, int c)
750 {
751 #ifdef USE_UTF8
752     return utf8_fromunicode(buf, c);
753 #else
754     *buf = c;
755     return 1;
756 #endif
757 }
758 #endif
759
760 /**
761  * Returns the unicode character at the given offset,
762  * or -1 if none.
763  */
764 static int get_char(struct current *current, int pos)
765 {
766     if (pos >= 0 && pos < sb_chars(current->buf)) {
767         int c;
768         int i = utf8_index(sb_str(current->buf), pos);
769         (void)utf8_tounicode(sb_str(current->buf) + i, &c);
770         return c;
771     }
772     return -1;
773 }
774
775 static int char_display_width(int ch)
776 {
777     if (ch < ' ') {
778         /* control chars take two positions */
779         return 2;
780     }
781     else {
782         return utf8_width(ch);
783     }
784 }
785
786 #ifndef NO_COMPLETION
787 static linenoiseCompletionCallback *completionCallback = NULL;
788 static void *completionUserdata = NULL;
789 static int showhints = 1;
790 static linenoiseHintsCallback *hintsCallback = NULL;
791 static linenoiseFreeHintsCallback *freeHintsCallback = NULL;
792 static void *hintsUserdata = NULL;
793
794 static void beep() {
795 #ifdef USE_TERMIOS
796     fprintf(stderr, "\x7");
797     fflush(stderr);
798 #endif
799 }
800
801 static void freeCompletions(linenoiseCompletions *lc) {
802     size_t i;
803     for (i = 0; i < lc->len; i++)
804         free(lc->cvec[i]);
805     free(lc->cvec);
806 }
807
808 static int completeLine(struct current *current) {
809     linenoiseCompletions lc = { 0, NULL };
810     int c = 0;
811
812     completionCallback(sb_str(current->buf),&lc,completionUserdata);
813     if (lc.len == 0) {
814         beep();
815     } else {
816         size_t stop = 0, i = 0;
817
818         while(!stop) {
819             /* Show completion or original buffer */
820             if (i < lc.len) {
821                 int chars = utf8_strlen(lc.cvec[i], -1);
822                 refreshLineAlt(current, current->prompt, lc.cvec[i], chars);
823             } else {
824                 refreshLine(current);
825             }
826
827             c = fd_read(current);
828             if (c == -1) {
829                 break;
830             }
831
832             switch(c) {
833                 case '\t': /* tab */
834                     i = (i+1) % (lc.len+1);
835                     if (i == lc.len) beep();
836                     break;
837                 case CHAR_ESCAPE: /* escape */
838                     /* Re-show original buffer */
839                     if (i < lc.len) {
840                         refreshLine(current);
841                     }
842                     stop = 1;
843                     break;
844                 default:
845                     /* Update buffer and return */
846                     if (i < lc.len) {
847                         set_current(current,lc.cvec[i]);
848                     }
849                     stop = 1;
850                     break;
851             }
852         }
853     }
854
855     freeCompletions(&lc);
856     return c; /* Return last read character */
857 }
858
859 /* Register a callback function to be called for tab-completion.
860    Returns the prior callback so that the caller may (if needed)
861    restore it when done. */
862 linenoiseCompletionCallback * linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn, void *userdata) {
863     linenoiseCompletionCallback * old = completionCallback;
864     completionCallback = fn;
865     completionUserdata = userdata;
866     return old;
867 }
868
869 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
870     lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
871     lc->cvec[lc->len++] = strdup(str);
872 }
873
874 void linenoiseSetHintsCallback(linenoiseHintsCallback *callback, void *userdata)
875 {
876     hintsCallback = callback;
877     hintsUserdata = userdata;
878 }
879
880 void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *callback)
881 {
882     freeHintsCallback = callback;
883 }
884
885 #endif
886
887
888 static const char *reduceSingleBuf(const char *buf, int availcols, int *cursor_pos)
889 {
890     /* We have availcols columns available.
891      * If necessary, strip chars off the front of buf until *cursor_pos
892      * fits within availcols
893      */
894     int needcols = 0;
895     int pos = 0;
896     int new_cursor_pos = *cursor_pos;
897     const char *pt = buf;
898
899     DRL("reduceSingleBuf: availcols=%d, cursor_pos=%d\n", availcols, *cursor_pos);
900
901     while (*pt) {
902         int ch;
903         int n = utf8_tounicode(pt, &ch);
904         pt += n;
905
906         needcols += char_display_width(ch);
907
908         /* If we need too many cols, strip
909          * chars off the front of buf to make it fit.
910          * We keep 3 extra cols to the right of the cursor.
911          * 2 for possible wide chars, 1 for the last column that
912          * can't be used.
913          */
914         while (needcols >= availcols - 3) {
915             n = utf8_tounicode(buf, &ch);
916             buf += n;
917             needcols -= char_display_width(ch);
918             DRL_CHAR(ch);
919
920             /* and adjust the apparent cursor position */
921             new_cursor_pos--;
922
923             if (buf == pt) {
924                 /* can't remove more than this */
925                 break;
926             }
927         }
928
929         if (pos++ == *cursor_pos) {
930             break;
931         }
932
933     }
934     DRL("<snip>");
935     DRL_STR(buf);
936     DRL("\nafter reduce, needcols=%d, new_cursor_pos=%d\n", needcols, new_cursor_pos);
937
938     /* Done, now new_cursor_pos contains the adjusted cursor position
939      * and buf points to he adjusted start
940      */
941     *cursor_pos = new_cursor_pos;
942     return buf;
943 }
944
945 static int mlmode = 0;
946
947 void linenoiseSetMultiLine(int enableml)
948 {
949     mlmode = enableml;
950 }
951
952 /* Helper of refreshSingleLine() and refreshMultiLine() to show hints
953  * to the right of the prompt.
954  * Returns 1 if a hint was shown, or 0 if not
955  * If 'display' is 0, does no output. Just returns the appropriate return code.
956  */
957 static int refreshShowHints(struct current *current, const char *buf, int availcols, int display)
958 {
959     int rc = 0;
960     if (showhints && hintsCallback && availcols > 0) {
961         int bold = 0;
962         int color = -1;
963         char *hint = hintsCallback(buf, &color, &bold, hintsUserdata);
964         if (hint) {
965             rc = 1;
966             if (display) {
967                 const char *pt;
968                 if (bold == 1 && color == -1) color = 37;
969                 if (bold || color > 0) {
970                     int props[3] = { bold, color, 49 }; /* bold, color, fgnormal */
971                     setOutputHighlight(current, props, 3);
972                 }
973                 DRL("<hint bold=%d,color=%d>", bold, color);
974                 pt = hint;
975                 while (*pt) {
976                     int ch;
977                     int n = utf8_tounicode(pt, &ch);
978                     int width = char_display_width(ch);
979
980                     if (width >= availcols) {
981                         DRL("<hinteol>");
982                         break;
983                     }
984                     DRL_CHAR(ch);
985
986                     availcols -= width;
987                     outputChars(current, pt, n);
988                     pt += n;
989                 }
990                 if (bold || color > 0) {
991                     clearOutputHighlight(current);
992                 }
993                 /* Call the function to free the hint returned. */
994                 if (freeHintsCallback) freeHintsCallback(hint, hintsUserdata);
995             }
996         }
997     }
998     return rc;
999 }
1000
1001 #ifdef USE_TERMIOS
1002 static void refreshStart(struct current *current)
1003 {
1004     /* We accumulate all output here */
1005     assert(current->output == NULL);
1006     current->output = sb_alloc();
1007 }
1008
1009 static void refreshEnd(struct current *current)
1010 {
1011     /* Output everything at once */
1012     IGNORE_RC(write(current->fd, sb_str(current->output), sb_len(current->output)));
1013     sb_free(current->output);
1014     current->output = NULL;
1015 }
1016
1017 static void refreshStartChars(struct current *current)
1018 {
1019 }
1020
1021 static void refreshNewline(struct current *current)
1022 {
1023     DRL("<nl>");
1024     outputChars(current, "\n", 1);
1025 }
1026
1027 static void refreshEndChars(struct current *current)
1028 {
1029 }
1030 #endif
1031
1032 static void refreshLineAlt(struct current *current, const char *prompt, const char *buf, int cursor_pos)
1033 {
1034     int i;
1035     const char *pt;
1036     int displaycol;
1037     int displayrow;
1038     int visible;
1039     int currentpos;
1040     int notecursor;
1041     int cursorcol = 0;
1042     int cursorrow = 0;
1043     int hint;
1044     struct esc_parser parser;
1045
1046 #ifdef DEBUG_REFRESHLINE
1047     dfh = fopen("linenoise.debuglog", "a");
1048 #endif
1049
1050     /* Should intercept SIGWINCH. For now, just get the size every time */
1051     getWindowSize(current);
1052
1053     refreshStart(current);
1054
1055     DRL("wincols=%d, cursor_pos=%d, nrows=%d, rpos=%d\n", current->cols, cursor_pos, current->nrows, current->rpos);
1056
1057     /* Here is the plan:
1058      * (a) move the the bottom row, going down the appropriate number of lines
1059      * (b) move to beginning of line and erase the current line
1060      * (c) go up one line and do the same, until we have erased up to the first row
1061      * (d) output the prompt, counting cols and rows, taking into account escape sequences
1062      * (e) output the buffer, counting cols and rows
1063      *   (e') when we hit the current pos, save the cursor position
1064      * (f) move the cursor to the saved cursor position
1065      * (g) save the current cursor row and number of rows
1066      */
1067
1068     /* (a) - The cursor is currently at row rpos */
1069     cursorDown(current, current->nrows - current->rpos - 1);
1070     DRL("<cud=%d>", current->nrows - current->rpos - 1);
1071
1072     /* (b), (c) - Erase lines upwards until we get to the first row */
1073     for (i = 0; i < current->nrows; i++) {
1074         if (i) {
1075             DRL("<cup>");
1076             cursorUp(current, 1);
1077         }
1078         DRL("<clearline>");
1079         cursorToLeft(current);
1080         eraseEol(current);
1081     }
1082     DRL("\n");
1083
1084     /* (d) First output the prompt. control sequences don't take up display space */
1085     pt = prompt;
1086     displaycol = 0; /* current display column */
1087     displayrow = 0; /* current display row */
1088     visible = 1;
1089
1090     refreshStartChars(current);
1091
1092     while (*pt) {
1093         int width;
1094         int ch;
1095         int n = utf8_tounicode(pt, &ch);
1096
1097         if (visible && ch == CHAR_ESCAPE) {
1098             /* The start of an escape sequence, so not visible */
1099             visible = 0;
1100             initParseEscapeSeq(&parser, 'm');
1101             DRL("<esc-seq-start>");
1102         }
1103
1104         if (ch == '\n' || ch == '\r') {
1105             /* treat both CR and NL the same and force wrap */
1106             refreshNewline(current);
1107             displaycol = 0;
1108             displayrow++;
1109         }
1110         else {
1111             width = visible * utf8_width(ch);
1112
1113             displaycol += width;
1114             if (displaycol >= current->cols) {
1115                 /* need to wrap to the next line because of newline or if it doesn't fit
1116                  * XXX this is a problem in single line mode
1117                  */
1118                 refreshNewline(current);
1119                 displaycol = width;
1120                 displayrow++;
1121             }
1122
1123             DRL_CHAR(ch);
1124 #ifdef USE_WINCONSOLE
1125             if (visible) {
1126                 outputChars(current, pt, n);
1127             }
1128 #else
1129             outputChars(current, pt, n);
1130 #endif
1131         }
1132         pt += n;
1133
1134         if (!visible) {
1135             switch (parseEscapeSequence(&parser, ch)) {
1136                 case EP_END:
1137                     visible = 1;
1138                     setOutputHighlight(current, parser.props, parser.numprops);
1139                     DRL("<esc-seq-end,numprops=%d>", parser.numprops);
1140                     break;
1141                 case EP_ERROR:
1142                     DRL("<esc-seq-err>");
1143                     visible = 1;
1144                     break;
1145             }
1146         }
1147     }
1148
1149     /* Now we are at the first line with all lines erased */
1150     DRL("\nafter prompt: displaycol=%d, displayrow=%d\n", displaycol, displayrow);
1151
1152
1153     /* (e) output the buffer, counting cols and rows */
1154     if (mlmode == 0) {
1155         /* In this mode we may need to trim chars from the start of the buffer until the
1156          * cursor fits in the window.
1157          */
1158         pt = reduceSingleBuf(buf, current->cols - displaycol, &cursor_pos);
1159     }
1160     else {
1161         pt = buf;
1162     }
1163
1164     currentpos = 0;
1165     notecursor = -1;
1166
1167     while (*pt) {
1168         int ch;
1169         int n = utf8_tounicode(pt, &ch);
1170         int width = char_display_width(ch);
1171
1172         if (currentpos == cursor_pos) {
1173             /* (e') wherever we output this character is where we want the cursor */
1174             notecursor = 1;
1175         }
1176
1177         if (displaycol + width >= current->cols) {
1178             if (mlmode == 0) {
1179                 /* In single line mode stop once we print as much as we can on one line */
1180                 DRL("<slmode>");
1181                 break;
1182             }
1183             /* need to wrap to the next line since it doesn't fit */
1184             refreshNewline(current);
1185             displaycol = 0;
1186             displayrow++;
1187         }
1188
1189         if (notecursor == 1) {
1190             /* (e') Save this position as the current cursor position */
1191             cursorcol = displaycol;
1192             cursorrow = displayrow;
1193             notecursor = 0;
1194             DRL("<cursor>");
1195         }
1196
1197         displaycol += width;
1198
1199         if (ch < ' ') {
1200             outputControlChar(current, ch + '@');
1201         }
1202         else {
1203             outputChars(current, pt, n);
1204         }
1205         DRL_CHAR(ch);
1206         if (width != 1) {
1207             DRL("<w=%d>", width);
1208         }
1209
1210         pt += n;
1211         currentpos++;
1212     }
1213
1214     /* If we didn't see the cursor, it is at the current location */
1215     if (notecursor) {
1216         DRL("<cursor>");
1217         cursorcol = displaycol;
1218         cursorrow = displayrow;
1219     }
1220
1221     DRL("\nafter buf: displaycol=%d, displayrow=%d, cursorcol=%d, cursorrow=%d\n", displaycol, displayrow, cursorcol, cursorrow);
1222
1223     /* (f) show hints */
1224     hint = refreshShowHints(current, buf, current->cols - displaycol, 1);
1225
1226     /* Remember how many many cols are available for insert optimisation */
1227     if (prompt == current->prompt && hint == 0) {
1228         current->colsright = current->cols - displaycol;
1229         current->colsleft = displaycol;
1230     }
1231     else {
1232         /* Can't optimise */
1233         current->colsright = 0;
1234         current->colsleft = 0;
1235     }
1236     DRL("\nafter hints: colsleft=%d, colsright=%d\n\n", current->colsleft, current->colsright);
1237
1238     refreshEndChars(current);
1239
1240     /* (g) move the cursor to the correct place */
1241     cursorUp(current, displayrow - cursorrow);
1242     setCursorPos(current, cursorcol);
1243
1244     /* (h) Update the number of rows if larger, but never reduce this */
1245     if (displayrow >= current->nrows) {
1246         current->nrows = displayrow + 1;
1247     }
1248     /* And remember the row that the cursor is on */
1249     current->rpos = cursorrow;
1250
1251     refreshEnd(current);
1252
1253 #ifdef DEBUG_REFRESHLINE
1254     fclose(dfh);
1255 #endif
1256 }
1257
1258 static void refreshLine(struct current *current)
1259 {
1260     refreshLineAlt(current, current->prompt, sb_str(current->buf), current->pos);
1261 }
1262
1263 static void set_current(struct current *current, const char *str)
1264 {
1265     sb_clear(current->buf);
1266     sb_append(current->buf, str);
1267     current->pos = sb_chars(current->buf);
1268 }
1269
1270 /**
1271  * Removes the char at 'pos'.
1272  *
1273  * Returns 1 if the line needs to be refreshed, 2 if not
1274  * and 0 if nothing was removed
1275  */
1276 static int remove_char(struct current *current, int pos)
1277 {
1278     if (pos >= 0 && pos < sb_chars(current->buf)) {
1279         int offset = utf8_index(sb_str(current->buf), pos);
1280         int nbytes = utf8_index(sb_str(current->buf) + offset, 1);
1281         int rc = 1;
1282
1283         /* Now we try to optimise in the simple but very common case that:
1284          * - outputChars() can be used directly (not win32)
1285          * - we are removing the char at EOL
1286          * - the buffer is not empty
1287          * - there are columns available to the left
1288          * - the char being deleted is not a wide or utf-8 character
1289          * - no hints are being shown
1290          */
1291         if (current->output && current->pos == pos + 1 && current->pos == sb_chars(current->buf) && pos > 0) {
1292 #ifdef USE_UTF8
1293             /* Could implement utf8_prev_len() but simplest just to not optimise this case */
1294             char last = sb_str(current->buf)[offset];
1295 #else
1296             char last = 0;
1297 #endif
1298             if (current->colsleft > 0 && (last & 0x80) == 0) {
1299                 /* Have cols on the left and not a UTF-8 char or continuation */
1300                 /* Yes, can optimise */
1301                 current->colsleft--;
1302                 current->colsright++;
1303                 rc = 2;
1304             }
1305         }
1306
1307         sb_delete(current->buf, offset, nbytes);
1308
1309         if (current->pos > pos) {
1310             current->pos--;
1311         }
1312         if (rc == 2) {
1313             if (refreshShowHints(current, sb_str(current->buf), current->colsright, 0)) {
1314                 /* A hint needs to be shown, so can't optimise after all */
1315                 rc = 1;
1316             }
1317             else {
1318                 /* optimised output */
1319                 outputChars(current, "\b \b", 3);
1320             }
1321         }
1322         return rc;
1323         return 1;
1324     }
1325     return 0;
1326 }
1327
1328 /**
1329  * Insert 'ch' at position 'pos'
1330  *
1331  * Returns 1 if the line needs to be refreshed, 2 if not
1332  * and 0 if nothing was inserted (no room)
1333  */
1334 static int insert_char(struct current *current, int pos, int ch)
1335 {
1336     if (pos >= 0 && pos <= sb_chars(current->buf)) {
1337         char buf[MAX_UTF8_LEN + 1];
1338         int offset = utf8_index(sb_str(current->buf), pos);
1339         int n = utf8_getchars(buf, ch);
1340         int rc = 1;
1341
1342         /* null terminate since sb_insert() requires it */
1343         buf[n] = 0;
1344
1345         /* Now we try to optimise in the simple but very common case that:
1346          * - outputChars() can be used directly (not win32)
1347          * - we are inserting at EOL
1348          * - there are enough columns available
1349          * - no hints are being shown
1350          */
1351         if (current->output && pos == current->pos && pos == sb_chars(current->buf)) {
1352             int width = char_display_width(ch);
1353             if (current->colsright > width) {
1354                 /* Yes, can optimise */
1355                 current->colsright -= width;
1356                 current->colsleft -= width;
1357                 rc = 2;
1358             }
1359         }
1360         sb_insert(current->buf, offset, buf);
1361         if (current->pos >= pos) {
1362             current->pos++;
1363         }
1364         if (rc == 2) {
1365             if (refreshShowHints(current, sb_str(current->buf), current->colsright, 0)) {
1366                 /* A hint needs to be shown, so can't optimise after all */
1367                 rc = 1;
1368             }
1369             else {
1370                 /* optimised output */
1371                 outputChars(current, buf, n);
1372             }
1373         }
1374         return rc;
1375     }
1376     return 0;
1377 }
1378
1379 /**
1380  * Captures up to 'n' characters starting at 'pos' for the cut buffer.
1381  *
1382  * This replaces any existing characters in the cut buffer.
1383  */
1384 static void capture_chars(struct current *current, int pos, int nchars)
1385 {
1386     if (pos >= 0 && (pos + nchars - 1) < sb_chars(current->buf)) {
1387         int offset = utf8_index(sb_str(current->buf), pos);
1388         int nbytes = utf8_index(sb_str(current->buf) + offset, nchars);
1389
1390         if (nbytes > 0) {
1391             if (current->capture) {
1392                 sb_clear(current->capture);
1393             }
1394             else {
1395                 current->capture = sb_alloc();
1396             }
1397             sb_append_len(current->capture, sb_str(current->buf) + offset, nbytes);
1398         }
1399     }
1400 }
1401
1402 /**
1403  * Removes up to 'n' characters at cursor position 'pos'.
1404  *
1405  * Returns 0 if no chars were removed or non-zero otherwise.
1406  */
1407 static int remove_chars(struct current *current, int pos, int n)
1408 {
1409     int removed = 0;
1410
1411     /* First save any chars which will be removed */
1412     capture_chars(current, pos, n);
1413
1414     while (n-- && remove_char(current, pos)) {
1415         removed++;
1416     }
1417     return removed;
1418 }
1419 /**
1420  * Inserts the characters (string) 'chars' at the cursor position 'pos'.
1421  *
1422  * Returns 0 if no chars were inserted or non-zero otherwise.
1423  */
1424 static int insert_chars(struct current *current, int pos, const char *chars)
1425 {
1426     int inserted = 0;
1427
1428     while (*chars) {
1429         int ch;
1430         int n = utf8_tounicode(chars, &ch);
1431         if (insert_char(current, pos, ch) == 0) {
1432             break;
1433         }
1434         inserted++;
1435         pos++;
1436         chars += n;
1437     }
1438     return inserted;
1439 }
1440
1441 /**
1442  * Returns the keycode to process, or 0 if none.
1443  */
1444 static int reverseIncrementalSearch(struct current *current)
1445 {
1446     /* Display the reverse-i-search prompt and process chars */
1447     char rbuf[50];
1448     char rprompt[80];
1449     int rchars = 0;
1450     int rlen = 0;
1451     int searchpos = history_len - 1;
1452     int c;
1453
1454     rbuf[0] = 0;
1455     while (1) {
1456         int n = 0;
1457         const char *p = NULL;
1458         int skipsame = 0;
1459         int searchdir = -1;
1460
1461         snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1462         refreshLineAlt(current, rprompt, sb_str(current->buf), current->pos);
1463         c = fd_read(current);
1464         if (c == ctrl('H') || c == CHAR_DELETE) {
1465             if (rchars) {
1466                 int p = utf8_index(rbuf, --rchars);
1467                 rbuf[p] = 0;
1468                 rlen = strlen(rbuf);
1469             }
1470             continue;
1471         }
1472 #ifdef USE_TERMIOS
1473         if (c == CHAR_ESCAPE) {
1474             c = check_special(current->fd);
1475         }
1476 #endif
1477         if (c == ctrl('P') || c == SPECIAL_UP) {
1478             /* Search for the previous (earlier) match */
1479             if (searchpos > 0) {
1480                 searchpos--;
1481             }
1482             skipsame = 1;
1483         }
1484         else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1485             /* Search for the next (later) match */
1486             if (searchpos < history_len) {
1487                 searchpos++;
1488             }
1489             searchdir = 1;
1490             skipsame = 1;
1491         }
1492         else if (c >= ' ') {
1493             /* >= here to allow for null terminator */
1494             if (rlen >= (int)sizeof(rbuf) - MAX_UTF8_LEN) {
1495                 continue;
1496             }
1497
1498             n = utf8_getchars(rbuf + rlen, c);
1499             rlen += n;
1500             rchars++;
1501             rbuf[rlen] = 0;
1502
1503             /* Adding a new char resets the search location */
1504             searchpos = history_len - 1;
1505         }
1506         else {
1507             /* Exit from incremental search mode */
1508             break;
1509         }
1510
1511         /* Now search through the history for a match */
1512         for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1513             p = strstr(history[searchpos], rbuf);
1514             if (p) {
1515                 /* Found a match */
1516                 if (skipsame && strcmp(history[searchpos], sb_str(current->buf)) == 0) {
1517                     /* But it is identical, so skip it */
1518                     continue;
1519                 }
1520                 /* Copy the matching line and set the cursor position */
1521                 set_current(current,history[searchpos]);
1522                 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1523                 break;
1524             }
1525         }
1526         if (!p && n) {
1527             /* No match, so don't add it */
1528             rchars--;
1529             rlen -= n;
1530             rbuf[rlen] = 0;
1531         }
1532     }
1533     if (c == ctrl('G') || c == ctrl('C')) {
1534         /* ctrl-g terminates the search with no effect */
1535         set_current(current, "");
1536         c = 0;
1537     }
1538     else if (c == ctrl('J')) {
1539         /* ctrl-j terminates the search leaving the buffer in place */
1540         c = 0;
1541     }
1542
1543     /* Go process the char normally */
1544     refreshLine(current);
1545     return c;
1546 }
1547
1548 static int linenoiseEdit(struct current *current) {
1549     int history_index = 0;
1550
1551     /* The latest history entry is always our current buffer, that
1552      * initially is just an empty string. */
1553     linenoiseHistoryAdd("");
1554
1555     set_current(current, "");
1556     refreshLine(current);
1557
1558     while(1) {
1559         int dir = -1;
1560         int c = fd_read(current);
1561
1562 #ifndef NO_COMPLETION
1563         /* Only autocomplete when the callback is set. It returns < 0 when
1564          * there was an error reading from fd. Otherwise it will return the
1565          * character that should be handled next. */
1566         if (c == '\t' && current->pos == sb_chars(current->buf) && completionCallback != NULL) {
1567             c = completeLine(current);
1568         }
1569 #endif
1570         if (c == ctrl('R')) {
1571             /* reverse incremental search will provide an alternative keycode or 0 for none */
1572             c = reverseIncrementalSearch(current);
1573             /* go on to process the returned char normally */
1574         }
1575
1576 #ifdef USE_TERMIOS
1577         if (c == CHAR_ESCAPE) {   /* escape sequence */
1578             c = check_special(current->fd);
1579         }
1580 #endif
1581         if (c == -1) {
1582             /* Return on errors */
1583             return sb_len(current->buf);
1584         }
1585
1586         switch(c) {
1587         case SPECIAL_NONE:
1588             break;
1589         case '\r':    /* enter/CR */
1590         case '\n':    /* LF */
1591             history_len--;
1592             free(history[history_len]);
1593             current->pos = sb_chars(current->buf);
1594             if (mlmode || hintsCallback) {
1595                 showhints = 0;
1596                 refreshLine(current);
1597                 showhints = 1;
1598             }
1599             return sb_len(current->buf);
1600         case ctrl('C'):     /* ctrl-c */
1601             errno = EAGAIN;
1602             return -1;
1603         case ctrl('Z'):     /* ctrl-z */
1604 #ifdef SIGTSTP
1605             /* send ourselves SIGSUSP */
1606             disableRawMode(current);
1607             raise(SIGTSTP);
1608             /* and resume */
1609             enableRawMode(current);
1610             refreshLine(current);
1611 #endif
1612             continue;
1613         case CHAR_DELETE:   /* backspace */
1614         case ctrl('H'):
1615             if (remove_char(current, current->pos - 1) == 1) {
1616                 refreshLine(current);
1617             }
1618             break;
1619         case ctrl('D'):     /* ctrl-d */
1620             if (sb_len(current->buf) == 0) {
1621                 /* Empty line, so EOF */
1622                 history_len--;
1623                 free(history[history_len]);
1624                 return -1;
1625             }
1626             /* Otherwise fall through to delete char to right of cursor */
1627         case SPECIAL_DELETE:
1628             if (remove_char(current, current->pos) == 1) {
1629                 refreshLine(current);
1630             }
1631             break;
1632         case SPECIAL_INSERT:
1633             /* Ignore. Expansion Hook.
1634              * Future possibility: Toggle Insert/Overwrite Modes
1635              */
1636             break;
1637         case ctrl('W'):    /* ctrl-w, delete word at left. save deleted chars */
1638             /* eat any spaces on the left */
1639             {
1640                 int pos = current->pos;
1641                 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1642                     pos--;
1643                 }
1644
1645                 /* now eat any non-spaces on the left */
1646                 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1647                     pos--;
1648                 }
1649
1650                 if (remove_chars(current, pos, current->pos - pos)) {
1651                     refreshLine(current);
1652                 }
1653             }
1654             break;
1655         case ctrl('T'):    /* ctrl-t */
1656             if (current->pos > 0 && current->pos <= sb_chars(current->buf)) {
1657                 /* If cursor is at end, transpose the previous two chars */
1658                 int fixer = (current->pos == sb_chars(current->buf));
1659                 c = get_char(current, current->pos - fixer);
1660                 remove_char(current, current->pos - fixer);
1661                 insert_char(current, current->pos - 1, c);
1662                 refreshLine(current);
1663             }
1664             break;
1665         case ctrl('V'):    /* ctrl-v */
1666             /* Insert the ^V first */
1667             if (insert_char(current, current->pos, c)) {
1668                 refreshLine(current);
1669                 /* Now wait for the next char. Can insert anything except \0 */
1670                 c = fd_read(current);
1671
1672                 /* Remove the ^V first */
1673                 remove_char(current, current->pos - 1);
1674                 if (c > 0) {
1675                     /* Insert the actual char, can't be error or null */
1676                     insert_char(current, current->pos, c);
1677                 }
1678                 refreshLine(current);
1679             }
1680             break;
1681         case ctrl('B'):
1682         case SPECIAL_LEFT:
1683             if (current->pos > 0) {
1684                 current->pos--;
1685                 refreshLine(current);
1686             }
1687             break;
1688         case ctrl('F'):
1689         case SPECIAL_RIGHT:
1690             if (current->pos < sb_chars(current->buf)) {
1691                 current->pos++;
1692                 refreshLine(current);
1693             }
1694             break;
1695         case SPECIAL_PAGE_UP:
1696           dir = history_len - history_index - 1; /* move to start of history */
1697           goto history_navigation;
1698         case SPECIAL_PAGE_DOWN:
1699           dir = -history_index; /* move to 0 == end of history, i.e. current */
1700           goto history_navigation;
1701         case ctrl('P'):
1702         case SPECIAL_UP:
1703             dir = 1;
1704           goto history_navigation;
1705         case ctrl('N'):
1706         case SPECIAL_DOWN:
1707 history_navigation:
1708             if (history_len > 1) {
1709                 /* Update the current history entry before to
1710                  * overwrite it with tne next one. */
1711                 free(history[history_len - 1 - history_index]);
1712                 history[history_len - 1 - history_index] = strdup(sb_str(current->buf));
1713                 /* Show the new entry */
1714                 history_index += dir;
1715                 if (history_index < 0) {
1716                     history_index = 0;
1717                     break;
1718                 } else if (history_index >= history_len) {
1719                     history_index = history_len - 1;
1720                     break;
1721                 }
1722                 set_current(current, history[history_len - 1 - history_index]);
1723                 refreshLine(current);
1724             }
1725             break;
1726         case ctrl('A'): /* Ctrl+a, go to the start of the line */
1727         case SPECIAL_HOME:
1728             current->pos = 0;
1729             refreshLine(current);
1730             break;
1731         case ctrl('E'): /* ctrl+e, go to the end of the line */
1732         case SPECIAL_END:
1733             current->pos = sb_chars(current->buf);
1734             refreshLine(current);
1735             break;
1736         case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */
1737             if (remove_chars(current, 0, current->pos)) {
1738                 refreshLine(current);
1739             }
1740             break;
1741         case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */
1742             if (remove_chars(current, current->pos, sb_chars(current->buf) - current->pos)) {
1743                 refreshLine(current);
1744             }
1745             break;
1746         case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */
1747             if (current->capture && insert_chars(current, current->pos, sb_str(current->capture))) {
1748                 refreshLine(current);
1749             }
1750             break;
1751         case ctrl('L'): /* Ctrl+L, clear screen */
1752             linenoiseClearScreen();
1753             /* Force recalc of window size for serial terminals */
1754             current->cols = 0;
1755             current->rpos = 0;
1756             refreshLine(current);
1757             break;
1758         default:
1759             /* Only tab is allowed without ^V */
1760             if (c == '\t' || c >= ' ') {
1761                 if (insert_char(current, current->pos, c) == 1) {
1762                     refreshLine(current);
1763                 }
1764             }
1765             break;
1766         }
1767     }
1768     return sb_len(current->buf);
1769 }
1770
1771 int linenoiseColumns(void)
1772 {
1773     struct current current;
1774     current.output = NULL;
1775     enableRawMode (&current);
1776     getWindowSize (&current);
1777     disableRawMode (&current);
1778     return current.cols;
1779 }
1780
1781 /**
1782  * Reads a line from the file handle (without the trailing NL or CRNL)
1783  * and returns it in a stringbuf.
1784  * Returns NULL if no characters are read before EOF or error.
1785  *
1786  * Note that the character count will *not* be correct for lines containing
1787  * utf8 sequences. Do not rely on the character count.
1788  */
1789 static stringbuf *sb_getline(FILE *fh)
1790 {
1791     stringbuf *sb = sb_alloc();
1792     int c;
1793     int n = 0;
1794
1795     while ((c = getc(fh)) != EOF) {
1796         char ch;
1797         n++;
1798         if (c == '\r') {
1799             /* CRLF -> LF */
1800             continue;
1801         }
1802         if (c == '\n' || c == '\r') {
1803             break;
1804         }
1805         ch = c;
1806         /* ignore the effect of character count for partial utf8 sequences */
1807         sb_append_len(sb, &ch, 1);
1808     }
1809     if (n == 0) {
1810         sb_free(sb);
1811         return NULL;
1812     }
1813     return sb;
1814 }
1815
1816 char *linenoise(const char *prompt)
1817 {
1818     int count;
1819     struct current current;
1820     stringbuf *sb;
1821
1822     memset(&current, 0, sizeof(current));
1823
1824     if (enableRawMode(&current) == -1) {
1825         printf("%s", prompt);
1826         fflush(stdout);
1827         sb = sb_getline(stdin);
1828     }
1829     else {
1830         current.buf = sb_alloc();
1831         current.pos = 0;
1832         current.nrows = 1;
1833         current.prompt = prompt;
1834
1835         count = linenoiseEdit(&current);
1836
1837         disableRawMode(&current);
1838         printf("\n");
1839
1840         sb_free(current.capture);
1841         if (count == -1) {
1842             sb_free(current.buf);
1843             return NULL;
1844         }
1845         sb = current.buf;
1846     }
1847     return sb ? sb_to_string(sb) : NULL;
1848 }
1849
1850 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1851 int linenoiseHistoryAddAllocated(char *line) {
1852
1853     if (history_max_len == 0) {
1854 notinserted:
1855         free(line);
1856         return 0;
1857     }
1858     if (history == NULL) {
1859         history = (char **)calloc(sizeof(char*), history_max_len);
1860     }
1861
1862     /* do not insert duplicate lines into history */
1863     if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1864         goto notinserted;
1865     }
1866
1867     if (history_len == history_max_len) {
1868         free(history[0]);
1869         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1870         history_len--;
1871     }
1872     history[history_len] = line;
1873     history_len++;
1874     return 1;
1875 }
1876
1877 int linenoiseHistoryAdd(const char *line) {
1878     return linenoiseHistoryAddAllocated(strdup(line));
1879 }
1880
1881 int linenoiseHistoryGetMaxLen(void) {
1882     return history_max_len;
1883 }
1884
1885 int linenoiseHistorySetMaxLen(int len) {
1886     char **newHistory;
1887
1888     if (len < 1) return 0;
1889     if (history) {
1890         int tocopy = history_len;
1891
1892         newHistory = (char **)calloc(sizeof(char*), len);
1893
1894         /* If we can't copy everything, free the elements we'll not use. */
1895         if (len < tocopy) {
1896             int j;
1897
1898             for (j = 0; j < tocopy-len; j++) free(history[j]);
1899             tocopy = len;
1900         }
1901         memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy);
1902         free(history);
1903         history = newHistory;
1904     }
1905     history_max_len = len;
1906     if (history_len > history_max_len)
1907         history_len = history_max_len;
1908     return 1;
1909 }
1910
1911 /* Save the history in the specified file. On success 0 is returned
1912  * otherwise -1 is returned. */
1913 int linenoiseHistorySave(const char *filename) {
1914     FILE *fp = fopen(filename,"w");
1915     int j;
1916
1917     if (fp == NULL) return -1;
1918     for (j = 0; j < history_len; j++) {
1919         const char *str = history[j];
1920         /* Need to encode backslash, nl and cr */
1921         while (*str) {
1922             if (*str == '\\') {
1923                 fputs("\\\\", fp);
1924             }
1925             else if (*str == '\n') {
1926                 fputs("\\n", fp);
1927             }
1928             else if (*str == '\r') {
1929                 fputs("\\r", fp);
1930             }
1931             else {
1932                 fputc(*str, fp);
1933             }
1934             str++;
1935         }
1936         fputc('\n', fp);
1937     }
1938
1939     fclose(fp);
1940     return 0;
1941 }
1942
1943 /* Load the history from the specified file.
1944  *
1945  * If the file does not exist or can't be opened, no operation is performed
1946  * and -1 is returned.
1947  * Otherwise 0 is returned.
1948  */
1949 int linenoiseHistoryLoad(const char *filename) {
1950     FILE *fp = fopen(filename,"r");
1951     stringbuf *sb;
1952
1953     if (fp == NULL) return -1;
1954
1955     while ((sb = sb_getline(fp)) != NULL) {
1956         /* Take the stringbuf and decode backslash escaped values */
1957         char *buf = sb_to_string(sb);
1958         char *dest = buf;
1959         const char *src;
1960
1961         for (src = buf; *src; src++) {
1962             char ch = *src;
1963
1964             if (ch == '\\') {
1965                 src++;
1966                 if (*src == 'n') {
1967                     ch = '\n';
1968                 }
1969                 else if (*src == 'r') {
1970                     ch = '\r';
1971                 } else {
1972                     ch = *src;
1973                 }
1974             }
1975             *dest++ = ch;
1976         }
1977         *dest = 0;
1978
1979         linenoiseHistoryAddAllocated(buf);
1980     }
1981     fclose(fp);
1982     return 0;
1983 }
1984
1985 /* Provide access to the history buffer.
1986  *
1987  * If 'len' is not NULL, the length is stored in *len.
1988  */
1989 char **linenoiseHistory(int *len) {
1990     if (len) {
1991         *len = history_len;
1992     }
1993     return history;
1994 }