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