]> git.lizzy.rs Git - linenoise.git/blob - linenoise.c
Add support for utf16 surrogate pairs on Windows
[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 #include "stringbuf.h"
146 #include "utf8.h"
147
148 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
149
150 #define ctrl(C) ((C) - '@')
151
152 /* Use -ve numbers here to co-exist with normal unicode chars */
153 enum {
154     SPECIAL_NONE,
155     /* don't use -1 here since that indicates error */
156     SPECIAL_UP = -20,
157     SPECIAL_DOWN = -21,
158     SPECIAL_LEFT = -22,
159     SPECIAL_RIGHT = -23,
160     SPECIAL_DELETE = -24,
161     SPECIAL_HOME = -25,
162     SPECIAL_END = -26,
163     SPECIAL_INSERT = -27,
164     SPECIAL_PAGE_UP = -28,
165     SPECIAL_PAGE_DOWN = -29,
166
167     /* Some handy names for other special keycodes */
168     CHAR_ESCAPE = 27,
169     CHAR_DELETE = 127,
170 };
171
172 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
173 static int history_len = 0;
174 static char **history = NULL;
175
176 /* Structure to contain the status of the current (being edited) line */
177 struct current {
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 */
183     const char *prompt;
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 */
194 #ifdef USE_UTF8
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? */
199 #endif
200 #endif
201 };
202
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);
213
214 void linenoiseHistoryFree(void) {
215     if (history) {
216         int j;
217
218         for (j = 0; j < history_len; j++)
219             free(history[j]);
220         free(history);
221         history = NULL;
222         history_len = 0;
223     }
224 }
225
226 struct esc_parser {
227     enum {
228         EP_START,   /* looking for ESC */
229         EP_ESC,     /* looking for [ */
230         EP_DIGITS,  /* parsing digits */
231         EP_PROPS,   /* parsing digits or semicolons */
232         EP_END,     /* ok */
233         EP_ERROR,   /* error */
234     } state;
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 */
240 };
241
242 /**
243  * Initialise the escape sequence parser at *parser.
244  *
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.
248  */
249 static void initParseEscapeSeq(struct esc_parser *parser, int termchar)
250 {
251     parser->state = EP_START;
252     parser->maxprops = sizeof(parser->props) / sizeof(*parser->props);
253     parser->numprops = 0;
254     parser->current = 0;
255     parser->termchar = termchar;
256 }
257
258 /**
259  * Pass character 'ch' into the state machine to parse:
260  *   'ESC' '[' <digits> (';' <digits>)* <termchar>
261  *
262  * The first character must be ESC.
263  * Returns the current state. The state machine is done when it returns either EP_END
264  * or EP_ERROR.
265  *
266  * On EP_END, the "property/attribute" values can be read from parser->props[]
267  * of length parser->numprops.
268  */
269 static int parseEscapeSequence(struct esc_parser *parser, int ch)
270 {
271     switch (parser->state) {
272         case EP_START:
273             parser->state = (ch == '\x1b') ? EP_ESC : EP_ERROR;
274             break;
275         case EP_ESC:
276             parser->state = (ch == '[') ? EP_DIGITS : EP_ERROR;
277             break;
278         case EP_PROPS:
279             if (ch == ';') {
280                 parser->state = EP_DIGITS;
281 donedigits:
282                 if (parser->numprops + 1 < parser->maxprops) {
283                     parser->props[parser->numprops++] = parser->current;
284                     parser->current = 0;
285                 }
286                 break;
287             }
288             /* fall through */
289         case EP_DIGITS:
290             if (ch >= '0' && ch <= '9') {
291                 parser->current = parser->current * 10 + (ch - '0');
292                 parser->state = EP_PROPS;
293                 break;
294             }
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;
299                     break;
300                 }
301             }
302             parser->state = EP_END;
303             goto donedigits;
304         case EP_END:
305             parser->state = EP_ERROR;
306             break;
307         case EP_ERROR:
308             break;
309     }
310     return parser->state;
311 }
312
313 /*#define DEBUG_REFRESHLINE*/
314
315 #ifdef DEBUG_REFRESHLINE
316 #define DRL(ARGS...) fprintf(dfh, ARGS)
317 static FILE *dfh;
318
319 static void DRL_CHAR(int ch)
320 {
321     if (ch < ' ') {
322         DRL("^%c", ch + '@');
323     }
324     else if (ch > 127) {
325         DRL("\\u%04x", ch);
326     }
327     else {
328         DRL("%c", ch);
329     }
330 }
331 static void DRL_STR(const char *str)
332 {
333     while (*str) {
334         int ch;
335         int n = utf8_tounicode(str, &ch);
336         str += n;
337         DRL_CHAR(ch);
338     }
339 }
340 #else
341 #define DRL(ARGS...)
342 #define DRL_CHAR(ch)
343 #define DRL_STR(str)
344 #endif
345
346 #if defined(USE_WINCONSOLE)
347 #include "linenoise-win32.c"
348 #endif
349
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 */
355
356 static const char *unsupported_term[] = {"dumb","cons25","emacs",NULL};
357
358 static int isUnsupportedTerm(void) {
359     char *term = getenv("TERM");
360
361     if (term) {
362         int j;
363         for (j = 0; unsupported_term[j]; j++) {
364             if (strcmp(term, unsupported_term[j]) == 0) {
365                 return 1;
366             }
367         }
368     }
369     return 0;
370 }
371
372 static int enableRawMode(struct current *current) {
373     struct termios raw;
374
375     current->fd = STDIN_FILENO;
376     current->cols = 0;
377
378     if (!isatty(current->fd) || isUnsupportedTerm() ||
379         tcgetattr(current->fd, &orig_termios) == -1) {
380 fatal:
381         errno = ENOTTY;
382         return -1;
383     }
384
385     if (!atexit_registered) {
386         atexit(linenoiseAtExit);
387         atexit_registered = 1;
388     }
389
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 */
404
405     /* put terminal in raw mode after flushing */
406     if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
407         goto fatal;
408     }
409     rawmode = 1;
410     return 0;
411 }
412
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)
416         rawmode = 0;
417 }
418
419 /* At exit we'll try to fix the terminal to the initial conditions. */
420 static void linenoiseAtExit(void) {
421     if (rawmode) {
422         tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
423     }
424     linenoiseHistoryFree();
425 }
426
427 /* gcc/glibc insists that we care about the return code of write!
428  * Clarification: This means that a void-cast like "(void) (EXPR)"
429  * does not work.
430  */
431 #define IGNORE_RC(EXPR) if (EXPR) {}
432
433 /**
434  * Output bytes directly, or accumulate output (if current->output is set)
435  */
436 static void outputChars(struct current *current, const char *buf, int len)
437 {
438     if (len < 0) {
439         len = strlen(buf);
440     }
441     if (current->output) {
442         sb_append_len(current->output, buf, len);
443     }
444     else {
445         IGNORE_RC(write(current->fd, buf, len));
446     }
447 }
448
449 /* Like outputChars, but using printf-style formatting
450  */
451 static void outputFormatted(struct current *current, const char *format, ...)
452 {
453     va_list args;
454     char buf[64];
455     int n;
456
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));
461     va_end(args);
462     outputChars(current, buf, n);
463 }
464
465 static void cursorToLeft(struct current *current)
466 {
467     outputChars(current, "\r", -1);
468 }
469
470 static void setOutputHighlight(struct current *current, const int *props, int nprops)
471 {
472     outputChars(current, "\x1b[", -1);
473     while (nprops--) {
474         outputFormatted(current, "%d%c", *props, (nprops == 0) ? 'm' : ';');
475         props++;
476     }
477 }
478
479 static void eraseEol(struct current *current)
480 {
481     outputChars(current, "\x1b[0K", -1);
482 }
483
484 static void setCursorPos(struct current *current, int x)
485 {
486     if (x == 0) {
487         cursorToLeft(current);
488     }
489     else {
490         outputFormatted(current, "\r\x1b[%dC", x);
491     }
492 }
493
494 static void cursorUp(struct current *current, int n)
495 {
496     if (n) {
497         outputFormatted(current, "\x1b[%dA", n);
498     }
499 }
500
501 static void cursorDown(struct current *current, int n)
502 {
503     if (n) {
504         outputFormatted(current, "\x1b[%dB", n);
505     }
506 }
507
508 void linenoiseClearScreen(void)
509 {
510     write(STDOUT_FILENO, "\x1b[H\x1b[2J", 7);
511 }
512
513 /**
514  * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
515  *
516  * A timeout of -1 means to wait forever.
517  *
518  * Returns -1 if no char is received within the time or an error occurs.
519  */
520 static int fd_read_char(int fd, int timeout)
521 {
522     struct pollfd p;
523     unsigned char c;
524
525     p.fd = fd;
526     p.events = POLLIN;
527
528     if (poll(&p, 1, timeout) == 0) {
529         /* timeout */
530         return -1;
531     }
532     if (read(fd, &c, 1) != 1) {
533         return -1;
534     }
535     return c;
536 }
537
538 /**
539  * Reads a complete utf-8 character
540  * and returns the unicode value, or -1 on error.
541  */
542 static int fd_read(struct current *current)
543 {
544 #ifdef USE_UTF8
545     char buf[MAX_UTF8_LEN];
546     int n;
547     int i;
548     int c;
549
550     if (read(current->fd, &buf[0], 1) != 1) {
551         return -1;
552     }
553     n = utf8_charlen(buf[0]);
554     if (n < 1) {
555         return -1;
556     }
557     for (i = 1; i < n; i++) {
558         if (read(current->fd, &buf[i], 1) != 1) {
559             return -1;
560         }
561     }
562     /* decode and return the character */
563     utf8_tounicode(buf, &c);
564     return c;
565 #else
566     return fd_read_char(current->fd, -1);
567 #endif
568 }
569
570
571 /**
572  * Stores the current cursor column in '*cols'.
573  * Returns 1 if OK, or 0 if failed to determine cursor pos.
574  */
575 static int queryCursor(struct current *current, int* cols)
576 {
577     struct esc_parser parser;
578     int ch;
579
580     /* Should not be buffering this output, it needs to go immediately */
581     assert(current->output == NULL);
582
583     /* control sequence - report cursor location */
584     outputChars(current, "\x1b[6n", -1);
585
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)) {
590             default:
591                 continue;
592             case EP_END:
593                 if (parser.numprops == 2 && parser.props[1] < 1000) {
594                     *cols = parser.props[1];
595                     return 1;
596                 }
597                 break;
598             case EP_ERROR:
599                 break;
600         }
601         /* failed */
602         break;
603     }
604     return 0;
605 }
606
607 /**
608  * Updates current->cols with the current window size (width)
609  */
610 static int getWindowSize(struct current *current)
611 {
612     struct winsize ws;
613
614     if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
615         current->cols = ws.ws_col;
616         return 0;
617     }
618
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.
624      *
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.
632      */
633
634     if (current->cols == 0) {
635         int here;
636
637         /* If anything fails => default 80 */
638         current->cols = 80;
639
640         /* (a) */
641         if (queryCursor (current, &here)) {
642             /* (b) */
643             setCursorPos(current, 999);
644
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..
648              */
649             if (queryCursor (current, &current->cols)) {
650                 /* (d) Reset the cursor back to the original location. */
651                 if (current->cols > here) {
652                     setCursorPos(current, here);
653                 }
654             }
655         }
656     }
657
658     return 0;
659 }
660
661 /**
662  * If CHAR_ESCAPE was received, reads subsequent
663  * chars to determine if this is a known special key.
664  *
665  * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
666  *
667  * If no additional char is received within a short time,
668  * CHAR_ESCAPE is returned.
669  */
670 static int check_special(int fd)
671 {
672     int c = fd_read_char(fd, 50);
673     int c2;
674
675     if (c < 0) {
676         return CHAR_ESCAPE;
677     }
678
679     c2 = fd_read_char(fd, 50);
680     if (c2 < 0) {
681         return c2;
682     }
683     if (c == '[' || c == 'O') {
684         /* Potential arrow key */
685         switch (c2) {
686             case 'A':
687                 return SPECIAL_UP;
688             case 'B':
689                 return SPECIAL_DOWN;
690             case 'C':
691                 return SPECIAL_RIGHT;
692             case 'D':
693                 return SPECIAL_LEFT;
694             case 'F':
695                 return SPECIAL_END;
696             case 'H':
697                 return SPECIAL_HOME;
698         }
699     }
700     if (c == '[' && c2 >= '1' && c2 <= '8') {
701         /* extended escape */
702         c = fd_read_char(fd, 50);
703         if (c == '~') {
704             switch (c2) {
705                 case '2':
706                     return SPECIAL_INSERT;
707                 case '3':
708                     return SPECIAL_DELETE;
709                 case '5':
710                     return SPECIAL_PAGE_UP;
711                 case '6':
712                     return SPECIAL_PAGE_DOWN;
713                 case '7':
714                     return SPECIAL_HOME;
715                 case '8':
716                     return SPECIAL_END;
717             }
718         }
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);
722         }
723     }
724
725     return SPECIAL_NONE;
726 }
727 #endif
728
729 static void clearOutputHighlight(struct current *current)
730 {
731     int nohighlight = 0;
732     setOutputHighlight(current, &nohighlight, 1);
733 }
734
735 static void outputControlChar(struct current *current, char ch)
736 {
737     int reverse = 7;
738     setOutputHighlight(current, &reverse, 1);
739     outputChars(current, "^", 1);
740     outputChars(current, &ch, 1);
741     clearOutputHighlight(current);
742 }
743
744 #ifndef utf8_getchars
745 static int utf8_getchars(char *buf, int c)
746 {
747 #ifdef USE_UTF8
748     return utf8_fromunicode(buf, c);
749 #else
750     *buf = c;
751     return 1;
752 #endif
753 }
754 #endif
755
756 /**
757  * Returns the unicode character at the given offset,
758  * or -1 if none.
759  */
760 static int get_char(struct current *current, int pos)
761 {
762     if (pos >= 0 && pos < sb_chars(current->buf)) {
763         int c;
764         int i = utf8_index(sb_str(current->buf), pos);
765         (void)utf8_tounicode(sb_str(current->buf) + i, &c);
766         return c;
767     }
768     return -1;
769 }
770
771 static int char_display_width(int ch)
772 {
773     if (ch < ' ') {
774         /* control chars take two positions */
775         return 2;
776     }
777     else {
778         return utf8_width(ch);
779     }
780 }
781
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;
789
790 static void beep() {
791 #ifdef USE_TERMIOS
792     fprintf(stderr, "\x7");
793     fflush(stderr);
794 #endif
795 }
796
797 static void freeCompletions(linenoiseCompletions *lc) {
798     size_t i;
799     for (i = 0; i < lc->len; i++)
800         free(lc->cvec[i]);
801     free(lc->cvec);
802 }
803
804 static int completeLine(struct current *current) {
805     linenoiseCompletions lc = { 0, NULL };
806     int c = 0;
807
808     completionCallback(sb_str(current->buf),&lc,completionUserdata);
809     if (lc.len == 0) {
810         beep();
811     } else {
812         size_t stop = 0, i = 0;
813
814         while(!stop) {
815             /* Show completion or original buffer */
816             if (i < lc.len) {
817                 int chars = utf8_strlen(lc.cvec[i], -1);
818                 refreshLineAlt(current, current->prompt, lc.cvec[i], chars);
819             } else {
820                 refreshLine(current);
821             }
822
823             c = fd_read(current);
824             if (c == -1) {
825                 break;
826             }
827
828             switch(c) {
829                 case '\t': /* tab */
830                     i = (i+1) % (lc.len+1);
831                     if (i == lc.len) beep();
832                     break;
833                 case CHAR_ESCAPE: /* escape */
834                     /* Re-show original buffer */
835                     if (i < lc.len) {
836                         refreshLine(current);
837                     }
838                     stop = 1;
839                     break;
840                 default:
841                     /* Update buffer and return */
842                     if (i < lc.len) {
843                         set_current(current,lc.cvec[i]);
844                     }
845                     stop = 1;
846                     break;
847             }
848         }
849     }
850
851     freeCompletions(&lc);
852     return c; /* Return last read character */
853 }
854
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;
862     return old;
863 }
864
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);
868 }
869
870 void linenoiseSetHintsCallback(linenoiseHintsCallback *callback, void *userdata)
871 {
872     hintsCallback = callback;
873     hintsUserdata = userdata;
874 }
875
876 void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *callback)
877 {
878     freeHintsCallback = callback;
879 }
880
881 #endif
882
883
884 static const char *reduceSingleBuf(const char *buf, int availcols, int *cursor_pos)
885 {
886     /* We have availcols columns available.
887      * If necessary, strip chars off the front of buf until *cursor_pos
888      * fits within availcols
889      */
890     int needcols = 0;
891     int pos = 0;
892     int new_cursor_pos = *cursor_pos;
893     const char *pt = buf;
894
895     DRL("reduceSingleBuf: availcols=%d, cursor_pos=%d\n", availcols, *cursor_pos);
896
897     while (*pt) {
898         int ch;
899         int n = utf8_tounicode(pt, &ch);
900         pt += n;
901
902         needcols += char_display_width(ch);
903
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
908          * can't be used.
909          */
910         while (needcols >= availcols - 3) {
911             n = utf8_tounicode(buf, &ch);
912             buf += n;
913             needcols -= char_display_width(ch);
914             DRL_CHAR(ch);
915
916             /* and adjust the apparent cursor position */
917             new_cursor_pos--;
918
919             if (buf == pt) {
920                 /* can't remove more than this */
921                 break;
922             }
923         }
924
925         if (pos++ == *cursor_pos) {
926             break;
927         }
928
929     }
930     DRL("<snip>");
931     DRL_STR(buf);
932     DRL("\nafter reduce, needcols=%d, new_cursor_pos=%d\n", needcols, new_cursor_pos);
933
934     /* Done, now new_cursor_pos contains the adjusted cursor position
935      * and buf points to he adjusted start
936      */
937     *cursor_pos = new_cursor_pos;
938     return buf;
939 }
940
941 static int mlmode = 0;
942
943 void linenoiseSetMultiLine(int enableml)
944 {
945     mlmode = enableml;
946 }
947
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) {
952         int bold = 0;
953         int color = -1;
954         char *hint = hintsCallback(buf, &color, &bold, hintsUserdata);
955         if (hint) {
956             const char *pt;
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);
961             }
962             DRL("<hint bold=%d,color=%d>", bold, color);
963             pt = hint;
964             while (*pt) {
965                 int ch;
966                 int n = utf8_tounicode(pt, &ch);
967                 int width = char_display_width(ch);
968
969                 if (width >= availcols) {
970                     DRL("<hinteol>");
971                     break;
972                 }
973                 DRL_CHAR(ch);
974
975                 availcols -= width;
976                 outputChars(current, pt, n);
977                 pt += n;
978             }
979             if (bold || color > 0) {
980                 clearOutputHighlight(current);
981             }
982             /* Call the function to free the hint returned. */
983             if (freeHintsCallback) freeHintsCallback(hint, hintsUserdata);
984         }
985     }
986 }
987
988 #ifdef USE_TERMIOS
989 static void refreshStart(struct current *current)
990 {
991     /* We accumulate all output here */
992     assert(current->output == NULL);
993     current->output = sb_alloc();
994 }
995
996 static void refreshEnd(struct current *current)
997 {
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;
1002 }
1003
1004 static void refreshStartChars(struct current *current)
1005 {
1006 }
1007
1008 static void refreshNewline(struct current *current)
1009 {
1010     DRL("<nl>");
1011     outputChars(current, "\n", 1);
1012 }
1013
1014 static void refreshEndChars(struct current *current)
1015 {
1016 }
1017 #endif
1018
1019 static void refreshLineAlt(struct current *current, const char *prompt, const char *buf, int cursor_pos)
1020 {
1021     int i;
1022     const char *pt;
1023     int displaycol;
1024     int displayrow;
1025     int visible;
1026     int currentpos;
1027     int notecursor;
1028     int cursorcol = 0;
1029     int cursorrow = 0;
1030     struct esc_parser parser;
1031
1032 #ifdef DEBUG_REFRESHLINE
1033     dfh = fopen("linenoise.debuglog", "a");
1034 #endif
1035
1036     /* Should intercept SIGWINCH. For now, just get the size every time */
1037     getWindowSize(current);
1038
1039     refreshStart(current);
1040
1041     DRL("wincols=%d, cursor_pos=%d, nrows=%d, rpos=%d\n", current->cols, cursor_pos, current->nrows, current->rpos);
1042
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
1052      */
1053
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);
1057
1058     /* (b), (c) - Erase lines upwards until we get to the first row */
1059     for (i = 0; i < current->nrows; i++) {
1060         if (i) {
1061             DRL("<cup>");
1062             cursorUp(current, 1);
1063         }
1064         DRL("<clearline>");
1065         cursorToLeft(current);
1066         eraseEol(current);
1067     }
1068     DRL("\n");
1069
1070     /* (d) First output the prompt. control sequences don't take up display space */
1071     pt = prompt;
1072     displaycol = 0; /* current display column */
1073     displayrow = 0; /* current display row */
1074     visible = 1;
1075
1076     refreshStartChars(current);
1077
1078     while (*pt) {
1079         int width;
1080         int ch;
1081         int n = utf8_tounicode(pt, &ch);
1082
1083         if (visible && ch == CHAR_ESCAPE) {
1084             /* The start of an escape sequence, so not visible */
1085             visible = 0;
1086             initParseEscapeSeq(&parser, 'm');
1087             DRL("<esc-seq-start>");
1088         }
1089
1090         if (ch == '\n' || ch == '\r') {
1091             /* treat both CR and NL the same and force wrap */
1092             refreshNewline(current);
1093             displaycol = 0;
1094             displayrow++;
1095         }
1096         else {
1097             width = visible * utf8_width(ch);
1098
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
1103                  */
1104                 refreshNewline(current);
1105                 displaycol = width;
1106                 displayrow++;
1107             }
1108
1109             DRL_CHAR(ch);
1110 #ifdef USE_WINCONSOLE
1111             if (visible) {
1112                 outputChars(current, pt, n);
1113             }
1114 #else
1115             outputChars(current, pt, n);
1116 #endif
1117         }
1118         pt += n;
1119
1120         if (!visible) {
1121             switch (parseEscapeSequence(&parser, ch)) {
1122                 case EP_END:
1123                     visible = 1;
1124                     setOutputHighlight(current, parser.props, parser.numprops);
1125                     DRL("<esc-seq-end,numprops=%d>", parser.numprops);
1126                     break;
1127                 case EP_ERROR:
1128                     DRL("<esc-seq-err>");
1129                     visible = 1;
1130                     break;
1131             }
1132         }
1133     }
1134
1135     /* Now we are at the first line with all lines erased */
1136     DRL("\nafter prompt: displaycol=%d, displayrow=%d\n", displaycol, displayrow);
1137
1138
1139     /* (e) output the buffer, counting cols and rows */
1140     if (mlmode == 0) {
1141         /* In this mode we may need to trim chars from the start of the buffer until the
1142          * cursor fits in the window.
1143          */
1144         pt = reduceSingleBuf(buf, current->cols - displaycol, &cursor_pos);
1145     }
1146     else {
1147         pt = buf;
1148     }
1149
1150     currentpos = 0;
1151     notecursor = -1;
1152
1153     while (*pt) {
1154         int ch;
1155         int n = utf8_tounicode(pt, &ch);
1156         int width = char_display_width(ch);
1157
1158         if (currentpos == cursor_pos) {
1159             /* (e') wherever we output this character is where we want the cursor */
1160             notecursor = 1;
1161         }
1162
1163         if (displaycol + width >= current->cols) {
1164             if (mlmode == 0) {
1165                 /* In single line mode stop once we print as much as we can on one line */
1166                 DRL("<slmode>");
1167                 break;
1168             }
1169             /* need to wrap to the next line since it doesn't fit */
1170             refreshNewline(current);
1171             displaycol = 0;
1172             displayrow++;
1173         }
1174
1175         if (notecursor == 1) {
1176             /* (e') Save this position as the current cursor position */
1177             cursorcol = displaycol;
1178             cursorrow = displayrow;
1179             notecursor = 0;
1180             DRL("<cursor>");
1181         }
1182
1183         displaycol += width;
1184
1185         if (ch < ' ') {
1186             outputControlChar(current, ch + '@');
1187         }
1188         else {
1189             outputChars(current, pt, n);
1190         }
1191         DRL_CHAR(ch);
1192         if (width != 1) {
1193             DRL("<w=%d>", width);
1194         }
1195
1196         pt += n;
1197         currentpos++;
1198     }
1199
1200     /* If we didn't see the cursor, it is at the current location */
1201     if (notecursor) {
1202         DRL("<cursor>");
1203         cursorcol = displaycol;
1204         cursorrow = displayrow;
1205     }
1206
1207     DRL("\nafter buf: displaycol=%d, displayrow=%d, cursorcol=%d, cursorrow=%d\n\n", displaycol, displayrow, cursorcol, cursorrow);
1208
1209     /* (f) show hints */
1210     refreshShowHints(current, buf, current->cols - displaycol);
1211
1212     refreshEndChars(current);
1213
1214     /* (g) move the cursor to the correct place */
1215     cursorUp(current, displayrow - cursorrow);
1216     setCursorPos(current, cursorcol);
1217
1218     /* (h) Update the number of rows if larger, but never reduce this */
1219     if (displayrow >= current->nrows) {
1220         current->nrows = displayrow + 1;
1221     }
1222     /* And remember the row that the cursor is on */
1223     current->rpos = cursorrow;
1224
1225     refreshEnd(current);
1226
1227 #ifdef DEBUG_REFRESHLINE
1228     fclose(dfh);
1229 #endif
1230 }
1231
1232 static void refreshLine(struct current *current)
1233 {
1234     refreshLineAlt(current, current->prompt, sb_str(current->buf), current->pos);
1235 }
1236
1237 static void set_current(struct current *current, const char *str)
1238 {
1239     sb_clear(current->buf);
1240     sb_append(current->buf, str);
1241     current->pos = sb_chars(current->buf);
1242 }
1243
1244 /**
1245  * Removes the char at 'pos'.
1246  *
1247  * Returns 1 if the line needs to be refreshed, 2 if not
1248  * and 0 if nothing was removed
1249  */
1250 static int remove_char(struct current *current, int pos)
1251 {
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);
1255
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
1259          */
1260         sb_delete(current->buf, offset, nbytes);
1261
1262         if (current->pos > pos) {
1263             current->pos--;
1264         }
1265         return 1;
1266     }
1267     return 0;
1268 }
1269
1270 /**
1271  * Insert 'ch' at position 'pos'
1272  *
1273  * Returns 1 if the line needs to be refreshed, 2 if not
1274  * and 0 if nothing was inserted (no room)
1275  */
1276 static int insert_char(struct current *current, int pos, int ch)
1277 {
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);
1282
1283         /* null terminate since sb_insert() requires it */
1284         buf[n] = 0;
1285
1286         /* Optimisation removed - see reason in remove_char() */
1287
1288         sb_insert(current->buf, offset, buf);
1289         if (current->pos >= pos) {
1290             current->pos++;
1291         }
1292         return 1;
1293     }
1294     return 0;
1295 }
1296
1297 /**
1298  * Captures up to 'n' characters starting at 'pos' for the cut buffer.
1299  *
1300  * This replaces any existing characters in the cut buffer.
1301  */
1302 static void capture_chars(struct current *current, int pos, int nchars)
1303 {
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);
1307
1308         if (nbytes) {
1309             if (current->capture) {
1310                 sb_clear(current->capture);
1311             }
1312             else {
1313                 current->capture = sb_alloc();
1314             }
1315             sb_append_len(current->capture, sb_str(current->buf) + offset, nbytes);
1316         }
1317     }
1318 }
1319
1320 /**
1321  * Removes up to 'n' characters at cursor position 'pos'.
1322  *
1323  * Returns 0 if no chars were removed or non-zero otherwise.
1324  */
1325 static int remove_chars(struct current *current, int pos, int n)
1326 {
1327     int removed = 0;
1328
1329     /* First save any chars which will be removed */
1330     capture_chars(current, pos, n);
1331
1332     while (n-- && remove_char(current, pos)) {
1333         removed++;
1334     }
1335     return removed;
1336 }
1337 /**
1338  * Inserts the characters (string) 'chars' at the cursor position 'pos'.
1339  *
1340  * Returns 0 if no chars were inserted or non-zero otherwise.
1341  */
1342 static int insert_chars(struct current *current, int pos, const char *chars)
1343 {
1344     int inserted = 0;
1345
1346     while (*chars) {
1347         int ch;
1348         int n = utf8_tounicode(chars, &ch);
1349         if (insert_char(current, pos, ch) == 0) {
1350             break;
1351         }
1352         inserted++;
1353         pos++;
1354         chars += n;
1355     }
1356     return inserted;
1357 }
1358
1359 /**
1360  * Returns the keycode to process, or 0 if none.
1361  */
1362 static int reverseIncrementalSearch(struct current *current)
1363 {
1364     /* Display the reverse-i-search prompt and process chars */
1365     char rbuf[50];
1366     char rprompt[80];
1367     int rchars = 0;
1368     int rlen = 0;
1369     int searchpos = history_len - 1;
1370     int c;
1371
1372     rbuf[0] = 0;
1373     while (1) {
1374         int n = 0;
1375         const char *p = NULL;
1376         int skipsame = 0;
1377         int searchdir = -1;
1378
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) {
1383             if (rchars) {
1384                 int p = utf8_index(rbuf, --rchars);
1385                 rbuf[p] = 0;
1386                 rlen = strlen(rbuf);
1387             }
1388             continue;
1389         }
1390 #ifdef USE_TERMIOS
1391         if (c == CHAR_ESCAPE) {
1392             c = check_special(current->fd);
1393         }
1394 #endif
1395         if (c == ctrl('P') || c == SPECIAL_UP) {
1396             /* Search for the previous (earlier) match */
1397             if (searchpos > 0) {
1398                 searchpos--;
1399             }
1400             skipsame = 1;
1401         }
1402         else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1403             /* Search for the next (later) match */
1404             if (searchpos < history_len) {
1405                 searchpos++;
1406             }
1407             searchdir = 1;
1408             skipsame = 1;
1409         }
1410         else if (c >= ' ') {
1411             /* >= here to allow for null terminator */
1412             if (rlen >= (int)sizeof(rbuf) - MAX_UTF8_LEN) {
1413                 continue;
1414             }
1415
1416             n = utf8_getchars(rbuf + rlen, c);
1417             rlen += n;
1418             rchars++;
1419             rbuf[rlen] = 0;
1420
1421             /* Adding a new char resets the search location */
1422             searchpos = history_len - 1;
1423         }
1424         else {
1425             /* Exit from incremental search mode */
1426             break;
1427         }
1428
1429         /* Now search through the history for a match */
1430         for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1431             p = strstr(history[searchpos], rbuf);
1432             if (p) {
1433                 /* Found a match */
1434                 if (skipsame && strcmp(history[searchpos], sb_str(current->buf)) == 0) {
1435                     /* But it is identical, so skip it */
1436                     continue;
1437                 }
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]);
1441                 break;
1442             }
1443         }
1444         if (!p && n) {
1445             /* No match, so don't add it */
1446             rchars--;
1447             rlen -= n;
1448             rbuf[rlen] = 0;
1449         }
1450     }
1451     if (c == ctrl('G') || c == ctrl('C')) {
1452         /* ctrl-g terminates the search with no effect */
1453         set_current(current, "");
1454         c = 0;
1455     }
1456     else if (c == ctrl('J')) {
1457         /* ctrl-j terminates the search leaving the buffer in place */
1458         c = 0;
1459     }
1460
1461     /* Go process the char normally */
1462     refreshLine(current);
1463     return c;
1464 }
1465
1466 static int linenoiseEdit(struct current *current) {
1467     int history_index = 0;
1468
1469     /* The latest history entry is always our current buffer, that
1470      * initially is just an empty string. */
1471     linenoiseHistoryAdd("");
1472
1473     set_current(current, "");
1474     refreshLine(current);
1475
1476     while(1) {
1477         int dir = -1;
1478         int c = fd_read(current);
1479
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);
1486         }
1487 #endif
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 */
1492         }
1493
1494 #ifdef USE_TERMIOS
1495         if (c == CHAR_ESCAPE) {   /* escape sequence */
1496             c = check_special(current->fd);
1497         }
1498 #endif
1499         if (c == -1) {
1500             /* Return on errors */
1501             return sb_len(current->buf);
1502         }
1503
1504         switch(c) {
1505         case SPECIAL_NONE:
1506             break;
1507         case '\r':    /* enter */
1508             history_len--;
1509             free(history[history_len]);
1510             current->pos = sb_chars(current->buf);
1511             if (mlmode || hintsCallback) {
1512                 showhints = 0;
1513                 refreshLine(current);
1514                 showhints = 1;
1515             }
1516             return sb_len(current->buf);
1517         case ctrl('C'):     /* ctrl-c */
1518             errno = EAGAIN;
1519             return -1;
1520         case ctrl('Z'):     /* ctrl-z */
1521 #ifdef SIGTSTP
1522             /* send ourselves SIGSUSP */
1523             disableRawMode(current);
1524             raise(SIGTSTP);
1525             /* and resume */
1526             enableRawMode(current);
1527             refreshLine(current);
1528 #endif
1529             continue;
1530         case CHAR_DELETE:   /* backspace */
1531         case ctrl('H'):
1532             if (remove_char(current, current->pos - 1) == 1) {
1533                 refreshLine(current);
1534             }
1535             break;
1536         case ctrl('D'):     /* ctrl-d */
1537             if (sb_len(current->buf) == 0) {
1538                 /* Empty line, so EOF */
1539                 history_len--;
1540                 free(history[history_len]);
1541                 return -1;
1542             }
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);
1547             }
1548             break;
1549         case SPECIAL_INSERT:
1550             /* Ignore. Expansion Hook.
1551              * Future possibility: Toggle Insert/Overwrite Modes
1552              */
1553             break;
1554         case ctrl('W'):    /* ctrl-w, delete word at left. save deleted chars */
1555             /* eat any spaces on the left */
1556             {
1557                 int pos = current->pos;
1558                 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1559                     pos--;
1560                 }
1561
1562                 /* now eat any non-spaces on the left */
1563                 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1564                     pos--;
1565                 }
1566
1567                 if (remove_chars(current, pos, current->pos - pos)) {
1568                     refreshLine(current);
1569                 }
1570             }
1571             break;
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);
1580             }
1581             break;
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);
1588
1589                 /* Remove the ^V first */
1590                 remove_char(current, current->pos - 1);
1591                 if (c > 0) {
1592                     /* Insert the actual char, can't be error or null */
1593                     insert_char(current, current->pos, c);
1594                 }
1595                 refreshLine(current);
1596             }
1597             break;
1598         case ctrl('B'):
1599         case SPECIAL_LEFT:
1600             if (current->pos > 0) {
1601                 current->pos--;
1602                 refreshLine(current);
1603             }
1604             break;
1605         case ctrl('F'):
1606         case SPECIAL_RIGHT:
1607             if (current->pos < sb_chars(current->buf)) {
1608                 current->pos++;
1609                 refreshLine(current);
1610             }
1611             break;
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;
1618         case ctrl('P'):
1619         case SPECIAL_UP:
1620             dir = 1;
1621           goto history_navigation;
1622         case ctrl('N'):
1623         case SPECIAL_DOWN:
1624 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) {
1633                     history_index = 0;
1634                     break;
1635                 } else if (history_index >= history_len) {
1636                     history_index = history_len - 1;
1637                     break;
1638                 }
1639                 set_current(current, history[history_len - 1 - history_index]);
1640                 refreshLine(current);
1641             }
1642             break;
1643         case ctrl('A'): /* Ctrl+a, go to the start of the line */
1644         case SPECIAL_HOME:
1645             current->pos = 0;
1646             refreshLine(current);
1647             break;
1648         case ctrl('E'): /* ctrl+e, go to the end of the line */
1649         case SPECIAL_END:
1650             current->pos = sb_chars(current->buf);
1651             refreshLine(current);
1652             break;
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);
1656             }
1657             break;
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);
1661             }
1662             break;
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);
1666             }
1667             break;
1668         case ctrl('L'): /* Ctrl+L, clear screen */
1669             linenoiseClearScreen();
1670             /* Force recalc of window size for serial terminals */
1671             current->cols = 0;
1672             current->rpos = 0;
1673             refreshLine(current);
1674             break;
1675         default:
1676             /* Only tab is allowed without ^V */
1677             if (c == '\t' || c >= ' ') {
1678                 if (insert_char(current, current->pos, c) == 1) {
1679                     refreshLine(current);
1680                 }
1681             }
1682             break;
1683         }
1684     }
1685     return sb_len(current->buf);
1686 }
1687
1688 int linenoiseColumns(void)
1689 {
1690     struct current current;
1691     enableRawMode (&current);
1692     getWindowSize (&current);
1693     disableRawMode (&current);
1694     return current.cols;
1695 }
1696
1697 /**
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.
1701  *
1702  * Note that the character count will *not* be correct for lines containing
1703  * utf8 sequences. Do not rely on the character count.
1704  */
1705 static stringbuf *sb_getline(FILE *fh)
1706 {
1707     stringbuf *sb = sb_alloc();
1708     int c;
1709     int n = 0;
1710
1711     while ((c = getc(fh)) != EOF) {
1712         char ch;
1713         n++;
1714         if (c == '\r') {
1715             /* CRLF -> LF */
1716             continue;
1717         }
1718         if (c == '\n' || c == '\r') {
1719             break;
1720         }
1721         ch = c;
1722         /* ignore the effect of character count for partial utf8 sequences */
1723         sb_append_len(sb, &ch, 1);
1724     }
1725     if (n == 0) {
1726         sb_free(sb);
1727         return NULL;
1728     }
1729     return sb;
1730 }
1731
1732 char *linenoise(const char *prompt)
1733 {
1734     int count;
1735     struct current current;
1736     stringbuf *sb;
1737
1738     memset(&current, 0, sizeof(current));
1739
1740     if (enableRawMode(&current) == -1) {
1741         printf("%s", prompt);
1742         fflush(stdout);
1743         sb = sb_getline(stdin);
1744     }
1745     else {
1746         current.buf = sb_alloc();
1747         current.pos = 0;
1748         current.nrows = 1;
1749         current.prompt = prompt;
1750
1751         count = linenoiseEdit(&current);
1752
1753         disableRawMode(&current);
1754         printf("\n");
1755
1756         sb_free(current.capture);
1757         if (count == -1) {
1758             sb_free(current.buf);
1759             return NULL;
1760         }
1761         sb = current.buf;
1762     }
1763     return sb ? sb_to_string(sb) : NULL;
1764 }
1765
1766 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1767 int linenoiseHistoryAddAllocated(char *line) {
1768
1769     if (history_max_len == 0) {
1770 notinserted:
1771         free(line);
1772         return 0;
1773     }
1774     if (history == NULL) {
1775         history = (char **)calloc(sizeof(char*), history_max_len);
1776     }
1777
1778     /* do not insert duplicate lines into history */
1779     if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1780         goto notinserted;
1781     }
1782
1783     if (history_len == history_max_len) {
1784         free(history[0]);
1785         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1786         history_len--;
1787     }
1788     history[history_len] = line;
1789     history_len++;
1790     return 1;
1791 }
1792
1793 int linenoiseHistoryAdd(const char *line) {
1794     return linenoiseHistoryAddAllocated(strdup(line));
1795 }
1796
1797 int linenoiseHistoryGetMaxLen(void) {
1798     return history_max_len;
1799 }
1800
1801 int linenoiseHistorySetMaxLen(int len) {
1802     char **newHistory;
1803
1804     if (len < 1) return 0;
1805     if (history) {
1806         int tocopy = history_len;
1807
1808         newHistory = (char **)calloc(sizeof(char*), len);
1809
1810         /* If we can't copy everything, free the elements we'll not use. */
1811         if (len < tocopy) {
1812             int j;
1813
1814             for (j = 0; j < tocopy-len; j++) free(history[j]);
1815             tocopy = len;
1816         }
1817         memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy);
1818         free(history);
1819         history = newHistory;
1820     }
1821     history_max_len = len;
1822     if (history_len > history_max_len)
1823         history_len = history_max_len;
1824     return 1;
1825 }
1826
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");
1831     int j;
1832
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 */
1837         while (*str) {
1838             if (*str == '\\') {
1839                 fputs("\\\\", fp);
1840             }
1841             else if (*str == '\n') {
1842                 fputs("\\n", fp);
1843             }
1844             else if (*str == '\r') {
1845                 fputs("\\r", fp);
1846             }
1847             else {
1848                 fputc(*str, fp);
1849             }
1850             str++;
1851         }
1852         fputc('\n', fp);
1853     }
1854
1855     fclose(fp);
1856     return 0;
1857 }
1858
1859 /* Load the history from the specified file.
1860  *
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.
1864  */
1865 int linenoiseHistoryLoad(const char *filename) {
1866     FILE *fp = fopen(filename,"r");
1867     stringbuf *sb;
1868
1869     if (fp == NULL) return -1;
1870
1871     while ((sb = sb_getline(fp)) != NULL) {
1872         /* Take the stringbuf and decode backslash escaped values */
1873         char *buf = sb_to_string(sb);
1874         char *dest = buf;
1875         const char *src;
1876
1877         for (src = buf; *src; src++) {
1878             char ch = *src;
1879
1880             if (ch == '\\') {
1881                 src++;
1882                 if (*src == 'n') {
1883                     ch = '\n';
1884                 }
1885                 else if (*src == 'r') {
1886                     ch = '\r';
1887                 } else {
1888                     ch = *src;
1889                 }
1890             }
1891             *dest++ = ch;
1892         }
1893         *dest = 0;
1894
1895         linenoiseHistoryAddAllocated(buf);
1896     }
1897     fclose(fp);
1898     return 0;
1899 }
1900
1901 /* Provide access to the history buffer.
1902  *
1903  * If 'len' is not NULL, the length is stored in *len.
1904  */
1905 char **linenoiseHistory(int *len) {
1906     if (len) {
1907         *len = history_len;
1908     }
1909     return history;
1910 }