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