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