]> git.lizzy.rs Git - linenoise.git/blob - linenoise.c
Support more HOME/END escape sequences
[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 <= '8') {
457         /* extended escape */
458         c = fd_read_char(fd, 50);
459         if (c == '~') {
460             switch (c2) {
461                 case '3':
462                     return SPECIAL_DELETE;
463                 case '7':
464                     return SPECIAL_HOME;
465                 case '8':
466                     return SPECIAL_END;
467             }
468         }
469         while (c != -1 && c != '~') {
470             /* .e.g \e[12~ or '\e[11;2~   discard the complete sequence */
471             c = fd_read_char(fd, 50);
472         }
473     }
474
475     return SPECIAL_NONE;
476 }
477 #elif defined(USE_WINCONSOLE)
478
479 static DWORD orig_consolemode = 0;
480
481 static int enableRawMode(struct current *current) {
482     DWORD n;
483     INPUT_RECORD irec;
484
485     current->outh = GetStdHandle(STD_OUTPUT_HANDLE);
486     current->inh = GetStdHandle(STD_INPUT_HANDLE);
487
488     if (!PeekConsoleInput(current->inh, &irec, 1, &n)) {
489         return -1;
490     }
491     if (getWindowSize(current) != 0) {
492         return -1;
493     }
494     if (GetConsoleMode(current->inh, &orig_consolemode)) {
495         SetConsoleMode(current->inh, ENABLE_PROCESSED_INPUT);
496     }
497     return 0;
498 }
499
500 static void disableRawMode(struct current *current)
501 {
502     SetConsoleMode(current->inh, orig_consolemode);
503 }
504
505 static void clearScreen(struct current *current)
506 {
507     COORD topleft = { 0, 0 };
508     DWORD n;
509
510     FillConsoleOutputCharacter(current->outh, ' ',
511         current->cols * current->rows, topleft, &n);
512     FillConsoleOutputAttribute(current->outh,
513         FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN,
514         current->cols * current->rows, topleft, &n);
515     SetConsoleCursorPosition(current->outh, topleft);
516 }
517
518 static void cursorToLeft(struct current *current)
519 {
520     COORD pos = { 0, current->y };
521     DWORD n;
522
523     FillConsoleOutputAttribute(current->outh,
524         FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, current->cols, pos, &n);
525     current->x = 0;
526 }
527
528 static int outputChars(struct current *current, const char *buf, int len)
529 {
530     COORD pos = { current->x, current->y };
531     WriteConsoleOutputCharacter(current->outh, buf, len, pos, 0);
532     current->x += len;
533     return 0;
534 }
535
536 static void outputControlChar(struct current *current, char ch)
537 {
538     COORD pos = { current->x, current->y };
539     DWORD n;
540
541     FillConsoleOutputAttribute(current->outh, BACKGROUND_INTENSITY, 2, pos, &n);
542     outputChars(current, "^", 1);
543     outputChars(current, &ch, 1);
544 }
545
546 static void eraseEol(struct current *current)
547 {
548     COORD pos = { current->x, current->y };
549     DWORD n;
550
551     FillConsoleOutputCharacter(current->outh, ' ', current->cols - current->x, pos, &n);
552 }
553
554 static void setCursorPos(struct current *current, int x)
555 {
556     COORD pos = { x, current->y };
557
558     SetConsoleCursorPosition(current->outh, pos);
559     current->x = x;
560 }
561
562 static int fd_read(struct current *current)
563 {
564     while (1) {
565         INPUT_RECORD irec;
566         DWORD n;
567         if (WaitForSingleObject(current->inh, INFINITE) != WAIT_OBJECT_0) {
568             break;
569         }
570         if (!ReadConsoleInput (current->inh, &irec, 1, &n)) {
571             break;
572         }
573         if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown) {
574             KEY_EVENT_RECORD *k = &irec.Event.KeyEvent;
575             if (k->dwControlKeyState & ENHANCED_KEY) {
576                 switch (k->wVirtualKeyCode) {
577                  case VK_LEFT:
578                     return SPECIAL_LEFT;
579                  case VK_RIGHT:
580                     return SPECIAL_RIGHT;
581                  case VK_UP:
582                     return SPECIAL_UP;
583                  case VK_DOWN:
584                     return SPECIAL_DOWN;
585                  case VK_DELETE:
586                     return SPECIAL_DELETE;
587                  case VK_HOME:
588                     return SPECIAL_HOME;
589                  case VK_END:
590                     return SPECIAL_END;
591                 }
592             }
593             /* Note that control characters are already translated in AsciiChar */
594             else {
595 #ifdef USE_UTF8
596                 return k->uChar.UnicodeChar;
597 #else
598                 return k->uChar.AsciiChar;
599 #endif
600             }
601         }
602     }
603     return -1;
604 }
605
606 static int getWindowSize(struct current *current)
607 {
608     CONSOLE_SCREEN_BUFFER_INFO info;
609     if (!GetConsoleScreenBufferInfo(current->outh, &info)) {
610         return -1;
611     }
612     current->cols = info.dwSize.X;
613     current->rows = info.dwSize.Y;
614     if (current->cols <= 0 || current->rows <= 0) {
615         current->cols = 80;
616         return -1;
617     }
618     current->y = info.dwCursorPosition.Y;
619     current->x = info.dwCursorPosition.X;
620     return 0;
621 }
622 #endif
623
624 static int utf8_getchars(char *buf, int c)
625 {
626 #ifdef USE_UTF8
627     return utf8_fromunicode(buf, c);
628 #else
629     *buf = c;
630     return 1;
631 #endif
632 }
633
634 /**
635  * Returns the unicode character at the given offset,
636  * or -1 if none.
637  */
638 static int get_char(struct current *current, int pos)
639 {
640     if (pos >= 0 && pos < current->chars) {
641         int c;
642         int i = utf8_index(current->buf, pos);
643         (void)utf8_tounicode(current->buf + i, &c);
644         return c;
645     }
646     return -1;
647 }
648
649 static void refreshLine(const char *prompt, struct current *current)
650 {
651     int plen;
652     int pchars;
653     int backup = 0;
654     int i;
655     const char *buf = current->buf;
656     int chars = current->chars;
657     int pos = current->pos;
658     int b;
659     int ch;
660     int n;
661
662     /* Should intercept SIGWINCH. For now, just get the size every time */
663     getWindowSize(current);
664
665     plen = strlen(prompt);
666     pchars = utf8_strlen(prompt, plen);
667
668     /* Account for a line which is too long to fit in the window.
669      * Note that control chars require an extra column
670      */
671
672     /* How many cols are required to the left of 'pos'?
673      * The prompt, plus one extra for each control char
674      */
675     n = pchars + utf8_strlen(buf, current->len);
676     b = 0;
677     for (i = 0; i < pos; i++) {
678         b += utf8_tounicode(buf + b, &ch);
679         if (ch < ' ') {
680             n++;
681         }
682     }
683
684     /* If too many are need, strip chars off the front of 'buf'
685      * until it fits. Note that if the current char is a control character,
686      * we need one extra col.
687      */
688     if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
689         n++;
690     }
691
692     while (n >= current->cols) {
693         b = utf8_tounicode(buf, &ch);
694         if (ch < ' ') {
695             n--;
696         }
697         n--;
698         buf += b;
699         pos--;
700         chars--;
701     }
702
703     /* Cursor to left edge, then the prompt */
704     cursorToLeft(current);
705     outputChars(current, prompt, plen);
706
707     /* Now the current buffer content */
708
709     /* Need special handling for control characters.
710      * If we hit 'cols', stop.
711      */
712     b = 0; /* unwritted bytes */
713     n = 0; /* How many control chars were written */
714     for (i = 0; i < chars; i++) {
715         int ch;
716         int w = utf8_tounicode(buf + b, &ch);
717         if (ch < ' ') {
718             n++;
719         }
720         if (pchars + i + n >= current->cols) {
721             break;
722         }
723         if (ch < ' ') {
724             /* A control character, so write the buffer so far */
725             outputChars(current, buf, b);
726             buf += b + w;
727             b = 0;
728             outputControlChar(current, ch + '@');
729             if (i < pos) {
730                 backup++;
731             }
732         }
733         else {
734             b += w;
735         }
736     }
737     outputChars(current, buf, b);
738
739     /* Erase to right, move cursor to original position */
740     eraseEol(current);
741     setCursorPos(current, pos + pchars + backup);
742 }
743
744 static void set_current(struct current *current, const char *str)
745 {
746     strncpy(current->buf, str, current->bufmax);
747     current->buf[current->bufmax - 1] = 0;
748     current->len = strlen(current->buf);
749     current->pos = current->chars = utf8_strlen(current->buf, current->len);
750 }
751
752 static int has_room(struct current *current, int bytes)
753 {
754     return current->len + bytes < current->bufmax - 1;
755 }
756
757 /**
758  * Removes the char at 'pos'.
759  *
760  * Returns 1 if the line needs to be refreshed, 2 if not
761  * and 0 if nothing was removed
762  */
763 static int remove_char(struct current *current, int pos)
764 {
765     if (pos >= 0 && pos < current->chars) {
766         int p1, p2;
767         int ret = 1;
768         p1 = utf8_index(current->buf, pos);
769         p2 = p1 + utf8_index(current->buf + p1, 1);
770
771 #ifdef USE_TERMIOS
772         /* optimise remove char in the case of removing the last char */
773         if (current->pos == pos + 1 && current->pos == current->chars) {
774             if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
775                 ret = 2;
776                 fd_printf(current->fd, "\b \b");
777             }
778         }
779 #endif
780
781         /* Move the null char too */
782         memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
783         current->len -= (p2 - p1);
784         current->chars--;
785
786         if (current->pos > pos) {
787             current->pos--;
788         }
789         return ret;
790     }
791     return 0;
792 }
793
794 /**
795  * Insert 'ch' at position 'pos'
796  *
797  * Returns 1 if the line needs to be refreshed, 2 if not
798  * and 0 if nothing was inserted (no room)
799  */
800 static int insert_char(struct current *current, int pos, int ch)
801 {
802     char buf[3];
803     int n = utf8_getchars(buf, ch);
804
805     if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
806         int p1, p2;
807         int ret = 1;
808         p1 = utf8_index(current->buf, pos);
809         p2 = p1 + n;
810
811 #ifdef USE_TERMIOS
812         /* optimise the case where adding a single char to the end and no scrolling is needed */
813         if (current->pos == pos && current->chars == pos) {
814             if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
815                 IGNORE_RC(write(current->fd, buf, n));
816                 ret = 2;
817             }
818         }
819 #endif
820
821         memmove(current->buf + p2, current->buf + p1, current->len - p1);
822         memcpy(current->buf + p1, buf, n);
823         current->len += n;
824
825         current->chars++;
826         if (current->pos >= pos) {
827             current->pos++;
828         }
829         return ret;
830     }
831     return 0;
832 }
833
834 /**
835  * Returns 0 if no chars were removed or non-zero otherwise.
836  */
837 static int remove_chars(struct current *current, int pos, int n)
838 {
839     int removed = 0;
840     while (n-- && remove_char(current, pos)) {
841         removed++;
842     }
843     return removed;
844 }
845
846 #ifndef NO_COMPLETION
847 static linenoiseCompletionCallback *completionCallback = NULL;
848
849 static void beep() {
850 #ifdef USE_TERMIOS
851     fprintf(stderr, "\x7");
852     fflush(stderr);
853 #endif
854 }
855
856 static void freeCompletions(linenoiseCompletions *lc) {
857     size_t i;
858     for (i = 0; i < lc->len; i++)
859         free(lc->cvec[i]);
860     free(lc->cvec);
861 }
862
863 static int completeLine(struct current *current) {
864     linenoiseCompletions lc = { 0, NULL };
865     int c = 0;
866
867     completionCallback(current->buf,&lc);
868     if (lc.len == 0) {
869         beep();
870     } else {
871         size_t stop = 0, i = 0;
872
873         while(!stop) {
874             /* Show completion or original buffer */
875             if (i < lc.len) {
876                 struct current tmp = *current;
877                 tmp.buf = lc.cvec[i];
878                 tmp.pos = tmp.len = strlen(tmp.buf);
879                 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
880                 refreshLine(current->prompt, &tmp);
881             } else {
882                 refreshLine(current->prompt, current);
883             }
884
885             c = fd_read(current);
886             if (c == -1) {
887                 break;
888             }
889
890             switch(c) {
891                 case '\t': /* tab */
892                     i = (i+1) % (lc.len+1);
893                     if (i == lc.len) beep();
894                     break;
895                 case 27: /* escape */
896                     /* Re-show original buffer */
897                     if (i < lc.len) {
898                         refreshLine(current->prompt, current);
899                     }
900                     stop = 1;
901                     break;
902                 default:
903                     /* Update buffer and return */
904                     if (i < lc.len) {
905                         set_current(current,lc.cvec[i]);
906                     }
907                     stop = 1;
908                     break;
909             }
910         }
911     }
912
913     freeCompletions(&lc);
914     return c; /* Return last read character */
915 }
916
917 /* Register a callback function to be called for tab-completion. */
918 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
919     completionCallback = fn;
920 }
921
922 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
923     lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
924     lc->cvec[lc->len++] = strdup(str);
925 }
926
927 #endif
928
929 static int linenoisePrompt(struct current *current) {
930     int history_index = 0;
931
932     /* The latest history entry is always our current buffer, that
933      * initially is just an empty string. */
934     linenoiseHistoryAdd("");
935
936     set_current(current, "");
937     refreshLine(current->prompt, current);
938
939     while(1) {
940         int dir = -1;
941         int c = fd_read(current);
942
943 #ifndef NO_COMPLETION
944         /* Only autocomplete when the callback is set. It returns < 0 when
945          * there was an error reading from fd. Otherwise it will return the
946          * character that should be handled next. */
947         if (c == 9 && completionCallback != NULL) {
948             c = completeLine(current);
949             /* Return on errors */
950             if (c < 0) return current->len;
951             /* Read next character when 0 */
952             if (c == 0) continue;
953         }
954 #endif
955
956 process_char:
957         if (c == -1) return current->len;
958 #ifdef USE_TERMIOS
959         if (c == 27) {   /* escape sequence */
960             c = check_special(current->fd);
961         }
962 #endif
963         switch(c) {
964         case '\r':    /* enter */
965             history_len--;
966             free(history[history_len]);
967             return current->len;
968         case ctrl('C'):     /* ctrl-c */
969             errno = EAGAIN;
970             return -1;
971         case 127:   /* backspace */
972         case ctrl('H'):
973             if (remove_char(current, current->pos - 1) == 1) {
974                 refreshLine(current->prompt, current);
975             }
976             break;
977         case ctrl('D'):     /* ctrl-d */
978             if (current->len == 0) {
979                 /* Empty line, so EOF */
980                 history_len--;
981                 free(history[history_len]);
982                 return -1;
983             }
984             /* Otherwise delete char to right of cursor */
985             if (remove_char(current, current->pos)) {
986                 refreshLine(current->prompt, current);
987             }
988             break;
989         case ctrl('W'):    /* ctrl-w */
990             /* eat any spaces on the left */
991             {
992                 int pos = current->pos;
993                 while (pos > 0 && get_char(current, pos - 1) == ' ') {
994                     pos--;
995                 }
996
997                 /* now eat any non-spaces on the left */
998                 while (pos > 0 && get_char(current, pos - 1) != ' ') {
999                     pos--;
1000                 }
1001
1002                 if (remove_chars(current, pos, current->pos - pos)) {
1003                     refreshLine(current->prompt, current);
1004                 }
1005             }
1006             break;
1007         case ctrl('R'):    /* ctrl-r */
1008             {
1009                 /* Display the reverse-i-search prompt and process chars */
1010                 char rbuf[50];
1011                 char rprompt[80];
1012                 int rchars = 0;
1013                 int rlen = 0;
1014                 int searchpos = history_len - 1;
1015
1016                 rbuf[0] = 0;
1017                 while (1) {
1018                     int n = 0;
1019                     const char *p = NULL;
1020                     int skipsame = 0;
1021                     int searchdir = -1;
1022
1023                     snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1024                     refreshLine(rprompt, current);
1025                     c = fd_read(current);
1026                     if (c == ctrl('H') || c == 127) {
1027                         if (rchars) {
1028                             int p = utf8_index(rbuf, --rchars);
1029                             rbuf[p] = 0;
1030                             rlen = strlen(rbuf);
1031                         }
1032                         continue;
1033                     }
1034 #ifdef USE_TERMIOS
1035                     if (c == 27) {
1036                         c = check_special(current->fd);
1037                     }
1038 #endif
1039                     if (c == ctrl('P') || c == SPECIAL_UP) {
1040                         /* Search for the previous (earlier) match */
1041                         if (searchpos > 0) {
1042                             searchpos--;
1043                         }
1044                         skipsame = 1;
1045                     }
1046                     else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1047                         /* Search for the next (later) match */
1048                         if (searchpos < history_len) {
1049                             searchpos++;
1050                         }
1051                         searchdir = 1;
1052                         skipsame = 1;
1053                     }
1054                     else if (c >= ' ') {
1055                         if (rlen >= (int)sizeof(rbuf) + 3) {
1056                             continue;
1057                         }
1058
1059                         n = utf8_getchars(rbuf + rlen, c);
1060                         rlen += n;
1061                         rchars++;
1062                         rbuf[rlen] = 0;
1063
1064                         /* Adding a new char resets the search location */
1065                         searchpos = history_len - 1;
1066                     }
1067                     else {
1068                         /* Exit from incremental search mode */
1069                         break;
1070                     }
1071
1072                     /* Now search through the history for a match */
1073                     for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1074                         p = strstr(history[searchpos], rbuf);
1075                         if (p) {
1076                             /* Found a match */
1077                             if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
1078                                 /* But it is identical, so skip it */
1079                                 continue;
1080                             }
1081                             /* Copy the matching line and set the cursor position */
1082                             set_current(current,history[searchpos]);
1083                             current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1084                             break;
1085                         }
1086                     }
1087                     if (!p && n) {
1088                         /* No match, so don't add it */
1089                         rchars--;
1090                         rlen -= n;
1091                         rbuf[rlen] = 0;
1092                     }
1093                 }
1094                 if (c == ctrl('G') || c == ctrl('C')) {
1095                     /* ctrl-g terminates the search with no effect */
1096                     set_current(current, "");
1097                     c = 0;
1098                 }
1099                 else if (c == ctrl('J')) {
1100                     /* ctrl-j terminates the search leaving the buffer in place */
1101                     c = 0;
1102                 }
1103                 /* Go process the char normally */
1104                 refreshLine(current->prompt, current);
1105                 goto process_char;
1106             }
1107             break;
1108         case ctrl('T'):    /* ctrl-t */
1109             if (current->pos > 0 && current->pos < current->chars) {
1110                 c = get_char(current, current->pos);
1111                 remove_char(current, current->pos);
1112                 insert_char(current, current->pos - 1, c);
1113                 refreshLine(current->prompt, current);
1114             }
1115             break;
1116         case ctrl('V'):    /* ctrl-v */
1117             if (has_room(current, 3)) {
1118                 /* Insert the ^V first */
1119                 if (insert_char(current, current->pos, c)) {
1120                     refreshLine(current->prompt, current);
1121                     /* Now wait for the next char. Can insert anything except \0 */
1122                     c = fd_read(current);
1123
1124                     /* Remove the ^V first */
1125                     remove_char(current, current->pos - 1);
1126                     if (c != -1) {
1127                         /* Insert the actual char */
1128                         insert_char(current, current->pos, c);
1129                     }
1130                     refreshLine(current->prompt, current);
1131                 }
1132             }
1133             break;
1134         case ctrl('B'):
1135         case SPECIAL_LEFT:
1136             if (current->pos > 0) {
1137                 current->pos--;
1138                 refreshLine(current->prompt, current);
1139             }
1140             break;
1141         case ctrl('F'):
1142         case SPECIAL_RIGHT:
1143             if (current->pos < current->chars) {
1144                 current->pos++;
1145                 refreshLine(current->prompt, current);
1146             }
1147             break;
1148         case ctrl('P'):
1149         case SPECIAL_UP:
1150             dir = 1;
1151         case ctrl('N'):
1152         case SPECIAL_DOWN:
1153             if (history_len > 1) {
1154                 /* Update the current history entry before to
1155                  * overwrite it with tne next one. */
1156                 free(history[history_len-1-history_index]);
1157                 history[history_len-1-history_index] = strdup(current->buf);
1158                 /* Show the new entry */
1159                 history_index += dir;
1160                 if (history_index < 0) {
1161                     history_index = 0;
1162                     break;
1163                 } else if (history_index >= history_len) {
1164                     history_index = history_len-1;
1165                     break;
1166                 }
1167                 set_current(current, history[history_len-1-history_index]);
1168                 refreshLine(current->prompt, current);
1169             }
1170             break;
1171
1172         case SPECIAL_DELETE:
1173             if (remove_char(current, current->pos) == 1) {
1174                 refreshLine(current->prompt, current);
1175             }
1176             break;
1177         case SPECIAL_HOME:
1178             current->pos = 0;
1179             refreshLine(current->prompt, current);
1180             break;
1181         case SPECIAL_END:
1182             current->pos = current->chars;
1183             refreshLine(current->prompt, current);
1184             break;
1185         default:
1186             /* Only tab is allowed without ^V */
1187             if (c == '\t' || c >= ' ') {
1188                 if (insert_char(current, current->pos, c) == 1) {
1189                     refreshLine(current->prompt, current);
1190                 }
1191             }
1192             break;
1193         case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
1194             if (remove_chars(current, 0, current->pos)) {
1195                 refreshLine(current->prompt, current);
1196             }
1197             break;
1198         case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
1199             if (remove_chars(current, current->pos, current->chars - current->pos)) {
1200                 refreshLine(current->prompt, current);
1201             }
1202             break;
1203         case ctrl('A'): /* Ctrl+a, go to the start of the line */
1204             current->pos = 0;
1205             refreshLine(current->prompt, current);
1206             break;
1207         case ctrl('E'): /* ctrl+e, go to the end of the line */
1208             current->pos = current->chars;
1209             refreshLine(current->prompt, current);
1210             break;
1211         case ctrl('L'): /* Ctrl+L, clear screen */
1212             /* clear screen */
1213             clearScreen(current);
1214             /* Force recalc of window size for serial terminals */
1215             current->cols = 0;
1216             refreshLine(current->prompt, current);
1217             break;
1218         }
1219     }
1220     return current->len;
1221 }
1222
1223 char *linenoise(const char *prompt)
1224 {
1225     int count;
1226     struct current current;
1227     char buf[LINENOISE_MAX_LINE];
1228
1229     if (enableRawMode(&current) == -1) {
1230         printf("%s", prompt);
1231         fflush(stdout);
1232         if (fgets(buf, sizeof(buf), stdin) == NULL) {
1233                 return NULL;
1234         }
1235         count = strlen(buf);
1236         if (count && buf[count-1] == '\n') {
1237             count--;
1238             buf[count] = '\0';
1239         }
1240     }
1241     else
1242     {
1243         current.buf = buf;
1244         current.bufmax = sizeof(buf);
1245         current.len = 0;
1246         current.chars = 0;
1247         current.pos = 0;
1248         current.prompt = prompt;
1249
1250         count = linenoisePrompt(&current);
1251         disableRawMode(&current);
1252         printf("\n");
1253         if (count == -1) {
1254             return NULL;
1255         }
1256     }
1257     return strdup(buf);
1258 }
1259
1260 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1261 int linenoiseHistoryAdd(const char *line) {
1262     char *linecopy;
1263
1264     if (history_max_len == 0) return 0;
1265     if (history == NULL) {
1266         history = (char **)malloc(sizeof(char*)*history_max_len);
1267         if (history == NULL) return 0;
1268         memset(history,0,(sizeof(char*)*history_max_len));
1269     }
1270
1271     /* do not insert duplicate lines into history */
1272     if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1273         return 0;
1274     }
1275
1276     linecopy = strdup(line);
1277     if (!linecopy) return 0;
1278     if (history_len == history_max_len) {
1279         free(history[0]);
1280         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1281         history_len--;
1282     }
1283     history[history_len] = linecopy;
1284     history_len++;
1285     return 1;
1286 }
1287
1288 int linenoiseHistorySetMaxLen(int len) {
1289     char **newHistory;
1290
1291     if (len < 1) return 0;
1292     if (history) {
1293         int tocopy = history_len;
1294
1295         newHistory = (char **)malloc(sizeof(char*)*len);
1296         if (newHistory == NULL) return 0;
1297         if (len < tocopy) tocopy = len;
1298         memcpy(newHistory,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
1299         free(history);
1300         history = newHistory;
1301     }
1302     history_max_len = len;
1303     if (history_len > history_max_len)
1304         history_len = history_max_len;
1305     return 1;
1306 }
1307
1308 /* Save the history in the specified file. On success 0 is returned
1309  * otherwise -1 is returned. */
1310 int linenoiseHistorySave(const char *filename) {
1311     FILE *fp = fopen(filename,"w");
1312     int j;
1313
1314     if (fp == NULL) return -1;
1315     for (j = 0; j < history_len; j++) {
1316         const char *str = history[j];
1317         /* Need to encode backslash, nl and cr */
1318         while (*str) {
1319             if (*str == '\\') {
1320                 fputs("\\\\", fp);
1321             }
1322             else if (*str == '\n') {
1323                 fputs("\\n", fp);
1324             }
1325             else if (*str == '\r') {
1326                 fputs("\\r", fp);
1327             }
1328             else {
1329                 fputc(*str, fp);
1330             }
1331             str++;
1332         }
1333         fputc('\n', fp);
1334     }
1335
1336     fclose(fp);
1337     return 0;
1338 }
1339
1340 /* Load the history from the specified file. If the file does not exist
1341  * zero is returned and no operation is performed.
1342  *
1343  * If the file exists and the operation succeeded 0 is returned, otherwise
1344  * on error -1 is returned. */
1345 int linenoiseHistoryLoad(const char *filename) {
1346     FILE *fp = fopen(filename,"r");
1347     char buf[LINENOISE_MAX_LINE];
1348
1349     if (fp == NULL) return -1;
1350
1351     while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1352         char *src, *dest;
1353
1354         /* Decode backslash escaped values */
1355         for (src = dest = buf; *src; src++) {
1356             char ch = *src;
1357
1358             if (ch == '\\') {
1359                 src++;
1360                 if (*src == 'n') {
1361                     ch = '\n';
1362                 }
1363                 else if (*src == 'r') {
1364                     ch = '\r';
1365                 } else {
1366                     ch = *src;
1367                 }
1368             }
1369             *dest++ = ch;
1370         }
1371         /* Remove trailing newline */
1372         if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1373             dest--;
1374         }
1375         *dest = 0;
1376
1377         linenoiseHistoryAdd(buf);
1378     }
1379     fclose(fp);
1380     return 0;
1381 }
1382
1383 /* Provide access to the history buffer.
1384  *
1385  * If 'len' is not NULL, the length is stored in *len.
1386  */
1387 char **linenoiseHistory(int *len) {
1388     if (len) {
1389         *len = history_len;
1390     }
1391     return history;
1392 }