]> git.lizzy.rs Git - linenoise.git/blob - linenoise.c
Add support for HOME and END keys
[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 const 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) if (EXPR) {}
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 = (char **)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     SPECIAL_HOME = -25,
638     SPECIAL_END = -26,
639 };
640
641 /**
642  * If escape (27) was received, reads subsequent
643  * chars to determine if this is a known special key.
644  *
645  * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
646  *
647  * If no additional char is received within a short time,
648  * 27 is returned.
649  */
650 static int check_special(int fd)
651 {
652     int c = fd_read_char(fd, 50);
653     int c2;
654
655     if (c < 0) {
656         return 27;
657     }
658
659     c2 = fd_read_char(fd, 50);
660     if (c2 < 0) {
661         return c2;
662     }
663     if (c == '[' || c == 'O') {
664         /* Potential arrow key */
665         switch (c2) {
666             case 'A':
667                 return SPECIAL_UP;
668             case 'B':
669                 return SPECIAL_DOWN;
670             case 'C':
671                 return SPECIAL_RIGHT;
672             case 'D':
673                 return SPECIAL_LEFT;
674             case 'F':
675                 return SPECIAL_END;
676             case 'H':
677                 return SPECIAL_HOME;
678         }
679     }
680     if (c == '[' && c2 >= '1' && c2 <= '6') {
681         /* extended escape */
682         int c3 = fd_read_char(fd, 50);
683         if (c2 == '3' && c3 == '~') {
684             /* delete char under cursor */
685             return SPECIAL_DELETE;
686         }
687         while (c3 != -1 && c3 != '~') {
688             /* .e.g \e[12~ or '\e[11;2~   discard the complete sequence */
689             c3 = fd_read_char(fd, 50);
690         }
691     }
692
693     return SPECIAL_NONE;
694 }
695
696 #define ctrl(C) ((C) - '@')
697
698 static int linenoisePrompt(struct current *current) {
699     int history_index = 0;
700
701     /* The latest history entry is always our current buffer, that
702      * initially is just an empty string. */
703     linenoiseHistoryAdd("");
704
705     set_current(current, "");
706     refreshLine(current->prompt, current);
707
708     while(1) {
709         int c = fd_read(current->fd);
710
711 #ifndef NO_COMPLETION
712         /* Only autocomplete when the callback is set. It returns < 0 when
713          * there was an error reading from fd. Otherwise it will return the
714          * character that should be handled next. */
715         if (c == 9 && completionCallback != NULL) {
716             c = completeLine(current);
717             /* Return on errors */
718             if (c < 0) return current->len;
719             /* Read next character when 0 */
720             if (c == 0) continue;
721         }
722 #endif
723
724 process_char:
725         if (c == -1) return current->len;
726         switch(c) {
727         case '\r':    /* enter */
728             history_len--;
729             free(history[history_len]);
730             return current->len;
731         case ctrl('C'):     /* ctrl-c */
732             errno = EAGAIN;
733             return -1;
734         case 127:   /* backspace */
735         case ctrl('H'):
736             if (remove_char(current, current->pos - 1) == 1) {
737                 refreshLine(current->prompt, current);
738             }
739             break;
740         case ctrl('D'):     /* ctrl-d */
741             if (current->len == 0) {
742                 /* Empty line, so EOF */
743                 history_len--;
744                 free(history[history_len]);
745                 return -1;
746             }
747             /* Otherwise delete char to right of cursor */
748             if (remove_char(current, current->pos)) {
749                 refreshLine(current->prompt, current);
750             }
751             break;
752         case ctrl('W'):    /* ctrl-w */
753             /* eat any spaces on the left */
754             {
755                 int pos = current->pos;
756                 while (pos > 0 && get_char(current, pos - 1) == ' ') {
757                     pos--;
758                 }
759
760                 /* now eat any non-spaces on the left */
761                 while (pos > 0 && get_char(current, pos - 1) != ' ') {
762                     pos--;
763                 }
764
765                 if (remove_chars(current, pos, current->pos - pos)) {
766                     refreshLine(current->prompt, current);
767                 }
768             }
769             break;
770         case ctrl('R'):    /* ctrl-r */
771             {
772                 /* Display the reverse-i-search prompt and process chars */
773                 char rbuf[50];
774                 char rprompt[80];
775                 int rchars = 0;
776                 int rlen = 0;
777                 int searchpos = history_len - 1;
778
779                 rbuf[0] = 0;
780                 while (1) {
781                     int n = 0;
782                     const char *p = NULL;
783                     int skipsame = 0;
784                     int searchdir = -1;
785
786                     snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
787                     refreshLine(rprompt, current);
788                     c = fd_read(current->fd);
789                     if (c == ctrl('H') || c == 127) {
790                         if (rchars) {
791                             int p = utf8_index(rbuf, --rchars);
792                             rbuf[p] = 0;
793                             rlen = strlen(rbuf);
794                         }
795                         continue;
796                     }
797                     if (c == 27) {
798                         c = check_special(current->fd);
799                     }
800                     if (c == ctrl('P') || c == SPECIAL_UP) {
801                         /* Search for the previous (earlier) match */
802                         if (searchpos > 0) {
803                             searchpos--;
804                         }
805                         skipsame = 1;
806                     }
807                     else if (c == ctrl('N') || c == SPECIAL_DOWN) {
808                         /* Search for the next (later) match */
809                         if (searchpos < history_len) {
810                             searchpos++;
811                         }
812                         searchdir = 1;
813                         skipsame = 1;
814                     }
815                     else if (c >= ' ') {
816                         if (rlen >= (int)sizeof(rbuf) + 3) {
817                             continue;
818                         }
819
820                         n = utf8_getchars(rbuf + rlen, c);
821                         rlen += n;
822                         rchars++;
823                         rbuf[rlen] = 0;
824
825                         /* Adding a new char resets the search location */
826                         searchpos = history_len - 1;
827                     }
828                     else {
829                         /* Exit from incremental search mode */
830                         break;
831                     }
832
833                     /* Now search through the history for a match */
834                     for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
835                         p = strstr(history[searchpos], rbuf);
836                         if (p) {
837                             /* Found a match */
838                             if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
839                                 /* But it is identical, so skip it */
840                                 continue;
841                             }
842                             /* Copy the matching line and set the cursor position */
843                             set_current(current,history[searchpos]);
844                             current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
845                             break;
846                         }
847                     }
848                     if (!p && n) {
849                         /* No match, so don't add it */
850                         rchars--;
851                         rlen -= n;
852                         rbuf[rlen] = 0;
853                     }
854                 }
855                 if (c == ctrl('G') || c == ctrl('C')) {
856                     /* ctrl-g terminates the search with no effect */
857                     set_current(current, "");
858                     c = 0;
859                 }
860                 else if (c == ctrl('J')) {
861                     /* ctrl-j terminates the search leaving the buffer in place */
862                     c = 0;
863                 }
864                 /* Go process the char normally */
865                 refreshLine(current->prompt, current);
866                 goto process_char;
867             }
868             break;
869         case ctrl('T'):    /* ctrl-t */
870             if (current->pos > 0 && current->pos < current->chars) {
871                 c = get_char(current, current->pos);
872                 remove_char(current, current->pos);
873                 insert_char(current, current->pos - 1, c);
874                 refreshLine(current->prompt, current);
875             }
876             break;
877         case ctrl('V'):    /* ctrl-v */
878             if (has_room(current, 3)) {
879                 /* Insert the ^V first */
880                 if (insert_char(current, current->pos, c)) {
881                     refreshLine(current->prompt, current);
882                     /* Now wait for the next char. Can insert anything except \0 */
883                     c = fd_read(current->fd);
884
885                     /* Remove the ^V first */
886                     remove_char(current, current->pos - 1);
887                     if (c != -1) {
888                         /* Insert the actual char */
889                         insert_char(current, current->pos, c);
890                     }
891                     refreshLine(current->prompt, current);
892                 }
893             }
894             break;
895         case ctrl('B'):     /* ctrl-b */
896         case ctrl('F'):     /* ctrl-f */
897         case ctrl('P'):    /* ctrl-p */
898         case ctrl('N'):    /* ctrl-n */
899         case 27: {   /* escape sequence */
900             int dir = -1;
901             if (c == 27) {
902                 c = check_special(current->fd);
903             }
904             switch (c) {
905                 case ctrl('B'):
906                 case SPECIAL_LEFT:
907                     if (current->pos > 0) {
908                         current->pos--;
909                         refreshLine(current->prompt, current);
910                     }
911                     break;
912                 case ctrl('F'):
913                 case SPECIAL_RIGHT:
914                     if (current->pos < current->chars) {
915                         current->pos++;
916                         refreshLine(current->prompt, current);
917                     }
918                     break;
919                 case ctrl('P'):
920                 case SPECIAL_UP:
921                     dir = 1;
922                 case ctrl('N'):
923                 case SPECIAL_DOWN:
924                     if (history_len > 1) {
925                         /* Update the current history entry before to
926                          * overwrite it with tne next one. */
927                         free(history[history_len-1-history_index]);
928                         history[history_len-1-history_index] = strdup(current->buf);
929                         /* Show the new entry */
930                         history_index += dir;
931                         if (history_index < 0) {
932                             history_index = 0;
933                             break;
934                         } else if (history_index >= history_len) {
935                             history_index = history_len-1;
936                             break;
937                         }
938                         set_current(current, history[history_len-1-history_index]);
939                         refreshLine(current->prompt, current);
940                     }
941                     break;
942
943                 case SPECIAL_DELETE:
944                     if (remove_char(current, current->pos) == 1) {
945                         refreshLine(current->prompt, current);
946                     }
947                     break;
948                 case SPECIAL_HOME:
949                     current->pos = 0;
950                     refreshLine(current->prompt, current);
951                     break;
952                 case SPECIAL_END:
953                     current->pos = current->chars;
954                     refreshLine(current->prompt, current);
955                     break;
956             }
957             }
958             break;
959         default:
960             /* Only tab is allowed without ^V */
961             if (c == '\t' || c >= ' ') {
962                 if (insert_char(current, current->pos, c) == 1) {
963                     refreshLine(current->prompt, current);
964                 }
965             }
966             break;
967         case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
968             if (remove_chars(current, 0, current->pos)) {
969                 refreshLine(current->prompt, current);
970             }
971             break;
972         case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
973             if (remove_chars(current, current->pos, current->chars - current->pos)) {
974                 refreshLine(current->prompt, current);
975             }
976             break;
977         case ctrl('A'): /* Ctrl+a, go to the start of the line */
978             current->pos = 0;
979             refreshLine(current->prompt, current);
980             break;
981         case ctrl('E'): /* ctrl+e, go to the end of the line */
982             current->pos = current->chars;
983             refreshLine(current->prompt, current);
984             break;
985         case ctrl('L'): /* Ctrl+L, clear screen */
986             /* clear screen */
987             fd_printf(current->fd, "\x1b[H\x1b[2J");
988             /* Force recalc of window size for serial terminals */
989             current->cols = 0;
990             refreshLine(current->prompt, current);
991             break;
992         }
993     }
994     return current->len;
995 }
996
997 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
998     int fd = STDIN_FILENO;
999     int count;
1000
1001     if (buflen == 0) {
1002         errno = EINVAL;
1003         return -1;
1004     }
1005     if (!isatty(STDIN_FILENO)) {
1006         if (fgets(buf, buflen, stdin) == NULL) return -1;
1007         count = strlen(buf);
1008         if (count && buf[count-1] == '\n') {
1009             count--;
1010             buf[count] = '\0';
1011         }
1012     } else {
1013         struct current current;
1014
1015         if (enableRawMode(fd) == -1) return -1;
1016
1017         current.fd = fd;
1018         current.buf = buf;
1019         current.bufmax = buflen;
1020         current.len = 0;
1021         current.chars = 0;
1022         current.pos = 0;
1023         current.cols = 0;
1024         current.prompt = prompt;
1025
1026         count = linenoisePrompt(&current);
1027         disableRawMode(fd);
1028
1029         printf("\n");
1030     }
1031     return count;
1032 }
1033
1034 char *linenoise(const char *prompt) {
1035     char buf[LINENOISE_MAX_LINE];
1036     int count;
1037
1038     if (isUnsupportedTerm()) {
1039         size_t len;
1040
1041         printf("%s",prompt);
1042         fflush(stdout);
1043         if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
1044         len = strlen(buf);
1045         while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
1046             len--;
1047             buf[len] = '\0';
1048         }
1049         return strdup(buf);
1050     } else {
1051         count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
1052         if (count == -1) return NULL;
1053         return strdup(buf);
1054     }
1055 }
1056
1057 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1058 int linenoiseHistoryAdd(const char *line) {
1059     char *linecopy;
1060
1061     if (history_max_len == 0) return 0;
1062     if (history == NULL) {
1063         history = (char**)malloc(sizeof(char*)*history_max_len);
1064         if (history == NULL) return 0;
1065         memset(history,0,(sizeof(char*)*history_max_len));
1066     }
1067     linecopy = strdup(line);
1068     if (!linecopy) return 0;
1069     if (history_len == history_max_len) {
1070         free(history[0]);
1071         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1072         history_len--;
1073     }
1074     history[history_len] = linecopy;
1075     history_len++;
1076     return 1;
1077 }
1078
1079 int linenoiseHistorySetMaxLen(int len) {
1080     char **newHistory;
1081
1082     if (len < 1) return 0;
1083     if (history) {
1084         int tocopy = history_len;
1085
1086         newHistory = (char**)malloc(sizeof(char*)*len);
1087         if (newHistory == NULL) return 0;
1088         if (len < tocopy) tocopy = len;
1089         memcpy(newHistory,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
1090         free(history);
1091         history = newHistory;
1092     }
1093     history_max_len = len;
1094     if (history_len > history_max_len)
1095         history_len = history_max_len;
1096     return 1;
1097 }
1098
1099 /* Save the history in the specified file. On success 0 is returned
1100  * otherwise -1 is returned. */
1101 int linenoiseHistorySave(const char *filename) {
1102     FILE *fp = fopen(filename,"w");
1103     int j;
1104
1105     if (fp == NULL) return -1;
1106     for (j = 0; j < history_len; j++) {
1107         const char *str = history[j];
1108         /* Need to encode backslash, nl and cr */
1109         while (*str) {
1110             if (*str == '\\') {
1111                 fputs("\\\\", fp);
1112             }
1113             else if (*str == '\n') {
1114                 fputs("\\n", fp);
1115             }
1116             else if (*str == '\r') {
1117                 fputs("\\r", fp);
1118             }
1119             else {
1120                 fputc(*str, fp);
1121             }
1122             str++;
1123         }
1124         fputc('\n', fp);
1125     }
1126
1127     fclose(fp);
1128     return 0;
1129 }
1130
1131 /* Load the history from the specified file. If the file does not exist
1132  * zero is returned and no operation is performed.
1133  *
1134  * If the file exists and the operation succeeded 0 is returned, otherwise
1135  * on error -1 is returned. */
1136 int linenoiseHistoryLoad(const char *filename) {
1137     FILE *fp = fopen(filename,"r");
1138     char buf[LINENOISE_MAX_LINE];
1139
1140     if (fp == NULL) return -1;
1141
1142     while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1143         char *src, *dest;
1144
1145         /* Decode backslash escaped values */
1146         for (src = dest = buf; *src; src++) {
1147             char ch = *src;
1148
1149             if (ch == '\\') {
1150                 src++;
1151                 if (*src == 'n') {
1152                     ch = '\n';
1153                 }
1154                 else if (*src == 'r') {
1155                     ch = '\r';
1156                 } else {
1157                     ch = *src;
1158                 }
1159             }
1160             *dest++ = ch;
1161         }
1162         /* Remove trailing newline */
1163         if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1164             dest--;
1165         }
1166         *dest = 0;
1167
1168         linenoiseHistoryAdd(buf);
1169     }
1170     fclose(fp);
1171     return 0;
1172 }
1173
1174 /* Provide access to the history buffer.
1175  *
1176  * If 'len' is not NULL, the length is stored in *len.
1177  */
1178 char **linenoiseHistory(int *len) {
1179     if (len) {
1180         *len = history_len;
1181     }
1182     return history;
1183 }