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