]> git.lizzy.rs Git - linenoise.git/blob - linenoise.c
Minor compiler warning fixes
[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  * with three 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
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
130 static int isUnsupportedTerm(void) {
131     char *term = getenv("TERM");
132     int j;
133
134     if (term == NULL) return 0;
135     for (j = 0; unsupported_term[j]; j++)
136         if (!strcasecmp(term,unsupported_term[j])) return 1;
137     return 0;
138 }
139
140 static void freeHistory(void) {
141     if (history) {
142         int j;
143
144         for (j = 0; j < history_len; j++)
145             free(history[j]);
146         free(history);
147     }
148 }
149
150 static int enableRawMode(int fd) {
151     struct termios raw;
152
153     if (!isatty(STDIN_FILENO)) goto fatal;
154     if (!atexit_registered) {
155         atexit(linenoiseAtExit);
156         atexit_registered = 1;
157     }
158     if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
159
160     raw = orig_termios;  /* modify the original mode */
161     /* input modes: no break, no CR to NL, no parity check, no strip char,
162      * no start/stop output control. */
163     raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
164     /* output modes - disable post processing */
165     raw.c_oflag &= ~(OPOST);
166     /* control modes - set 8 bit chars */
167     raw.c_cflag |= (CS8);
168     /* local modes - choing off, canonical off, no extended functions,
169      * no signal chars (^Z,^C) */
170     raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
171     /* control chars - set return condition: min number of bytes and timer.
172      * We want read to return every single byte, without timeout. */
173     raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
174
175     /* put terminal in raw mode after flushing */
176     if (tcsetattr(fd,TCSADRAIN,&raw) < 0) goto fatal;
177     rawmode = 1;
178     return 0;
179
180 fatal:
181     errno = ENOTTY;
182     return -1;
183 }
184
185 static void disableRawMode(int fd) {
186     /* Don't even check the return value as it's too late. */
187     if (rawmode && tcsetattr(fd,TCSADRAIN,&orig_termios) != -1)
188         rawmode = 0;
189 }
190
191 /* At exit we'll try to fix the terminal to the initial conditions. */
192 static void linenoiseAtExit(void) {
193     disableRawMode(STDIN_FILENO);
194     freeHistory();
195 }
196
197 static int getColumns(void) {
198     struct winsize ws;
199
200     if (ioctl(1, TIOCGWINSZ, &ws) == -1) return 80;
201     return ws.ws_col;
202 }
203
204 /* Structure to contain the status of the current (being edited) line */
205 struct current {
206     int fd;     /* Terminal fd */
207     char *buf;  /* Current buffer. Always null terminated */
208     int bufmax; /* Size of the buffer, including space for the null termination */
209     int len;    /* Number of bytes in 'buf' */
210     int chars;  /* Number of chars in 'buf' (utf-8 chars) */
211     int pos;    /* Cursor position, measured in chars */
212     int cols;   /* Size of the window, in chars */
213 };
214
215 /* gcc/glibc insists that we care about the return code of write! */
216 #define IGNORE_RC(EXPR) ((EXPR) < 0 ? -1 : 0)
217
218 /* This is fd_printf() on some systems, but use a different
219  * name to avoid conflicts
220  */
221 static void fd_printf(int fd, const char *format, ...)
222 {
223     va_list args;
224     char buf[64];
225     int n;
226
227     va_start(args, format);
228     n = vsnprintf(buf, sizeof(buf), format, args);
229     va_end(args);
230     IGNORE_RC(write(fd, buf, n));
231 }
232
233 static int utf8_getchars(char *buf, int c)
234 {
235 #ifdef USE_UTF8
236     return utf8_fromunicode(buf, c);
237 #else
238     *buf = c;
239     return 1;
240 #endif
241 }
242
243 /**
244  * Returns the unicode character at the given offset,
245  * or -1 if none.
246  */
247 static int get_char(struct current *current, int pos)
248 {
249     if (pos >= 0 && pos < current->chars) {
250         int c;
251         int i = utf8_index(current->buf, pos);
252         (void)utf8_tounicode(current->buf + i, &c);
253         return c;
254     }
255     return -1;
256 }
257
258 static void refreshLine(const char *prompt, struct current *current) {
259     int plen;
260     int pchars;
261     int backup = 0;
262     int i;
263     const char *buf = current->buf;
264     int chars = current->chars;
265     int pos = current->pos;
266     int b;
267     int ch;
268     int n;
269
270     /* Should intercept SIGWINCH. For now, just get the size every time */
271     current->cols = getColumns();
272
273     plen = strlen(prompt);
274     pchars = utf8_strlen(prompt, plen);
275
276     /* Account for a line which is too long to fit in the window.
277      * Note that control chars require an extra column
278      */
279
280     /* How many cols are required to the left of 'pos'?
281      * The prompt, plus one extra for each control char
282      */
283     n = pchars + utf8_strlen(buf, current->len);
284     b = 0;
285     for (i = 0; i < pos; i++) {
286         b += utf8_tounicode(buf + b, &ch);
287         if (ch < ' ') {
288             n++;
289         }
290     }
291
292     /* If too many are need, strip chars off the front of 'buf'
293      * until it fits. Note that if the current char is a control character,
294      * we need one extra col.
295      */
296     if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
297         n++;
298     }
299
300     while (n >= current->cols) {
301         b = utf8_tounicode(buf, &ch);
302         if (ch < ' ') {
303             n--;
304         }
305         n--;
306         buf += b;
307         pos--;
308         chars--;
309     }
310
311     /* Cursor to left edge, then the prompt */
312     fd_printf(current->fd, "\x1b[0G");
313     IGNORE_RC(write(current->fd, prompt, plen));
314
315     /* Now the current buffer content */
316
317     /* Need special handling for control characters.
318      * If we hit 'cols', stop.
319      */
320     b = 0; /* unwritted bytes */
321     n = 0; /* How many control chars were written */
322     for (i = 0; i < chars; i++) {
323         int ch;
324         int w = utf8_tounicode(buf + b, &ch);
325         if (ch < ' ') {
326             n++;
327         }
328         if (pchars + i + n >= current->cols) {
329             break;
330         }
331         if (ch < ' ') {
332             /* A control character, so write the buffer so far */
333             IGNORE_RC(write(current->fd, buf, b));
334             buf += b + w;
335             b = 0;
336             fd_printf(current->fd, "\033[7m^%c\033[0m", ch + '@');
337             if (i < pos) {
338                 backup++;
339             }
340         }
341         else {
342             b += w;
343         }
344     }
345     IGNORE_RC(write(current->fd, buf, b));
346
347     /* Erase to right, move cursor to original position */
348     fd_printf(current->fd, "\x1b[0K" "\x1b[0G\x1b[%dC", pos + pchars + backup);
349 }
350
351 static void set_current(struct current *current, const char *str)
352 {
353     strncpy(current->buf, str, current->bufmax);
354     current->buf[current->bufmax - 1] = 0;
355     current->len = strlen(current->buf);
356     current->pos = current->chars = utf8_strlen(current->buf, current->len);
357 }
358
359 static int has_room(struct current *current, int bytes)
360 {
361     return current->len + bytes < current->bufmax - 1;
362 }
363
364 static int remove_char(struct current *current, int pos)
365 {
366     if (pos >= 0 && pos < current->chars) {
367         int p1, p2;
368         p1 = utf8_index(current->buf, pos);
369         p2 = p1 + utf8_index(current->buf + p1, 1);
370         /* Move the null char too */
371         memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
372         current->len -= (p2 - p1);
373         current->chars--;
374         if (current->pos > pos) {
375             current->pos--;
376         }
377         return 1;
378     }
379     return 0;
380 }
381
382 static int insert_char(struct current *current, int pos, int ch)
383 {
384     char buf[3];
385     int n = utf8_getchars(buf, ch);
386
387     if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
388         int p1, p2;
389         p1 = utf8_index(current->buf, pos);
390         p2 = p1 + n;
391         memmove(current->buf + p2, current->buf + p1, current->len - p1);
392         memcpy(current->buf + p1, buf, n);
393         current->len += n;
394         current->chars++;
395         if (current->pos >= pos) {
396             current->pos++;
397         }
398         return 1;
399     }
400     return 0;
401 }
402
403 #ifndef NO_COMPLETION
404 static linenoiseCompletionCallback *completionCallback = NULL;
405
406 static void beep() {
407     fprintf(stderr, "\x7");
408     fflush(stderr);
409 }
410
411 static void freeCompletions(linenoiseCompletions *lc) {
412     size_t i;
413     for (i = 0; i < lc->len; i++)
414         free(lc->cvec[i]);
415     free(lc->cvec);
416 }
417
418 static int completeLine(const char *prompt, struct current *current) {
419     linenoiseCompletions lc = { 0, NULL };
420     int c = 0;
421
422     completionCallback(current->buf,&lc);
423     if (lc.len == 0) {
424         beep();
425     } else {
426         size_t stop = 0, i = 0;
427
428         while(!stop) {
429             /* Show completion or original buffer */
430             if (i < lc.len) {
431                 struct current tmp = *current;
432                 tmp.buf = lc.cvec[i];
433                 tmp.pos = tmp.len = strlen(tmp.buf);
434                 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
435                 refreshLine(prompt, &tmp);
436             } else {
437                 refreshLine(prompt, current);
438             }
439
440             c = fd_read(current->fd);
441             if (c < 0) {
442                 break;
443             }
444
445             switch(c) {
446                 case '\t': /* tab */
447                     i = (i+1) % (lc.len+1);
448                     if (i == lc.len) beep();
449                     break;
450                 case 27: /* escape */
451                     /* Re-show original buffer */
452                     if (i < lc.len) {
453                         refreshLine(prompt, current);
454                     }
455                     stop = 1;
456                     break;
457                 default:
458                     /* Update buffer and return */
459                     if (i < lc.len) {
460                         set_current(current,lc.cvec[i]);
461                     }
462                     stop = 1;
463                     break;
464             }
465         }
466     }
467
468     freeCompletions(&lc);
469     return c; /* Return last read character */
470 }
471
472 /* Register a callback function to be called for tab-completion. */
473 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
474     completionCallback = fn;
475 }
476
477 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
478     lc->cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
479     lc->cvec[lc->len++] = strdup(str);
480 }
481
482 #endif
483
484 /* XXX: Optimise this later */
485 static int remove_chars(struct current *current, int pos, int n)
486 {
487     int removed = 0;
488     while (n-- && remove_char(current, pos)) {
489         removed++;
490     }
491     return removed;
492 }
493
494 /**
495  * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
496  *
497  * A timeout of -1 means to wait forever.
498  *
499  * Returns -1 if no char is received within the time or an error occurs.
500  */
501 static int fd_read_char(int fd, int timeout)
502 {
503     struct pollfd p;
504     unsigned char c;
505
506     p.fd = fd;
507     p.events = POLLIN;
508
509     if (poll(&p, 1, timeout) == 0) {
510         /* timeout */
511         return -1;
512     }
513     if (read(fd, &c, 1) != 1) {
514         return -1;
515     }
516     return c;
517 }
518
519 /**
520  * Reads a complete utf-8 character
521  * and returns the unicode value, or -1 on error.
522  */
523 static int fd_read(int fd)
524 {
525 #ifdef USE_UTF8
526     char buf[4];
527     int n;
528     int i;
529     int c;
530
531     if (read(fd, &buf[0], 1) != 1) {
532         return -1;
533     }
534     n = utf8_charlen(buf[0]);
535     if (n < 1 || n > 3) {
536         return -1;
537     }
538     for (i = 1; i < n; i++) {
539         if (read(fd, &buf[i], 1) != 1) {
540             return -1;
541         }
542     }
543     buf[n] = 0;
544     /* decode and return the character */
545     utf8_tounicode(buf, &c);
546     return c;
547 #else
548     return fd_read_char(fd, -1);
549 #endif
550 }
551
552 /* Use -ve numbers here to co-exist with normal unicode chars */
553 enum {
554     SPECIAL_NONE,
555     SPECIAL_UP = -20,
556     SPECIAL_DOWN = -21,
557     SPECIAL_LEFT = -22,
558     SPECIAL_RIGHT = -23,
559     SPECIAL_DELETE = -24,
560 };
561
562 /**
563  * If escape (27) was received, reads subsequent
564  * chars to determine if this is a known special key.
565  *
566  * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
567  *
568  * If no additional char is received within a short time,
569  * 27 is returned.
570  */
571 static int check_special(int fd)
572 {
573     int c = fd_read_char(fd, 50);
574     int c2;
575
576     if (c < 0) {
577         return 27;
578     }
579
580     c2 = fd_read_char(fd, 50);
581     if (c2 < 0) {
582         return c2;
583     }
584     if (c == '[' || c == 'O') {
585         /* Potential arrow key */
586         switch (c2) {
587             case 'A':
588                 return SPECIAL_UP;
589             case 'B':
590                 return SPECIAL_DOWN;
591             case 'C':
592                 return SPECIAL_RIGHT;
593             case 'D':
594                 return SPECIAL_LEFT;
595         }
596     }
597     if (c == '[' && c2 >= '1' && c2 <= '6') {
598         /* extended escape */
599         int c3 = fd_read_char(fd, 50);
600         if (c2 == '3' && c3 == '~') {
601             /* delete char under cursor */
602             return SPECIAL_DELETE;
603         }
604         while (c3 != -1 && c3 != '~') {
605             /* .e.g \e[12~ or '\e[11;2~   discard the complete sequence */
606             c3 = fd_read_char(fd, 50);
607         }
608     }
609
610     return SPECIAL_NONE;
611 }
612
613 #define ctrl(C) ((C) - '@')
614
615 static int linenoisePrompt(const char *prompt, struct current *current) {
616     int history_index = 0;
617
618     /* The latest history entry is always our current buffer, that
619      * initially is just an empty string. */
620     linenoiseHistoryAdd("");
621
622     set_current(current, "");
623     refreshLine(prompt, current);
624
625     while(1) {
626         int c = fd_read(current->fd);
627
628 #ifndef NO_COMPLETION
629         /* Only autocomplete when the callback is set. It returns < 0 when
630          * there was an error reading from fd. Otherwise it will return the
631          * character that should be handled next. */
632         if (c == 9 && completionCallback != NULL) {
633             c = completeLine(prompt, current);
634             /* Return on errors */
635             if (c < 0) return current->len;
636             /* Read next character when 0 */
637             if (c == 0) continue;
638         }
639 #endif
640
641 process_char:
642         if (c == -1) return current->len;
643         switch(c) {
644         case '\r':    /* enter */
645             history_len--;
646             free(history[history_len]);
647             return current->len;
648         case ctrl('C'):     /* ctrl-c */
649             errno = EAGAIN;
650             return -1;
651         case 127:   /* backspace */
652         case ctrl('H'):
653             if (remove_char(current, current->pos - 1)) {
654                 refreshLine(prompt, current);
655             }
656             break;
657         case ctrl('D'):     /* ctrl-d */
658             if (current->len == 0) {
659                 /* Empty line, so EOF */
660                 history_len--;
661                 free(history[history_len]);
662                 return -1;
663             }
664             /* Otherwise delete char to right of cursor */
665             if (remove_char(current, current->pos)) {
666                 refreshLine(prompt, current);
667             }
668             break;
669         case ctrl('W'):    /* ctrl-w */
670             /* eat any spaces on the left */
671             {
672                 int pos = current->pos;
673                 while (pos > 0 && get_char(current, pos - 1) == ' ') {
674                     pos--;
675                 }
676
677                 /* now eat any non-spaces on the left */
678                 while (pos > 0 && get_char(current, pos - 1) != ' ') {
679                     pos--;
680                 }
681
682                 if (remove_chars(current, pos, current->pos - pos)) {
683                     refreshLine(prompt, current);
684                 }
685             }
686             break;
687         case ctrl('R'):    /* ctrl-r */
688             {
689                 /* Display the reverse-i-search prompt and process chars */
690                 char rbuf[50];
691                 char rprompt[80];
692                 int rchars = 0;
693                 int rlen = 0;
694                 int searchpos = history_len - 1;
695
696                 rbuf[0] = 0;
697                 while (1) {
698                     int n = 0;
699                     const char *p = NULL;
700                     int skipsame = 0;
701                     int searchdir = -1;
702
703                     snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
704                     refreshLine(rprompt, current);
705                     c = fd_read(current->fd);
706                     if (c == ctrl('H') || c == 127) {
707                         if (rchars) {
708                             int p = utf8_index(rbuf, --rchars);
709                             rbuf[p] = 0;
710                             rlen = strlen(rbuf);
711                         }
712                         continue;
713                     }
714                     if (c == 27) {
715                         c = check_special(current->fd);
716                     }
717                     if (c == ctrl('P') || c == SPECIAL_UP) {
718                         /* Search for the previous (earlier) match */
719                         if (searchpos > 0) {
720                             searchpos--;
721                         }
722                         skipsame = 1;
723                     }
724                     else if (c == ctrl('N') || c == SPECIAL_DOWN) {
725                         /* Search for the next (later) match */
726                         if (searchpos < history_len) {
727                             searchpos++;
728                         }
729                         searchdir = 1;
730                         skipsame = 1;
731                     }
732                     else if (c >= ' ') {
733                         if (rlen >= (int)sizeof(rbuf) + 3) {
734                             continue;
735                         }
736
737                         n = utf8_getchars(rbuf + rlen, c);
738                         rlen += n;
739                         rchars++;
740                         rbuf[rlen] = 0;
741
742                         /* Adding a new char resets the search location */
743                         searchpos = history_len - 1;
744                     }
745                     else {
746                         /* Exit from incremental search mode */
747                         break;
748                     }
749
750                     /* Now search through the history for a match */
751                     for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
752                         p = strstr(history[searchpos], rbuf);
753                         if (p) {
754                             /* Found a match */
755                             if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
756                                 /* But it is identical, so skip it */
757                                 continue;
758                             }
759                             /* Copy the matching line and set the cursor position */
760                             set_current(current,history[searchpos]);
761                             current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
762                             break;
763                         }
764                     }
765                     if (!p && n) {
766                         /* No match, so don't add it */
767                         rchars--;
768                         rlen -= n;
769                         rbuf[rlen] = 0;
770                     }
771                 }
772                 if (c == ctrl('G') || c == ctrl('C')) {
773                     /* ctrl-g terminates the search with no effect */
774                     set_current(current, "");
775                     c = 0;
776                 }
777                 else if (c == ctrl('J')) {
778                     /* ctrl-j terminates the search leaving the buffer in place */
779                     c = 0;
780                 }
781                 /* Go process the char normally */
782                 refreshLine(prompt, current);
783                 goto process_char;
784             }
785             break;
786         case ctrl('T'):    /* ctrl-t */
787             if (current->pos > 0 && current->pos < current->chars) {
788                 c = get_char(current, current->pos);
789                 remove_char(current, current->pos);
790                 insert_char(current, current->pos - 1, c);
791                 refreshLine(prompt, current);
792             }
793             break;
794         case ctrl('V'):    /* ctrl-v */
795             if (has_room(current, 3)) {
796                 /* Insert the ^V first */
797                 if (insert_char(current, current->pos, c)) {
798                     refreshLine(prompt, current);
799                     /* Now wait for the next char. Can insert anything except \0 */
800                     c = fd_read(current->fd);
801
802                     /* Remove the ^V first */
803                     remove_char(current, current->pos - 1);
804                     if (c != -1) {
805                         /* Insert the actual char */
806                         insert_char(current, current->pos, c);
807                     }
808                     refreshLine(prompt, current);
809                 }
810             }
811             break;
812         case ctrl('B'):     /* ctrl-b */
813         case ctrl('F'):     /* ctrl-f */
814         case ctrl('P'):    /* ctrl-p */
815         case ctrl('N'):    /* ctrl-n */
816         case 27: {   /* escape sequence */
817             int dir = -1;
818             if (c == 27) {
819                 c = check_special(current->fd);
820             }
821             switch (c) {
822                 case ctrl('B'):
823                 case SPECIAL_LEFT:
824                     if (current->pos > 0) {
825                         current->pos--;
826                         refreshLine(prompt, current);
827                     }
828                     break;
829                 case ctrl('F'):
830                 case SPECIAL_RIGHT:
831                     if (current->pos < current->chars) {
832                         current->pos++;
833                         refreshLine(prompt, current);
834                     }
835                     break;
836                 case ctrl('P'):
837                 case SPECIAL_UP:
838                     dir = 1;
839                 case ctrl('N'):
840                 case SPECIAL_DOWN:
841                     if (history_len > 1) {
842                         /* Update the current history entry before to
843                          * overwrite it with tne next one. */
844                         free(history[history_len-1-history_index]);
845                         history[history_len-1-history_index] = strdup(current->buf);
846                         /* Show the new entry */
847                         history_index += dir;
848                         if (history_index < 0) {
849                             history_index = 0;
850                             break;
851                         } else if (history_index >= history_len) {
852                             history_index = history_len-1;
853                             break;
854                         }
855                         set_current(current, history[history_len-1-history_index]);
856                         refreshLine(prompt, current);
857                     }
858                     break;
859
860                 case SPECIAL_DELETE:
861                     if (remove_char(current, current->pos)) {
862                         refreshLine(prompt, current);
863                     }
864                     break;
865             }
866             }
867             break;
868         default:
869             /* Only tab is allowed without ^V */
870             if (c == '\t' || c >= ' ') {
871                 if (insert_char(current, current->pos, c)) {
872                     refreshLine(prompt, current);
873                 }
874             }
875             break;
876         case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
877             if (remove_chars(current, 0, current->pos)) {
878                 refreshLine(prompt, current);
879             }
880             break;
881         case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
882             if (remove_chars(current, current->pos, current->chars - current->pos)) {
883                 refreshLine(prompt, current);
884             }
885             break;
886         case ctrl('A'): /* Ctrl+a, go to the start of the line */
887             current->pos = 0;
888             refreshLine(prompt, current);
889             break;
890         case ctrl('E'): /* ctrl+e, go to the end of the line */
891             current->pos = current->chars;
892             refreshLine(prompt, current);
893             break;
894         case ctrl('L'): /* Ctrl+L, clear screen */
895             /* clear screen */
896             fd_printf(current->fd, "\x1b[H\x1b[2J");
897             refreshLine(prompt, current);
898             break;
899         }
900     }
901     return current->len;
902 }
903
904 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
905     int fd = STDIN_FILENO;
906     int count;
907
908     if (buflen == 0) {
909         errno = EINVAL;
910         return -1;
911     }
912     if (!isatty(STDIN_FILENO)) {
913         if (fgets(buf, buflen, stdin) == NULL) return -1;
914         count = strlen(buf);
915         if (count && buf[count-1] == '\n') {
916             count--;
917             buf[count] = '\0';
918         }
919     } else {
920         struct current current;
921
922         if (enableRawMode(fd) == -1) return -1;
923
924         current.fd = fd;
925         current.buf = buf;
926         current.bufmax = buflen;
927         current.len = 0;
928         current.chars = 0;
929         current.pos = 0;
930         current.cols = 0;
931
932         count = linenoisePrompt(prompt, &current);
933         disableRawMode(fd);
934
935         printf("\n");
936     }
937     return count;
938 }
939
940 char *linenoise(const char *prompt) {
941     char buf[LINENOISE_MAX_LINE];
942     int count;
943
944     if (isUnsupportedTerm()) {
945         size_t len;
946
947         printf("%s",prompt);
948         fflush(stdout);
949         if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
950         len = strlen(buf);
951         while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
952             len--;
953             buf[len] = '\0';
954         }
955         return strdup(buf);
956     } else {
957         count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
958         if (count == -1) return NULL;
959         return strdup(buf);
960     }
961 }
962
963 /* Using a circular buffer is smarter, but a bit more complex to handle. */
964 int linenoiseHistoryAdd(const char *line) {
965     char *linecopy;
966
967     if (history_max_len == 0) return 0;
968     if (history == NULL) {
969         history = malloc(sizeof(char*)*history_max_len);
970         if (history == NULL) return 0;
971         memset(history,0,(sizeof(char*)*history_max_len));
972     }
973     linecopy = strdup(line);
974     if (!linecopy) return 0;
975     if (history_len == history_max_len) {
976         free(history[0]);
977         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
978         history_len--;
979     }
980     history[history_len] = linecopy;
981     history_len++;
982     return 1;
983 }
984
985 int linenoiseHistorySetMaxLen(int len) {
986     char **new;
987
988     if (len < 1) return 0;
989     if (history) {
990         int tocopy = history_len;
991
992         new = malloc(sizeof(char*)*len);
993         if (new == NULL) return 0;
994         if (len < tocopy) tocopy = len;
995         memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
996         free(history);
997         history = new;
998     }
999     history_max_len = len;
1000     if (history_len > history_max_len)
1001         history_len = history_max_len;
1002     return 1;
1003 }
1004
1005 /* Save the history in the specified file. On success 0 is returned
1006  * otherwise -1 is returned. */
1007 int linenoiseHistorySave(char *filename) {
1008     FILE *fp = fopen(filename,"w");
1009     int j;
1010
1011     if (fp == NULL) return -1;
1012     for (j = 0; j < history_len; j++) {
1013         const char *str = history[j];
1014         /* Need to encode backslash, nl and cr */
1015         while (*str) {
1016             if (*str == '\\') {
1017                 fputs("\\\\", fp);
1018             }
1019             else if (*str == '\n') {
1020                 fputs("\\n", fp);
1021             }
1022             else if (*str == '\r') {
1023                 fputs("\\r", fp);
1024             }
1025             else {
1026                 fputc(*str, fp);
1027             }
1028             str++;
1029         }
1030         fputc('\n', fp);
1031     }
1032
1033     fclose(fp);
1034     return 0;
1035 }
1036
1037 /* Load the history from the specified file. If the file does not exist
1038  * zero is returned and no operation is performed.
1039  *
1040  * If the file exists and the operation succeeded 0 is returned, otherwise
1041  * on error -1 is returned. */
1042 int linenoiseHistoryLoad(char *filename) {
1043     FILE *fp = fopen(filename,"r");
1044     char buf[LINENOISE_MAX_LINE];
1045
1046     if (fp == NULL) return -1;
1047
1048     while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1049         char *src, *dest;
1050
1051         /* Decode backslash escaped values */
1052         for (src = dest = buf; *src; src++) {
1053             char ch = *src;
1054
1055             if (ch == '\\') {
1056                 src++;
1057                 if (*src == 'n') {
1058                     ch = '\n';
1059                 }
1060                 else if (*src == 'r') {
1061                     ch = '\r';
1062                 } else {
1063                     ch = *src;
1064                 }
1065             }
1066             *dest++ = ch;
1067         }
1068         /* Remove trailing newline */
1069         if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1070             dest--;
1071         }
1072         *dest = 0;
1073
1074         linenoiseHistoryAdd(buf);
1075     }
1076     fclose(fp);
1077     return 0;
1078 }
1079
1080 /* Provide access to the history buffer.
1081  *
1082  * If 'len' is not NULL, the length is stored in *len.
1083  */
1084 char **linenoiseHistory(int *len) {
1085     if (len) {
1086         *len = history_len;
1087     }
1088     return history;
1089 }