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