]> git.lizzy.rs Git - linenoise.git/blob - linenoise.c
Bug fix. Ensure that current->cols is initialized
[linenoise.git] / linenoise.c
1 /* linenoise.c -- guerrilla line editing library against the idea that a
2  * line editing lib needs to be 20,000 lines of C code.
3  *
4  * You can find the latest source code at:
5  *
6  *   http://github.com/msteveb/linenoise
7  *   (forked from http://github.com/antirez/linenoise)
8  *
9  * Does a number of crazy assumptions that happen to be true in 99.9999% of
10  * the 2010 UNIX computers around.
11  *
12  * ------------------------------------------------------------------------
13  *
14  * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
15  * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
16  * Copyright (c) 2011, Steve Bennett <steveb at workware dot net dot au>
17  *
18  * All rights reserved.
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions are
22  * met:
23  *
24  *  *  Redistributions of source code must retain the above copyright
25  *     notice, this list of conditions and the following disclaimer.
26  *
27  *  *  Redistributions in binary form must reproduce the above copyright
28  *     notice, this list of conditions and the following disclaimer in the
29  *     documentation and/or other materials provided with the distribution.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42  *
43  * ------------------------------------------------------------------------
44  *
45  * References:
46  * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
47  * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
48  *
49  * Bloat:
50  * - Completion?
51  *
52  * Unix/termios
53  * ------------
54  * List of escape sequences used by this program, we do everything just
55  * a few sequences. In order to be so cheap we may have some
56  * flickering effect with some slow terminal, but the lesser sequences
57  * the more compatible.
58  *
59  * EL (Erase Line)
60  *    Sequence: ESC [ n K
61  *    Effect: if n is 0 or missing, clear from cursor to end of line
62  *    Effect: if n is 1, clear from beginning of line to cursor
63  *    Effect: if n is 2, clear entire line
64  *
65  * CUF (CUrsor Forward)
66  *    Sequence: ESC [ n C
67  *    Effect: moves cursor forward of n chars
68  *
69  * CR (Carriage Return)
70  *    Sequence: \r
71  *    Effect: moves cursor to column 1
72  *
73  * The following are used to clear the screen: ESC [ H ESC [ 2 J
74  * This is actually composed of two sequences:
75  *
76  * cursorhome
77  *    Sequence: ESC [ H
78  *    Effect: moves the cursor to upper left corner
79  *
80  * ED2 (Clear entire screen)
81  *    Sequence: ESC [ 2 J
82  *    Effect: clear the whole screen
83  *
84  * == For highlighting control characters, we also use the following two ==
85  * SO (enter StandOut)
86  *    Sequence: ESC [ 7 m
87  *    Effect: Uses some standout mode such as reverse video
88  *
89  * SE (Standout End)
90  *    Sequence: ESC [ 0 m
91  *    Effect: Exit standout mode
92  *
93  * == Only used if TIOCGWINSZ fails ==
94  * DSR/CPR (Report cursor position)
95  *    Sequence: ESC [ 6 n
96  *    Effect: reports current cursor position as ESC [ NNN ; MMM R
97  *
98  * win32/console
99  * -------------
100  * If __MINGW32__ is defined, the win32 console API is used.
101  * This could probably be made to work for the msvc compiler too.
102  * This support based in part on work by Jon Griffiths.
103  */
104
105 #ifdef _WIN32 /* Windows platform, either MinGW or Visual Studio (MSVC) */
106 #include <windows.h>
107 #include <fcntl.h>
108 #define USE_WINCONSOLE
109 #ifdef __MINGW32__
110 #define HAVE_UNISTD_H
111 #else
112 /* Microsoft headers don't like old POSIX names */
113 #define strdup _strdup
114 #define snprintf _snprintf
115 #endif
116 #else
117 #include <termios.h>
118 #include <sys/ioctl.h>
119 #include <sys/poll.h>
120 #define USE_TERMIOS
121 #define HAVE_UNISTD_H
122 #endif
123
124 #ifdef HAVE_UNISTD_H
125 #include <unistd.h>
126 #endif
127 #include <stdlib.h>
128 #include <stdarg.h>
129 #include <stdio.h>
130 #include <errno.h>
131 #include <string.h>
132 #include <stdlib.h>
133 #include <sys/types.h>
134
135 #include "linenoise.h"
136 #include "utf8.h"
137
138 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
139 #define LINENOISE_MAX_LINE 4096
140
141 #define ctrl(C) ((C) - '@')
142
143 /* Use -ve numbers here to co-exist with normal unicode chars */
144 enum {
145     SPECIAL_NONE,
146     SPECIAL_UP = -20,
147     SPECIAL_DOWN = -21,
148     SPECIAL_LEFT = -22,
149     SPECIAL_RIGHT = -23,
150     SPECIAL_DELETE = -24,
151     SPECIAL_HOME = -25,
152     SPECIAL_END = -26,
153     SPECIAL_INSERT = -27,
154     SPECIAL_PAGE_UP = -28,
155     SPECIAL_PAGE_DOWN = -29
156 };
157
158 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
159 static int history_len = 0;
160 static char **history = NULL;
161
162 /* Structure to contain the status of the current (being edited) line */
163 struct current {
164     char *buf;  /* Current buffer. Always null terminated */
165     int bufmax; /* Size of the buffer, including space for the null termination */
166     int len;    /* Number of bytes in 'buf' */
167     int chars;  /* Number of chars in 'buf' (utf-8 chars) */
168     int pos;    /* Cursor position, measured in chars */
169     int cols;   /* Size of the window, in chars */
170     const char *prompt;
171     char *capture; /* Allocated capture buffer, or NULL for none. Always null terminated */
172 #if defined(USE_TERMIOS)
173     int fd;     /* Terminal fd */
174 #elif defined(USE_WINCONSOLE)
175     HANDLE outh; /* Console output handle */
176     HANDLE inh; /* Console input handle */
177     int rows;   /* Screen rows */
178     int x;      /* Current column during output */
179     int y;      /* Current row */
180 #endif
181 };
182
183 static int fd_read(struct current *current);
184 static int getWindowSize(struct current *current);
185
186 void linenoiseHistoryFree(void) {
187     if (history) {
188         int j;
189
190         for (j = 0; j < history_len; j++)
191             free(history[j]);
192         free(history);
193         history = NULL;
194         history_len = 0;
195     }
196 }
197
198 #if defined(USE_TERMIOS)
199 static void linenoiseAtExit(void);
200 static struct termios orig_termios; /* in order to restore at exit */
201 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
202 static int atexit_registered = 0; /* register atexit just 1 time */
203
204 static const char *unsupported_term[] = {"dumb","cons25",NULL};
205
206 static int isUnsupportedTerm(void) {
207     char *term = getenv("TERM");
208
209     if (term) {
210         int j;
211         for (j = 0; unsupported_term[j]; j++) {
212             if (strcmp(term, unsupported_term[j]) == 0) {
213                 return 1;
214             }
215         }
216     }
217     return 0;
218 }
219
220 static int enableRawMode(struct current *current) {
221     struct termios raw;
222
223     current->fd = STDIN_FILENO;
224     current->cols = 0;
225
226     if (!isatty(current->fd) || isUnsupportedTerm() ||
227         tcgetattr(current->fd, &orig_termios) == -1) {
228 fatal:
229         errno = ENOTTY;
230         return -1;
231     }
232
233     if (!atexit_registered) {
234         atexit(linenoiseAtExit);
235         atexit_registered = 1;
236     }
237
238     raw = orig_termios;  /* modify the original mode */
239     /* input modes: no break, no CR to NL, no parity check, no strip char,
240      * no start/stop output control. */
241     raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
242     /* output modes - disable post processing */
243     raw.c_oflag &= ~(OPOST);
244     /* control modes - set 8 bit chars */
245     raw.c_cflag |= (CS8);
246     /* local modes - choing off, canonical off, no extended functions,
247      * no signal chars (^Z,^C) */
248     raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
249     /* control chars - set return condition: min number of bytes and timer.
250      * We want read to return every single byte, without timeout. */
251     raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
252
253     /* put terminal in raw mode after flushing */
254     if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
255         goto fatal;
256     }
257     rawmode = 1;
258     return 0;
259 }
260
261 static void disableRawMode(struct current *current) {
262     /* Don't even check the return value as it's too late. */
263     if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
264         rawmode = 0;
265 }
266
267 /* At exit we'll try to fix the terminal to the initial conditions. */
268 static void linenoiseAtExit(void) {
269     if (rawmode) {
270         tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
271     }
272     linenoiseHistoryFree();
273 }
274
275 /* gcc/glibc insists that we care about the return code of write!
276  * Clarification: This means that a void-cast like "(void) (EXPR)"
277  * does not work.
278  */
279 #define IGNORE_RC(EXPR) if (EXPR) {}
280
281 /* This is fdprintf() on some systems, but use a different
282  * name to avoid conflicts
283  */
284 static void fd_printf(int fd, const char *format, ...)
285 {
286     va_list args;
287     char buf[64];
288     int n;
289
290     va_start(args, format);
291     n = vsnprintf(buf, sizeof(buf), format, args);
292     va_end(args);
293     IGNORE_RC(write(fd, buf, n));
294 }
295
296 static void clearScreen(struct current *current)
297 {
298     fd_printf(current->fd, "\x1b[H\x1b[2J");
299 }
300
301 static void cursorToLeft(struct current *current)
302 {
303     fd_printf(current->fd, "\r");
304 }
305
306 static int outputChars(struct current *current, const char *buf, int len)
307 {
308     return write(current->fd, buf, len);
309 }
310
311 static void outputControlChar(struct current *current, char ch)
312 {
313     fd_printf(current->fd, "\x1b[7m^%c\x1b[0m", ch);
314 }
315
316 static void eraseEol(struct current *current)
317 {
318     fd_printf(current->fd, "\x1b[0K");
319 }
320
321 static void setCursorPos(struct current *current, int x)
322 {
323     fd_printf(current->fd, "\r\x1b[%dC", x);
324 }
325
326 /**
327  * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
328  *
329  * A timeout of -1 means to wait forever.
330  *
331  * Returns -1 if no char is received within the time or an error occurs.
332  */
333 static int fd_read_char(int fd, int timeout)
334 {
335     struct pollfd p;
336     unsigned char c;
337
338     p.fd = fd;
339     p.events = POLLIN;
340
341     if (poll(&p, 1, timeout) == 0) {
342         /* timeout */
343         return -1;
344     }
345     if (read(fd, &c, 1) != 1) {
346         return -1;
347     }
348     return c;
349 }
350
351 /**
352  * Reads a complete utf-8 character
353  * and returns the unicode value, or -1 on error.
354  */
355 static int fd_read(struct current *current)
356 {
357 #ifdef USE_UTF8
358     char buf[4];
359     int n;
360     int i;
361     int c;
362
363     if (read(current->fd, &buf[0], 1) != 1) {
364         return -1;
365     }
366     n = utf8_charlen(buf[0]);
367     if (n < 1 || n > 3) {
368         return -1;
369     }
370     for (i = 1; i < n; i++) {
371         if (read(current->fd, &buf[i], 1) != 1) {
372             return -1;
373         }
374     }
375     buf[n] = 0;
376     /* decode and return the character */
377     utf8_tounicode(buf, &c);
378     return c;
379 #else
380     return fd_read_char(current->fd, -1);
381 #endif
382 }
383
384 static int countColorControlChars(const char* prompt)
385 {
386     /* ANSI color control sequences have the form:
387      * "\x1b" "[" [0-9;]* "m"
388      * We parse them with a simple state machine.
389      */
390
391     enum {
392         search_esc,
393         expect_bracket,
394         expect_trail
395     } state = search_esc;
396     int len = 0, found = 0;
397     char ch;
398
399     /* XXX: Strictly we should be checking utf8 chars rather than
400      *      bytes in case of the extremely unlikely scenario where
401      *      an ANSI sequence is part of a utf8 sequence.
402      */
403     while ((ch = *prompt++) != 0) {
404         switch (state) {
405         case search_esc:
406             if (ch == '\x1b') {
407                 state = expect_bracket;
408             }
409             break;
410         case expect_bracket:
411             if (ch == '[') {
412                 state = expect_trail;
413                 /* 3 for "\e[ ... m" */
414                 len = 3;
415                 break;
416             }
417             state = search_esc;
418             break;
419         case expect_trail:
420             if ((ch == ';') || ((ch >= '0' && ch <= '9'))) {
421                 /* 0-9, or semicolon */
422                 len++;
423                 break;
424             }
425             if (ch == 'm') {
426                 found += len;
427             }
428             state = search_esc;
429             break;
430         }
431     }
432
433     return found;
434 }
435
436 static int getWindowSize(struct current *current)
437 {
438     struct winsize ws;
439
440     if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
441         current->cols = ws.ws_col;
442         return 0;
443     }
444
445     /* Failed to query the window size. Perhaps we are on a serial terminal.
446      * Try to query the width by sending the cursor as far to the right
447      * and reading back the cursor position.
448      * Note that this is only done once per call to linenoise rather than
449      * every time the line is refreshed for efficiency reasons.
450      */
451     if (current->cols == 0) {
452         current->cols = 80;
453
454         /* Move cursor far right and report cursor position, then back to the left */
455         fd_printf(current->fd, "\x1b[999C" "\x1b[6n");
456
457         /* Parse the response: ESC [ rows ; cols R */
458         if (fd_read_char(current->fd, 100) == 0x1b && fd_read_char(current->fd, 100) == '[') {
459             int n = 0;
460             while (1) {
461                 int ch = fd_read_char(current->fd, 100);
462                 if (ch == ';') {
463                     /* Ignore rows */
464                     n = 0;
465                 }
466                 else if (ch == 'R') {
467                     /* Got cols */
468                     if (n != 0 && n < 1000) {
469                         current->cols = n;
470                     }
471                     break;
472                 }
473                 else if (ch >= 0 && ch <= '9') {
474                     n = n * 10 + ch - '0';
475                 }
476                 else {
477                     break;
478                 }
479             }
480         }
481     }
482     return 0;
483 }
484
485 /**
486  * If escape (27) was received, reads subsequent
487  * chars to determine if this is a known special key.
488  *
489  * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
490  *
491  * If no additional char is received within a short time,
492  * 27 is returned.
493  */
494 static int check_special(int fd)
495 {
496     int c = fd_read_char(fd, 50);
497     int c2;
498
499     if (c < 0) {
500         return 27;
501     }
502
503     c2 = fd_read_char(fd, 50);
504     if (c2 < 0) {
505         return c2;
506     }
507     if (c == '[' || c == 'O') {
508         /* Potential arrow key */
509         switch (c2) {
510             case 'A':
511                 return SPECIAL_UP;
512             case 'B':
513                 return SPECIAL_DOWN;
514             case 'C':
515                 return SPECIAL_RIGHT;
516             case 'D':
517                 return SPECIAL_LEFT;
518             case 'F':
519                 return SPECIAL_END;
520             case 'H':
521                 return SPECIAL_HOME;
522         }
523     }
524     if (c == '[' && c2 >= '1' && c2 <= '8') {
525         /* extended escape */
526         c = fd_read_char(fd, 50);
527         if (c == '~') {
528             switch (c2) {
529                 case '2':
530                     return SPECIAL_INSERT;
531                 case '3':
532                     return SPECIAL_DELETE;
533                 case '5':
534                     return SPECIAL_PAGE_UP;
535                 case '6':
536                     return SPECIAL_PAGE_DOWN;
537                 case '7':
538                     return SPECIAL_HOME;
539                 case '8':
540                     return SPECIAL_END;
541             }
542         }
543         while (c != -1 && c != '~') {
544             /* .e.g \e[12~ or '\e[11;2~   discard the complete sequence */
545             c = fd_read_char(fd, 50);
546         }
547     }
548
549     return SPECIAL_NONE;
550 }
551 #elif defined(USE_WINCONSOLE)
552
553 static DWORD orig_consolemode = 0;
554
555 static int enableRawMode(struct current *current) {
556     DWORD n;
557     INPUT_RECORD irec;
558
559     current->outh = GetStdHandle(STD_OUTPUT_HANDLE);
560     current->inh = GetStdHandle(STD_INPUT_HANDLE);
561
562     if (!PeekConsoleInput(current->inh, &irec, 1, &n)) {
563         return -1;
564     }
565     if (getWindowSize(current) != 0) {
566         return -1;
567     }
568     if (GetConsoleMode(current->inh, &orig_consolemode)) {
569         SetConsoleMode(current->inh, ENABLE_PROCESSED_INPUT);
570     }
571     return 0;
572 }
573
574 static void disableRawMode(struct current *current)
575 {
576     SetConsoleMode(current->inh, orig_consolemode);
577 }
578
579 static void clearScreen(struct current *current)
580 {
581     COORD topleft = { 0, 0 };
582     DWORD n;
583
584     FillConsoleOutputCharacter(current->outh, ' ',
585         current->cols * current->rows, topleft, &n);
586     FillConsoleOutputAttribute(current->outh,
587         FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN,
588         current->cols * current->rows, topleft, &n);
589     SetConsoleCursorPosition(current->outh, topleft);
590 }
591
592 static void cursorToLeft(struct current *current)
593 {
594     COORD pos = { 0, (SHORT)current->y };
595     DWORD n;
596
597     FillConsoleOutputAttribute(current->outh,
598         FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, current->cols, pos, &n);
599     current->x = 0;
600 }
601
602 static int outputChars(struct current *current, const char *buf, int len)
603 {
604     COORD pos = { (SHORT)current->x, (SHORT)current->y };
605     DWORD n;
606
607     WriteConsoleOutputCharacter(current->outh, buf, len, pos, &n);
608     current->x += len;
609     return 0;
610 }
611
612 static void outputControlChar(struct current *current, char ch)
613 {
614     COORD pos = { (SHORT)current->x, (SHORT)current->y };
615     DWORD n;
616
617     FillConsoleOutputAttribute(current->outh, BACKGROUND_INTENSITY, 2, pos, &n);
618     outputChars(current, "^", 1);
619     outputChars(current, &ch, 1);
620 }
621
622 static void eraseEol(struct current *current)
623 {
624     COORD pos = { (SHORT)current->x, (SHORT)current->y };
625     DWORD n;
626
627     FillConsoleOutputCharacter(current->outh, ' ', current->cols - current->x, pos, &n);
628 }
629
630 static void setCursorPos(struct current *current, int x)
631 {
632     COORD pos = { (SHORT)x, (SHORT)current->y };
633
634     SetConsoleCursorPosition(current->outh, pos);
635     current->x = x;
636 }
637
638 static int fd_read(struct current *current)
639 {
640     while (1) {
641         INPUT_RECORD irec;
642         DWORD n;
643         if (WaitForSingleObject(current->inh, INFINITE) != WAIT_OBJECT_0) {
644             break;
645         }
646         if (!ReadConsoleInput (current->inh, &irec, 1, &n)) {
647             break;
648         }
649         if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown) {
650             KEY_EVENT_RECORD *k = &irec.Event.KeyEvent;
651             if (k->dwControlKeyState & ENHANCED_KEY) {
652                 switch (k->wVirtualKeyCode) {
653                  case VK_LEFT:
654                     return SPECIAL_LEFT;
655                  case VK_RIGHT:
656                     return SPECIAL_RIGHT;
657                  case VK_UP:
658                     return SPECIAL_UP;
659                  case VK_DOWN:
660                     return SPECIAL_DOWN;
661                  case VK_INSERT:
662                     return SPECIAL_INSERT;
663                  case VK_DELETE:
664                     return SPECIAL_DELETE;
665                  case VK_HOME:
666                     return SPECIAL_HOME;
667                  case VK_END:
668                     return SPECIAL_END;
669                  case VK_PRIOR:
670                     return SPECIAL_PAGE_UP;
671                  case VK_NEXT:
672                     return SPECIAL_PAGE_DOWN;
673                 }
674             }
675             /* Note that control characters are already translated in AsciiChar */
676             else {
677 #ifdef USE_UTF8
678                 return k->uChar.UnicodeChar;
679 #else
680                 return k->uChar.AsciiChar;
681 #endif
682             }
683         }
684     }
685     return -1;
686 }
687
688 static int countColorControlChars(const char* prompt)
689 {
690     /* For windows we assume that there are no embedded ansi color
691      * control sequences.
692      */
693     return 0;
694 }
695
696 static int getWindowSize(struct current *current)
697 {
698     CONSOLE_SCREEN_BUFFER_INFO info;
699     if (!GetConsoleScreenBufferInfo(current->outh, &info)) {
700         return -1;
701     }
702     current->cols = info.dwSize.X;
703     current->rows = info.dwSize.Y;
704     if (current->cols <= 0 || current->rows <= 0) {
705         current->cols = 80;
706         return -1;
707     }
708     current->y = info.dwCursorPosition.Y;
709     current->x = info.dwCursorPosition.X;
710     return 0;
711 }
712 #endif
713
714 static int utf8_getchars(char *buf, int c)
715 {
716 #ifdef USE_UTF8
717     return utf8_fromunicode(buf, c);
718 #else
719     *buf = c;
720     return 1;
721 #endif
722 }
723
724 /**
725  * Returns the unicode character at the given offset,
726  * or -1 if none.
727  */
728 static int get_char(struct current *current, int pos)
729 {
730     if (pos >= 0 && pos < current->chars) {
731         int c;
732         int i = utf8_index(current->buf, pos);
733         (void)utf8_tounicode(current->buf + i, &c);
734         return c;
735     }
736     return -1;
737 }
738
739 static void refreshLine(const char *prompt, struct current *current)
740 {
741     int plen;
742     int pchars;
743     int backup = 0;
744     int i;
745     const char *buf = current->buf;
746     int chars = current->chars;
747     int pos = current->pos;
748     int b;
749     int ch;
750     int n;
751
752     /* Should intercept SIGWINCH. For now, just get the size every time */
753     getWindowSize(current);
754
755     plen = strlen(prompt);
756     pchars = utf8_strlen(prompt, plen);
757
758     /* Scan the prompt for embedded ansi color control sequences and
759      * discount them as characters/columns.
760      */
761     pchars -= countColorControlChars(prompt);
762
763     /* Account for a line which is too long to fit in the window.
764      * Note that control chars require an extra column
765      */
766
767     /* How many cols are required to the left of 'pos'?
768      * The prompt, plus one extra for each control char
769      */
770     n = pchars + utf8_strlen(buf, current->len);
771     b = 0;
772     for (i = 0; i < pos; i++) {
773         b += utf8_tounicode(buf + b, &ch);
774         if (ch < ' ') {
775             n++;
776         }
777     }
778
779     /* If too many are needed, strip chars off the front of 'buf'
780      * until it fits. Note that if the current char is a control character,
781      * we need one extra col.
782      */
783     if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
784         n++;
785     }
786
787     while (n >= current->cols && pos > 0) {
788         b = utf8_tounicode(buf, &ch);
789         if (ch < ' ') {
790             n--;
791         }
792         n--;
793         buf += b;
794         pos--;
795         chars--;
796     }
797
798     /* Cursor to left edge, then the prompt */
799     cursorToLeft(current);
800     outputChars(current, prompt, plen);
801
802     /* Now the current buffer content */
803
804     /* Need special handling for control characters.
805      * If we hit 'cols', stop.
806      */
807     b = 0; /* unwritted bytes */
808     n = 0; /* How many control chars were written */
809     for (i = 0; i < chars; i++) {
810         int ch;
811         int w = utf8_tounicode(buf + b, &ch);
812         if (ch < ' ') {
813             n++;
814         }
815         if (pchars + i + n >= current->cols) {
816             break;
817         }
818         if (ch < ' ') {
819             /* A control character, so write the buffer so far */
820             outputChars(current, buf, b);
821             buf += b + w;
822             b = 0;
823             outputControlChar(current, ch + '@');
824             if (i < pos) {
825                 backup++;
826             }
827         }
828         else {
829             b += w;
830         }
831     }
832     outputChars(current, buf, b);
833
834     /* Erase to right, move cursor to original position */
835     eraseEol(current);
836     setCursorPos(current, pos + pchars + backup);
837 }
838
839 static void set_current(struct current *current, const char *str)
840 {
841     strncpy(current->buf, str, current->bufmax);
842     current->buf[current->bufmax - 1] = 0;
843     current->len = strlen(current->buf);
844     current->pos = current->chars = utf8_strlen(current->buf, current->len);
845 }
846
847 static int has_room(struct current *current, int bytes)
848 {
849     return current->len + bytes < current->bufmax - 1;
850 }
851
852 /**
853  * Removes the char at 'pos'.
854  *
855  * Returns 1 if the line needs to be refreshed, 2 if not
856  * and 0 if nothing was removed
857  */
858 static int remove_char(struct current *current, int pos)
859 {
860     if (pos >= 0 && pos < current->chars) {
861         int p1, p2;
862         int ret = 1;
863         p1 = utf8_index(current->buf, pos);
864         p2 = p1 + utf8_index(current->buf + p1, 1);
865
866 #ifdef USE_TERMIOS
867         /* optimise remove char in the case of removing the last char */
868         if (current->pos == pos + 1 && current->pos == current->chars) {
869             if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
870                 ret = 2;
871                 fd_printf(current->fd, "\b \b");
872             }
873         }
874 #endif
875
876         /* Move the null char too */
877         memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
878         current->len -= (p2 - p1);
879         current->chars--;
880
881         if (current->pos > pos) {
882             current->pos--;
883         }
884         return ret;
885     }
886     return 0;
887 }
888
889 /**
890  * Insert 'ch' at position 'pos'
891  *
892  * Returns 1 if the line needs to be refreshed, 2 if not
893  * and 0 if nothing was inserted (no room)
894  */
895 static int insert_char(struct current *current, int pos, int ch)
896 {
897     char buf[3];
898     int n = utf8_getchars(buf, ch);
899
900     if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
901         int p1, p2;
902         int ret = 1;
903         p1 = utf8_index(current->buf, pos);
904         p2 = p1 + n;
905
906 #ifdef USE_TERMIOS
907         /* optimise the case where adding a single char to the end and no scrolling is needed */
908         if (current->pos == pos && current->chars == pos) {
909             if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
910                 IGNORE_RC(write(current->fd, buf, n));
911                 ret = 2;
912             }
913         }
914 #endif
915
916         memmove(current->buf + p2, current->buf + p1, current->len - p1);
917         memcpy(current->buf + p1, buf, n);
918         current->len += n;
919
920         current->chars++;
921         if (current->pos >= pos) {
922             current->pos++;
923         }
924         return ret;
925     }
926     return 0;
927 }
928
929 /**
930  * Captures up to 'n' characters starting at 'pos' for the cut buffer.
931  *
932  * This replaces any existing characters in the cut buffer.
933  */
934 static void capture_chars(struct current *current, int pos, int n)
935 {
936     if (pos >= 0 && (pos + n - 1) < current->chars) {
937         int p1 = utf8_index(current->buf, pos);
938         int nbytes = utf8_index(current->buf + p1, n);
939
940         if (nbytes) {
941             free(current->capture);
942             /* Include space for the null terminator */
943             current->capture = (char *)malloc(nbytes + 1);
944             memcpy(current->capture, current->buf + p1, nbytes);
945             current->capture[nbytes] = '\0';
946         }
947     }
948 }
949
950 /**
951  * Removes up to 'n' characters at cursor position 'pos'.
952  *
953  * Returns 0 if no chars were removed or non-zero otherwise.
954  */
955 static int remove_chars(struct current *current, int pos, int n)
956 {
957     int removed = 0;
958
959     /* First save any chars which will be removed */
960     capture_chars(current, pos, n);
961
962     while (n-- && remove_char(current, pos)) {
963         removed++;
964     }
965     return removed;
966 }
967 /**
968  * Inserts the characters (string) 'chars' at the cursor position 'pos'.
969  *
970  * Returns 0 if no chars were inserted or non-zero otherwise.
971  */
972 static int insert_chars(struct current *current, int pos, const char *chars)
973 {
974     int inserted = 0;
975
976     while (*chars) {
977         int ch;
978         int n = utf8_tounicode(chars, &ch);
979         if (insert_char(current, pos, ch) == 0) {
980             break;
981         }
982         inserted++;
983         pos++;
984         chars += n;
985     }
986     return inserted;
987 }
988
989 #ifndef NO_COMPLETION
990 static linenoiseCompletionCallback *completionCallback = NULL;
991
992 static void beep() {
993 #ifdef USE_TERMIOS
994     fprintf(stderr, "\x7");
995     fflush(stderr);
996 #endif
997 }
998
999 static void freeCompletions(linenoiseCompletions *lc) {
1000     size_t i;
1001     for (i = 0; i < lc->len; i++)
1002         free(lc->cvec[i]);
1003     free(lc->cvec);
1004 }
1005
1006 static int completeLine(struct current *current) {
1007     linenoiseCompletions lc = { 0, NULL };
1008     int c = 0;
1009
1010     completionCallback(current->buf,&lc);
1011     if (lc.len == 0) {
1012         beep();
1013     } else {
1014         size_t stop = 0, i = 0;
1015
1016         while(!stop) {
1017             /* Show completion or original buffer */
1018             if (i < lc.len) {
1019                 struct current tmp = *current;
1020                 tmp.buf = lc.cvec[i];
1021                 tmp.pos = tmp.len = strlen(tmp.buf);
1022                 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
1023                 refreshLine(current->prompt, &tmp);
1024             } else {
1025                 refreshLine(current->prompt, current);
1026             }
1027
1028             c = fd_read(current);
1029             if (c == -1) {
1030                 break;
1031             }
1032
1033             switch(c) {
1034                 case '\t': /* tab */
1035                     i = (i+1) % (lc.len+1);
1036                     if (i == lc.len) beep();
1037                     break;
1038                 case 27: /* escape */
1039                     /* Re-show original buffer */
1040                     if (i < lc.len) {
1041                         refreshLine(current->prompt, current);
1042                     }
1043                     stop = 1;
1044                     break;
1045                 default:
1046                     /* Update buffer and return */
1047                     if (i < lc.len) {
1048                         set_current(current,lc.cvec[i]);
1049                     }
1050                     stop = 1;
1051                     break;
1052             }
1053         }
1054     }
1055
1056     freeCompletions(&lc);
1057     return c; /* Return last read character */
1058 }
1059
1060 /* Register a callback function to be called for tab-completion. */
1061 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
1062     completionCallback = fn;
1063 }
1064
1065 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
1066     lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
1067     lc->cvec[lc->len++] = strdup(str);
1068 }
1069
1070 #endif
1071
1072 static int linenoiseEdit(struct current *current) {
1073     int history_index = 0;
1074
1075     /* The latest history entry is always our current buffer, that
1076      * initially is just an empty string. */
1077     linenoiseHistoryAdd("");
1078
1079     set_current(current, "");
1080     refreshLine(current->prompt, current);
1081
1082     while(1) {
1083         int dir = -1;
1084         int c = fd_read(current);
1085
1086 #ifndef NO_COMPLETION
1087         /* Only autocomplete when the callback is set. It returns < 0 when
1088          * there was an error reading from fd. Otherwise it will return the
1089          * character that should be handled next. */
1090         if (c == '\t' && current->pos == current->chars && completionCallback != NULL) {
1091             c = completeLine(current);
1092             /* Return on errors */
1093             if (c < 0) return current->len;
1094             /* Read next character when 0 */
1095             if (c == 0) continue;
1096         }
1097 #endif
1098
1099 process_char:
1100         if (c == -1) return current->len;
1101 #ifdef USE_TERMIOS
1102         if (c == 27) {   /* escape sequence */
1103             c = check_special(current->fd);
1104         }
1105 #endif
1106         switch(c) {
1107         case '\r':    /* enter */
1108             history_len--;
1109             free(history[history_len]);
1110             return current->len;
1111         case ctrl('C'):     /* ctrl-c */
1112             errno = EAGAIN;
1113             return -1;
1114         case 127:   /* backspace */
1115         case ctrl('H'):
1116             if (remove_char(current, current->pos - 1) == 1) {
1117                 refreshLine(current->prompt, current);
1118             }
1119             break;
1120         case ctrl('D'):     /* ctrl-d */
1121             if (current->len == 0) {
1122                 /* Empty line, so EOF */
1123                 history_len--;
1124                 free(history[history_len]);
1125                 return -1;
1126             }
1127             /* Otherwise fall through to delete char to right of cursor */
1128         case SPECIAL_DELETE:
1129             if (remove_char(current, current->pos) == 1) {
1130                 refreshLine(current->prompt, current);
1131             }
1132             break;
1133         case SPECIAL_INSERT:
1134             /* Ignore. Expansion Hook.
1135              * Future possibility: Toggle Insert/Overwrite Modes
1136              */
1137             break;
1138         case ctrl('W'):    /* ctrl-w, delete word at left. save deleted chars */
1139             /* eat any spaces on the left */
1140             {
1141                 int pos = current->pos;
1142                 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1143                     pos--;
1144                 }
1145
1146                 /* now eat any non-spaces on the left */
1147                 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1148                     pos--;
1149                 }
1150
1151                 if (remove_chars(current, pos, current->pos - pos)) {
1152                     refreshLine(current->prompt, current);
1153                 }
1154             }
1155             break;
1156         case ctrl('R'):    /* ctrl-r */
1157             {
1158                 /* Display the reverse-i-search prompt and process chars */
1159                 char rbuf[50];
1160                 char rprompt[80];
1161                 int rchars = 0;
1162                 int rlen = 0;
1163                 int searchpos = history_len - 1;
1164
1165                 rbuf[0] = 0;
1166                 while (1) {
1167                     int n = 0;
1168                     const char *p = NULL;
1169                     int skipsame = 0;
1170                     int searchdir = -1;
1171
1172                     snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1173                     refreshLine(rprompt, current);
1174                     c = fd_read(current);
1175                     if (c == ctrl('H') || c == 127) {
1176                         if (rchars) {
1177                             int p = utf8_index(rbuf, --rchars);
1178                             rbuf[p] = 0;
1179                             rlen = strlen(rbuf);
1180                         }
1181                         continue;
1182                     }
1183 #ifdef USE_TERMIOS
1184                     if (c == 27) {
1185                         c = check_special(current->fd);
1186                     }
1187 #endif
1188                     if (c == ctrl('P') || c == SPECIAL_UP) {
1189                         /* Search for the previous (earlier) match */
1190                         if (searchpos > 0) {
1191                             searchpos--;
1192                         }
1193                         skipsame = 1;
1194                     }
1195                     else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1196                         /* Search for the next (later) match */
1197                         if (searchpos < history_len) {
1198                             searchpos++;
1199                         }
1200                         searchdir = 1;
1201                         skipsame = 1;
1202                     }
1203                     else if (c >= ' ') {
1204                         if (rlen >= (int)sizeof(rbuf) + 3) {
1205                             continue;
1206                         }
1207
1208                         n = utf8_getchars(rbuf + rlen, c);
1209                         rlen += n;
1210                         rchars++;
1211                         rbuf[rlen] = 0;
1212
1213                         /* Adding a new char resets the search location */
1214                         searchpos = history_len - 1;
1215                     }
1216                     else {
1217                         /* Exit from incremental search mode */
1218                         break;
1219                     }
1220
1221                     /* Now search through the history for a match */
1222                     for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1223                         p = strstr(history[searchpos], rbuf);
1224                         if (p) {
1225                             /* Found a match */
1226                             if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
1227                                 /* But it is identical, so skip it */
1228                                 continue;
1229                             }
1230                             /* Copy the matching line and set the cursor position */
1231                             set_current(current,history[searchpos]);
1232                             current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1233                             break;
1234                         }
1235                     }
1236                     if (!p && n) {
1237                         /* No match, so don't add it */
1238                         rchars--;
1239                         rlen -= n;
1240                         rbuf[rlen] = 0;
1241                     }
1242                 }
1243                 if (c == ctrl('G') || c == ctrl('C')) {
1244                     /* ctrl-g terminates the search with no effect */
1245                     set_current(current, "");
1246                     c = 0;
1247                 }
1248                 else if (c == ctrl('J')) {
1249                     /* ctrl-j terminates the search leaving the buffer in place */
1250                     c = 0;
1251                 }
1252                 /* Go process the char normally */
1253                 refreshLine(current->prompt, current);
1254                 goto process_char;
1255             }
1256             break;
1257         case ctrl('T'):    /* ctrl-t */
1258             if (current->pos > 0 && current->pos <= current->chars) {
1259                 /* If cursor is at end, transpose the previous two chars */
1260                 int fixer = (current->pos == current->chars);
1261                 c = get_char(current, current->pos - fixer);
1262                 remove_char(current, current->pos - fixer);
1263                 insert_char(current, current->pos - 1, c);
1264                 refreshLine(current->prompt, current);
1265             }
1266             break;
1267         case ctrl('V'):    /* ctrl-v */
1268             if (has_room(current, 3)) {
1269                 /* Insert the ^V first */
1270                 if (insert_char(current, current->pos, c)) {
1271                     refreshLine(current->prompt, current);
1272                     /* Now wait for the next char. Can insert anything except \0 */
1273                     c = fd_read(current);
1274
1275                     /* Remove the ^V first */
1276                     remove_char(current, current->pos - 1);
1277                     if (c != -1) {
1278                         /* Insert the actual char */
1279                         insert_char(current, current->pos, c);
1280                     }
1281                     refreshLine(current->prompt, current);
1282                 }
1283             }
1284             break;
1285         case ctrl('B'):
1286         case SPECIAL_LEFT:
1287             if (current->pos > 0) {
1288                 current->pos--;
1289                 refreshLine(current->prompt, current);
1290             }
1291             break;
1292         case ctrl('F'):
1293         case SPECIAL_RIGHT:
1294             if (current->pos < current->chars) {
1295                 current->pos++;
1296                 refreshLine(current->prompt, current);
1297             }
1298             break;
1299         case SPECIAL_PAGE_UP:
1300           dir = history_len - history_index - 1; /* move to start of history */
1301           goto history_navigation;
1302         case SPECIAL_PAGE_DOWN:
1303           dir = -history_index; /* move to 0 == end of history, i.e. current */
1304           goto history_navigation;
1305         case ctrl('P'):
1306         case SPECIAL_UP:
1307             dir = 1;
1308           goto history_navigation;
1309         case ctrl('N'):
1310         case SPECIAL_DOWN:
1311 history_navigation:
1312             if (history_len > 1) {
1313                 /* Update the current history entry before to
1314                  * overwrite it with tne next one. */
1315                 free(history[history_len - 1 - history_index]);
1316                 history[history_len - 1 - history_index] = strdup(current->buf);
1317                 /* Show the new entry */
1318                 history_index += dir;
1319                 if (history_index < 0) {
1320                     history_index = 0;
1321                     break;
1322                 } else if (history_index >= history_len) {
1323                     history_index = history_len - 1;
1324                     break;
1325                 }
1326                 set_current(current, history[history_len - 1 - history_index]);
1327                 refreshLine(current->prompt, current);
1328             }
1329             break;
1330         case ctrl('A'): /* Ctrl+a, go to the start of the line */
1331         case SPECIAL_HOME:
1332             current->pos = 0;
1333             refreshLine(current->prompt, current);
1334             break;
1335         case ctrl('E'): /* ctrl+e, go to the end of the line */
1336         case SPECIAL_END:
1337             current->pos = current->chars;
1338             refreshLine(current->prompt, current);
1339             break;
1340         case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */
1341             if (remove_chars(current, 0, current->pos)) {
1342                 refreshLine(current->prompt, current);
1343             }
1344             break;
1345         case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */
1346             if (remove_chars(current, current->pos, current->chars - current->pos)) {
1347                 refreshLine(current->prompt, current);
1348             }
1349             break;
1350         case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */
1351             if (current->capture && insert_chars(current, current->pos, current->capture)) {
1352                 refreshLine(current->prompt, current);
1353             }
1354             break;
1355         case ctrl('L'): /* Ctrl+L, clear screen */
1356             clearScreen(current);
1357             /* Force recalc of window size for serial terminals */
1358             current->cols = 0;
1359             refreshLine(current->prompt, current);
1360             break;
1361         default:
1362             /* Only tab is allowed without ^V */
1363             if (c == '\t' || c >= ' ') {
1364                 if (insert_char(current, current->pos, c) == 1) {
1365                     refreshLine(current->prompt, current);
1366                 }
1367             }
1368             break;
1369         }
1370     }
1371     return current->len;
1372 }
1373
1374 int linenoiseColumns(void)
1375 {
1376     struct current current;
1377     enableRawMode (&current);
1378     getWindowSize (&current);
1379     disableRawMode (&current);
1380     return current.cols;
1381 }
1382
1383 char *linenoise(const char *prompt)
1384 {
1385     int count;
1386     struct current current;
1387     char buf[LINENOISE_MAX_LINE];
1388
1389     if (enableRawMode(&current) == -1) {
1390         printf("%s", prompt);
1391         fflush(stdout);
1392         if (fgets(buf, sizeof(buf), stdin) == NULL) {
1393             return NULL;
1394         }
1395         count = strlen(buf);
1396         if (count && buf[count-1] == '\n') {
1397             count--;
1398             buf[count] = '\0';
1399         }
1400     }
1401     else
1402     {
1403         current.buf = buf;
1404         current.bufmax = sizeof(buf);
1405         current.len = 0;
1406         current.chars = 0;
1407         current.pos = 0;
1408         current.prompt = prompt;
1409         current.capture = NULL;
1410
1411         count = linenoiseEdit(&current);
1412
1413         disableRawMode(&current);
1414         printf("\n");
1415
1416         free(current.capture);
1417         if (count == -1) {
1418             return NULL;
1419         }
1420     }
1421     return strdup(buf);
1422 }
1423
1424 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1425 int linenoiseHistoryAdd(const char *line) {
1426     char *linecopy;
1427
1428     if (history_max_len == 0) return 0;
1429     if (history == NULL) {
1430         history = (char **)malloc(sizeof(char*)*history_max_len);
1431         if (history == NULL) return 0;
1432         memset(history,0,(sizeof(char*)*history_max_len));
1433     }
1434
1435     /* do not insert duplicate lines into history */
1436     if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1437         return 0;
1438     }
1439
1440     linecopy = strdup(line);
1441     if (!linecopy) return 0;
1442     if (history_len == history_max_len) {
1443         free(history[0]);
1444         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1445         history_len--;
1446     }
1447     history[history_len] = linecopy;
1448     history_len++;
1449     return 1;
1450 }
1451
1452 int linenoiseHistoryGetMaxLen(void) {
1453     return history_max_len;
1454 }
1455
1456 int linenoiseHistorySetMaxLen(int len) {
1457     char **newHistory;
1458
1459     if (len < 1) return 0;
1460     if (history) {
1461         int tocopy = history_len;
1462
1463         newHistory = (char **)malloc(sizeof(char*)*len);
1464         if (newHistory == NULL) return 0;
1465
1466         /* If we can't copy everything, free the elements we'll not use. */
1467         if (len < tocopy) {
1468             int j;
1469
1470             for (j = 0; j < tocopy-len; j++) free(history[j]);
1471             tocopy = len;
1472         }
1473         memset(newHistory,0,sizeof(char*)*len);
1474         memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy);
1475         free(history);
1476         history = newHistory;
1477     }
1478     history_max_len = len;
1479     if (history_len > history_max_len)
1480         history_len = history_max_len;
1481     return 1;
1482 }
1483
1484 /* Save the history in the specified file. On success 0 is returned
1485  * otherwise -1 is returned. */
1486 int linenoiseHistorySave(const char *filename) {
1487     FILE *fp = fopen(filename,"w");
1488     int j;
1489
1490     if (fp == NULL) return -1;
1491     for (j = 0; j < history_len; j++) {
1492         const char *str = history[j];
1493         /* Need to encode backslash, nl and cr */
1494         while (*str) {
1495             if (*str == '\\') {
1496                 fputs("\\\\", fp);
1497             }
1498             else if (*str == '\n') {
1499                 fputs("\\n", fp);
1500             }
1501             else if (*str == '\r') {
1502                 fputs("\\r", fp);
1503             }
1504             else {
1505                 fputc(*str, fp);
1506             }
1507             str++;
1508         }
1509         fputc('\n', fp);
1510     }
1511
1512     fclose(fp);
1513     return 0;
1514 }
1515
1516 /* Load the history from the specified file. If the file does not exist
1517  * zero is returned and no operation is performed.
1518  *
1519  * If the file exists and the operation succeeded 0 is returned, otherwise
1520  * on error -1 is returned. */
1521 int linenoiseHistoryLoad(const char *filename) {
1522     FILE *fp = fopen(filename,"r");
1523     char buf[LINENOISE_MAX_LINE];
1524
1525     if (fp == NULL) return -1;
1526
1527     while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1528         char *src, *dest;
1529
1530         /* Decode backslash escaped values */
1531         for (src = dest = buf; *src; src++) {
1532             char ch = *src;
1533
1534             if (ch == '\\') {
1535                 src++;
1536                 if (*src == 'n') {
1537                     ch = '\n';
1538                 }
1539                 else if (*src == 'r') {
1540                     ch = '\r';
1541                 } else {
1542                     ch = *src;
1543                 }
1544             }
1545             *dest++ = ch;
1546         }
1547         /* Remove trailing newline */
1548         if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1549             dest--;
1550         }
1551         *dest = 0;
1552
1553         linenoiseHistoryAdd(buf);
1554     }
1555     fclose(fp);
1556     return 0;
1557 }
1558
1559 /* Provide access to the history buffer.
1560  *
1561  * If 'len' is not NULL, the length is stored in *len.
1562  */
1563 char **linenoiseHistory(int *len) {
1564     if (len) {
1565         *len = history_len;
1566     }
1567     return history;
1568 }