]> git.lizzy.rs Git - linenoise.git/blob - linenoise.c
63a75123355cb429bc306a976f79491fbc202998
[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/antirez/linenoise
7  *
8  * Does a number of crazy assumptions that happen to be true in 99.9999% of
9  * the 2010 UNIX computers around.
10  *
11  * ------------------------------------------------------------------------
12  *
13  * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
14  * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
15  *
16  * All rights reserved.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions are
20  * met:
21  *
22  *  *  Redistributions of source code must retain the above copyright
23  *     notice, this list of conditions and the following disclaimer.
24  *
25  *  *  Redistributions in binary form must reproduce the above copyright
26  *     notice, this list of conditions and the following disclaimer in the
27  *     documentation and/or other materials provided with the distribution.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  * ------------------------------------------------------------------------
42  *
43  * References:
44  * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
45  * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
46  *
47  * Todo list:
48  * - Win32 support
49  * - Save and load history containing newlines
50  *
51  * Bloat:
52  * - Completion?
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  * CHA (Cursor Horizontal Absolute)
60  *    Sequence: ESC [ n G
61  *    Effect: moves cursor to column n (1 based)
62  *
63  * EL (Erase Line)
64  *    Sequence: ESC [ n K
65  *    Effect: if n is 0 or missing, clear from cursor to end of line
66  *    Effect: if n is 1, clear from beginning of line to cursor
67  *    Effect: if n is 2, clear entire line
68  *
69  * CUF (CUrsor Forward)
70  *    Sequence: ESC [ n C
71  *    Effect: moves cursor forward of n chars
72  *
73  * The following are used to clear the screen: ESC [ H ESC [ 2 J
74  * This is actually composed of two sequences:
75  *
76  * cursorhome
77  *    Sequence: ESC [ H
78  *    Effect: moves the cursor to upper left corner
79  *
80  * ED2 (Clear entire screen)
81  *    Sequence: ESC [ 2 J
82  *    Effect: clear the whole screen
83  *
84  * == For highlighting control characters, we also use the following two ==
85  * SO (enter StandOut)
86  *    Sequence: ESC [ 7 m
87  *    Effect: Uses some standout mode such as reverse video
88  *
89  * SE (Standout End)
90  *    Sequence: ESC [ 0 m
91  *    Effect: Exit standout mode
92  *
93  * == Only used if TIOCGWINSZ fails ==
94  * DSR/CPR (Report cursor position)
95  *    Sequence: ESC [ 6 n
96  *    Effect: reports current cursor position as ESC [ NNN ; MMM R
97  */
98
99 #include <termios.h>
100 #include <unistd.h>
101 #include <stdlib.h>
102 #include <stdarg.h>
103 #include <stdio.h>
104 #include <errno.h>
105 #include <string.h>
106 #include <stdlib.h>
107 #include <sys/types.h>
108 #include <sys/ioctl.h>
109 #include <sys/poll.h>
110 #include <unistd.h>
111 #include "linenoise.h"
112
113 #include "linenoise.h"
114 #include "utf8.h"
115
116 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
117 #define LINENOISE_MAX_LINE 4096
118 static char *unsupported_term[] = {"dumb","cons25",NULL};
119
120 static struct termios orig_termios; /* in order to restore at exit */
121 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
122 static int atexit_registered = 0; /* register atexit just 1 time */
123 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
124 static int history_len = 0;
125 static char **history = NULL;
126
127 static void linenoiseAtExit(void);
128 static int fd_read(int fd);
129 static void getColumns(int fd, int *cols);
130
131 static int isUnsupportedTerm(void) {
132     char *term = getenv("TERM");
133     int j;
134
135     if (term == NULL) return 0;
136     for (j = 0; unsupported_term[j]; j++)
137         if (!strcasecmp(term,unsupported_term[j])) return 1;
138     return 0;
139 }
140
141 static void freeHistory(void) {
142     if (history) {
143         int j;
144
145         for (j = 0; j < history_len; j++)
146             free(history[j]);
147         free(history);
148     }
149 }
150
151 static int enableRawMode(int fd) {
152     struct termios raw;
153
154     if (!isatty(STDIN_FILENO)) goto fatal;
155     if (!atexit_registered) {
156         atexit(linenoiseAtExit);
157         atexit_registered = 1;
158     }
159     if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
160
161     raw = orig_termios;  /* modify the original mode */
162     /* input modes: no break, no CR to NL, no parity check, no strip char,
163      * no start/stop output control. */
164     raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
165     /* output modes - disable post processing */
166     raw.c_oflag &= ~(OPOST);
167     /* control modes - set 8 bit chars */
168     raw.c_cflag |= (CS8);
169     /* local modes - choing off, canonical off, no extended functions,
170      * no signal chars (^Z,^C) */
171     raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
172     /* control chars - set return condition: min number of bytes and timer.
173      * We want read to return every single byte, without timeout. */
174     raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
175
176     /* put terminal in raw mode after flushing */
177     if (tcsetattr(fd,TCSADRAIN,&raw) < 0) goto fatal;
178     rawmode = 1;
179     return 0;
180
181 fatal:
182     errno = ENOTTY;
183     return -1;
184 }
185
186 static void disableRawMode(int fd) {
187     /* Don't even check the return value as it's too late. */
188     if (rawmode && tcsetattr(fd,TCSADRAIN,&orig_termios) != -1)
189         rawmode = 0;
190 }
191
192 /* At exit we'll try to fix the terminal to the initial conditions. */
193 static void linenoiseAtExit(void) {
194     disableRawMode(STDIN_FILENO);
195     freeHistory();
196 }
197
198 /* Structure to contain the status of the current (being edited) line */
199 struct current {
200     int fd;     /* Terminal fd */
201     char *buf;  /* Current buffer. Always null terminated */
202     int bufmax; /* Size of the buffer, including space for the null termination */
203     int len;    /* Number of bytes in 'buf' */
204     int chars;  /* Number of chars in 'buf' (utf-8 chars) */
205     int pos;    /* Cursor position, measured in chars */
206     int cols;   /* Size of the window, in chars */
207     const char *prompt;
208 };
209
210 /* gcc/glibc insists that we care about the return code of write! */
211 #define IGNORE_RC(EXPR) ((EXPR) < 0 ? -1 : 0)
212
213 /* This is fd_printf() on some systems, but use a different
214  * name to avoid conflicts
215  */
216 static void fd_printf(int fd, const char *format, ...)
217 {
218     va_list args;
219     char buf[64];
220     int n;
221
222     va_start(args, format);
223     n = vsnprintf(buf, sizeof(buf), format, args);
224     va_end(args);
225     IGNORE_RC(write(fd, buf, n));
226 }
227
228 static int utf8_getchars(char *buf, int c)
229 {
230 #ifdef USE_UTF8
231     return utf8_fromunicode(buf, c);
232 #else
233     *buf = c;
234     return 1;
235 #endif
236 }
237
238 /**
239  * Returns the unicode character at the given offset,
240  * or -1 if none.
241  */
242 static int get_char(struct current *current, int pos)
243 {
244     if (pos >= 0 && pos < current->chars) {
245         int c;
246         int i = utf8_index(current->buf, pos);
247         (void)utf8_tounicode(current->buf + i, &c);
248         return c;
249     }
250     return -1;
251 }
252
253 static void refreshLine(const char *prompt, struct current *current) {
254     int plen;
255     int pchars;
256     int backup = 0;
257     int i;
258     const char *buf = current->buf;
259     int chars = current->chars;
260     int pos = current->pos;
261     int b;
262     int ch;
263     int n;
264
265     /* Should intercept SIGWINCH. For now, just get the size every time */
266     getColumns(current->fd, &current->cols);
267
268     plen = strlen(prompt);
269     pchars = utf8_strlen(prompt, plen);
270
271     /* Account for a line which is too long to fit in the window.
272      * Note that control chars require an extra column
273      */
274
275     /* How many cols are required to the left of 'pos'?
276      * The prompt, plus one extra for each control char
277      */
278     n = pchars + utf8_strlen(buf, current->len);
279     b = 0;
280     for (i = 0; i < pos; i++) {
281         b += utf8_tounicode(buf + b, &ch);
282         if (ch < ' ') {
283             n++;
284         }
285     }
286
287     /* If too many are need, strip chars off the front of 'buf'
288      * until it fits. Note that if the current char is a control character,
289      * we need one extra col.
290      */
291     if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
292         n++;
293     }
294
295     while (n >= current->cols) {
296         b = utf8_tounicode(buf, &ch);
297         if (ch < ' ') {
298             n--;
299         }
300         n--;
301         buf += b;
302         pos--;
303         chars--;
304     }
305
306     /* Cursor to left edge, then the prompt */
307     fd_printf(current->fd, "\x1b[1G");
308     IGNORE_RC(write(current->fd, prompt, plen));
309
310     /* Now the current buffer content */
311
312     /* Need special handling for control characters.
313      * If we hit 'cols', stop.
314      */
315     b = 0; /* unwritted bytes */
316     n = 0; /* How many control chars were written */
317     for (i = 0; i < chars; i++) {
318         int ch;
319         int w = utf8_tounicode(buf + b, &ch);
320         if (ch < ' ') {
321             n++;
322         }
323         if (pchars + i + n >= current->cols) {
324             break;
325         }
326         if (ch < ' ') {
327             /* A control character, so write the buffer so far */
328             IGNORE_RC(write(current->fd, buf, b));
329             buf += b + w;
330             b = 0;
331             fd_printf(current->fd, "\033[7m^%c\033[0m", ch + '@');
332             if (i < pos) {
333                 backup++;
334             }
335         }
336         else {
337             b += w;
338         }
339     }
340     IGNORE_RC(write(current->fd, buf, b));
341
342     /* Erase to right, move cursor to original position */
343     fd_printf(current->fd, "\x1b[0K" "\x1b[1G\x1b[%dC", pos + pchars + backup);
344 }
345
346 static void set_current(struct current *current, const char *str)
347 {
348     strncpy(current->buf, str, current->bufmax);
349     current->buf[current->bufmax - 1] = 0;
350     current->len = strlen(current->buf);
351     current->pos = current->chars = utf8_strlen(current->buf, current->len);
352 }
353
354 static int has_room(struct current *current, int bytes)
355 {
356     return current->len + bytes < current->bufmax - 1;
357 }
358
359 /**
360  * Removes the char at 'pos'.
361  * 
362  * Returns 1 if the line needs to be refreshed, 2 if not
363  * and 0 if nothing was removed
364  */
365 static int remove_char(struct current *current, int pos)
366 {
367     if (pos >= 0 && pos < current->chars) {
368         int p1, p2;
369         int ret = 1;
370         p1 = utf8_index(current->buf, pos);
371         p2 = p1 + utf8_index(current->buf + p1, 1);
372
373         /* optimise remove char in the case of removing the last char */
374         if (current->pos == pos + 1 && current->pos == current->chars) {
375             if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
376                 ret = 2;
377                 fd_printf(current->fd, "\b \b");
378             }
379         }
380
381         /* Move the null char too */
382         memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
383         current->len -= (p2 - p1);
384         current->chars--;
385
386         if (current->pos > pos) {
387             current->pos--;
388         }
389         return ret;
390     }
391     return 0;
392 }
393
394 /**
395  * Insert 'ch' at position 'pos'
396  * 
397  * Returns 1 if the line needs to be refreshed, 2 if not
398  * and 0 if nothing was inserted (no room)
399  */
400 static int insert_char(struct current *current, int pos, int ch)
401 {
402     char buf[3];
403     int n = utf8_getchars(buf, ch);
404
405     if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
406         int p1, p2;
407         int ret = 1;
408         p1 = utf8_index(current->buf, pos);
409         p2 = p1 + n;
410
411         /* optimise the case where adding a single char to the end and no scrolling is needed */
412         if (current->pos == pos && current->chars == pos) {
413             if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
414                 IGNORE_RC(write(current->fd, buf, n));
415                 ret = 2;
416             }
417         }
418
419         memmove(current->buf + p2, current->buf + p1, current->len - p1);
420         memcpy(current->buf + p1, buf, n);
421         current->len += n;
422
423         current->chars++;
424         if (current->pos >= pos) {
425             current->pos++;
426         }
427         return ret;
428     }
429     return 0;
430 }
431
432 #ifndef NO_COMPLETION
433 static linenoiseCompletionCallback *completionCallback = NULL;
434
435 static void beep() {
436     fprintf(stderr, "\x7");
437     fflush(stderr);
438 }
439
440 static void freeCompletions(linenoiseCompletions *lc) {
441     size_t i;
442     for (i = 0; i < lc->len; i++)
443         free(lc->cvec[i]);
444     free(lc->cvec);
445 }
446
447 static int completeLine(struct current *current) {
448     linenoiseCompletions lc = { 0, NULL };
449     int c = 0;
450
451     completionCallback(current->buf,&lc);
452     if (lc.len == 0) {
453         beep();
454     } else {
455         size_t stop = 0, i = 0;
456
457         while(!stop) {
458             /* Show completion or original buffer */
459             if (i < lc.len) {
460                 struct current tmp = *current;
461                 tmp.buf = lc.cvec[i];
462                 tmp.pos = tmp.len = strlen(tmp.buf);
463                 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
464                 refreshLine(current->prompt, &tmp);
465             } else {
466                 refreshLine(current->prompt, current);
467             }
468
469             c = fd_read(current->fd);
470             if (c < 0) {
471                 break;
472             }
473
474             switch(c) {
475                 case '\t': /* tab */
476                     i = (i+1) % (lc.len+1);
477                     if (i == lc.len) beep();
478                     break;
479                 case 27: /* escape */
480                     /* Re-show original buffer */
481                     if (i < lc.len) {
482                         refreshLine(current->prompt, current);
483                     }
484                     stop = 1;
485                     break;
486                 default:
487                     /* Update buffer and return */
488                     if (i < lc.len) {
489                         set_current(current,lc.cvec[i]);
490                     }
491                     stop = 1;
492                     break;
493             }
494         }
495     }
496
497     freeCompletions(&lc);
498     return c; /* Return last read character */
499 }
500
501 /* Register a callback function to be called for tab-completion. */
502 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
503     completionCallback = fn;
504 }
505
506 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
507     lc->cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
508     lc->cvec[lc->len++] = strdup(str);
509 }
510
511 #endif
512
513 /**
514  * Returns 0 if no chars were removed or non-zero otherwise.
515  */
516 static int remove_chars(struct current *current, int pos, int n)
517 {
518     int removed = 0;
519     while (n-- && remove_char(current, pos)) {
520         removed++;
521     }
522     return removed;
523 }
524
525 /**
526  * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
527  *
528  * A timeout of -1 means to wait forever.
529  *
530  * Returns -1 if no char is received within the time or an error occurs.
531  */
532 static int fd_read_char(int fd, int timeout)
533 {
534     struct pollfd p;
535     unsigned char c;
536
537     p.fd = fd;
538     p.events = POLLIN;
539
540     if (poll(&p, 1, timeout) == 0) {
541         /* timeout */
542         return -1;
543     }
544     if (read(fd, &c, 1) != 1) {
545         return -1;
546     }
547     return c;
548 }
549
550 /**
551  * Reads a complete utf-8 character
552  * and returns the unicode value, or -1 on error.
553  */
554 static int fd_read(int fd)
555 {
556 #ifdef USE_UTF8
557     char buf[4];
558     int n;
559     int i;
560     int c;
561
562     if (read(fd, &buf[0], 1) != 1) {
563         return -1;
564     }
565     n = utf8_charlen(buf[0]);
566     if (n < 1 || n > 3) {
567         return -1;
568     }
569     for (i = 1; i < n; i++) {
570         if (read(fd, &buf[i], 1) != 1) {
571             return -1;
572         }
573     }
574     buf[n] = 0;
575     /* decode and return the character */
576     utf8_tounicode(buf, &c);
577     return c;
578 #else
579     return fd_read_char(fd, -1);
580 #endif
581 }
582
583 static void getColumns(int fd, int *cols) {
584     struct winsize ws;
585
586     if (ioctl(1, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
587         *cols = ws.ws_col;
588         return;
589     }
590     /* Failed to query the window size. Perhaps we are on a serial terminal.
591      * Try to query the width by sending the cursor as far to the right
592      * and reading back the cursor position.
593      * Note that this is only done once per call to linenoise rather than
594      * every time the line is refreshed for efficiency reasons.
595      */
596     if (*cols == 0) {
597         *cols = 80;
598
599         /* Move cursor far right and report cursor position */
600         fd_printf(fd, "\x1b[999G" "\x1b[6n");
601
602         /* Parse the response: ESC [ rows ; cols R */
603         if (fd_read_char(fd, 100) == 0x1b && fd_read_char(fd, 100) == '[') {
604             int n = 0;
605             while (1) {
606                 int ch = fd_read_char(fd, 100);
607                 if (ch == ';') {
608                     /* Ignore rows */
609                     n = 0;
610                 }
611                 else if (ch == 'R') {
612                     /* Got cols */
613                     if (n != 0 && n < 1000) {
614                         *cols = n;
615                     }
616                     break;
617                 }
618                 else if (ch >= 0 && ch <= '9') {
619                     n = n * 10 + ch - '0';
620                 }
621                 else {
622                     break;
623                 }
624             }
625         }
626     }
627 }
628
629 /* Use -ve numbers here to co-exist with normal unicode chars */
630 enum {
631     SPECIAL_NONE,
632     SPECIAL_UP = -20,
633     SPECIAL_DOWN = -21,
634     SPECIAL_LEFT = -22,
635     SPECIAL_RIGHT = -23,
636     SPECIAL_DELETE = -24,
637 };
638
639 /**
640  * If escape (27) was received, reads subsequent
641  * chars to determine if this is a known special key.
642  *
643  * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
644  *
645  * If no additional char is received within a short time,
646  * 27 is returned.
647  */
648 static int check_special(int fd)
649 {
650     int c = fd_read_char(fd, 50);
651     int c2;
652
653     if (c < 0) {
654         return 27;
655     }
656
657     c2 = fd_read_char(fd, 50);
658     if (c2 < 0) {
659         return c2;
660     }
661     if (c == '[' || c == 'O') {
662         /* Potential arrow key */
663         switch (c2) {
664             case 'A':
665                 return SPECIAL_UP;
666             case 'B':
667                 return SPECIAL_DOWN;
668             case 'C':
669                 return SPECIAL_RIGHT;
670             case 'D':
671                 return SPECIAL_LEFT;
672         }
673     }
674     if (c == '[' && c2 >= '1' && c2 <= '6') {
675         /* extended escape */
676         int c3 = fd_read_char(fd, 50);
677         if (c2 == '3' && c3 == '~') {
678             /* delete char under cursor */
679             return SPECIAL_DELETE;
680         }
681         while (c3 != -1 && c3 != '~') {
682             /* .e.g \e[12~ or '\e[11;2~   discard the complete sequence */
683             c3 = fd_read_char(fd, 50);
684         }
685     }
686
687     return SPECIAL_NONE;
688 }
689
690 #define ctrl(C) ((C) - '@')
691
692 static int linenoisePrompt(struct current *current) {
693     int history_index = 0;
694
695     /* The latest history entry is always our current buffer, that
696      * initially is just an empty string. */
697     linenoiseHistoryAdd("");
698
699     set_current(current, "");
700     refreshLine(current->prompt, current);
701
702     while(1) {
703         int c = fd_read(current->fd);
704
705 #ifndef NO_COMPLETION
706         /* Only autocomplete when the callback is set. It returns < 0 when
707          * there was an error reading from fd. Otherwise it will return the
708          * character that should be handled next. */
709         if (c == 9 && completionCallback != NULL) {
710             c = completeLine(current);
711             /* Return on errors */
712             if (c < 0) return current->len;
713             /* Read next character when 0 */
714             if (c == 0) continue;
715         }
716 #endif
717
718 process_char:
719         if (c == -1) return current->len;
720         switch(c) {
721         case '\r':    /* enter */
722             history_len--;
723             free(history[history_len]);
724             return current->len;
725         case ctrl('C'):     /* ctrl-c */
726             errno = EAGAIN;
727             return -1;
728         case 127:   /* backspace */
729         case ctrl('H'):
730             if (remove_char(current, current->pos - 1) == 1) {
731                 refreshLine(current->prompt, current);
732             }
733             break;
734         case ctrl('D'):     /* ctrl-d */
735             if (current->len == 0) {
736                 /* Empty line, so EOF */
737                 history_len--;
738                 free(history[history_len]);
739                 return -1;
740             }
741             /* Otherwise delete char to right of cursor */
742             if (remove_char(current, current->pos)) {
743                 refreshLine(current->prompt, current);
744             }
745             break;
746         case ctrl('W'):    /* ctrl-w */
747             /* eat any spaces on the left */
748             {
749                 int pos = current->pos;
750                 while (pos > 0 && get_char(current, pos - 1) == ' ') {
751                     pos--;
752                 }
753
754                 /* now eat any non-spaces on the left */
755                 while (pos > 0 && get_char(current, pos - 1) != ' ') {
756                     pos--;
757                 }
758
759                 if (remove_chars(current, pos, current->pos - pos)) {
760                     refreshLine(current->prompt, current);
761                 }
762             }
763             break;
764         case ctrl('R'):    /* ctrl-r */
765             {
766                 /* Display the reverse-i-search prompt and process chars */
767                 char rbuf[50];
768                 char rprompt[80];
769                 int rchars = 0;
770                 int rlen = 0;
771                 int searchpos = history_len - 1;
772
773                 rbuf[0] = 0;
774                 while (1) {
775                     int n = 0;
776                     const char *p = NULL;
777                     int skipsame = 0;
778                     int searchdir = -1;
779
780                     snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
781                     refreshLine(rprompt, current);
782                     c = fd_read(current->fd);
783                     if (c == ctrl('H') || c == 127) {
784                         if (rchars) {
785                             int p = utf8_index(rbuf, --rchars);
786                             rbuf[p] = 0;
787                             rlen = strlen(rbuf);
788                         }
789                         continue;
790                     }
791                     if (c == 27) {
792                         c = check_special(current->fd);
793                     }
794                     if (c == ctrl('P') || c == SPECIAL_UP) {
795                         /* Search for the previous (earlier) match */
796                         if (searchpos > 0) {
797                             searchpos--;
798                         }
799                         skipsame = 1;
800                     }
801                     else if (c == ctrl('N') || c == SPECIAL_DOWN) {
802                         /* Search for the next (later) match */
803                         if (searchpos < history_len) {
804                             searchpos++;
805                         }
806                         searchdir = 1;
807                         skipsame = 1;
808                     }
809                     else if (c >= ' ') {
810                         if (rlen >= (int)sizeof(rbuf) + 3) {
811                             continue;
812                         }
813
814                         n = utf8_getchars(rbuf + rlen, c);
815                         rlen += n;
816                         rchars++;
817                         rbuf[rlen] = 0;
818
819                         /* Adding a new char resets the search location */
820                         searchpos = history_len - 1;
821                     }
822                     else {
823                         /* Exit from incremental search mode */
824                         break;
825                     }
826
827                     /* Now search through the history for a match */
828                     for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
829                         p = strstr(history[searchpos], rbuf);
830                         if (p) {
831                             /* Found a match */
832                             if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
833                                 /* But it is identical, so skip it */
834                                 continue;
835                             }
836                             /* Copy the matching line and set the cursor position */
837                             set_current(current,history[searchpos]);
838                             current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
839                             break;
840                         }
841                     }
842                     if (!p && n) {
843                         /* No match, so don't add it */
844                         rchars--;
845                         rlen -= n;
846                         rbuf[rlen] = 0;
847                     }
848                 }
849                 if (c == ctrl('G') || c == ctrl('C')) {
850                     /* ctrl-g terminates the search with no effect */
851                     set_current(current, "");
852                     c = 0;
853                 }
854                 else if (c == ctrl('J')) {
855                     /* ctrl-j terminates the search leaving the buffer in place */
856                     c = 0;
857                 }
858                 /* Go process the char normally */
859                 refreshLine(current->prompt, current);
860                 goto process_char;
861             }
862             break;
863         case ctrl('T'):    /* ctrl-t */
864             if (current->pos > 0 && current->pos < current->chars) {
865                 c = get_char(current, current->pos);
866                 remove_char(current, current->pos);
867                 insert_char(current, current->pos - 1, c);
868                 refreshLine(current->prompt, current);
869             }
870             break;
871         case ctrl('V'):    /* ctrl-v */
872             if (has_room(current, 3)) {
873                 /* Insert the ^V first */
874                 if (insert_char(current, current->pos, c)) {
875                     refreshLine(current->prompt, current);
876                     /* Now wait for the next char. Can insert anything except \0 */
877                     c = fd_read(current->fd);
878
879                     /* Remove the ^V first */
880                     remove_char(current, current->pos - 1);
881                     if (c != -1) {
882                         /* Insert the actual char */
883                         insert_char(current, current->pos, c);
884                     }
885                     refreshLine(current->prompt, current);
886                 }
887             }
888             break;
889         case ctrl('B'):     /* ctrl-b */
890         case ctrl('F'):     /* ctrl-f */
891         case ctrl('P'):    /* ctrl-p */
892         case ctrl('N'):    /* ctrl-n */
893         case 27: {   /* escape sequence */
894             int dir = -1;
895             if (c == 27) {
896                 c = check_special(current->fd);
897             }
898             switch (c) {
899                 case ctrl('B'):
900                 case SPECIAL_LEFT:
901                     if (current->pos > 0) {
902                         current->pos--;
903                         refreshLine(current->prompt, current);
904                     }
905                     break;
906                 case ctrl('F'):
907                 case SPECIAL_RIGHT:
908                     if (current->pos < current->chars) {
909                         current->pos++;
910                         refreshLine(current->prompt, current);
911                     }
912                     break;
913                 case ctrl('P'):
914                 case SPECIAL_UP:
915                     dir = 1;
916                 case ctrl('N'):
917                 case SPECIAL_DOWN:
918                     if (history_len > 1) {
919                         /* Update the current history entry before to
920                          * overwrite it with tne next one. */
921                         free(history[history_len-1-history_index]);
922                         history[history_len-1-history_index] = strdup(current->buf);
923                         /* Show the new entry */
924                         history_index += dir;
925                         if (history_index < 0) {
926                             history_index = 0;
927                             break;
928                         } else if (history_index >= history_len) {
929                             history_index = history_len-1;
930                             break;
931                         }
932                         set_current(current, history[history_len-1-history_index]);
933                         refreshLine(current->prompt, current);
934                     }
935                     break;
936
937                 case SPECIAL_DELETE:
938                     if (remove_char(current, current->pos) == 1) {
939                         refreshLine(current->prompt, current);
940                     }
941                     break;
942             }
943             }
944             break;
945         default:
946             /* Only tab is allowed without ^V */
947             if (c == '\t' || c >= ' ') {
948                 if (insert_char(current, current->pos, c) == 1) {
949                     refreshLine(current->prompt, current);
950                 }
951             }
952             break;
953         case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
954             if (remove_chars(current, 0, current->pos)) {
955                 refreshLine(current->prompt, current);
956             }
957             break;
958         case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
959             if (remove_chars(current, current->pos, current->chars - current->pos)) {
960                 refreshLine(current->prompt, current);
961             }
962             break;
963         case ctrl('A'): /* Ctrl+a, go to the start of the line */
964             current->pos = 0;
965             refreshLine(current->prompt, current);
966             break;
967         case ctrl('E'): /* ctrl+e, go to the end of the line */
968             current->pos = current->chars;
969             refreshLine(current->prompt, current);
970             break;
971         case ctrl('L'): /* Ctrl+L, clear screen */
972             /* clear screen */
973             fd_printf(current->fd, "\x1b[H\x1b[2J");
974             /* Force recalc of window size for serial terminals */
975             current->cols = 0;
976             refreshLine(current->prompt, current);
977             break;
978         }
979     }
980     return current->len;
981 }
982
983 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
984     int fd = STDIN_FILENO;
985     int count;
986
987     if (buflen == 0) {
988         errno = EINVAL;
989         return -1;
990     }
991     if (!isatty(STDIN_FILENO)) {
992         if (fgets(buf, buflen, stdin) == NULL) return -1;
993         count = strlen(buf);
994         if (count && buf[count-1] == '\n') {
995             count--;
996             buf[count] = '\0';
997         }
998     } else {
999         struct current current;
1000
1001         if (enableRawMode(fd) == -1) return -1;
1002
1003         current.fd = fd;
1004         current.buf = buf;
1005         current.bufmax = buflen;
1006         current.len = 0;
1007         current.chars = 0;
1008         current.pos = 0;
1009         current.cols = 0;
1010         current.prompt = prompt;
1011
1012         count = linenoisePrompt(&current);
1013         disableRawMode(fd);
1014
1015         printf("\n");
1016     }
1017     return count;
1018 }
1019
1020 char *linenoise(const char *prompt) {
1021     char buf[LINENOISE_MAX_LINE];
1022     int count;
1023
1024     if (isUnsupportedTerm()) {
1025         size_t len;
1026
1027         printf("%s",prompt);
1028         fflush(stdout);
1029         if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
1030         len = strlen(buf);
1031         while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
1032             len--;
1033             buf[len] = '\0';
1034         }
1035         return strdup(buf);
1036     } else {
1037         count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
1038         if (count == -1) return NULL;
1039         return strdup(buf);
1040     }
1041 }
1042
1043 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1044 int linenoiseHistoryAdd(const char *line) {
1045     char *linecopy;
1046
1047     if (history_max_len == 0) return 0;
1048     if (history == NULL) {
1049         history = malloc(sizeof(char*)*history_max_len);
1050         if (history == NULL) return 0;
1051         memset(history,0,(sizeof(char*)*history_max_len));
1052     }
1053     linecopy = strdup(line);
1054     if (!linecopy) return 0;
1055     if (history_len == history_max_len) {
1056         free(history[0]);
1057         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1058         history_len--;
1059     }
1060     history[history_len] = linecopy;
1061     history_len++;
1062     return 1;
1063 }
1064
1065 int linenoiseHistorySetMaxLen(int len) {
1066     char **new;
1067
1068     if (len < 1) return 0;
1069     if (history) {
1070         int tocopy = history_len;
1071
1072         new = malloc(sizeof(char*)*len);
1073         if (new == NULL) return 0;
1074         if (len < tocopy) tocopy = len;
1075         memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
1076         free(history);
1077         history = new;
1078     }
1079     history_max_len = len;
1080     if (history_len > history_max_len)
1081         history_len = history_max_len;
1082     return 1;
1083 }
1084
1085 /* Save the history in the specified file. On success 0 is returned
1086  * otherwise -1 is returned. */
1087 int linenoiseHistorySave(char *filename) {
1088     FILE *fp = fopen(filename,"w");
1089     int j;
1090
1091     if (fp == NULL) return -1;
1092     for (j = 0; j < history_len; j++) {
1093         const char *str = history[j];
1094         /* Need to encode backslash, nl and cr */
1095         while (*str) {
1096             if (*str == '\\') {
1097                 fputs("\\\\", fp);
1098             }
1099             else if (*str == '\n') {
1100                 fputs("\\n", fp);
1101             }
1102             else if (*str == '\r') {
1103                 fputs("\\r", fp);
1104             }
1105             else {
1106                 fputc(*str, fp);
1107             }
1108             str++;
1109         }
1110         fputc('\n', fp);
1111     }
1112
1113     fclose(fp);
1114     return 0;
1115 }
1116
1117 /* Load the history from the specified file. If the file does not exist
1118  * zero is returned and no operation is performed.
1119  *
1120  * If the file exists and the operation succeeded 0 is returned, otherwise
1121  * on error -1 is returned. */
1122 int linenoiseHistoryLoad(char *filename) {
1123     FILE *fp = fopen(filename,"r");
1124     char buf[LINENOISE_MAX_LINE];
1125
1126     if (fp == NULL) return -1;
1127
1128     while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1129         char *src, *dest;
1130
1131         /* Decode backslash escaped values */
1132         for (src = dest = buf; *src; src++) {
1133             char ch = *src;
1134
1135             if (ch == '\\') {
1136                 src++;
1137                 if (*src == 'n') {
1138                     ch = '\n';
1139                 }
1140                 else if (*src == 'r') {
1141                     ch = '\r';
1142                 } else {
1143                     ch = *src;
1144                 }
1145             }
1146             *dest++ = ch;
1147         }
1148         /* Remove trailing newline */
1149         if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1150             dest--;
1151         }
1152         *dest = 0;
1153
1154         linenoiseHistoryAdd(buf);
1155     }
1156     fclose(fp);
1157     return 0;
1158 }
1159
1160 /* Provide access to the history buffer.
1161  *
1162  * If 'len' is not NULL, the length is stored in *len.
1163  */
1164 char **linenoiseHistory(int *len) {
1165     if (len) {
1166         *len = history_len;
1167     }
1168     return history;
1169 }