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