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