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