]> git.lizzy.rs Git - linenoise.git/blob - linenoise.c
Bug fix. Discount the characters of ANSI color control sequences.
[linenoise.git] / linenoise.c
1 /* linenoise.c -- guerrilla line editing library against the idea that a
2  * line editing lib needs to be 20,000 lines of C code.
3  *
4  * You can find the latest source code at:
5  *
6  *   http://github.com/msteveb/linenoise
7  *   (forked from http://github.com/antirez/linenoise)
8  *
9  * Does a number of crazy assumptions that happen to be true in 99.9999% of
10  * the 2010 UNIX computers around.
11  *
12  * ------------------------------------------------------------------------
13  *
14  * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
15  * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
16  * Copyright (c) 2011, Steve Bennett <steveb at workware dot net dot au>
17  *
18  * All rights reserved.
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions are
22  * met:
23  *
24  *  *  Redistributions of source code must retain the above copyright
25  *     notice, this list of conditions and the following disclaimer.
26  *
27  *  *  Redistributions in binary form must reproduce the above copyright
28  *     notice, this list of conditions and the following disclaimer in the
29  *     documentation and/or other materials provided with the distribution.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42  *
43  * ------------------------------------------------------------------------
44  *
45  * References:
46  * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
47  * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
48  *
49  * Bloat:
50  * - Completion?
51  *
52  * Unix/termios
53  * ------------
54  * List of escape sequences used by this program, we do everything just
55  * a few sequences. In order to be so cheap we may have some
56  * flickering effect with some slow terminal, but the lesser sequences
57  * the more compatible.
58  *
59  * 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 countColorControlChars(const char* prompt, int plen)
385 {
386     /* ANSI color control sequences have the form:
387      * "\x1b" "[" [0-9;]+ "m"
388      * We parse them with a simple state machine.
389      */
390
391     enum {
392         search_esc,
393         expect_bracket,
394         expect_inner,
395         expect_trail
396     } state = search_esc;
397     int len, found = 0;
398     char ch;
399
400     /* XXX: Strictly we should be checking utf8 chars rather than
401      *      bytes in case of the extremely unlikely scenario where
402      *      an ANSI sequence is part of a utf8 sequence.
403      */
404     for (; plen ; plen--, prompt++) {
405         ch = *prompt;
406
407         switch (state) {
408         case search_esc:
409             len = 0;
410             if (ch == '\x1b') {
411                 state = expect_bracket;
412                 len++;
413             }
414             break;
415         case expect_bracket:
416             if (ch == '[') {
417                 state = expect_inner;
418                 len++;
419             } else {
420                 state = search_esc;
421             }
422             break;
423         case expect_inner:
424             if (ch >= '0' && ch <= '9') {
425                 len++;
426                 state = expect_trail;
427             } else {
428                 state = search_esc;
429             }
430             break;
431         case expect_trail:
432             if (ch == 'm') {
433                 len++;
434                 found += len;
435                 state = search_esc;
436             } else if ((ch != ';') && ((ch < '0') || (ch > '9'))) {
437                 state = search_esc;
438             }
439             /* 0-9, or semicolon */
440             len++;
441             break;
442         }
443     }
444
445     return found;
446 }
447
448 static int getWindowSize(struct current *current)
449 {
450     struct winsize ws;
451
452     if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
453         current->cols = ws.ws_col;
454         return 0;
455     }
456
457     /* Failed to query the window size. Perhaps we are on a serial terminal.
458      * Try to query the width by sending the cursor as far to the right
459      * and reading back the cursor position.
460      * Note that this is only done once per call to linenoise rather than
461      * every time the line is refreshed for efficiency reasons.
462      */
463     if (current->cols == 0) {
464         current->cols = 80;
465
466         /* Move cursor far right and report cursor position, then back to the left */
467         fd_printf(current->fd, "\x1b[999C" "\x1b[6n");
468
469         /* Parse the response: ESC [ rows ; cols R */
470         if (fd_read_char(current->fd, 100) == 0x1b && fd_read_char(current->fd, 100) == '[') {
471             int n = 0;
472             while (1) {
473                 int ch = fd_read_char(current->fd, 100);
474                 if (ch == ';') {
475                     /* Ignore rows */
476                     n = 0;
477                 }
478                 else if (ch == 'R') {
479                     /* Got cols */
480                     if (n != 0 && n < 1000) {
481                         current->cols = n;
482                     }
483                     break;
484                 }
485                 else if (ch >= 0 && ch <= '9') {
486                     n = n * 10 + ch - '0';
487                 }
488                 else {
489                     break;
490                 }
491             }
492         }
493     }
494     return 0;
495 }
496
497 /**
498  * If escape (27) was received, reads subsequent
499  * chars to determine if this is a known special key.
500  *
501  * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
502  *
503  * If no additional char is received within a short time,
504  * 27 is returned.
505  */
506 static int check_special(int fd)
507 {
508     int c = fd_read_char(fd, 50);
509     int c2;
510
511     if (c < 0) {
512         return 27;
513     }
514
515     c2 = fd_read_char(fd, 50);
516     if (c2 < 0) {
517         return c2;
518     }
519     if (c == '[' || c == 'O') {
520         /* Potential arrow key */
521         switch (c2) {
522             case 'A':
523                 return SPECIAL_UP;
524             case 'B':
525                 return SPECIAL_DOWN;
526             case 'C':
527                 return SPECIAL_RIGHT;
528             case 'D':
529                 return SPECIAL_LEFT;
530             case 'F':
531                 return SPECIAL_END;
532             case 'H':
533                 return SPECIAL_HOME;
534         }
535     }
536     if (c == '[' && c2 >= '1' && c2 <= '8') {
537         /* extended escape */
538         c = fd_read_char(fd, 50);
539         if (c == '~') {
540             switch (c2) {
541                 case '2':
542                     return SPECIAL_INSERT;
543                 case '3':
544                     return SPECIAL_DELETE;
545                 case '5':
546                     return SPECIAL_PAGE_UP;
547                 case '6':
548                     return SPECIAL_PAGE_DOWN;
549                 case '7':
550                     return SPECIAL_HOME;
551                 case '8':
552                     return SPECIAL_END;
553             }
554         }
555         while (c != -1 && c != '~') {
556             /* .e.g \e[12~ or '\e[11;2~   discard the complete sequence */
557             c = fd_read_char(fd, 50);
558         }
559     }
560
561     return SPECIAL_NONE;
562 }
563 #elif defined(USE_WINCONSOLE)
564
565 static DWORD orig_consolemode = 0;
566
567 static int enableRawMode(struct current *current) {
568     DWORD n;
569     INPUT_RECORD irec;
570
571     current->outh = GetStdHandle(STD_OUTPUT_HANDLE);
572     current->inh = GetStdHandle(STD_INPUT_HANDLE);
573
574     if (!PeekConsoleInput(current->inh, &irec, 1, &n)) {
575         return -1;
576     }
577     if (getWindowSize(current) != 0) {
578         return -1;
579     }
580     if (GetConsoleMode(current->inh, &orig_consolemode)) {
581         SetConsoleMode(current->inh, ENABLE_PROCESSED_INPUT);
582     }
583     return 0;
584 }
585
586 static void disableRawMode(struct current *current)
587 {
588     SetConsoleMode(current->inh, orig_consolemode);
589 }
590
591 static void clearScreen(struct current *current)
592 {
593     COORD topleft = { 0, 0 };
594     DWORD n;
595
596     FillConsoleOutputCharacter(current->outh, ' ',
597         current->cols * current->rows, topleft, &n);
598     FillConsoleOutputAttribute(current->outh,
599         FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN,
600         current->cols * current->rows, topleft, &n);
601     SetConsoleCursorPosition(current->outh, topleft);
602 }
603
604 static void cursorToLeft(struct current *current)
605 {
606     COORD pos = { 0, (SHORT)current->y };
607     DWORD n;
608
609     FillConsoleOutputAttribute(current->outh,
610         FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, current->cols, pos, &n);
611     current->x = 0;
612 }
613
614 static int outputChars(struct current *current, const char *buf, int len)
615 {
616     COORD pos = { (SHORT)current->x, (SHORT)current->y };
617     DWORD n;
618
619     WriteConsoleOutputCharacter(current->outh, buf, len, pos, &n);
620     current->x += len;
621     return 0;
622 }
623
624 static void outputControlChar(struct current *current, char ch)
625 {
626     COORD pos = { (SHORT)current->x, (SHORT)current->y };
627     DWORD n;
628
629     FillConsoleOutputAttribute(current->outh, BACKGROUND_INTENSITY, 2, pos, &n);
630     outputChars(current, "^", 1);
631     outputChars(current, &ch, 1);
632 }
633
634 static void eraseEol(struct current *current)
635 {
636     COORD pos = { (SHORT)current->x, (SHORT)current->y };
637     DWORD n;
638
639     FillConsoleOutputCharacter(current->outh, ' ', current->cols - current->x, pos, &n);
640 }
641
642 static void setCursorPos(struct current *current, int x)
643 {
644     COORD pos = { (SHORT)x, (SHORT)current->y };
645
646     SetConsoleCursorPosition(current->outh, pos);
647     current->x = x;
648 }
649
650 static int fd_read(struct current *current)
651 {
652     while (1) {
653         INPUT_RECORD irec;
654         DWORD n;
655         if (WaitForSingleObject(current->inh, INFINITE) != WAIT_OBJECT_0) {
656             break;
657         }
658         if (!ReadConsoleInput (current->inh, &irec, 1, &n)) {
659             break;
660         }
661         if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown) {
662             KEY_EVENT_RECORD *k = &irec.Event.KeyEvent;
663             if (k->dwControlKeyState & ENHANCED_KEY) {
664                 switch (k->wVirtualKeyCode) {
665                  case VK_LEFT:
666                     return SPECIAL_LEFT;
667                  case VK_RIGHT:
668                     return SPECIAL_RIGHT;
669                  case VK_UP:
670                     return SPECIAL_UP;
671                  case VK_DOWN:
672                     return SPECIAL_DOWN;
673                  case VK_INSERT:
674                     return SPECIAL_INSERT;
675                  case VK_DELETE:
676                     return SPECIAL_DELETE;
677                  case VK_HOME:
678                     return SPECIAL_HOME;
679                  case VK_END:
680                     return SPECIAL_END;
681                  case VK_PRIOR:
682                     return SPECIAL_PAGE_UP;
683                  case VK_NEXT:
684                     return SPECIAL_PAGE_DOWN;
685                 }
686             }
687             /* Note that control characters are already translated in AsciiChar */
688             else {
689 #ifdef USE_UTF8
690                 return k->uChar.UnicodeChar;
691 #else
692                 return k->uChar.AsciiChar;
693 #endif
694             }
695         }
696     }
697     return -1;
698 }
699
700 static int countColorControlChars(char* prompt, int plen)
701 {
702     /* For windows we assume that there are no embedded ansi color
703      * control sequences.
704      */
705     return 0;
706 }
707
708 static int getWindowSize(struct current *current)
709 {
710     CONSOLE_SCREEN_BUFFER_INFO info;
711     if (!GetConsoleScreenBufferInfo(current->outh, &info)) {
712         return -1;
713     }
714     current->cols = info.dwSize.X;
715     current->rows = info.dwSize.Y;
716     if (current->cols <= 0 || current->rows <= 0) {
717         current->cols = 80;
718         return -1;
719     }
720     current->y = info.dwCursorPosition.Y;
721     current->x = info.dwCursorPosition.X;
722     return 0;
723 }
724 #endif
725
726 static int utf8_getchars(char *buf, int c)
727 {
728 #ifdef USE_UTF8
729     return utf8_fromunicode(buf, c);
730 #else
731     *buf = c;
732     return 1;
733 #endif
734 }
735
736 /**
737  * Returns the unicode character at the given offset,
738  * or -1 if none.
739  */
740 static int get_char(struct current *current, int pos)
741 {
742     if (pos >= 0 && pos < current->chars) {
743         int c;
744         int i = utf8_index(current->buf, pos);
745         (void)utf8_tounicode(current->buf + i, &c);
746         return c;
747     }
748     return -1;
749 }
750
751 static void refreshLine(const char *prompt, struct current *current)
752 {
753     int plen;
754     int pchars;
755     int backup = 0;
756     int i;
757     const char *buf = current->buf;
758     int chars = current->chars;
759     int pos = current->pos;
760     int b;
761     int ch;
762     int n;
763
764     /* Should intercept SIGWINCH. For now, just get the size every time */
765     getWindowSize(current);
766
767     plen = strlen(prompt);
768     pchars = utf8_strlen(prompt, plen);
769
770     /* Scan the prompt for embedded ansi color control sequences and
771      * discount them as characters/columns.
772      */
773     pchars -= countColorControlChars(prompt, plen);
774
775     /* Account for a line which is too long to fit in the window.
776      * Note that control chars require an extra column
777      */
778
779     /* How many cols are required to the left of 'pos'?
780      * The prompt, plus one extra for each control char
781      */
782     n = pchars + utf8_strlen(buf, current->len);
783     b = 0;
784     for (i = 0; i < pos; i++) {
785         b += utf8_tounicode(buf + b, &ch);
786         if (ch < ' ') {
787             n++;
788         }
789     }
790
791     /* If too many are needed, strip chars off the front of 'buf'
792      * until it fits. Note that if the current char is a control character,
793      * we need one extra col.
794      */
795     if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
796         n++;
797     }
798
799     while (n >= current->cols && pos > 0) {
800         b = utf8_tounicode(buf, &ch);
801         if (ch < ' ') {
802             n--;
803         }
804         n--;
805         buf += b;
806         pos--;
807         chars--;
808     }
809
810     /* Cursor to left edge, then the prompt */
811     cursorToLeft(current);
812     outputChars(current, prompt, plen);
813
814     /* Now the current buffer content */
815
816     /* Need special handling for control characters.
817      * If we hit 'cols', stop.
818      */
819     b = 0; /* unwritted bytes */
820     n = 0; /* How many control chars were written */
821     for (i = 0; i < chars; i++) {
822         int ch;
823         int w = utf8_tounicode(buf + b, &ch);
824         if (ch < ' ') {
825             n++;
826         }
827         if (pchars + i + n >= current->cols) {
828             break;
829         }
830         if (ch < ' ') {
831             /* A control character, so write the buffer so far */
832             outputChars(current, buf, b);
833             buf += b + w;
834             b = 0;
835             outputControlChar(current, ch + '@');
836             if (i < pos) {
837                 backup++;
838             }
839         }
840         else {
841             b += w;
842         }
843     }
844     outputChars(current, buf, b);
845
846     /* Erase to right, move cursor to original position */
847     eraseEol(current);
848     setCursorPos(current, pos + pchars + backup);
849 }
850
851 static void set_current(struct current *current, const char *str)
852 {
853     strncpy(current->buf, str, current->bufmax);
854     current->buf[current->bufmax - 1] = 0;
855     current->len = strlen(current->buf);
856     current->pos = current->chars = utf8_strlen(current->buf, current->len);
857 }
858
859 static int has_room(struct current *current, int bytes)
860 {
861     return current->len + bytes < current->bufmax - 1;
862 }
863
864 /**
865  * Removes the char at 'pos'.
866  *
867  * Returns 1 if the line needs to be refreshed, 2 if not
868  * and 0 if nothing was removed
869  */
870 static int remove_char(struct current *current, int pos)
871 {
872     if (pos >= 0 && pos < current->chars) {
873         int p1, p2;
874         int ret = 1;
875         p1 = utf8_index(current->buf, pos);
876         p2 = p1 + utf8_index(current->buf + p1, 1);
877
878 #ifdef USE_TERMIOS
879         /* optimise remove char in the case of removing the last char */
880         if (current->pos == pos + 1 && current->pos == current->chars) {
881             if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
882                 ret = 2;
883                 fd_printf(current->fd, "\b \b");
884             }
885         }
886 #endif
887
888         /* Move the null char too */
889         memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
890         current->len -= (p2 - p1);
891         current->chars--;
892
893         if (current->pos > pos) {
894             current->pos--;
895         }
896         return ret;
897     }
898     return 0;
899 }
900
901 /**
902  * Insert 'ch' at position 'pos'
903  *
904  * Returns 1 if the line needs to be refreshed, 2 if not
905  * and 0 if nothing was inserted (no room)
906  */
907 static int insert_char(struct current *current, int pos, int ch)
908 {
909     char buf[3];
910     int n = utf8_getchars(buf, ch);
911
912     if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
913         int p1, p2;
914         int ret = 1;
915         p1 = utf8_index(current->buf, pos);
916         p2 = p1 + n;
917
918 #ifdef USE_TERMIOS
919         /* optimise the case where adding a single char to the end and no scrolling is needed */
920         if (current->pos == pos && current->chars == pos) {
921             if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
922                 IGNORE_RC(write(current->fd, buf, n));
923                 ret = 2;
924             }
925         }
926 #endif
927
928         memmove(current->buf + p2, current->buf + p1, current->len - p1);
929         memcpy(current->buf + p1, buf, n);
930         current->len += n;
931
932         current->chars++;
933         if (current->pos >= pos) {
934             current->pos++;
935         }
936         return ret;
937     }
938     return 0;
939 }
940
941 /**
942  * Returns 0 if no chars were removed or non-zero otherwise.
943  */
944 static int remove_chars(struct current *current, int pos, int n)
945 {
946     int removed = 0;
947     while (n-- && remove_char(current, pos)) {
948         removed++;
949     }
950     return removed;
951 }
952
953 #ifndef NO_COMPLETION
954 static linenoiseCompletionCallback *completionCallback = NULL;
955
956 static void beep() {
957 #ifdef USE_TERMIOS
958     fprintf(stderr, "\x7");
959     fflush(stderr);
960 #endif
961 }
962
963 static void freeCompletions(linenoiseCompletions *lc) {
964     size_t i;
965     for (i = 0; i < lc->len; i++)
966         free(lc->cvec[i]);
967     free(lc->cvec);
968 }
969
970 static int completeLine(struct current *current) {
971     linenoiseCompletions lc = { 0, NULL };
972     int c = 0;
973
974     completionCallback(current->buf,&lc);
975     if (lc.len == 0) {
976         beep();
977     } else {
978         size_t stop = 0, i = 0;
979
980         while(!stop) {
981             /* Show completion or original buffer */
982             if (i < lc.len) {
983                 struct current tmp = *current;
984                 tmp.buf = lc.cvec[i];
985                 tmp.pos = tmp.len = strlen(tmp.buf);
986                 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
987                 refreshLine(current->prompt, &tmp);
988             } else {
989                 refreshLine(current->prompt, current);
990             }
991
992             c = fd_read(current);
993             if (c == -1) {
994                 break;
995             }
996
997             switch(c) {
998                 case '\t': /* tab */
999                     i = (i+1) % (lc.len+1);
1000                     if (i == lc.len) beep();
1001                     break;
1002                 case 27: /* escape */
1003                     /* Re-show original buffer */
1004                     if (i < lc.len) {
1005                         refreshLine(current->prompt, current);
1006                     }
1007                     stop = 1;
1008                     break;
1009                 default:
1010                     /* Update buffer and return */
1011                     if (i < lc.len) {
1012                         set_current(current,lc.cvec[i]);
1013                     }
1014                     stop = 1;
1015                     break;
1016             }
1017         }
1018     }
1019
1020     freeCompletions(&lc);
1021     return c; /* Return last read character */
1022 }
1023
1024 /* Register a callback function to be called for tab-completion. */
1025 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
1026     completionCallback = fn;
1027 }
1028
1029 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
1030     lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
1031     lc->cvec[lc->len++] = strdup(str);
1032 }
1033
1034 #endif
1035
1036 static int linenoisePrompt(struct current *current) {
1037     int history_index = 0;
1038
1039     /* The latest history entry is always our current buffer, that
1040      * initially is just an empty string. */
1041     linenoiseHistoryAdd("");
1042
1043     set_current(current, "");
1044     refreshLine(current->prompt, current);
1045
1046     while(1) {
1047         int dir = -1;
1048         int c = fd_read(current);
1049
1050 #ifndef NO_COMPLETION
1051         /* Only autocomplete when the callback is set. It returns < 0 when
1052          * there was an error reading from fd. Otherwise it will return the
1053          * character that should be handled next. */
1054         if (c == '\t' && current->pos == current->chars && completionCallback != NULL) {
1055             c = completeLine(current);
1056             /* Return on errors */
1057             if (c < 0) return current->len;
1058             /* Read next character when 0 */
1059             if (c == 0) continue;
1060         }
1061 #endif
1062
1063 process_char:
1064         if (c == -1) return current->len;
1065 #ifdef USE_TERMIOS
1066         if (c == 27) {   /* escape sequence */
1067             c = check_special(current->fd);
1068         }
1069 #endif
1070         switch(c) {
1071         case '\r':    /* enter */
1072             history_len--;
1073             free(history[history_len]);
1074             return current->len;
1075         case ctrl('C'):     /* ctrl-c */
1076             errno = EAGAIN;
1077             return -1;
1078         case 127:   /* backspace */
1079         case ctrl('H'):
1080             if (remove_char(current, current->pos - 1) == 1) {
1081                 refreshLine(current->prompt, current);
1082             }
1083             break;
1084         case ctrl('D'):     /* ctrl-d */
1085             if (current->len == 0) {
1086                 /* Empty line, so EOF */
1087                 history_len--;
1088                 free(history[history_len]);
1089                 return -1;
1090             }
1091             /* Otherwise fall through to delete char to right of cursor */
1092         case SPECIAL_DELETE:
1093             if (remove_char(current, current->pos) == 1) {
1094                 refreshLine(current->prompt, current);
1095             }
1096             break;
1097         case SPECIAL_INSERT:
1098             /* Ignore. Expansion Hook.
1099              * Future possibility: Toggle Insert/Overwrite Modes
1100              */
1101             break;
1102         case ctrl('W'):    /* ctrl-w */
1103             /* eat any spaces on the left */
1104             {
1105                 int pos = current->pos;
1106                 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1107                     pos--;
1108                 }
1109
1110                 /* now eat any non-spaces on the left */
1111                 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1112                     pos--;
1113                 }
1114
1115                 if (remove_chars(current, pos, current->pos - pos)) {
1116                     refreshLine(current->prompt, current);
1117                 }
1118             }
1119             break;
1120         case ctrl('R'):    /* ctrl-r */
1121             {
1122                 /* Display the reverse-i-search prompt and process chars */
1123                 char rbuf[50];
1124                 char rprompt[80];
1125                 int rchars = 0;
1126                 int rlen = 0;
1127                 int searchpos = history_len - 1;
1128
1129                 rbuf[0] = 0;
1130                 while (1) {
1131                     int n = 0;
1132                     const char *p = NULL;
1133                     int skipsame = 0;
1134                     int searchdir = -1;
1135
1136                     snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1137                     refreshLine(rprompt, current);
1138                     c = fd_read(current);
1139                     if (c == ctrl('H') || c == 127) {
1140                         if (rchars) {
1141                             int p = utf8_index(rbuf, --rchars);
1142                             rbuf[p] = 0;
1143                             rlen = strlen(rbuf);
1144                         }
1145                         continue;
1146                     }
1147 #ifdef USE_TERMIOS
1148                     if (c == 27) {
1149                         c = check_special(current->fd);
1150                     }
1151 #endif
1152                     if (c == ctrl('P') || c == SPECIAL_UP) {
1153                         /* Search for the previous (earlier) match */
1154                         if (searchpos > 0) {
1155                             searchpos--;
1156                         }
1157                         skipsame = 1;
1158                     }
1159                     else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1160                         /* Search for the next (later) match */
1161                         if (searchpos < history_len) {
1162                             searchpos++;
1163                         }
1164                         searchdir = 1;
1165                         skipsame = 1;
1166                     }
1167                     else if (c >= ' ') {
1168                         if (rlen >= (int)sizeof(rbuf) + 3) {
1169                             continue;
1170                         }
1171
1172                         n = utf8_getchars(rbuf + rlen, c);
1173                         rlen += n;
1174                         rchars++;
1175                         rbuf[rlen] = 0;
1176
1177                         /* Adding a new char resets the search location */
1178                         searchpos = history_len - 1;
1179                     }
1180                     else {
1181                         /* Exit from incremental search mode */
1182                         break;
1183                     }
1184
1185                     /* Now search through the history for a match */
1186                     for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1187                         p = strstr(history[searchpos], rbuf);
1188                         if (p) {
1189                             /* Found a match */
1190                             if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
1191                                 /* But it is identical, so skip it */
1192                                 continue;
1193                             }
1194                             /* Copy the matching line and set the cursor position */
1195                             set_current(current,history[searchpos]);
1196                             current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1197                             break;
1198                         }
1199                     }
1200                     if (!p && n) {
1201                         /* No match, so don't add it */
1202                         rchars--;
1203                         rlen -= n;
1204                         rbuf[rlen] = 0;
1205                     }
1206                 }
1207                 if (c == ctrl('G') || c == ctrl('C')) {
1208                     /* ctrl-g terminates the search with no effect */
1209                     set_current(current, "");
1210                     c = 0;
1211                 }
1212                 else if (c == ctrl('J')) {
1213                     /* ctrl-j terminates the search leaving the buffer in place */
1214                     c = 0;
1215                 }
1216                 /* Go process the char normally */
1217                 refreshLine(current->prompt, current);
1218                 goto process_char;
1219             }
1220             break;
1221         case ctrl('T'):    /* ctrl-t */
1222             if (current->pos > 0 && current->pos <= current->chars) {
1223                 /* If cursor is at end, transpose the previous two chars */
1224                 int fixer = (current->pos == current->chars);
1225                 c = get_char(current, current->pos - fixer);
1226                 remove_char(current, current->pos - fixer);
1227                 insert_char(current, current->pos - 1, c);
1228                 refreshLine(current->prompt, current);
1229             }
1230             break;
1231         case ctrl('V'):    /* ctrl-v */
1232             if (has_room(current, 3)) {
1233                 /* Insert the ^V first */
1234                 if (insert_char(current, current->pos, c)) {
1235                     refreshLine(current->prompt, current);
1236                     /* Now wait for the next char. Can insert anything except \0 */
1237                     c = fd_read(current);
1238
1239                     /* Remove the ^V first */
1240                     remove_char(current, current->pos - 1);
1241                     if (c != -1) {
1242                         /* Insert the actual char */
1243                         insert_char(current, current->pos, c);
1244                     }
1245                     refreshLine(current->prompt, current);
1246                 }
1247             }
1248             break;
1249         case ctrl('B'):
1250         case SPECIAL_LEFT:
1251             if (current->pos > 0) {
1252                 current->pos--;
1253                 refreshLine(current->prompt, current);
1254             }
1255             break;
1256         case ctrl('F'):
1257         case SPECIAL_RIGHT:
1258             if (current->pos < current->chars) {
1259                 current->pos++;
1260                 refreshLine(current->prompt, current);
1261             }
1262             break;
1263         case SPECIAL_PAGE_UP:
1264           dir = history_len - history_index - 1; /* move to start of history */
1265           goto history_navigation;
1266         case SPECIAL_PAGE_DOWN:
1267           dir = -history_index; /* move to 0 == end of history, i.e. current */
1268           goto history_navigation;
1269         case ctrl('P'):
1270         case SPECIAL_UP:
1271             dir = 1;
1272           goto history_navigation;
1273         case ctrl('N'):
1274         case SPECIAL_DOWN:
1275 history_navigation:
1276             if (history_len > 1) {
1277                 /* Update the current history entry before to
1278                  * overwrite it with tne next one. */
1279                 free(history[history_len - 1 - history_index]);
1280                 history[history_len - 1 - history_index] = strdup(current->buf);
1281                 /* Show the new entry */
1282                 history_index += dir;
1283                 if (history_index < 0) {
1284                     history_index = 0;
1285                     break;
1286                 } else if (history_index >= history_len) {
1287                     history_index = history_len - 1;
1288                     break;
1289                 }
1290                 set_current(current, history[history_len - 1 - history_index]);
1291                 refreshLine(current->prompt, current);
1292             }
1293             break;
1294         case ctrl('A'): /* Ctrl+a, go to the start of the line */
1295         case SPECIAL_HOME:
1296             current->pos = 0;
1297             refreshLine(current->prompt, current);
1298             break;
1299         case ctrl('E'): /* ctrl+e, go to the end of the line */
1300         case SPECIAL_END:
1301             current->pos = current->chars;
1302             refreshLine(current->prompt, current);
1303             break;
1304         case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
1305             if (remove_chars(current, 0, current->pos)) {
1306                 refreshLine(current->prompt, current);
1307             }
1308             break;
1309         case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
1310             if (remove_chars(current, current->pos, current->chars - current->pos)) {
1311                 refreshLine(current->prompt, current);
1312             }
1313             break;
1314         case ctrl('L'): /* Ctrl+L, clear screen */
1315             clearScreen(current);
1316             /* Force recalc of window size for serial terminals */
1317             current->cols = 0;
1318             refreshLine(current->prompt, current);
1319             break;
1320         default:
1321             /* Only tab is allowed without ^V */
1322             if (c == '\t' || c >= ' ') {
1323                 if (insert_char(current, current->pos, c) == 1) {
1324                     refreshLine(current->prompt, current);
1325                 }
1326             }
1327             break;
1328         }
1329     }
1330     return current->len;
1331 }
1332
1333 int linenoiseColumns(void)
1334 {
1335     struct current current;
1336     enableRawMode (&current);
1337     getWindowSize (&current);
1338     disableRawMode (&current);
1339     return current.cols;
1340 }
1341
1342 char *linenoise(const char *prompt)
1343 {
1344     int count;
1345     struct current current;
1346     char buf[LINENOISE_MAX_LINE];
1347
1348     if (enableRawMode(&current) == -1) {
1349         printf("%s", prompt);
1350         fflush(stdout);
1351         if (fgets(buf, sizeof(buf), stdin) == NULL) {
1352             return NULL;
1353         }
1354         count = strlen(buf);
1355         if (count && buf[count-1] == '\n') {
1356             count--;
1357             buf[count] = '\0';
1358         }
1359     }
1360     else
1361     {
1362         current.buf = buf;
1363         current.bufmax = sizeof(buf);
1364         current.len = 0;
1365         current.chars = 0;
1366         current.pos = 0;
1367         current.prompt = prompt;
1368
1369         count = linenoisePrompt(&current);
1370         disableRawMode(&current);
1371         printf("\n");
1372         if (count == -1) {
1373             return NULL;
1374         }
1375     }
1376     return strdup(buf);
1377 }
1378
1379 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1380 int linenoiseHistoryAdd(const char *line) {
1381     char *linecopy;
1382
1383     if (history_max_len == 0) return 0;
1384     if (history == NULL) {
1385         history = (char **)malloc(sizeof(char*)*history_max_len);
1386         if (history == NULL) return 0;
1387         memset(history,0,(sizeof(char*)*history_max_len));
1388     }
1389
1390     /* do not insert duplicate lines into history */
1391     if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1392         return 0;
1393     }
1394
1395     linecopy = strdup(line);
1396     if (!linecopy) return 0;
1397     if (history_len == history_max_len) {
1398         free(history[0]);
1399         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1400         history_len--;
1401     }
1402     history[history_len] = linecopy;
1403     history_len++;
1404     return 1;
1405 }
1406
1407 int linenoiseHistoryGetMaxLen(void) {
1408     return history_max_len;
1409 }
1410
1411 int linenoiseHistorySetMaxLen(int len) {
1412     char **newHistory;
1413
1414     if (len < 1) return 0;
1415     if (history) {
1416         int tocopy = history_len;
1417
1418         newHistory = (char **)malloc(sizeof(char*)*len);
1419         if (newHistory == NULL) return 0;
1420         if (len < tocopy) tocopy = len;
1421         memcpy(newHistory,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
1422         free(history);
1423         history = newHistory;
1424     }
1425     history_max_len = len;
1426     if (history_len > history_max_len)
1427         history_len = history_max_len;
1428     return 1;
1429 }
1430
1431 /* Save the history in the specified file. On success 0 is returned
1432  * otherwise -1 is returned. */
1433 int linenoiseHistorySave(const char *filename) {
1434     FILE *fp = fopen(filename,"w");
1435     int j;
1436
1437     if (fp == NULL) return -1;
1438     for (j = 0; j < history_len; j++) {
1439         const char *str = history[j];
1440         /* Need to encode backslash, nl and cr */
1441         while (*str) {
1442             if (*str == '\\') {
1443                 fputs("\\\\", fp);
1444             }
1445             else if (*str == '\n') {
1446                 fputs("\\n", fp);
1447             }
1448             else if (*str == '\r') {
1449                 fputs("\\r", fp);
1450             }
1451             else {
1452                 fputc(*str, fp);
1453             }
1454             str++;
1455         }
1456         fputc('\n', fp);
1457     }
1458
1459     fclose(fp);
1460     return 0;
1461 }
1462
1463 /* Load the history from the specified file. If the file does not exist
1464  * zero is returned and no operation is performed.
1465  *
1466  * If the file exists and the operation succeeded 0 is returned, otherwise
1467  * on error -1 is returned. */
1468 int linenoiseHistoryLoad(const char *filename) {
1469     FILE *fp = fopen(filename,"r");
1470     char buf[LINENOISE_MAX_LINE];
1471
1472     if (fp == NULL) return -1;
1473
1474     while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1475         char *src, *dest;
1476
1477         /* Decode backslash escaped values */
1478         for (src = dest = buf; *src; src++) {
1479             char ch = *src;
1480
1481             if (ch == '\\') {
1482                 src++;
1483                 if (*src == 'n') {
1484                     ch = '\n';
1485                 }
1486                 else if (*src == 'r') {
1487                     ch = '\r';
1488                 } else {
1489                     ch = *src;
1490                 }
1491             }
1492             *dest++ = ch;
1493         }
1494         /* Remove trailing newline */
1495         if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1496             dest--;
1497         }
1498         *dest = 0;
1499
1500         linenoiseHistoryAdd(buf);
1501     }
1502     fclose(fp);
1503     return 0;
1504 }
1505
1506 /* Provide access to the history buffer.
1507  *
1508  * If 'len' is not NULL, the length is stored in *len.
1509  */
1510 char **linenoiseHistory(int *len) {
1511     if (len) {
1512         *len = history_len;
1513     }
1514     return history;
1515 }