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