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