]> git.lizzy.rs Git - linenoise.git/blob - linenoise.c
Merge pull request #19 from bblanchon/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;
646     DWORD n;
647
648     pos.X = 0;
649     pos.Y = (SHORT)current->y;
650
651     FillConsoleOutputAttribute(current->outh,
652         FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, current->cols, pos, &n);
653     current->x = 0;
654 }
655
656 static int outputChars(struct current *current, const char *buf, int len)
657 {
658     COORD pos;
659     DWORD n;
660
661     pos.X = (SHORT)current->x;
662     pos.Y = (SHORT)current->y;
663
664     WriteConsoleOutputCharacter(current->outh, buf, len, pos, &n);
665     current->x += len;
666     return 0;
667 }
668
669 static void outputControlChar(struct current *current, char ch)
670 {
671     COORD pos;
672     DWORD n;
673
674     pos.X = (SHORT) current->x;
675     pos.Y = (SHORT) current->y;
676
677     FillConsoleOutputAttribute(current->outh, BACKGROUND_INTENSITY, 2, pos, &n);
678     outputChars(current, "^", 1);
679     outputChars(current, &ch, 1);
680 }
681
682 static void eraseEol(struct current *current)
683 {
684     COORD pos;
685     DWORD n;
686
687     pos.X = (SHORT) current->x;
688     pos.Y = (SHORT) current->y;
689
690     FillConsoleOutputCharacter(current->outh, ' ', current->cols - current->x, pos, &n);
691 }
692
693 static void setCursorPos(struct current *current, int x)
694 {
695     COORD pos;
696
697     pos.X = (SHORT)x;
698     pos.Y = (SHORT) current->y;
699
700     SetConsoleCursorPosition(current->outh, pos);
701     current->x = x;
702 }
703
704 static int fd_read(struct current *current)
705 {
706     while (1) {
707         INPUT_RECORD irec;
708         DWORD n;
709         if (WaitForSingleObject(current->inh, INFINITE) != WAIT_OBJECT_0) {
710             break;
711         }
712         if (!ReadConsoleInput (current->inh, &irec, 1, &n)) {
713             break;
714         }
715         if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown) {
716             KEY_EVENT_RECORD *k = &irec.Event.KeyEvent;
717             if (k->dwControlKeyState & ENHANCED_KEY) {
718                 switch (k->wVirtualKeyCode) {
719                  case VK_LEFT:
720                     return SPECIAL_LEFT;
721                  case VK_RIGHT:
722                     return SPECIAL_RIGHT;
723                  case VK_UP:
724                     return SPECIAL_UP;
725                  case VK_DOWN:
726                     return SPECIAL_DOWN;
727                  case VK_INSERT:
728                     return SPECIAL_INSERT;
729                  case VK_DELETE:
730                     return SPECIAL_DELETE;
731                  case VK_HOME:
732                     return SPECIAL_HOME;
733                  case VK_END:
734                     return SPECIAL_END;
735                  case VK_PRIOR:
736                     return SPECIAL_PAGE_UP;
737                  case VK_NEXT:
738                     return SPECIAL_PAGE_DOWN;
739                 }
740             }
741             /* Note that control characters are already translated in AsciiChar */
742             else if (k->wVirtualKeyCode == VK_CONTROL)
743                 continue;
744             else {
745 #ifdef USE_UTF8
746                 return k->uChar.UnicodeChar;
747 #else
748                 return k->uChar.AsciiChar;
749 #endif
750             }
751         }
752     }
753     return -1;
754 }
755
756 static int countColorControlChars(const char* prompt)
757 {
758     /* For windows we assume that there are no embedded ansi color
759      * control sequences.
760      */
761     return 0;
762 }
763
764 static int getWindowSize(struct current *current)
765 {
766     CONSOLE_SCREEN_BUFFER_INFO info;
767     if (!GetConsoleScreenBufferInfo(current->outh, &info)) {
768         return -1;
769     }
770     current->cols = info.dwSize.X;
771     current->rows = info.dwSize.Y;
772     if (current->cols <= 0 || current->rows <= 0) {
773         current->cols = 80;
774         return -1;
775     }
776     current->y = info.dwCursorPosition.Y;
777     current->x = info.dwCursorPosition.X;
778     return 0;
779 }
780 #endif
781
782 static int utf8_getchars(char *buf, int c)
783 {
784 #ifdef USE_UTF8
785     return utf8_fromunicode(buf, c);
786 #else
787     *buf = c;
788     return 1;
789 #endif
790 }
791
792 /**
793  * Returns the unicode character at the given offset,
794  * or -1 if none.
795  */
796 static int get_char(struct current *current, int pos)
797 {
798     if (pos >= 0 && pos < current->chars) {
799         int c;
800         int i = utf8_index(current->buf, pos);
801         (void)utf8_tounicode(current->buf + i, &c);
802         return c;
803     }
804     return -1;
805 }
806
807 static void refreshLine(const char *prompt, struct current *current)
808 {
809     int plen;
810     int pchars;
811     int backup = 0;
812     int i;
813     const char *buf = current->buf;
814     int chars = current->chars;
815     int pos = current->pos;
816     int b;
817     int ch;
818     int n;
819
820     /* Should intercept SIGWINCH. For now, just get the size every time */
821     getWindowSize(current);
822
823     plen = strlen(prompt);
824     pchars = utf8_strlen(prompt, plen);
825
826     /* Scan the prompt for embedded ansi color control sequences and
827      * discount them as characters/columns.
828      */
829     pchars -= countColorControlChars(prompt);
830
831     /* Account for a line which is too long to fit in the window.
832      * Note that control chars require an extra column
833      */
834
835     /* How many cols are required to the left of 'pos'?
836      * The prompt, plus one extra for each control char
837      */
838     n = pchars + utf8_strlen(buf, current->len);
839     b = 0;
840     for (i = 0; i < pos; i++) {
841         b += utf8_tounicode(buf + b, &ch);
842         if (ch < ' ') {
843             n++;
844         }
845     }
846
847     /* If too many are needed, strip chars off the front of 'buf'
848      * until it fits. Note that if the current char is a control character,
849      * we need one extra col.
850      */
851     if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
852         n++;
853     }
854
855     while (n >= current->cols && pos > 0) {
856         b = utf8_tounicode(buf, &ch);
857         if (ch < ' ') {
858             n--;
859         }
860         n--;
861         buf += b;
862         pos--;
863         chars--;
864     }
865
866     /* Cursor to left edge, then the prompt */
867     cursorToLeft(current);
868     outputChars(current, prompt, plen);
869
870     /* Now the current buffer content */
871
872     /* Need special handling for control characters.
873      * If we hit 'cols', stop.
874      */
875     b = 0; /* unwritted bytes */
876     n = 0; /* How many control chars were written */
877     for (i = 0; i < chars; i++) {
878         int ch;
879         int w = utf8_tounicode(buf + b, &ch);
880         if (ch < ' ') {
881             n++;
882         }
883         if (pchars + i + n >= current->cols) {
884             break;
885         }
886         if (ch < ' ') {
887             /* A control character, so write the buffer so far */
888             outputChars(current, buf, b);
889             buf += b + w;
890             b = 0;
891             outputControlChar(current, ch + '@');
892             if (i < pos) {
893                 backup++;
894             }
895         }
896         else {
897             b += w;
898         }
899     }
900     outputChars(current, buf, b);
901
902     /* Erase to right, move cursor to original position */
903     eraseEol(current);
904     setCursorPos(current, pos + pchars + backup);
905 }
906
907 static void set_current(struct current *current, const char *str)
908 {
909     strncpy(current->buf, str, current->bufmax);
910     current->buf[current->bufmax - 1] = 0;
911     current->len = strlen(current->buf);
912     current->pos = current->chars = utf8_strlen(current->buf, current->len);
913 }
914
915 static int has_room(struct current *current, int bytes)
916 {
917     return current->len + bytes < current->bufmax - 1;
918 }
919
920 /**
921  * Removes the char at 'pos'.
922  *
923  * Returns 1 if the line needs to be refreshed, 2 if not
924  * and 0 if nothing was removed
925  */
926 static int remove_char(struct current *current, int pos)
927 {
928     if (pos >= 0 && pos < current->chars) {
929         int p1, p2;
930         int ret = 1;
931         p1 = utf8_index(current->buf, pos);
932         p2 = p1 + utf8_index(current->buf + p1, 1);
933
934 #ifdef USE_TERMIOS
935         /* optimise remove char in the case of removing the last char */
936         if (current->pos == pos + 1 && current->pos == current->chars) {
937             if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
938                 ret = 2;
939                 fd_printf(current->fd, "\b \b");
940             }
941         }
942 #endif
943
944         /* Move the null char too */
945         memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
946         current->len -= (p2 - p1);
947         current->chars--;
948
949         if (current->pos > pos) {
950             current->pos--;
951         }
952         return ret;
953     }
954     return 0;
955 }
956
957 /**
958  * Insert 'ch' at position 'pos'
959  *
960  * Returns 1 if the line needs to be refreshed, 2 if not
961  * and 0 if nothing was inserted (no room)
962  */
963 static int insert_char(struct current *current, int pos, int ch)
964 {
965     char buf[3];
966     int n = utf8_getchars(buf, ch);
967
968     if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
969         int p1, p2;
970         int ret = 1;
971         p1 = utf8_index(current->buf, pos);
972         p2 = p1 + n;
973
974 #ifdef USE_TERMIOS
975         /* optimise the case where adding a single char to the end and no scrolling is needed */
976         if (current->pos == pos && current->chars == pos) {
977             if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
978                 IGNORE_RC(write(current->fd, buf, n));
979                 ret = 2;
980             }
981         }
982 #endif
983
984         memmove(current->buf + p2, current->buf + p1, current->len - p1);
985         memcpy(current->buf + p1, buf, n);
986         current->len += n;
987
988         current->chars++;
989         if (current->pos >= pos) {
990             current->pos++;
991         }
992         return ret;
993     }
994     return 0;
995 }
996
997 /**
998  * Captures up to 'n' characters starting at 'pos' for the cut buffer.
999  *
1000  * This replaces any existing characters in the cut buffer.
1001  */
1002 static void capture_chars(struct current *current, int pos, int n)
1003 {
1004     if (pos >= 0 && (pos + n - 1) < current->chars) {
1005         int p1 = utf8_index(current->buf, pos);
1006         int nbytes = utf8_index(current->buf + p1, n);
1007
1008         if (nbytes) {
1009             free(current->capture);
1010             /* Include space for the null terminator */
1011             current->capture = (char *)malloc(nbytes + 1);
1012             memcpy(current->capture, current->buf + p1, nbytes);
1013             current->capture[nbytes] = '\0';
1014         }
1015     }
1016 }
1017
1018 /**
1019  * Removes up to 'n' characters at cursor position 'pos'.
1020  *
1021  * Returns 0 if no chars were removed or non-zero otherwise.
1022  */
1023 static int remove_chars(struct current *current, int pos, int n)
1024 {
1025     int removed = 0;
1026
1027     /* First save any chars which will be removed */
1028     capture_chars(current, pos, n);
1029
1030     while (n-- && remove_char(current, pos)) {
1031         removed++;
1032     }
1033     return removed;
1034 }
1035 /**
1036  * Inserts the characters (string) 'chars' at the cursor position 'pos'.
1037  *
1038  * Returns 0 if no chars were inserted or non-zero otherwise.
1039  */
1040 static int insert_chars(struct current *current, int pos, const char *chars)
1041 {
1042     int inserted = 0;
1043
1044     while (*chars) {
1045         int ch;
1046         int n = utf8_tounicode(chars, &ch);
1047         if (insert_char(current, pos, ch) == 0) {
1048             break;
1049         }
1050         inserted++;
1051         pos++;
1052         chars += n;
1053     }
1054     return inserted;
1055 }
1056
1057 #ifndef NO_COMPLETION
1058 static linenoiseCompletionCallback *completionCallback = NULL;
1059
1060 static void beep() {
1061 #ifdef USE_TERMIOS
1062     fprintf(stderr, "\x7");
1063     fflush(stderr);
1064 #endif
1065 }
1066
1067 static void freeCompletions(linenoiseCompletions *lc) {
1068     size_t i;
1069     for (i = 0; i < lc->len; i++)
1070         free(lc->cvec[i]);
1071     free(lc->cvec);
1072 }
1073
1074 static int completeLine(struct current *current) {
1075     linenoiseCompletions lc = { 0, NULL };
1076     int c = 0;
1077
1078     completionCallback(current->buf,&lc);
1079     if (lc.len == 0) {
1080         beep();
1081     } else {
1082         size_t stop = 0, i = 0;
1083
1084         while(!stop) {
1085             /* Show completion or original buffer */
1086             if (i < lc.len) {
1087                 struct current tmp = *current;
1088                 tmp.buf = lc.cvec[i];
1089                 tmp.pos = tmp.len = strlen(tmp.buf);
1090                 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
1091                 refreshLine(current->prompt, &tmp);
1092             } else {
1093                 refreshLine(current->prompt, current);
1094             }
1095
1096             c = fd_read(current);
1097             if (c == -1) {
1098                 break;
1099             }
1100
1101             switch(c) {
1102                 case '\t': /* tab */
1103                     i = (i+1) % (lc.len+1);
1104                     if (i == lc.len) beep();
1105                     break;
1106                 case 27: /* escape */
1107                     /* Re-show original buffer */
1108                     if (i < lc.len) {
1109                         refreshLine(current->prompt, current);
1110                     }
1111                     stop = 1;
1112                     break;
1113                 default:
1114                     /* Update buffer and return */
1115                     if (i < lc.len) {
1116                         set_current(current,lc.cvec[i]);
1117                     }
1118                     stop = 1;
1119                     break;
1120             }
1121         }
1122     }
1123
1124     freeCompletions(&lc);
1125     return c; /* Return last read character */
1126 }
1127
1128 /* Register a callback function to be called for tab-completion.
1129    Returns the prior callback so that the caller may (if needed)
1130    restore it when done. */
1131 linenoiseCompletionCallback * linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
1132     linenoiseCompletionCallback * old = completionCallback;
1133     completionCallback = fn;
1134     return old;
1135 }
1136
1137 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
1138     lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
1139     lc->cvec[lc->len++] = strdup(str);
1140 }
1141
1142 #endif
1143
1144 static int linenoiseEdit(struct current *current) {
1145     int history_index = 0;
1146
1147     /* The latest history entry is always our current buffer, that
1148      * initially is just an empty string. */
1149     linenoiseHistoryAdd("");
1150
1151     set_current(current, "");
1152     refreshLine(current->prompt, current);
1153
1154     while(1) {
1155         int dir = -1;
1156         int c = fd_read(current);
1157
1158 #ifndef NO_COMPLETION
1159         /* Only autocomplete when the callback is set. It returns < 0 when
1160          * there was an error reading from fd. Otherwise it will return the
1161          * character that should be handled next. */
1162         if (c == '\t' && current->pos == current->chars && completionCallback != NULL) {
1163             c = completeLine(current);
1164             /* Return on errors */
1165             if (c < 0) return current->len;
1166             /* Read next character when 0 */
1167             if (c == 0) continue;
1168         }
1169 #endif
1170
1171 process_char:
1172         if (c == -1) return current->len;
1173 #ifdef USE_TERMIOS
1174         if (c == 27) {   /* escape sequence */
1175             c = check_special(current->fd);
1176         }
1177 #endif
1178         switch(c) {
1179         case '\r':    /* enter */
1180             history_len--;
1181             free(history[history_len]);
1182             return current->len;
1183         case ctrl('C'):     /* ctrl-c */
1184             errno = EAGAIN;
1185             return -1;
1186         case 127:   /* backspace */
1187         case ctrl('H'):
1188             if (remove_char(current, current->pos - 1) == 1) {
1189                 refreshLine(current->prompt, current);
1190             }
1191             break;
1192         case ctrl('D'):     /* ctrl-d */
1193             if (current->len == 0) {
1194                 /* Empty line, so EOF */
1195                 history_len--;
1196                 free(history[history_len]);
1197                 return -1;
1198             }
1199             /* Otherwise fall through to delete char to right of cursor */
1200         case SPECIAL_DELETE:
1201             if (remove_char(current, current->pos) == 1) {
1202                 refreshLine(current->prompt, current);
1203             }
1204             break;
1205         case SPECIAL_INSERT:
1206             /* Ignore. Expansion Hook.
1207              * Future possibility: Toggle Insert/Overwrite Modes
1208              */
1209             break;
1210         case ctrl('W'):    /* ctrl-w, delete word at left. save deleted chars */
1211             /* eat any spaces on the left */
1212             {
1213                 int pos = current->pos;
1214                 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1215                     pos--;
1216                 }
1217
1218                 /* now eat any non-spaces on the left */
1219                 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1220                     pos--;
1221                 }
1222
1223                 if (remove_chars(current, pos, current->pos - pos)) {
1224                     refreshLine(current->prompt, current);
1225                 }
1226             }
1227             break;
1228         case ctrl('R'):    /* ctrl-r */
1229             {
1230                 /* Display the reverse-i-search prompt and process chars */
1231                 char rbuf[50];
1232                 char rprompt[80];
1233                 int rchars = 0;
1234                 int rlen = 0;
1235                 int searchpos = history_len - 1;
1236
1237                 rbuf[0] = 0;
1238                 while (1) {
1239                     int n = 0;
1240                     const char *p = NULL;
1241                     int skipsame = 0;
1242                     int searchdir = -1;
1243
1244                     snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1245                     refreshLine(rprompt, current);
1246                     c = fd_read(current);
1247                     if (c == ctrl('H') || c == 127) {
1248                         if (rchars) {
1249                             int p = utf8_index(rbuf, --rchars);
1250                             rbuf[p] = 0;
1251                             rlen = strlen(rbuf);
1252                         }
1253                         continue;
1254                     }
1255 #ifdef USE_TERMIOS
1256                     if (c == 27) {
1257                         c = check_special(current->fd);
1258                     }
1259 #endif
1260                     if (c == ctrl('P') || c == SPECIAL_UP) {
1261                         /* Search for the previous (earlier) match */
1262                         if (searchpos > 0) {
1263                             searchpos--;
1264                         }
1265                         skipsame = 1;
1266                     }
1267                     else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1268                         /* Search for the next (later) match */
1269                         if (searchpos < history_len) {
1270                             searchpos++;
1271                         }
1272                         searchdir = 1;
1273                         skipsame = 1;
1274                     }
1275                     else if (c >= ' ') {
1276                         if (rlen >= (int)sizeof(rbuf) + 3) {
1277                             continue;
1278                         }
1279
1280                         n = utf8_getchars(rbuf + rlen, c);
1281                         rlen += n;
1282                         rchars++;
1283                         rbuf[rlen] = 0;
1284
1285                         /* Adding a new char resets the search location */
1286                         searchpos = history_len - 1;
1287                     }
1288                     else {
1289                         /* Exit from incremental search mode */
1290                         break;
1291                     }
1292
1293                     /* Now search through the history for a match */
1294                     for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1295                         p = strstr(history[searchpos], rbuf);
1296                         if (p) {
1297                             /* Found a match */
1298                             if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
1299                                 /* But it is identical, so skip it */
1300                                 continue;
1301                             }
1302                             /* Copy the matching line and set the cursor position */
1303                             set_current(current,history[searchpos]);
1304                             current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1305                             break;
1306                         }
1307                     }
1308                     if (!p && n) {
1309                         /* No match, so don't add it */
1310                         rchars--;
1311                         rlen -= n;
1312                         rbuf[rlen] = 0;
1313                     }
1314                 }
1315                 if (c == ctrl('G') || c == ctrl('C')) {
1316                     /* ctrl-g terminates the search with no effect */
1317                     set_current(current, "");
1318                     c = 0;
1319                 }
1320                 else if (c == ctrl('J')) {
1321                     /* ctrl-j terminates the search leaving the buffer in place */
1322                     c = 0;
1323                 }
1324                 /* Go process the char normally */
1325                 refreshLine(current->prompt, current);
1326                 goto process_char;
1327             }
1328             break;
1329         case ctrl('T'):    /* ctrl-t */
1330             if (current->pos > 0 && current->pos <= current->chars) {
1331                 /* If cursor is at end, transpose the previous two chars */
1332                 int fixer = (current->pos == current->chars);
1333                 c = get_char(current, current->pos - fixer);
1334                 remove_char(current, current->pos - fixer);
1335                 insert_char(current, current->pos - 1, c);
1336                 refreshLine(current->prompt, current);
1337             }
1338             break;
1339         case ctrl('V'):    /* ctrl-v */
1340             if (has_room(current, 3)) {
1341                 /* Insert the ^V first */
1342                 if (insert_char(current, current->pos, c)) {
1343                     refreshLine(current->prompt, current);
1344                     /* Now wait for the next char. Can insert anything except \0 */
1345                     c = fd_read(current);
1346
1347                     /* Remove the ^V first */
1348                     remove_char(current, current->pos - 1);
1349                     if (c != -1) {
1350                         /* Insert the actual char */
1351                         insert_char(current, current->pos, c);
1352                     }
1353                     refreshLine(current->prompt, current);
1354                 }
1355             }
1356             break;
1357         case ctrl('B'):
1358         case SPECIAL_LEFT:
1359             if (current->pos > 0) {
1360                 current->pos--;
1361                 refreshLine(current->prompt, current);
1362             }
1363             break;
1364         case ctrl('F'):
1365         case SPECIAL_RIGHT:
1366             if (current->pos < current->chars) {
1367                 current->pos++;
1368                 refreshLine(current->prompt, current);
1369             }
1370             break;
1371         case SPECIAL_PAGE_UP:
1372           dir = history_len - history_index - 1; /* move to start of history */
1373           goto history_navigation;
1374         case SPECIAL_PAGE_DOWN:
1375           dir = -history_index; /* move to 0 == end of history, i.e. current */
1376           goto history_navigation;
1377         case ctrl('P'):
1378         case SPECIAL_UP:
1379             dir = 1;
1380           goto history_navigation;
1381         case ctrl('N'):
1382         case SPECIAL_DOWN:
1383 history_navigation:
1384             if (history_len > 1) {
1385                 /* Update the current history entry before to
1386                  * overwrite it with tne next one. */
1387                 free(history[history_len - 1 - history_index]);
1388                 history[history_len - 1 - history_index] = strdup(current->buf);
1389                 /* Show the new entry */
1390                 history_index += dir;
1391                 if (history_index < 0) {
1392                     history_index = 0;
1393                     break;
1394                 } else if (history_index >= history_len) {
1395                     history_index = history_len - 1;
1396                     break;
1397                 }
1398                 set_current(current, history[history_len - 1 - history_index]);
1399                 refreshLine(current->prompt, current);
1400             }
1401             break;
1402         case ctrl('A'): /* Ctrl+a, go to the start of the line */
1403         case SPECIAL_HOME:
1404             current->pos = 0;
1405             refreshLine(current->prompt, current);
1406             break;
1407         case ctrl('E'): /* ctrl+e, go to the end of the line */
1408         case SPECIAL_END:
1409             current->pos = current->chars;
1410             refreshLine(current->prompt, current);
1411             break;
1412         case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */
1413             if (remove_chars(current, 0, current->pos)) {
1414                 refreshLine(current->prompt, current);
1415             }
1416             break;
1417         case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */
1418             if (remove_chars(current, current->pos, current->chars - current->pos)) {
1419                 refreshLine(current->prompt, current);
1420             }
1421             break;
1422         case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */
1423             if (current->capture && insert_chars(current, current->pos, current->capture)) {
1424                 refreshLine(current->prompt, current);
1425             }
1426             break;
1427         case ctrl('L'): /* Ctrl+L, clear screen */
1428             clearScreen(current);
1429             /* Force recalc of window size for serial terminals */
1430             current->cols = 0;
1431             refreshLine(current->prompt, current);
1432             break;
1433         default:
1434             /* Only tab is allowed without ^V */
1435             if (c == '\t' || c >= ' ') {
1436                 if (insert_char(current, current->pos, c) == 1) {
1437                     refreshLine(current->prompt, current);
1438                 }
1439             }
1440             break;
1441         }
1442     }
1443     return current->len;
1444 }
1445
1446 int linenoiseColumns(void)
1447 {
1448     struct current current;
1449     enableRawMode (&current);
1450     getWindowSize (&current);
1451     disableRawMode (&current);
1452     return current.cols;
1453 }
1454
1455 char *linenoise(const char *prompt)
1456 {
1457     int count;
1458     struct current current;
1459     char buf[LINENOISE_MAX_LINE];
1460
1461     if (enableRawMode(&current) == -1) {
1462         printf("%s", prompt);
1463         fflush(stdout);
1464         if (fgets(buf, sizeof(buf), stdin) == NULL) {
1465             return NULL;
1466         }
1467         count = strlen(buf);
1468         if (count && buf[count-1] == '\n') {
1469             count--;
1470             buf[count] = '\0';
1471         }
1472     }
1473     else
1474     {
1475         current.buf = buf;
1476         current.bufmax = sizeof(buf);
1477         current.len = 0;
1478         current.chars = 0;
1479         current.pos = 0;
1480         current.prompt = prompt;
1481         current.capture = NULL;
1482
1483         count = linenoiseEdit(&current);
1484
1485         disableRawMode(&current);
1486         printf("\n");
1487
1488         free(current.capture);
1489         if (count == -1) {
1490             return NULL;
1491         }
1492     }
1493     return strdup(buf);
1494 }
1495
1496 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1497 int linenoiseHistoryAdd(const char *line) {
1498     char *linecopy;
1499
1500     if (history_max_len == 0) return 0;
1501     if (history == NULL) {
1502         history = (char **)malloc(sizeof(char*)*history_max_len);
1503         if (history == NULL) return 0;
1504         memset(history,0,(sizeof(char*)*history_max_len));
1505     }
1506
1507     /* do not insert duplicate lines into history */
1508     if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1509         return 0;
1510     }
1511
1512     linecopy = strdup(line);
1513     if (!linecopy) return 0;
1514     if (history_len == history_max_len) {
1515         free(history[0]);
1516         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1517         history_len--;
1518     }
1519     history[history_len] = linecopy;
1520     history_len++;
1521     return 1;
1522 }
1523
1524 int linenoiseHistoryGetMaxLen(void) {
1525     return history_max_len;
1526 }
1527
1528 int linenoiseHistorySetMaxLen(int len) {
1529     char **newHistory;
1530
1531     if (len < 1) return 0;
1532     if (history) {
1533         int tocopy = history_len;
1534
1535         newHistory = (char **)malloc(sizeof(char*)*len);
1536         if (newHistory == NULL) return 0;
1537
1538         /* If we can't copy everything, free the elements we'll not use. */
1539         if (len < tocopy) {
1540             int j;
1541
1542             for (j = 0; j < tocopy-len; j++) free(history[j]);
1543             tocopy = len;
1544         }
1545         memset(newHistory,0,sizeof(char*)*len);
1546         memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy);
1547         free(history);
1548         history = newHistory;
1549     }
1550     history_max_len = len;
1551     if (history_len > history_max_len)
1552         history_len = history_max_len;
1553     return 1;
1554 }
1555
1556 /* Save the history in the specified file. On success 0 is returned
1557  * otherwise -1 is returned. */
1558 int linenoiseHistorySave(const char *filename) {
1559     FILE *fp = fopen(filename,"w");
1560     int j;
1561
1562     if (fp == NULL) return -1;
1563     for (j = 0; j < history_len; j++) {
1564         const char *str = history[j];
1565         /* Need to encode backslash, nl and cr */
1566         while (*str) {
1567             if (*str == '\\') {
1568                 fputs("\\\\", fp);
1569             }
1570             else if (*str == '\n') {
1571                 fputs("\\n", fp);
1572             }
1573             else if (*str == '\r') {
1574                 fputs("\\r", fp);
1575             }
1576             else {
1577                 fputc(*str, fp);
1578             }
1579             str++;
1580         }
1581         fputc('\n', fp);
1582     }
1583
1584     fclose(fp);
1585     return 0;
1586 }
1587
1588 /* Load the history from the specified file. If the file does not exist
1589  * zero is returned and no operation is performed.
1590  *
1591  * If the file exists and the operation succeeded 0 is returned, otherwise
1592  * on error -1 is returned. */
1593 int linenoiseHistoryLoad(const char *filename) {
1594     FILE *fp = fopen(filename,"r");
1595     char buf[LINENOISE_MAX_LINE];
1596
1597     if (fp == NULL) return -1;
1598
1599     while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1600         char *src, *dest;
1601
1602         /* Decode backslash escaped values */
1603         for (src = dest = buf; *src; src++) {
1604             char ch = *src;
1605
1606             if (ch == '\\') {
1607                 src++;
1608                 if (*src == 'n') {
1609                     ch = '\n';
1610                 }
1611                 else if (*src == 'r') {
1612                     ch = '\r';
1613                 } else {
1614                     ch = *src;
1615                 }
1616             }
1617             *dest++ = ch;
1618         }
1619         /* Remove trailing newline */
1620         if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1621             dest--;
1622         }
1623         *dest = 0;
1624
1625         linenoiseHistoryAdd(buf);
1626     }
1627     fclose(fp);
1628     return 0;
1629 }
1630
1631 /* Provide access to the history buffer.
1632  *
1633  * If 'len' is not NULL, the length is stored in *len.
1634  */
1635 char **linenoiseHistory(int *len) {
1636     if (len) {
1637         *len = history_len;
1638     }
1639     return history;
1640 }