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