]> git.lizzy.rs Git - linenoise.git/blob - linenoise.c
Make linenoiseClearScreen() public
[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 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
1067 static void beep() {
1068 #ifdef USE_TERMIOS
1069     fprintf(stderr, "\x7");
1070     fflush(stderr);
1071 #endif
1072 }
1073
1074 static void freeCompletions(linenoiseCompletions *lc) {
1075     size_t i;
1076     for (i = 0; i < lc->len; i++)
1077         free(lc->cvec[i]);
1078     free(lc->cvec);
1079 }
1080
1081 static int completeLine(struct current *current) {
1082     linenoiseCompletions lc = { 0, NULL };
1083     int c = 0;
1084
1085     completionCallback(current->buf,&lc);
1086     if (lc.len == 0) {
1087         beep();
1088     } else {
1089         size_t stop = 0, i = 0;
1090
1091         while(!stop) {
1092             /* Show completion or original buffer */
1093             if (i < lc.len) {
1094                 struct current tmp = *current;
1095                 tmp.buf = lc.cvec[i];
1096                 tmp.pos = tmp.len = strlen(tmp.buf);
1097                 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
1098                 refreshLine(current->prompt, &tmp);
1099             } else {
1100                 refreshLine(current->prompt, current);
1101             }
1102
1103             c = fd_read(current);
1104             if (c == -1) {
1105                 break;
1106             }
1107
1108             switch(c) {
1109                 case '\t': /* tab */
1110                     i = (i+1) % (lc.len+1);
1111                     if (i == lc.len) beep();
1112                     break;
1113                 case 27: /* escape */
1114                     /* Re-show original buffer */
1115                     if (i < lc.len) {
1116                         refreshLine(current->prompt, current);
1117                     }
1118                     stop = 1;
1119                     break;
1120                 default:
1121                     /* Update buffer and return */
1122                     if (i < lc.len) {
1123                         set_current(current,lc.cvec[i]);
1124                     }
1125                     stop = 1;
1126                     break;
1127             }
1128         }
1129     }
1130
1131     freeCompletions(&lc);
1132     return c; /* Return last read character */
1133 }
1134
1135 /* Register a callback function to be called for tab-completion.
1136    Returns the prior callback so that the caller may (if needed)
1137    restore it when done. */
1138 linenoiseCompletionCallback * linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
1139     linenoiseCompletionCallback * old = completionCallback;
1140     completionCallback = fn;
1141     return old;
1142 }
1143
1144 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
1145     lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
1146     lc->cvec[lc->len++] = strdup(str);
1147 }
1148
1149 #endif
1150
1151 static int linenoiseEdit(struct current *current) {
1152     int history_index = 0;
1153
1154     /* The latest history entry is always our current buffer, that
1155      * initially is just an empty string. */
1156     linenoiseHistoryAdd("");
1157
1158     set_current(current, "");
1159     refreshLine(current->prompt, current);
1160
1161     while(1) {
1162         int dir = -1;
1163         int c = fd_read(current);
1164
1165 #ifndef NO_COMPLETION
1166         /* Only autocomplete when the callback is set. It returns < 0 when
1167          * there was an error reading from fd. Otherwise it will return the
1168          * character that should be handled next. */
1169         if (c == '\t' && current->pos == current->chars && completionCallback != NULL) {
1170             c = completeLine(current);
1171             /* Return on errors */
1172             if (c < 0) return current->len;
1173             /* Read next character when 0 */
1174             if (c == 0) continue;
1175         }
1176 #endif
1177
1178 process_char:
1179         if (c == -1) return current->len;
1180 #ifdef USE_TERMIOS
1181         if (c == 27) {   /* escape sequence */
1182             c = check_special(current->fd);
1183         }
1184 #endif
1185         switch(c) {
1186         case '\r':    /* enter */
1187             history_len--;
1188             free(history[history_len]);
1189             return current->len;
1190         case ctrl('C'):     /* ctrl-c */
1191             errno = EAGAIN;
1192             return -1;
1193         case 127:   /* backspace */
1194         case ctrl('H'):
1195             if (remove_char(current, current->pos - 1) == 1) {
1196                 refreshLine(current->prompt, current);
1197             }
1198             break;
1199         case ctrl('D'):     /* ctrl-d */
1200             if (current->len == 0) {
1201                 /* Empty line, so EOF */
1202                 history_len--;
1203                 free(history[history_len]);
1204                 return -1;
1205             }
1206             /* Otherwise fall through to delete char to right of cursor */
1207         case SPECIAL_DELETE:
1208             if (remove_char(current, current->pos) == 1) {
1209                 refreshLine(current->prompt, current);
1210             }
1211             break;
1212         case SPECIAL_INSERT:
1213             /* Ignore. Expansion Hook.
1214              * Future possibility: Toggle Insert/Overwrite Modes
1215              */
1216             break;
1217         case ctrl('W'):    /* ctrl-w, delete word at left. save deleted chars */
1218             /* eat any spaces on the left */
1219             {
1220                 int pos = current->pos;
1221                 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1222                     pos--;
1223                 }
1224
1225                 /* now eat any non-spaces on the left */
1226                 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1227                     pos--;
1228                 }
1229
1230                 if (remove_chars(current, pos, current->pos - pos)) {
1231                     refreshLine(current->prompt, current);
1232                 }
1233             }
1234             break;
1235         case ctrl('R'):    /* ctrl-r */
1236             {
1237                 /* Display the reverse-i-search prompt and process chars */
1238                 char rbuf[50];
1239                 char rprompt[80];
1240                 int rchars = 0;
1241                 int rlen = 0;
1242                 int searchpos = history_len - 1;
1243
1244                 rbuf[0] = 0;
1245                 while (1) {
1246                     int n = 0;
1247                     const char *p = NULL;
1248                     int skipsame = 0;
1249                     int searchdir = -1;
1250
1251                     snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1252                     refreshLine(rprompt, current);
1253                     c = fd_read(current);
1254                     if (c == ctrl('H') || c == 127) {
1255                         if (rchars) {
1256                             int p = utf8_index(rbuf, --rchars);
1257                             rbuf[p] = 0;
1258                             rlen = strlen(rbuf);
1259                         }
1260                         continue;
1261                     }
1262 #ifdef USE_TERMIOS
1263                     if (c == 27) {
1264                         c = check_special(current->fd);
1265                     }
1266 #endif
1267                     if (c == ctrl('P') || c == SPECIAL_UP) {
1268                         /* Search for the previous (earlier) match */
1269                         if (searchpos > 0) {
1270                             searchpos--;
1271                         }
1272                         skipsame = 1;
1273                     }
1274                     else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1275                         /* Search for the next (later) match */
1276                         if (searchpos < history_len) {
1277                             searchpos++;
1278                         }
1279                         searchdir = 1;
1280                         skipsame = 1;
1281                     }
1282                     else if (c >= ' ') {
1283                         if (rlen >= (int)sizeof(rbuf) + 3) {
1284                             continue;
1285                         }
1286
1287                         n = utf8_getchars(rbuf + rlen, c);
1288                         rlen += n;
1289                         rchars++;
1290                         rbuf[rlen] = 0;
1291
1292                         /* Adding a new char resets the search location */
1293                         searchpos = history_len - 1;
1294                     }
1295                     else {
1296                         /* Exit from incremental search mode */
1297                         break;
1298                     }
1299
1300                     /* Now search through the history for a match */
1301                     for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1302                         p = strstr(history[searchpos], rbuf);
1303                         if (p) {
1304                             /* Found a match */
1305                             if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
1306                                 /* But it is identical, so skip it */
1307                                 continue;
1308                             }
1309                             /* Copy the matching line and set the cursor position */
1310                             set_current(current,history[searchpos]);
1311                             current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1312                             break;
1313                         }
1314                     }
1315                     if (!p && n) {
1316                         /* No match, so don't add it */
1317                         rchars--;
1318                         rlen -= n;
1319                         rbuf[rlen] = 0;
1320                     }
1321                 }
1322                 if (c == ctrl('G') || c == ctrl('C')) {
1323                     /* ctrl-g terminates the search with no effect */
1324                     set_current(current, "");
1325                     c = 0;
1326                 }
1327                 else if (c == ctrl('J')) {
1328                     /* ctrl-j terminates the search leaving the buffer in place */
1329                     c = 0;
1330                 }
1331                 /* Go process the char normally */
1332                 refreshLine(current->prompt, current);
1333                 goto process_char;
1334             }
1335             break;
1336         case ctrl('T'):    /* ctrl-t */
1337             if (current->pos > 0 && current->pos <= current->chars) {
1338                 /* If cursor is at end, transpose the previous two chars */
1339                 int fixer = (current->pos == current->chars);
1340                 c = get_char(current, current->pos - fixer);
1341                 remove_char(current, current->pos - fixer);
1342                 insert_char(current, current->pos - 1, c);
1343                 refreshLine(current->prompt, current);
1344             }
1345             break;
1346         case ctrl('V'):    /* ctrl-v */
1347             if (has_room(current, 3)) {
1348                 /* Insert the ^V first */
1349                 if (insert_char(current, current->pos, c)) {
1350                     refreshLine(current->prompt, current);
1351                     /* Now wait for the next char. Can insert anything except \0 */
1352                     c = fd_read(current);
1353
1354                     /* Remove the ^V first */
1355                     remove_char(current, current->pos - 1);
1356                     if (c != -1) {
1357                         /* Insert the actual char */
1358                         insert_char(current, current->pos, c);
1359                     }
1360                     refreshLine(current->prompt, current);
1361                 }
1362             }
1363             break;
1364         case ctrl('B'):
1365         case SPECIAL_LEFT:
1366             if (current->pos > 0) {
1367                 current->pos--;
1368                 refreshLine(current->prompt, current);
1369             }
1370             break;
1371         case ctrl('F'):
1372         case SPECIAL_RIGHT:
1373             if (current->pos < current->chars) {
1374                 current->pos++;
1375                 refreshLine(current->prompt, current);
1376             }
1377             break;
1378         case SPECIAL_PAGE_UP:
1379           dir = history_len - history_index - 1; /* move to start of history */
1380           goto history_navigation;
1381         case SPECIAL_PAGE_DOWN:
1382           dir = -history_index; /* move to 0 == end of history, i.e. current */
1383           goto history_navigation;
1384         case ctrl('P'):
1385         case SPECIAL_UP:
1386             dir = 1;
1387           goto history_navigation;
1388         case ctrl('N'):
1389         case SPECIAL_DOWN:
1390 history_navigation:
1391             if (history_len > 1) {
1392                 /* Update the current history entry before to
1393                  * overwrite it with tne next one. */
1394                 free(history[history_len - 1 - history_index]);
1395                 history[history_len - 1 - history_index] = strdup(current->buf);
1396                 /* Show the new entry */
1397                 history_index += dir;
1398                 if (history_index < 0) {
1399                     history_index = 0;
1400                     break;
1401                 } else if (history_index >= history_len) {
1402                     history_index = history_len - 1;
1403                     break;
1404                 }
1405                 set_current(current, history[history_len - 1 - history_index]);
1406                 refreshLine(current->prompt, current);
1407             }
1408             break;
1409         case ctrl('A'): /* Ctrl+a, go to the start of the line */
1410         case SPECIAL_HOME:
1411             current->pos = 0;
1412             refreshLine(current->prompt, current);
1413             break;
1414         case ctrl('E'): /* ctrl+e, go to the end of the line */
1415         case SPECIAL_END:
1416             current->pos = current->chars;
1417             refreshLine(current->prompt, current);
1418             break;
1419         case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */
1420             if (remove_chars(current, 0, current->pos)) {
1421                 refreshLine(current->prompt, current);
1422             }
1423             break;
1424         case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */
1425             if (remove_chars(current, current->pos, current->chars - current->pos)) {
1426                 refreshLine(current->prompt, current);
1427             }
1428             break;
1429         case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */
1430             if (current->capture && insert_chars(current, current->pos, current->capture)) {
1431                 refreshLine(current->prompt, current);
1432             }
1433             break;
1434         case ctrl('L'): /* Ctrl+L, clear screen */
1435             linenoiseClearScreen();
1436             /* Force recalc of window size for serial terminals */
1437             current->cols = 0;
1438             refreshLine(current->prompt, current);
1439             break;
1440         default:
1441             /* Only tab is allowed without ^V */
1442             if (c == '\t' || c >= ' ') {
1443                 if (insert_char(current, current->pos, c) == 1) {
1444                     refreshLine(current->prompt, current);
1445                 }
1446             }
1447             break;
1448         }
1449     }
1450     return current->len;
1451 }
1452
1453 int linenoiseColumns(void)
1454 {
1455     struct current current;
1456     enableRawMode (&current);
1457     getWindowSize (&current);
1458     disableRawMode (&current);
1459     return current.cols;
1460 }
1461
1462 char *linenoise(const char *prompt)
1463 {
1464     int count;
1465     struct current current;
1466     char buf[LINENOISE_MAX_LINE];
1467
1468     if (enableRawMode(&current) == -1) {
1469         printf("%s", prompt);
1470         fflush(stdout);
1471         if (fgets(buf, sizeof(buf), stdin) == NULL) {
1472             return NULL;
1473         }
1474         count = strlen(buf);
1475         if (count && buf[count-1] == '\n') {
1476             count--;
1477             buf[count] = '\0';
1478         }
1479     }
1480     else
1481     {
1482         current.buf = buf;
1483         current.bufmax = sizeof(buf);
1484         current.len = 0;
1485         current.chars = 0;
1486         current.pos = 0;
1487         current.prompt = prompt;
1488         current.capture = NULL;
1489
1490         count = linenoiseEdit(&current);
1491
1492         disableRawMode(&current);
1493         printf("\n");
1494
1495         free(current.capture);
1496         if (count == -1) {
1497             return NULL;
1498         }
1499     }
1500     return strdup(buf);
1501 }
1502
1503 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1504 int linenoiseHistoryAdd(const char *line) {
1505     char *linecopy;
1506
1507     if (history_max_len == 0) return 0;
1508     if (history == NULL) {
1509         history = (char **)malloc(sizeof(char*)*history_max_len);
1510         if (history == NULL) return 0;
1511         memset(history,0,(sizeof(char*)*history_max_len));
1512     }
1513
1514     /* do not insert duplicate lines into history */
1515     if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1516         return 0;
1517     }
1518
1519     linecopy = strdup(line);
1520     if (!linecopy) return 0;
1521     if (history_len == history_max_len) {
1522         free(history[0]);
1523         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1524         history_len--;
1525     }
1526     history[history_len] = linecopy;
1527     history_len++;
1528     return 1;
1529 }
1530
1531 int linenoiseHistoryGetMaxLen(void) {
1532     return history_max_len;
1533 }
1534
1535 int linenoiseHistorySetMaxLen(int len) {
1536     char **newHistory;
1537
1538     if (len < 1) return 0;
1539     if (history) {
1540         int tocopy = history_len;
1541
1542         newHistory = (char **)malloc(sizeof(char*)*len);
1543         if (newHistory == NULL) return 0;
1544
1545         /* If we can't copy everything, free the elements we'll not use. */
1546         if (len < tocopy) {
1547             int j;
1548
1549             for (j = 0; j < tocopy-len; j++) free(history[j]);
1550             tocopy = len;
1551         }
1552         memset(newHistory,0,sizeof(char*)*len);
1553         memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy);
1554         free(history);
1555         history = newHistory;
1556     }
1557     history_max_len = len;
1558     if (history_len > history_max_len)
1559         history_len = history_max_len;
1560     return 1;
1561 }
1562
1563 /* Save the history in the specified file. On success 0 is returned
1564  * otherwise -1 is returned. */
1565 int linenoiseHistorySave(const char *filename) {
1566     FILE *fp = fopen(filename,"w");
1567     int j;
1568
1569     if (fp == NULL) return -1;
1570     for (j = 0; j < history_len; j++) {
1571         const char *str = history[j];
1572         /* Need to encode backslash, nl and cr */
1573         while (*str) {
1574             if (*str == '\\') {
1575                 fputs("\\\\", fp);
1576             }
1577             else if (*str == '\n') {
1578                 fputs("\\n", fp);
1579             }
1580             else if (*str == '\r') {
1581                 fputs("\\r", fp);
1582             }
1583             else {
1584                 fputc(*str, fp);
1585             }
1586             str++;
1587         }
1588         fputc('\n', fp);
1589     }
1590
1591     fclose(fp);
1592     return 0;
1593 }
1594
1595 /* Load the history from the specified file. If the file does not exist
1596  * zero is returned and no operation is performed.
1597  *
1598  * If the file exists and the operation succeeded 0 is returned, otherwise
1599  * on error -1 is returned. */
1600 int linenoiseHistoryLoad(const char *filename) {
1601     FILE *fp = fopen(filename,"r");
1602     char buf[LINENOISE_MAX_LINE];
1603
1604     if (fp == NULL) return -1;
1605
1606     while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1607         char *src, *dest;
1608
1609         /* Decode backslash escaped values */
1610         for (src = dest = buf; *src; src++) {
1611             char ch = *src;
1612
1613             if (ch == '\\') {
1614                 src++;
1615                 if (*src == 'n') {
1616                     ch = '\n';
1617                 }
1618                 else if (*src == 'r') {
1619                     ch = '\r';
1620                 } else {
1621                     ch = *src;
1622                 }
1623             }
1624             *dest++ = ch;
1625         }
1626         /* Remove trailing newline */
1627         if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1628             dest--;
1629         }
1630         *dest = 0;
1631
1632         linenoiseHistoryAdd(buf);
1633     }
1634     fclose(fp);
1635     return 0;
1636 }
1637
1638 /* Provide access to the history buffer.
1639  *
1640  * If 'len' is not NULL, the length is stored in *len.
1641  */
1642 char **linenoiseHistory(int *len) {
1643     if (len) {
1644         *len = history_len;
1645     }
1646     return history;
1647 }