]> git.lizzy.rs Git - linenoise.git/blob - linenoise.c
Enable ^Z (SUSP) support
[linenoise.git] / linenoise.c
1 /* linenoise.c -- guerrilla line editing library against the idea that a
2  * line editing lib needs to be 20,000 lines of C code.
3  *
4  * You can find the latest source code at:
5  *
6  *   http://github.com/msteveb/linenoise
7  *   (forked from http://github.com/antirez/linenoise)
8  *
9  * Does a number of crazy assumptions that happen to be true in 99.9999% of
10  * the 2010 UNIX computers around.
11  *
12  * ------------------------------------------------------------------------
13  *
14  * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
15  * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
16  * Copyright (c) 2011, Steve Bennett <steveb at workware dot net dot au>
17  *
18  * All rights reserved.
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions are
22  * met:
23  *
24  *  *  Redistributions of source code must retain the above copyright
25  *     notice, this list of conditions and the following disclaimer.
26  *
27  *  *  Redistributions in binary form must reproduce the above copyright
28  *     notice, this list of conditions and the following disclaimer in the
29  *     documentation and/or other materials provided with the distribution.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42  *
43  * ------------------------------------------------------------------------
44  *
45  * References:
46  * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
47  * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
48  *
49  * Bloat:
50  * - Completion?
51  *
52  * Unix/termios
53  * ------------
54  * List of escape sequences used by this program, we do everything just
55  * a few sequences. In order to be so cheap we may have some
56  * flickering effect with some slow terminal, but the lesser sequences
57  * the more compatible.
58  *
59  * 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 <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 <signal.h>
133 #include <stdlib.h>
134 #include <sys/types.h>
135
136 #include "linenoise.h"
137 #include "utf8.h"
138
139 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
140 #define LINENOISE_MAX_LINE 4096
141
142 #define ctrl(C) ((C) - '@')
143
144 /* Use -ve numbers here to co-exist with normal unicode chars */
145 enum {
146     SPECIAL_NONE,
147     SPECIAL_UP = -20,
148     SPECIAL_DOWN = -21,
149     SPECIAL_LEFT = -22,
150     SPECIAL_RIGHT = -23,
151     SPECIAL_DELETE = -24,
152     SPECIAL_HOME = -25,
153     SPECIAL_END = -26,
154     SPECIAL_INSERT = -27,
155     SPECIAL_PAGE_UP = -28,
156     SPECIAL_PAGE_DOWN = -29
157 };
158
159 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
160 static int history_len = 0;
161 static char **history = NULL;
162
163 /* Structure to contain the status of the current (being edited) line */
164 struct current {
165     char *buf;  /* Current buffer. Always null terminated */
166     int bufmax; /* Size of the buffer, including space for the null termination */
167     int len;    /* Number of bytes in 'buf' */
168     int chars;  /* Number of chars in 'buf' (utf-8 chars) */
169     int pos;    /* Cursor position, measured in chars */
170     int cols;   /* Size of the window, in chars */
171     const char *prompt;
172     char *capture; /* Allocated capture buffer, or NULL for none. Always null terminated */
173 #if defined(USE_TERMIOS)
174     int fd;     /* Terminal fd */
175 #elif defined(USE_WINCONSOLE)
176     HANDLE outh; /* Console output handle */
177     HANDLE inh; /* Console input handle */
178     int rows;   /* Screen rows */
179     int x;      /* Current column during output */
180     int y;      /* Current row */
181 #endif
182 };
183
184 static int fd_read(struct current *current);
185 static int getWindowSize(struct current *current);
186
187 void linenoiseHistoryFree(void) {
188     if (history) {
189         int j;
190
191         for (j = 0; j < history_len; j++)
192             free(history[j]);
193         free(history);
194         history = NULL;
195         history_len = 0;
196     }
197 }
198
199 #if defined(USE_TERMIOS)
200 static void linenoiseAtExit(void);
201 static struct termios orig_termios; /* in order to restore at exit */
202 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
203 static int atexit_registered = 0; /* register atexit just 1 time */
204
205 static const char *unsupported_term[] = {"dumb","cons25",NULL};
206
207 static int isUnsupportedTerm(void) {
208     char *term = getenv("TERM");
209
210     if (term) {
211         int j;
212         for (j = 0; unsupported_term[j]; j++) {
213             if (strcmp(term, unsupported_term[j]) == 0) {
214                 return 1;
215             }
216         }
217     }
218     return 0;
219 }
220
221 static int enableRawMode(struct current *current) {
222     struct termios raw;
223
224     current->fd = STDIN_FILENO;
225     current->cols = 0;
226
227     if (!isatty(current->fd) || isUnsupportedTerm() ||
228         tcgetattr(current->fd, &orig_termios) == -1) {
229 fatal:
230         errno = ENOTTY;
231         return -1;
232     }
233
234     if (!atexit_registered) {
235         atexit(linenoiseAtExit);
236         atexit_registered = 1;
237     }
238
239     raw = orig_termios;  /* modify the original mode */
240     /* input modes: no break, no CR to NL, no parity check, no strip char,
241      * no start/stop output control. */
242     raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
243     /* output modes - actually, no need to disable post processing */
244     /*raw.c_oflag &= ~(OPOST);*/
245     /* control modes - set 8 bit chars */
246     raw.c_cflag |= (CS8);
247     /* local modes - choing off, canonical off, no extended functions,
248      * no signal chars (^Z,^C) */
249     raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
250     /* control chars - set return condition: min number of bytes and timer.
251      * We want read to return every single byte, without timeout. */
252     raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
253
254     /* put terminal in raw mode after flushing */
255     if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
256         goto fatal;
257     }
258     rawmode = 1;
259     return 0;
260 }
261
262 static void disableRawMode(struct current *current) {
263     /* Don't even check the return value as it's too late. */
264     if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
265         rawmode = 0;
266 }
267
268 /* At exit we'll try to fix the terminal to the initial conditions. */
269 static void linenoiseAtExit(void) {
270     if (rawmode) {
271         tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
272     }
273     linenoiseHistoryFree();
274 }
275
276 /* gcc/glibc insists that we care about the return code of write!
277  * Clarification: This means that a void-cast like "(void) (EXPR)"
278  * does not work.
279  */
280 #define IGNORE_RC(EXPR) if (EXPR) {}
281
282 /* This is fdprintf() on some systems, but use a different
283  * name to avoid conflicts
284  */
285 static void fd_printf(int fd, const char *format, ...)
286 {
287     va_list args;
288     char buf[64];
289     int n;
290
291     va_start(args, format);
292     n = vsnprintf(buf, sizeof(buf), format, args);
293     va_end(args);
294     IGNORE_RC(write(fd, buf, n));
295 }
296
297 void linenoiseClearScreen(void)
298 {
299     fd_printf(STDOUT_FILENO, "\x1b[H\x1b[2J");
300 }
301
302 static void cursorToLeft(struct current *current)
303 {
304     fd_printf(current->fd, "\r");
305 }
306
307 static int outputChars(struct current *current, const char *buf, int len)
308 {
309     return write(current->fd, buf, len);
310 }
311
312 static void outputControlChar(struct current *current, char ch)
313 {
314     fd_printf(current->fd, "\x1b[7m^%c\x1b[0m", ch);
315 }
316
317 static void eraseEol(struct current *current)
318 {
319     fd_printf(current->fd, "\x1b[0K");
320 }
321
322 static void setCursorPos(struct current *current, int x)
323 {
324     if (x == 0) {
325         cursorToLeft(current);
326     }
327     else {
328         fd_printf(current->fd, "\r\x1b[%dC", x);
329     }
330 }
331
332 /**
333  * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
334  *
335  * A timeout of -1 means to wait forever.
336  *
337  * Returns -1 if no char is received within the time or an error occurs.
338  */
339 static int fd_read_char(int fd, int timeout)
340 {
341     struct pollfd p;
342     unsigned char c;
343
344     p.fd = fd;
345     p.events = POLLIN;
346
347     if (poll(&p, 1, timeout) == 0) {
348         /* timeout */
349         return -1;
350     }
351     if (read(fd, &c, 1) != 1) {
352         return -1;
353     }
354     return c;
355 }
356
357 /**
358  * Reads a complete utf-8 character
359  * and returns the unicode value, or -1 on error.
360  */
361 static int fd_read(struct current *current)
362 {
363 #ifdef USE_UTF8
364     char buf[MAX_UTF8_LEN];
365     int n;
366     int i;
367     int c;
368
369     if (read(current->fd, &buf[0], 1) != 1) {
370         return -1;
371     }
372     n = utf8_charlen(buf[0]);
373     if (n < 1) {
374         return -1;
375     }
376     for (i = 1; i < n; i++) {
377         if (read(current->fd, &buf[i], 1) != 1) {
378             return -1;
379         }
380     }
381     /* decode and return the character */
382     utf8_tounicode(buf, &c);
383     return c;
384 #else
385     return fd_read_char(current->fd, -1);
386 #endif
387 }
388
389 static int countColorControlChars(const char* prompt)
390 {
391     /* ANSI color control sequences have the form:
392      * "\x1b" "[" [0-9;]* "m"
393      * We parse them with a simple state machine.
394      */
395
396     enum {
397         search_esc,
398         expect_bracket,
399         expect_trail
400     } state = search_esc;
401     int len = 0, found = 0;
402     char ch;
403
404     /* XXX: Strictly we should be checking utf8 chars rather than
405      *      bytes in case of the extremely unlikely scenario where
406      *      an ANSI sequence is part of a utf8 sequence.
407      */
408     while ((ch = *prompt++) != 0) {
409         switch (state) {
410         case search_esc:
411             if (ch == '\x1b') {
412                 state = expect_bracket;
413             }
414             break;
415         case expect_bracket:
416             if (ch == '[') {
417                 state = expect_trail;
418                 /* 3 for "\e[ ... m" */
419                 len = 3;
420                 break;
421             }
422             state = search_esc;
423             break;
424         case expect_trail:
425             if ((ch == ';') || ((ch >= '0' && ch <= '9'))) {
426                 /* 0-9, or semicolon */
427                 len++;
428                 break;
429             }
430             if (ch == 'm') {
431                 found += len;
432             }
433             state = search_esc;
434             break;
435         }
436     }
437
438     return found;
439 }
440
441 /**
442  * Stores the current cursor column in '*cols'.
443  * Returns 1 if OK, or 0 if failed to determine cursor pos.
444  */
445 static int queryCursor(int fd, int* cols)
446 {
447     /* control sequence - report cursor location */
448     fd_printf(fd, "\x1b[6n");
449
450     /* Parse the response: ESC [ rows ; cols R */
451     if (fd_read_char(fd, 100) == 0x1b &&
452         fd_read_char(fd, 100) == '[') {
453
454         int n = 0;
455         while (1) {
456             int ch = fd_read_char(fd, 100);
457             if (ch == ';') {
458                 /* Ignore rows */
459                 n = 0;
460             }
461             else if (ch == 'R') {
462                 /* Got cols */
463                 if (n != 0 && n < 1000) {
464                     *cols = n;
465                 }
466                 break;
467             }
468             else if (ch >= 0 && ch <= '9') {
469                 n = n * 10 + ch - '0';
470             }
471             else {
472                 break;
473             }
474         }
475         return 1;
476     }
477
478     return 0;
479 }
480
481 /**
482  * Updates current->cols with the current window size (width)
483  */
484 static int getWindowSize(struct current *current)
485 {
486     struct winsize ws;
487
488     if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
489         current->cols = ws.ws_col;
490         return 0;
491     }
492
493     /* Failed to query the window size. Perhaps we are on a serial terminal.
494      * Try to query the width by sending the cursor as far to the right
495      * and reading back the cursor position.
496      * Note that this is only done once per call to linenoise rather than
497      * every time the line is refreshed for efficiency reasons.
498      *
499      * In more detail, we:
500      * (a) request current cursor position,
501      * (b) move cursor far right,
502      * (c) request cursor position again,
503      * (d) at last move back to the old position.
504      * This gives us the width without messing with the externally
505      * visible cursor position.
506      */
507
508     if (current->cols == 0) {
509         int here;
510
511         current->cols = 80;
512
513         /* (a) */
514         if (queryCursor (current->fd, &here)) {
515             /* (b) */
516             fd_printf(current->fd, "\x1b[999C");
517
518             /* (c). Note: If (a) succeeded, then (c) should as well.
519              * For paranoia we still check and have a fallback action
520              * for (d) in case of failure..
521              */
522             if (!queryCursor (current->fd, &current->cols)) {
523                 /* (d') Unable to get accurate position data, reset
524                  * the cursor to the far left. While this may not
525                  * restore the exact original position it should not
526                  * be too bad.
527                  */
528                 fd_printf(current->fd, "\r");
529             } else {
530                 /* (d) Reset the cursor back to the original location. */
531                 if (current->cols > here) {
532                     fd_printf(current->fd, "\x1b[%dD", current->cols - here);
533                 }
534             }
535         } /* 1st query failed, doing nothing => default 80 */
536     }
537
538     return 0;
539 }
540
541 /**
542  * If escape (27) was received, reads subsequent
543  * chars to determine if this is a known special key.
544  *
545  * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
546  *
547  * If no additional char is received within a short time,
548  * 27 is returned.
549  */
550 static int check_special(int fd)
551 {
552     int c = fd_read_char(fd, 50);
553     int c2;
554
555     if (c < 0) {
556         return 27;
557     }
558
559     c2 = fd_read_char(fd, 50);
560     if (c2 < 0) {
561         return c2;
562     }
563     if (c == '[' || c == 'O') {
564         /* Potential arrow key */
565         switch (c2) {
566             case 'A':
567                 return SPECIAL_UP;
568             case 'B':
569                 return SPECIAL_DOWN;
570             case 'C':
571                 return SPECIAL_RIGHT;
572             case 'D':
573                 return SPECIAL_LEFT;
574             case 'F':
575                 return SPECIAL_END;
576             case 'H':
577                 return SPECIAL_HOME;
578         }
579     }
580     if (c == '[' && c2 >= '1' && c2 <= '8') {
581         /* extended escape */
582         c = fd_read_char(fd, 50);
583         if (c == '~') {
584             switch (c2) {
585                 case '2':
586                     return SPECIAL_INSERT;
587                 case '3':
588                     return SPECIAL_DELETE;
589                 case '5':
590                     return SPECIAL_PAGE_UP;
591                 case '6':
592                     return SPECIAL_PAGE_DOWN;
593                 case '7':
594                     return SPECIAL_HOME;
595                 case '8':
596                     return SPECIAL_END;
597             }
598         }
599         while (c != -1 && c != '~') {
600             /* .e.g \e[12~ or '\e[11;2~   discard the complete sequence */
601             c = fd_read_char(fd, 50);
602         }
603     }
604
605     return SPECIAL_NONE;
606 }
607 #elif defined(USE_WINCONSOLE)
608
609 static DWORD orig_consolemode = 0;
610
611 static int enableRawMode(struct current *current) {
612     DWORD n;
613     INPUT_RECORD irec;
614
615     current->outh = GetStdHandle(STD_OUTPUT_HANDLE);
616     current->inh = GetStdHandle(STD_INPUT_HANDLE);
617
618     if (!PeekConsoleInput(current->inh, &irec, 1, &n)) {
619         return -1;
620     }
621     if (getWindowSize(current) != 0) {
622         return -1;
623     }
624     if (GetConsoleMode(current->inh, &orig_consolemode)) {
625         SetConsoleMode(current->inh, ENABLE_PROCESSED_INPUT);
626     }
627     return 0;
628 }
629
630 static void disableRawMode(struct current *current)
631 {
632     SetConsoleMode(current->inh, orig_consolemode);
633 }
634
635 void linenoiseClearScreen(void)
636 {
637     /* XXX: This is ugly. Should just have the caller pass a handle */
638     struct current current;
639
640     current.outh = GetStdHandle(STD_OUTPUT_HANDLE);
641
642     if (getWindowSize(&current) == 0) {
643         COORD topleft = { 0, 0 };
644         DWORD n;
645
646         FillConsoleOutputCharacter(current.outh, ' ',
647             current.cols * current.rows, topleft, &n);
648         FillConsoleOutputAttribute(current.outh,
649             FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN,
650             current.cols * current.rows, topleft, &n);
651         SetConsoleCursorPosition(current.outh, topleft);
652     }
653 }
654
655 static void cursorToLeft(struct current *current)
656 {
657     COORD pos;
658     DWORD n;
659
660     pos.X = 0;
661     pos.Y = (SHORT)current->y;
662
663     FillConsoleOutputAttribute(current->outh,
664         FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, current->cols, pos, &n);
665     current->x = 0;
666 }
667
668 static int outputChars(struct current *current, const char *buf, int len)
669 {
670     COORD pos;
671     DWORD n;
672
673     pos.Y = (SHORT)current->y;
674
675 #ifdef USE_UTF8
676     while ( len > 0 ) {
677         int c, s;
678         wchar_t wc;
679
680         s = utf8_tounicode(buf, &c);
681
682         len -= s;
683         buf += s;
684
685         wc = (wchar_t)c;
686
687         pos.X = (SHORT)current->x;
688
689         /* fixed display utf8 character */
690         WriteConsoleOutputCharacterW(current->outh, &wc, 1, pos, &n);
691
692         current->x += utf8_width(c);
693     }
694 #else
695     pos.X = (SHORT)current->x;
696
697     WriteConsoleOutputCharacterA(current->outh, buf, len, pos, &n);
698     current->x += len;
699 #endif
700
701     return 0;
702 }
703
704 static void outputControlChar(struct current *current, char ch)
705 {
706     COORD pos;
707     DWORD n;
708
709     pos.X = (SHORT) current->x;
710     pos.Y = (SHORT) current->y;
711
712     FillConsoleOutputAttribute(current->outh, BACKGROUND_INTENSITY, 2, pos, &n);
713     outputChars(current, "^", 1);
714     outputChars(current, &ch, 1);
715 }
716
717 static void eraseEol(struct current *current)
718 {
719     COORD pos;
720     DWORD n;
721
722     pos.X = (SHORT) current->x;
723     pos.Y = (SHORT) current->y;
724
725     FillConsoleOutputCharacter(current->outh, ' ', current->cols - current->x, pos, &n);
726 }
727
728 static void setCursorPos(struct current *current, int x)
729 {
730     COORD pos;
731
732     pos.X = (SHORT)x;
733     pos.Y = (SHORT) current->y;
734
735     SetConsoleCursorPosition(current->outh, pos);
736     current->x = x;
737 }
738
739 static int fd_read(struct current *current)
740 {
741     while (1) {
742         INPUT_RECORD irec;
743         DWORD n;
744         if (WaitForSingleObject(current->inh, INFINITE) != WAIT_OBJECT_0) {
745             break;
746         }
747         if (!ReadConsoleInput (current->inh, &irec, 1, &n)) {
748             break;
749         }
750         if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown) {
751             KEY_EVENT_RECORD *k = &irec.Event.KeyEvent;
752             if (k->dwControlKeyState & ENHANCED_KEY) {
753                 switch (k->wVirtualKeyCode) {
754                  case VK_LEFT:
755                     return SPECIAL_LEFT;
756                  case VK_RIGHT:
757                     return SPECIAL_RIGHT;
758                  case VK_UP:
759                     return SPECIAL_UP;
760                  case VK_DOWN:
761                     return SPECIAL_DOWN;
762                  case VK_INSERT:
763                     return SPECIAL_INSERT;
764                  case VK_DELETE:
765                     return SPECIAL_DELETE;
766                  case VK_HOME:
767                     return SPECIAL_HOME;
768                  case VK_END:
769                     return SPECIAL_END;
770                  case VK_PRIOR:
771                     return SPECIAL_PAGE_UP;
772                  case VK_NEXT:
773                     return SPECIAL_PAGE_DOWN;
774                 }
775             }
776             /* Note that control characters are already translated in AsciiChar */
777             else if (k->wVirtualKeyCode == VK_CONTROL)
778                 continue;
779             else {
780 #ifdef USE_UTF8
781                 return k->uChar.UnicodeChar;
782 #else
783                 return k->uChar.AsciiChar;
784 #endif
785             }
786         }
787     }
788     return -1;
789 }
790
791 static int countColorControlChars(const char* prompt)
792 {
793     /* For windows we assume that there are no embedded ansi color
794      * control sequences.
795      */
796     return 0;
797 }
798
799 static int getWindowSize(struct current *current)
800 {
801     CONSOLE_SCREEN_BUFFER_INFO info;
802     if (!GetConsoleScreenBufferInfo(current->outh, &info)) {
803         return -1;
804     }
805     current->cols = info.dwSize.X;
806     current->rows = info.dwSize.Y;
807     if (current->cols <= 0 || current->rows <= 0) {
808         current->cols = 80;
809         return -1;
810     }
811     current->y = info.dwCursorPosition.Y;
812     current->x = info.dwCursorPosition.X;
813     return 0;
814 }
815 #endif
816
817 #ifndef utf8_getchars
818 static int utf8_getchars(char *buf, int c)
819 {
820 #ifdef USE_UTF8
821     return utf8_fromunicode(buf, c);
822 #else
823     *buf = c;
824     return 1;
825 #endif
826 }
827 #endif
828
829 /**
830  * Returns the unicode character at the given offset,
831  * or -1 if none.
832  */
833 static int get_char(struct current *current, int pos)
834 {
835     if (pos >= 0 && pos < current->chars) {
836         int c;
837         int i = utf8_index(current->buf, pos);
838         (void)utf8_tounicode(current->buf + i, &c);
839         return c;
840     }
841     return -1;
842 }
843
844 static void refreshLine(const char *prompt, struct current *current)
845 {
846     int plen;
847     int pchars;
848     int backup = 0;
849     int i;
850     const char *buf = current->buf;
851     int chars = current->chars;
852     int pos = current->pos;
853     int b;
854     int ch;
855     int n;
856     int width;
857     int bufwidth;
858
859     /* Should intercept SIGWINCH. For now, just get the size every time */
860     getWindowSize(current);
861
862     plen = strlen(prompt);
863     pchars = utf8_strwidth(prompt, utf8_strlen(prompt, plen));
864
865     /* Scan the prompt for embedded ansi color control sequences and
866      * discount them as characters/columns.
867      */
868     pchars -= countColorControlChars(prompt);
869
870     /* Account for a line which is too long to fit in the window.
871      * Note that control chars require an extra column
872      */
873
874     /* How many cols are required to the left of 'pos'?
875      * The prompt, plus one extra for each control char
876      */
877     n = pchars + utf8_strwidth(buf, utf8_strlen(buf, current->len));
878     b = 0;
879     for (i = 0; i < pos; i++) {
880         b += utf8_tounicode(buf + b, &ch);
881         if (ch < ' ') {
882             n++;
883         }
884     }
885
886     /* Pluse one if the current char is a control character */
887     if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
888         n++;
889     }
890
891     /* If too many are needed, strip chars off the front of 'buf'
892      * until it fits. Note that if the current char is a control character,
893      * we need one extra col.
894      */
895     while (n >= current->cols && pos > 0) {
896         b = utf8_tounicode(buf, &ch);
897         if (ch < ' ') {
898             n--;
899         }
900         n -= utf8_width(ch);
901         buf += b;
902         pos--;
903         chars--;
904     }
905
906     /* Cursor to left edge, then the prompt */
907     cursorToLeft(current);
908     outputChars(current, prompt, plen);
909
910     /* Now the current buffer content */
911
912     /* Need special handling for control characters.
913      * If we hit 'cols', stop.
914      */
915     b = 0; /* unwritted bytes */
916     n = 0; /* How many control chars were written */
917     width = 0; /* current display width */
918     bufwidth = utf8_strwidth(buf, pos);
919
920     for (i = 0; i < chars; i++) {
921         int ch;
922         int w = utf8_tounicode(buf + b, &ch);
923         if (ch < ' ') {
924             n++;
925         }
926
927         width += utf8_width(ch);
928
929         if (pchars + width + n >= current->cols) {
930             break;
931         }
932         if (ch < ' ') {
933             /* A control character, so write the buffer so far */
934             outputChars(current, buf, b);
935             buf += b + w;
936             b = 0;
937             outputControlChar(current, ch + '@');
938             if (i < pos) {
939                 backup++;
940             }
941         }
942         else {
943             b += w;
944         }
945     }
946     outputChars(current, buf, b);
947
948     /* Erase to right, move cursor to original position */
949     eraseEol(current);
950     setCursorPos(current, bufwidth + pchars + backup);
951 }
952
953 static void set_current(struct current *current, const char *str)
954 {
955     strncpy(current->buf, str, current->bufmax);
956     current->buf[current->bufmax - 1] = 0;
957     current->len = strlen(current->buf);
958     current->pos = current->chars = utf8_strlen(current->buf, current->len);
959 }
960
961 static int has_room(struct current *current, int bytes)
962 {
963     return current->len + bytes < current->bufmax - 1;
964 }
965
966 /**
967  * Removes the char at 'pos'.
968  *
969  * Returns 1 if the line needs to be refreshed, 2 if not
970  * and 0 if nothing was removed
971  */
972 static int remove_char(struct current *current, int pos)
973 {
974     if (pos >= 0 && pos < current->chars) {
975         int p1, p2;
976         int ret = 1;
977         p1 = utf8_index(current->buf, pos);
978         p2 = p1 + utf8_index(current->buf + p1, 1);
979
980 #ifdef USE_TERMIOS
981         /* optimise remove char in the case of removing the last char */
982         if (current->pos == pos + 1 && current->pos == current->chars) {
983             if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
984                 ret = 2;
985                 fd_printf(current->fd, "\b \b");
986             }
987         }
988 #endif
989
990         /* Move the null char too */
991         memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
992         current->len -= (p2 - p1);
993         current->chars--;
994
995         if (current->pos > pos) {
996             current->pos--;
997         }
998         return ret;
999     }
1000     return 0;
1001 }
1002
1003 /**
1004  * Insert 'ch' at position 'pos'
1005  *
1006  * Returns 1 if the line needs to be refreshed, 2 if not
1007  * and 0 if nothing was inserted (no room)
1008  */
1009 static int insert_char(struct current *current, int pos, int ch)
1010 {
1011     char buf[MAX_UTF8_LEN];
1012     int n = utf8_getchars(buf, ch);
1013
1014     if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
1015         int p1, p2;
1016         int ret = 1;
1017         p1 = utf8_index(current->buf, pos);
1018         p2 = p1 + n;
1019
1020 #ifdef USE_TERMIOS
1021         /* optimise the case where adding a single char to the end and no scrolling is needed */
1022         if (current->pos == pos && current->chars == pos) {
1023             if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
1024                 IGNORE_RC(write(current->fd, buf, n));
1025                 ret = 2;
1026             }
1027         }
1028 #endif
1029
1030         memmove(current->buf + p2, current->buf + p1, current->len - p1);
1031         memcpy(current->buf + p1, buf, n);
1032         current->len += n;
1033
1034         current->chars++;
1035         if (current->pos >= pos) {
1036             current->pos++;
1037         }
1038         return ret;
1039     }
1040     return 0;
1041 }
1042
1043 /**
1044  * Captures up to 'n' characters starting at 'pos' for the cut buffer.
1045  *
1046  * This replaces any existing characters in the cut buffer.
1047  */
1048 static void capture_chars(struct current *current, int pos, int n)
1049 {
1050     if (pos >= 0 && (pos + n - 1) < current->chars) {
1051         int p1 = utf8_index(current->buf, pos);
1052         int nbytes = utf8_index(current->buf + p1, n);
1053
1054         if (nbytes) {
1055             free(current->capture);
1056             /* Include space for the null terminator */
1057             current->capture = (char *)malloc(nbytes + 1);
1058             memcpy(current->capture, current->buf + p1, nbytes);
1059             current->capture[nbytes] = '\0';
1060         }
1061     }
1062 }
1063
1064 /**
1065  * Removes up to 'n' characters at cursor position 'pos'.
1066  *
1067  * Returns 0 if no chars were removed or non-zero otherwise.
1068  */
1069 static int remove_chars(struct current *current, int pos, int n)
1070 {
1071     int removed = 0;
1072
1073     /* First save any chars which will be removed */
1074     capture_chars(current, pos, n);
1075
1076     while (n-- && remove_char(current, pos)) {
1077         removed++;
1078     }
1079     return removed;
1080 }
1081 /**
1082  * Inserts the characters (string) 'chars' at the cursor position 'pos'.
1083  *
1084  * Returns 0 if no chars were inserted or non-zero otherwise.
1085  */
1086 static int insert_chars(struct current *current, int pos, const char *chars)
1087 {
1088     int inserted = 0;
1089
1090     while (*chars) {
1091         int ch;
1092         int n = utf8_tounicode(chars, &ch);
1093         if (insert_char(current, pos, ch) == 0) {
1094             break;
1095         }
1096         inserted++;
1097         pos++;
1098         chars += n;
1099     }
1100     return inserted;
1101 }
1102
1103 #ifndef NO_COMPLETION
1104 static linenoiseCompletionCallback *completionCallback = NULL;
1105 static void *completionUserdata = NULL;
1106
1107 static void beep() {
1108 #ifdef USE_TERMIOS
1109     fprintf(stderr, "\x7");
1110     fflush(stderr);
1111 #endif
1112 }
1113
1114 static void freeCompletions(linenoiseCompletions *lc) {
1115     size_t i;
1116     for (i = 0; i < lc->len; i++)
1117         free(lc->cvec[i]);
1118     free(lc->cvec);
1119 }
1120
1121 static int completeLine(struct current *current) {
1122     linenoiseCompletions lc = { 0, NULL };
1123     int c = 0;
1124
1125     completionCallback(current->buf,&lc,completionUserdata);
1126     if (lc.len == 0) {
1127         beep();
1128     } else {
1129         size_t stop = 0, i = 0;
1130
1131         while(!stop) {
1132             /* Show completion or original buffer */
1133             if (i < lc.len) {
1134                 struct current tmp = *current;
1135                 tmp.buf = lc.cvec[i];
1136                 tmp.pos = tmp.len = strlen(tmp.buf);
1137                 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
1138                 refreshLine(current->prompt, &tmp);
1139             } else {
1140                 refreshLine(current->prompt, current);
1141             }
1142
1143             c = fd_read(current);
1144             if (c == -1) {
1145                 break;
1146             }
1147
1148             switch(c) {
1149                 case '\t': /* tab */
1150                     i = (i+1) % (lc.len+1);
1151                     if (i == lc.len) beep();
1152                     break;
1153                 case 27: /* escape */
1154                     /* Re-show original buffer */
1155                     if (i < lc.len) {
1156                         refreshLine(current->prompt, current);
1157                     }
1158                     stop = 1;
1159                     break;
1160                 default:
1161                     /* Update buffer and return */
1162                     if (i < lc.len) {
1163                         set_current(current,lc.cvec[i]);
1164                     }
1165                     stop = 1;
1166                     break;
1167             }
1168         }
1169     }
1170
1171     freeCompletions(&lc);
1172     return c; /* Return last read character */
1173 }
1174
1175 /* Register a callback function to be called for tab-completion.
1176    Returns the prior callback so that the caller may (if needed)
1177    restore it when done. */
1178 linenoiseCompletionCallback * linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn, void *userdata) {
1179     linenoiseCompletionCallback * old = completionCallback;
1180     completionCallback = fn;
1181     completionUserdata = userdata;
1182     return old;
1183 }
1184
1185 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
1186     lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
1187     lc->cvec[lc->len++] = strdup(str);
1188 }
1189
1190 #endif
1191
1192 static int linenoiseEdit(struct current *current) {
1193     int history_index = 0;
1194
1195     /* The latest history entry is always our current buffer, that
1196      * initially is just an empty string. */
1197     linenoiseHistoryAdd("");
1198
1199     set_current(current, "");
1200     refreshLine(current->prompt, current);
1201
1202     while(1) {
1203         int dir = -1;
1204         int c = fd_read(current);
1205
1206 #ifndef NO_COMPLETION
1207         /* Only autocomplete when the callback is set. It returns < 0 when
1208          * there was an error reading from fd. Otherwise it will return the
1209          * character that should be handled next. */
1210         if (c == '\t' && current->pos == current->chars && completionCallback != NULL) {
1211             c = completeLine(current);
1212             /* Return on errors */
1213             if (c < 0) return current->len;
1214             /* Read next character when 0 */
1215             if (c == 0) continue;
1216         }
1217 #endif
1218
1219 process_char:
1220         if (c == -1) return current->len;
1221 #ifdef USE_TERMIOS
1222         if (c == 27) {   /* escape sequence */
1223             c = check_special(current->fd);
1224         }
1225 #endif
1226         switch(c) {
1227         case '\r':    /* enter */
1228             history_len--;
1229             free(history[history_len]);
1230             return current->len;
1231         case ctrl('C'):     /* ctrl-c */
1232             errno = EAGAIN;
1233             return -1;
1234         case ctrl('Z'):     /* ctrl-z */
1235 #ifdef SIGTSTP
1236             /* send ourselves SIGSUSP */
1237             disableRawMode(current);
1238             raise(SIGTSTP);
1239             /* and resume */
1240             enableRawMode(current);
1241             refreshLine(current->prompt, current);
1242 #endif
1243             continue;
1244         case 127:   /* backspace */
1245         case ctrl('H'):
1246             if (remove_char(current, current->pos - 1) == 1) {
1247                 refreshLine(current->prompt, current);
1248             }
1249             break;
1250         case ctrl('D'):     /* ctrl-d */
1251             if (current->len == 0) {
1252                 /* Empty line, so EOF */
1253                 history_len--;
1254                 free(history[history_len]);
1255                 return -1;
1256             }
1257             /* Otherwise fall through to delete char to right of cursor */
1258         case SPECIAL_DELETE:
1259             if (remove_char(current, current->pos) == 1) {
1260                 refreshLine(current->prompt, current);
1261             }
1262             break;
1263         case SPECIAL_INSERT:
1264             /* Ignore. Expansion Hook.
1265              * Future possibility: Toggle Insert/Overwrite Modes
1266              */
1267             break;
1268         case ctrl('W'):    /* ctrl-w, delete word at left. save deleted chars */
1269             /* eat any spaces on the left */
1270             {
1271                 int pos = current->pos;
1272                 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1273                     pos--;
1274                 }
1275
1276                 /* now eat any non-spaces on the left */
1277                 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1278                     pos--;
1279                 }
1280
1281                 if (remove_chars(current, pos, current->pos - pos)) {
1282                     refreshLine(current->prompt, current);
1283                 }
1284             }
1285             break;
1286         case ctrl('R'):    /* ctrl-r */
1287             {
1288                 /* Display the reverse-i-search prompt and process chars */
1289                 char rbuf[50];
1290                 char rprompt[80];
1291                 int rchars = 0;
1292                 int rlen = 0;
1293                 int searchpos = history_len - 1;
1294
1295                 rbuf[0] = 0;
1296                 while (1) {
1297                     int n = 0;
1298                     const char *p = NULL;
1299                     int skipsame = 0;
1300                     int searchdir = -1;
1301
1302                     snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1303                     refreshLine(rprompt, current);
1304                     c = fd_read(current);
1305                     if (c == ctrl('H') || c == 127) {
1306                         if (rchars) {
1307                             int p = utf8_index(rbuf, --rchars);
1308                             rbuf[p] = 0;
1309                             rlen = strlen(rbuf);
1310                         }
1311                         continue;
1312                     }
1313 #ifdef USE_TERMIOS
1314                     if (c == 27) {
1315                         c = check_special(current->fd);
1316                     }
1317 #endif
1318                     if (c == ctrl('P') || c == SPECIAL_UP) {
1319                         /* Search for the previous (earlier) match */
1320                         if (searchpos > 0) {
1321                             searchpos--;
1322                         }
1323                         skipsame = 1;
1324                     }
1325                     else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1326                         /* Search for the next (later) match */
1327                         if (searchpos < history_len) {
1328                             searchpos++;
1329                         }
1330                         searchdir = 1;
1331                         skipsame = 1;
1332                     }
1333                     else if (c >= ' ') {
1334                         /* >= here to allow for null terminator */
1335                         if (rlen >= (int)sizeof(rbuf) - MAX_UTF8_LEN) {
1336                             continue;
1337                         }
1338
1339                         n = utf8_getchars(rbuf + rlen, c);
1340                         rlen += n;
1341                         rchars++;
1342                         rbuf[rlen] = 0;
1343
1344                         /* Adding a new char resets the search location */
1345                         searchpos = history_len - 1;
1346                     }
1347                     else {
1348                         /* Exit from incremental search mode */
1349                         break;
1350                     }
1351
1352                     /* Now search through the history for a match */
1353                     for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1354                         p = strstr(history[searchpos], rbuf);
1355                         if (p) {
1356                             /* Found a match */
1357                             if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
1358                                 /* But it is identical, so skip it */
1359                                 continue;
1360                             }
1361                             /* Copy the matching line and set the cursor position */
1362                             set_current(current,history[searchpos]);
1363                             current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1364                             break;
1365                         }
1366                     }
1367                     if (!p && n) {
1368                         /* No match, so don't add it */
1369                         rchars--;
1370                         rlen -= n;
1371                         rbuf[rlen] = 0;
1372                     }
1373                 }
1374                 if (c == ctrl('G') || c == ctrl('C')) {
1375                     /* ctrl-g terminates the search with no effect */
1376                     set_current(current, "");
1377                     c = 0;
1378                 }
1379                 else if (c == ctrl('J')) {
1380                     /* ctrl-j terminates the search leaving the buffer in place */
1381                     c = 0;
1382                 }
1383                 /* Go process the char normally */
1384                 refreshLine(current->prompt, current);
1385                 goto process_char;
1386             }
1387             break;
1388         case ctrl('T'):    /* ctrl-t */
1389             if (current->pos > 0 && current->pos <= current->chars) {
1390                 /* If cursor is at end, transpose the previous two chars */
1391                 int fixer = (current->pos == current->chars);
1392                 c = get_char(current, current->pos - fixer);
1393                 remove_char(current, current->pos - fixer);
1394                 insert_char(current, current->pos - 1, c);
1395                 refreshLine(current->prompt, current);
1396             }
1397             break;
1398         case ctrl('V'):    /* ctrl-v */
1399             if (has_room(current, MAX_UTF8_LEN)) {
1400                 /* Insert the ^V first */
1401                 if (insert_char(current, current->pos, c)) {
1402                     refreshLine(current->prompt, current);
1403                     /* Now wait for the next char. Can insert anything except \0 */
1404                     c = fd_read(current);
1405
1406                     /* Remove the ^V first */
1407                     remove_char(current, current->pos - 1);
1408                     if (c != -1) {
1409                         /* Insert the actual char */
1410                         insert_char(current, current->pos, c);
1411                     }
1412                     refreshLine(current->prompt, current);
1413                 }
1414             }
1415             break;
1416         case ctrl('B'):
1417         case SPECIAL_LEFT:
1418             if (current->pos > 0) {
1419                 current->pos--;
1420                 refreshLine(current->prompt, current);
1421             }
1422             break;
1423         case ctrl('F'):
1424         case SPECIAL_RIGHT:
1425             if (current->pos < current->chars) {
1426                 current->pos++;
1427                 refreshLine(current->prompt, current);
1428             }
1429             break;
1430         case SPECIAL_PAGE_UP:
1431           dir = history_len - history_index - 1; /* move to start of history */
1432           goto history_navigation;
1433         case SPECIAL_PAGE_DOWN:
1434           dir = -history_index; /* move to 0 == end of history, i.e. current */
1435           goto history_navigation;
1436         case ctrl('P'):
1437         case SPECIAL_UP:
1438             dir = 1;
1439           goto history_navigation;
1440         case ctrl('N'):
1441         case SPECIAL_DOWN:
1442 history_navigation:
1443             if (history_len > 1) {
1444                 /* Update the current history entry before to
1445                  * overwrite it with tne next one. */
1446                 free(history[history_len - 1 - history_index]);
1447                 history[history_len - 1 - history_index] = strdup(current->buf);
1448                 /* Show the new entry */
1449                 history_index += dir;
1450                 if (history_index < 0) {
1451                     history_index = 0;
1452                     break;
1453                 } else if (history_index >= history_len) {
1454                     history_index = history_len - 1;
1455                     break;
1456                 }
1457                 set_current(current, history[history_len - 1 - history_index]);
1458                 refreshLine(current->prompt, current);
1459             }
1460             break;
1461         case ctrl('A'): /* Ctrl+a, go to the start of the line */
1462         case SPECIAL_HOME:
1463             current->pos = 0;
1464             refreshLine(current->prompt, current);
1465             break;
1466         case ctrl('E'): /* ctrl+e, go to the end of the line */
1467         case SPECIAL_END:
1468             current->pos = current->chars;
1469             refreshLine(current->prompt, current);
1470             break;
1471         case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */
1472             if (remove_chars(current, 0, current->pos)) {
1473                 refreshLine(current->prompt, current);
1474             }
1475             break;
1476         case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */
1477             if (remove_chars(current, current->pos, current->chars - current->pos)) {
1478                 refreshLine(current->prompt, current);
1479             }
1480             break;
1481         case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */
1482             if (current->capture && insert_chars(current, current->pos, current->capture)) {
1483                 refreshLine(current->prompt, current);
1484             }
1485             break;
1486         case ctrl('L'): /* Ctrl+L, clear screen */
1487             linenoiseClearScreen();
1488             /* Force recalc of window size for serial terminals */
1489             current->cols = 0;
1490             refreshLine(current->prompt, current);
1491             break;
1492         default:
1493             /* Only tab is allowed without ^V */
1494             if (c == '\t' || c >= ' ') {
1495                 if (insert_char(current, current->pos, c) == 1) {
1496                     refreshLine(current->prompt, current);
1497                 }
1498             }
1499             break;
1500         }
1501     }
1502     return current->len;
1503 }
1504
1505 int linenoiseColumns(void)
1506 {
1507     struct current current;
1508     enableRawMode (&current);
1509     getWindowSize (&current);
1510     disableRawMode (&current);
1511     return current.cols;
1512 }
1513
1514 char *linenoise(const char *prompt)
1515 {
1516     int count;
1517     struct current current;
1518     char buf[LINENOISE_MAX_LINE];
1519
1520     if (enableRawMode(&current) == -1) {
1521         printf("%s", prompt);
1522         fflush(stdout);
1523         if (fgets(buf, sizeof(buf), stdin) == NULL) {
1524             return NULL;
1525         }
1526         count = strlen(buf);
1527         if (count && buf[count-1] == '\n') {
1528             count--;
1529             buf[count] = '\0';
1530         }
1531     }
1532     else
1533     {
1534         current.buf = buf;
1535         current.bufmax = sizeof(buf);
1536         current.len = 0;
1537         current.chars = 0;
1538         current.pos = 0;
1539         current.prompt = prompt;
1540         current.capture = NULL;
1541
1542         count = linenoiseEdit(&current);
1543
1544         disableRawMode(&current);
1545         printf("\n");
1546
1547         free(current.capture);
1548         if (count == -1) {
1549             return NULL;
1550         }
1551     }
1552     return strdup(buf);
1553 }
1554
1555 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1556 int linenoiseHistoryAdd(const char *line) {
1557     char *linecopy;
1558
1559     if (history_max_len == 0) return 0;
1560     if (history == NULL) {
1561         history = (char **)malloc(sizeof(char*)*history_max_len);
1562         if (history == NULL) return 0;
1563         memset(history,0,(sizeof(char*)*history_max_len));
1564     }
1565
1566     /* do not insert duplicate lines into history */
1567     if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1568         return 0;
1569     }
1570
1571     linecopy = strdup(line);
1572     if (!linecopy) return 0;
1573     if (history_len == history_max_len) {
1574         free(history[0]);
1575         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1576         history_len--;
1577     }
1578     history[history_len] = linecopy;
1579     history_len++;
1580     return 1;
1581 }
1582
1583 int linenoiseHistoryGetMaxLen(void) {
1584     return history_max_len;
1585 }
1586
1587 int linenoiseHistorySetMaxLen(int len) {
1588     char **newHistory;
1589
1590     if (len < 1) return 0;
1591     if (history) {
1592         int tocopy = history_len;
1593
1594         newHistory = (char **)malloc(sizeof(char*)*len);
1595         if (newHistory == NULL) return 0;
1596
1597         /* If we can't copy everything, free the elements we'll not use. */
1598         if (len < tocopy) {
1599             int j;
1600
1601             for (j = 0; j < tocopy-len; j++) free(history[j]);
1602             tocopy = len;
1603         }
1604         memset(newHistory,0,sizeof(char*)*len);
1605         memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy);
1606         free(history);
1607         history = newHistory;
1608     }
1609     history_max_len = len;
1610     if (history_len > history_max_len)
1611         history_len = history_max_len;
1612     return 1;
1613 }
1614
1615 /* Save the history in the specified file. On success 0 is returned
1616  * otherwise -1 is returned. */
1617 int linenoiseHistorySave(const char *filename) {
1618     FILE *fp = fopen(filename,"w");
1619     int j;
1620
1621     if (fp == NULL) return -1;
1622     for (j = 0; j < history_len; j++) {
1623         const char *str = history[j];
1624         /* Need to encode backslash, nl and cr */
1625         while (*str) {
1626             if (*str == '\\') {
1627                 fputs("\\\\", fp);
1628             }
1629             else if (*str == '\n') {
1630                 fputs("\\n", fp);
1631             }
1632             else if (*str == '\r') {
1633                 fputs("\\r", fp);
1634             }
1635             else {
1636                 fputc(*str, fp);
1637             }
1638             str++;
1639         }
1640         fputc('\n', fp);
1641     }
1642
1643     fclose(fp);
1644     return 0;
1645 }
1646
1647 /* Load the history from the specified file. If the file does not exist
1648  * zero is returned and no operation is performed.
1649  *
1650  * If the file exists and the operation succeeded 0 is returned, otherwise
1651  * on error -1 is returned. */
1652 int linenoiseHistoryLoad(const char *filename) {
1653     FILE *fp = fopen(filename,"r");
1654     char buf[LINENOISE_MAX_LINE];
1655
1656     if (fp == NULL) return -1;
1657
1658     while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1659         char *src, *dest;
1660
1661         /* Decode backslash escaped values */
1662         for (src = dest = buf; *src; src++) {
1663             char ch = *src;
1664
1665             if (ch == '\\') {
1666                 src++;
1667                 if (*src == 'n') {
1668                     ch = '\n';
1669                 }
1670                 else if (*src == 'r') {
1671                     ch = '\r';
1672                 } else {
1673                     ch = *src;
1674                 }
1675             }
1676             *dest++ = ch;
1677         }
1678         /* Remove trailing newline */
1679         if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1680             dest--;
1681         }
1682         *dest = 0;
1683
1684         linenoiseHistoryAdd(buf);
1685     }
1686     fclose(fp);
1687     return 0;
1688 }
1689
1690 /* Provide access to the history buffer.
1691  *
1692  * If 'len' is not NULL, the length is stored in *len.
1693  */
1694 char **linenoiseHistory(int *len) {
1695     if (len) {
1696         *len = history_len;
1697     }
1698     return history;
1699 }