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