]> git.lizzy.rs Git - linenoise.git/blob - linenoise.c
d1d32caec8bdc0e46f3a40b9c82c208432cc4e58
[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/antirez/linenoise
7  *
8  * Does a number of crazy assumptions that happen to be true in 99.9999% of
9  * the 2010 UNIX computers around.
10  *
11  * ------------------------------------------------------------------------
12  *
13  * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
14  * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
15  *
16  * All rights reserved.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions are
20  * met:
21  *
22  *  *  Redistributions of source code must retain the above copyright
23  *     notice, this list of conditions and the following disclaimer.
24  *
25  *  *  Redistributions in binary form must reproduce the above copyright
26  *     notice, this list of conditions and the following disclaimer in the
27  *     documentation and/or other materials provided with the distribution.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  * ------------------------------------------------------------------------
42  *
43  * References:
44  * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
45  * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
46  *
47  * Todo list:
48  * - Switch to gets() if $TERM is something we can't support.
49  * - Win32 support
50  *
51  * Bloat:
52  * - Completion?
53  *
54  * List of escape sequences used by this program, we do everything just
55  * with three 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  * CHA (Cursor Horizontal Absolute)
60  *    Sequence: ESC [ n G
61  *    Effect: moves cursor to column n
62  *
63  * EL (Erase Line)
64  *    Sequence: ESC [ n K
65  *    Effect: if n is 0 or missing, clear from cursor to end of line
66  *    Effect: if n is 1, clear from beginning of line to cursor
67  *    Effect: if n is 2, clear entire line
68  *
69  * CUF (CUrsor Forward)
70  *    Sequence: ESC [ n C
71  *    Effect: moves cursor forward of n chars
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
99 #include <termios.h>
100 #include <unistd.h>
101 #include <stdlib.h>
102 #include <stdarg.h>
103 #include <stdio.h>
104 #include <errno.h>
105 #include <string.h>
106 #include <stdlib.h>
107 #include <sys/types.h>
108 #include <sys/ioctl.h>
109 #include <unistd.h>
110 #include "linenoise.h"
111
112 #include "linenoise.h"
113
114 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
115 #define LINENOISE_MAX_LINE 4096
116 static char *unsupported_term[] = {"dumb","cons25",NULL};
117
118 static struct termios orig_termios; /* in order to restore at exit */
119 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
120 static int atexit_registered = 0; /* register atexit just 1 time */
121 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
122 static int history_len = 0;
123 static char **history = NULL;
124
125 static void linenoiseAtExit(void);
126 static int fd_read(int fd);
127
128 static int isUnsupportedTerm(void) {
129     char *term = getenv("TERM");
130     int j;
131
132     if (term == NULL) return 0;
133     for (j = 0; unsupported_term[j]; j++)
134         if (!strcasecmp(term,unsupported_term[j])) return 1;
135     return 0;
136 }
137
138 static void freeHistory(void) {
139     if (history) {
140         int j;
141
142         for (j = 0; j < history_len; j++)
143             free(history[j]);
144         free(history);
145     }
146 }
147
148 static int enableRawMode(int fd) {
149     struct termios raw;
150
151     if (!isatty(STDIN_FILENO)) goto fatal;
152     if (!atexit_registered) {
153         atexit(linenoiseAtExit);
154         atexit_registered = 1;
155     }
156     if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
157
158     raw = orig_termios;  /* modify the original mode */
159     /* input modes: no break, no CR to NL, no parity check, no strip char,
160      * no start/stop output control. */
161     raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
162     /* output modes - disable post processing */
163     raw.c_oflag &= ~(OPOST);
164     /* control modes - set 8 bit chars */
165     raw.c_cflag |= (CS8);
166     /* local modes - choing off, canonical off, no extended functions,
167      * no signal chars (^Z,^C) */
168     raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
169     /* control chars - set return condition: min number of bytes and timer.
170      * We want read to return every single byte, without timeout. */
171     raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
172
173     /* put terminal in raw mode after flushing */
174     if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
175     rawmode = 1;
176     return 0;
177
178 fatal:
179     errno = ENOTTY;
180     return -1;
181 }
182
183 static void disableRawMode(int fd) {
184     /* Don't even check the return value as it's too late. */
185     if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1)
186         rawmode = 0;
187 }
188
189 /* At exit we'll try to fix the terminal to the initial conditions. */
190 static void linenoiseAtExit(void) {
191     disableRawMode(STDIN_FILENO);
192     freeHistory();
193 }
194
195 static int getColumns(void) {
196     struct winsize ws;
197
198     if (ioctl(1, TIOCGWINSZ, &ws) == -1) return 80;
199     return ws.ws_col;
200 }
201
202 /* Structure to contain the status of the current (being edited) line */
203 struct current {
204     int fd;     /* Terminal fd */
205     char *buf;  /* Current buffer. Always null terminated */
206     int bufmax; /* Size of the buffer, including space for the null termination */
207     int len;    /* Number of bytes in 'buf' */
208     int pos;    /* Cursor position, measured in chars */
209     int cols;   /* Size of the window, in chars */
210 };
211
212 /* This is fd_printf() on some systems, but use a different
213  * name to avoid conflicts
214  */
215 static void fd_printf(int fd, const char *format, ...)
216 {
217     va_list args;
218     char buf[64];
219     int n;
220
221     va_start(args, format);
222     n = vsnprintf(buf, sizeof(buf), format, args);
223     va_end(args);
224     write(fd, buf, n);
225 }
226
227 static void refreshLine(const char *prompt, struct current *c) {
228     size_t plen = strlen(prompt);
229     int extra = 0;
230     size_t i, p;
231     const char *buf = c->buf;
232     int len = c->len;
233     int pos = c->pos;
234
235     //fprintf(stderr, "\nrefreshLine: prompt=<<%s>>, buf=<<%s>>\n", prompt, c->buf);
236     //fprintf(stderr, "pos=%d, len=%d, cols=%d\n", pos, len, c->cols);
237
238     while((plen+pos) >= c->cols) {
239         buf++;
240         len--;
241         pos--;
242     }
243     while (plen+len > c->cols) {
244         len--;
245     }
246
247     /* Cursor to left edge, then the prompt */
248     fd_printf(c->fd, "\x1b[0G");
249     write(c->fd, prompt, strlen(prompt));
250
251     /* Now the current buffer content */
252     /* Need special handling for control characters */
253     p = 0;
254     for (i = 0; i < len; i++) {
255         if (buf[i] >= 0 && buf[i] < ' ') {
256             write(c->fd, buf + p, i - p);
257             p = i + 1;
258             fd_printf(c->fd, "\033[7m^%c\033[0m", buf[i] + '@');
259             if (i < pos) {
260                 extra++;
261             }
262         }
263     }
264     write(c->fd, buf + p, i - p);
265
266     /* Erase to right, move cursor to original position */
267     fd_printf(c->fd, "\x1b[0K" "\x1b[0G\x1b[%dC", (int)(pos+plen+extra));
268 }
269
270 static void set_current(struct current *current, const char *str)
271 {
272     strncpy(current->buf, str, current->bufmax);
273     current->buf[current->bufmax - 1] = 0;
274     current->len = strlen(current->buf);
275     current->pos = current->len;
276 }
277
278 static int has_room(struct current *current, int chars)
279 {
280     return current->len + chars < current->bufmax - 1;
281 }
282
283 static int remove_char(struct current *current, int pos)
284 {
285     //fprintf(stderr, "Trying to remove char at %d (pos=%d, len=%d)\n", pos, current->pos, current->len);
286     if (pos >= 0 && pos < current->len) {
287         if (current->pos > pos) {
288             current->pos--;
289         }
290         /* Move the null char too */
291         memmove(current->buf + pos, current->buf + pos + 1, current->len - pos);
292         current->len--;
293         return 1;
294     }
295     return 0;
296 }
297
298 static int insert_char(struct current *current, int pos, int ch)
299 {
300     if (has_room(current, 1) && pos >= 0 && pos <= current->len) {
301         memmove(current->buf+pos+1, current->buf + pos, current->len - pos);
302         current->buf[pos] = ch;
303         current->len++;
304         if (current->pos >= pos) {
305             current->pos++;
306         }
307         return 1;
308     }
309     return 0;
310 }
311
312 #ifndef NO_COMPLETION
313 static linenoiseCompletionCallback *completionCallback = NULL;
314
315 static void beep() {
316     fprintf(stderr, "\x7");
317     fflush(stderr);
318 }
319
320 static void freeCompletions(linenoiseCompletions *lc) {
321     size_t i;
322     for (i = 0; i < lc->len; i++)
323         free(lc->cvec[i]);
324     free(lc->cvec);
325 }
326
327 static int completeLine(const char *prompt, struct current *current) {
328     linenoiseCompletions lc = { 0, NULL };
329     int c = 0;
330
331     completionCallback(current->buf,&lc);
332     if (lc.len == 0) {
333         beep();
334     } else {
335         size_t stop = 0, i = 0;
336
337         while(!stop) {
338             /* Show completion or original buffer */
339             if (i < lc.len) {
340                 struct current tmp = *current;
341                 tmp.buf = lc.cvec[i];
342                 tmp.pos = tmp.len = strlen(tmp.buf);
343                 refreshLine(prompt, &tmp);
344             } else {
345                 refreshLine(prompt, current);
346             }
347
348             c = fd_read(current->fd);
349             if (c < 0) {
350                 break;
351             }
352
353             switch(c) {
354                 case '\t': /* tab */
355                     i = (i+1) % (lc.len+1);
356                     if (i == lc.len) beep();
357                     break;
358                 case 27: /* escape */
359                     /* Re-show original buffer */
360                     if (i < lc.len) {
361                         refreshLine(prompt, current);
362                     }
363                     stop = 1;
364                     break;
365                 default:
366                     /* Update buffer and return */
367                     if (i < lc.len) {
368                         set_current(current,lc.cvec[i]);
369                     }
370                     stop = 1;
371                     break;
372             }
373         }
374     }
375
376     freeCompletions(&lc);
377     return c; /* Return last read character */
378 }
379
380 /* Register a callback function to be called for tab-completion. */
381 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
382     completionCallback = fn;
383 }
384
385 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
386     lc->cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
387     lc->cvec[lc->len++] = strdup(str);
388 }
389
390 #endif
391
392 /* XXX: Optimise this later */
393 static int remove_chars(struct current *current, int pos, int n)
394 {
395     int removed = 0;
396     while (n-- && remove_char(current, pos)) {
397         removed++;
398     }
399     return removed;
400 }
401
402 static int fd_read(int fd)
403 {
404     unsigned char c;
405     if (read(fd, &c, 1) != 1) {
406         return -1;
407     }
408     return c;
409 }
410
411 #ifndef ctrl
412 #define ctrl(C) ((C) - '@')
413 #endif
414
415 static int linenoisePrompt(const char *prompt, struct current *current) {
416     size_t plen = strlen(prompt);
417     int history_index = 0;
418
419     /* The latest history entry is always our current buffer, that
420      * initially is just an empty string. */
421     linenoiseHistoryAdd("");
422
423     set_current(current, "");
424     refreshLine(prompt, current);
425
426     while(1) {
427         int ext;
428         int c;
429         int c2;
430
431         c = fd_read(current->fd);
432
433 #ifndef NO_COMPLETION
434         /* Only autocomplete when the callback is set. It returns < 0 when
435          * there was an error reading from fd. Otherwise it will return the
436          * character that should be handled next. */
437         if (c == 9 && completionCallback != NULL) {
438             c = completeLine(prompt, current);
439             /* Return on errors */
440             if (c < 0) return current->len;
441             /* Read next character when 0 */
442             if (c == 0) continue;
443         }
444 #endif
445
446 process_char:
447         if (c < 0) return current->len;
448         switch(c) {
449         case '\r':    /* enter */
450             history_len--;
451             free(history[history_len]);
452             return current->len;
453         case ctrl('C'):     /* ctrl-c */
454             errno = EAGAIN;
455             return -1;
456         case 127:   /* backspace */
457         case ctrl('H'):
458             if (remove_char(current, current->pos - 1)) {
459                 refreshLine(prompt, current);
460             }
461             break;
462         case ctrl('D'):     /* ctrl-d */
463             if (current->len == 0) {
464                 /* Empty line, so EOF */
465                 history_len--;
466                 free(history[history_len]);
467                 return -1;
468             }
469             /* Otherwise delete char to right of cursor */
470             if (remove_char(current, current->pos)) {
471                 refreshLine(prompt, current);
472             }
473             break;
474         case ctrl('W'):    /* ctrl-w */
475             /* eat any spaces on the left */
476             {
477                 int pos = current->pos;
478                 while (pos > 0 && current->buf[pos - 1] == ' ') {
479                     pos--;
480                 }
481
482                 /* now eat any non-spaces on the left */
483                 while (pos > 0 && current->buf[pos - 1] != ' ') {
484                     pos--;
485                 }
486
487                 if (remove_chars(current, pos, current->pos - pos)) {
488                     refreshLine(prompt, current);
489                 }
490             }
491             break;
492         case ctrl('R'):    /* ctrl-r */
493             {
494                 /* Display the reverse-i-search prompt and process chars */
495                 char rbuf[50];
496                 char rprompt[80];
497                 int i = 0;
498                 rbuf[0] = 0;
499                 while (1) {
500                     snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
501                     refreshLine(rprompt, current);
502                     c = fd_read(current->fd);
503                     if (c == ctrl('H') || c == 127) {
504                         if (i > 0) {
505                             rbuf[--i] = 0;
506                         }
507                         continue;
508                     }
509                     if (c >= ' ' && c <= '~') {
510                         if (i < (int)sizeof(rbuf)) {
511                             int j;
512                             const char *p = NULL;
513                             rbuf[i++] = c;
514                             rbuf[i] = 0;
515                             /* Now search back through the history for a match */
516                             for (j = history_len - 1; j > 0; j--) {
517                                 p = strstr(history[j], rbuf);
518                                 if (p) {
519                                     /* Found a match. Copy it */
520                                     set_current(current,history[j]);
521                                     current->pos = p - history[j];
522                                     break;
523                                 }
524                             }
525                             if (!p) {
526                                 /* No match, so don't add it */
527                                 rbuf[--i] = 0;
528                             }
529                         }
530                         continue;
531                     }
532                     break;
533                 }
534                 if (c == ctrl('G')) {
535                     /* ctrl-g terminates the search with no effect */
536                     set_current(current, "");
537                     c = 0;
538                 }
539                 else if (c == ctrl('J')) {
540                     /* ctrl-j terminates the search leaving the buffer in place */
541                     c = 0;
542                 }
543                 /* Go process the char normally */
544                 refreshLine(prompt, current);
545                 goto process_char;
546             }
547             break;
548         case ctrl('T'):    /* ctrl-t */
549             if (current->pos > 0 && current->pos < current->len) {
550                 int aux = current->buf[current->pos-1];
551                 current->buf[current->pos-1] = current->buf[current->pos];
552                 current->buf[current->pos] = aux;
553                 if (current->pos != current->len-1) current->pos++;
554                 refreshLine(prompt, current);
555             }
556             break;
557         case ctrl('V'):    /* ctrl-v */
558             if (has_room(current, 1)) {
559                 /* Insert the ^V first */
560                 if (insert_char(current, current->pos, c)) {
561                     refreshLine(prompt, current);
562                     /* Now wait for the next char. Can insert anything except \0 */
563                     c = fd_read(current->fd);
564                     if (c > 0) {
565                         /* Replace the ^V with the actual char */
566                         current->buf[current->pos - 1] = c;
567                     }
568                     else {
569                         remove_char(current, current->pos);
570                     }
571                     refreshLine(prompt, current);
572                 }
573             }
574             break;
575         case ctrl('B'):     /* ctrl-b */
576             goto left_arrow;
577         case ctrl('F'):     /* ctrl-f */
578             goto right_arrow;
579         case ctrl('P'):    /* ctrl-p */
580             c2 = 65;
581             goto up_down_arrow;
582         case ctrl('N'):    /* ctrl-n */
583             c2 = 66;
584             goto up_down_arrow;
585             break;
586         case 27:    /* escape sequence */
587             c = fd_read(current->fd);
588             if (c <= 0) {
589                 break;
590             }
591             c2 = fd_read(current->fd);
592             if (c <= 0) {
593                 break;
594             }
595             ext = (c == 91 || c == 79);
596             if (ext && c2 == 68) {
597 left_arrow:
598                 /* left arrow */
599                 if (current->pos > 0) {
600                     current->pos--;
601                     refreshLine(prompt, current);
602                 }
603             } else if (ext && c2 == 67) {
604 right_arrow:
605                 /* right arrow */
606                 if (current->pos < current->len) {
607                     current->pos++;
608                     refreshLine(prompt, current);
609                 }
610             } else if (ext && (c2 == 65 || c2 == 66)) {
611 up_down_arrow:
612                 /* up and down arrow: history */
613                 if (history_len > 1) {
614                     /* Update the current history entry before to
615                      * overwrite it with tne next one. */
616                     free(history[history_len-1-history_index]);
617                     history[history_len-1-history_index] = strdup(current->buf);
618                     /* Show the new entry */
619                     history_index += (c2 == 65) ? 1 : -1;
620                     if (history_index < 0) {
621                         history_index = 0;
622                         break;
623                     } else if (history_index >= history_len) {
624                         history_index = history_len-1;
625                         break;
626                     }
627                     set_current(current, history[history_len-1-history_index]);
628                     refreshLine(prompt, current);
629                 }
630             } else if (c == 91 && c2 > 48 && c2 < 55) {
631                 /* extended escape */
632                 c = fd_read(current->fd);
633                 if (c <= 0) {
634                     break;
635                 }
636                 fd_read(current->fd);
637                 if (c2 == 51 && c == 126) {
638                     /* delete char under cursor */
639                     if (remove_char(current, current->pos)) {
640                         refreshLine(prompt, current);
641                     }
642                 }
643             }
644             break;
645         default:
646             /* Note that the only control character currently permitted is tab */
647             if (c == '\t' || c < 0 || c >= ' ') {
648                 if (insert_char(current, current->pos, c)) {
649                     /* Avoid a full update of the line in the trivial case. */
650                     if (current->pos == current->len && c >= ' ' && plen + current->len < current->cols) {
651                         char ch = c;
652                         write(current->fd, &ch, 1);
653                     }
654                     else {
655                         refreshLine(prompt, current);
656                     }
657                 }
658             }
659             break;
660         case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
661             if (remove_chars(current, 0, current->pos)) {
662                 refreshLine(prompt, current);
663             }
664             break;
665         case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
666             if (remove_chars(current, current->pos, current->len - current->pos)) {
667                 refreshLine(prompt, current);
668             }
669             break;
670         case ctrl('A'): /* Ctrl+a, go to the start of the line */
671             current->pos = 0;
672             refreshLine(prompt, current);
673             break;
674         case ctrl('E'): /* ctrl+e, go to the end of the line */
675             current->pos = current->len;
676             refreshLine(prompt, current);
677             break;
678         case ctrl('L'): /* Ctrl+L, clear screen */
679             /* clear screen */
680             fd_printf(current->fd, "\x1b[H\x1b[2J");
681             refreshLine(prompt, current);
682             break;
683         }
684     }
685     return current->len;
686 }
687
688 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
689     int fd = STDIN_FILENO;
690     int count;
691
692     if (buflen == 0) {
693         errno = EINVAL;
694         return -1;
695     }
696     if (!isatty(STDIN_FILENO)) {
697         if (fgets(buf, buflen, stdin) == NULL) return -1;
698         count = strlen(buf);
699         if (count && buf[count-1] == '\n') {
700             count--;
701             buf[count] = '\0';
702         }
703     } else {
704         struct current current;
705
706         if (enableRawMode(fd) == -1) return -1;
707
708         current.fd = fd;
709         current.buf = buf;
710         current.bufmax = buflen;
711         current.len = 0;
712         current.pos = 0;
713         current.cols = getColumns();
714
715         count = linenoisePrompt(prompt, &current);
716         disableRawMode(fd);
717         printf("\n");
718     }
719     return count;
720 }
721
722 char *linenoise(const char *prompt) {
723     char buf[LINENOISE_MAX_LINE];
724     int count;
725
726     if (isUnsupportedTerm()) {
727         size_t len;
728
729         printf("%s",prompt);
730         fflush(stdout);
731         if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
732         len = strlen(buf);
733         while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
734             len--;
735             buf[len] = '\0';
736         }
737         return strdup(buf);
738     } else {
739         count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
740         if (count == -1) return NULL;
741         return strdup(buf);
742     }
743 }
744
745 /* Using a circular buffer is smarter, but a bit more complex to handle. */
746 int linenoiseHistoryAdd(const char *line) {
747     char *linecopy;
748
749     if (history_max_len == 0) return 0;
750     if (history == NULL) {
751         history = malloc(sizeof(char*)*history_max_len);
752         if (history == NULL) return 0;
753         memset(history,0,(sizeof(char*)*history_max_len));
754     }
755     linecopy = strdup(line);
756     if (!linecopy) return 0;
757     if (history_len == history_max_len) {
758         free(history[0]);
759         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
760         history_len--;
761     }
762     history[history_len] = linecopy;
763     history_len++;
764     return 1;
765 }
766
767 int linenoiseHistorySetMaxLen(int len) {
768     char **new;
769
770     if (len < 1) return 0;
771     if (history) {
772         int tocopy = history_len;
773
774         new = malloc(sizeof(char*)*len);
775         if (new == NULL) return 0;
776         if (len < tocopy) tocopy = len;
777         memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
778         free(history);
779         history = new;
780     }
781     history_max_len = len;
782     if (history_len > history_max_len)
783         history_len = history_max_len;
784     return 1;
785 }
786
787 /* Save the history in the specified file. On success 0 is returned
788  * otherwise -1 is returned. */
789 int linenoiseHistorySave(char *filename) {
790     FILE *fp = fopen(filename,"w");
791     int j;
792
793     if (fp == NULL) return -1;
794     for (j = 0; j < history_len; j++) {
795         const char *str = history[j];
796         /* Need to encode backslash, nl and cr */
797         while (*str) {
798             if (*str == '\\') {
799                 fputs("\\\\", fp);
800             }
801             else if (*str == '\n') {
802                 fputs("\\n", fp);
803             }
804             else if (*str == '\r') {
805                 fputs("\\r", fp);
806             }
807             else {
808                 fputc(*str, fp);
809             }
810             str++;
811         }
812         fputc('\n', fp);
813     }
814
815     fclose(fp);
816     return 0;
817 }
818
819 /* Load the history from the specified file. If the file does not exist
820  * zero is returned and no operation is performed.
821  *
822  * If the file exists and the operation succeeded 0 is returned, otherwise
823  * on error -1 is returned. */
824 int linenoiseHistoryLoad(char *filename) {
825     FILE *fp = fopen(filename,"r");
826     char buf[LINENOISE_MAX_LINE];
827
828     if (fp == NULL) return -1;
829
830     while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
831         char *src, *dest;
832
833         /* Decode backslash escaped values */
834         for (src = dest = buf; *src; src++) {
835             char ch = *src;
836
837             if (ch == '\\') {
838                 src++;
839                 if (*src == 'n') {
840                     ch = '\n';
841                 }
842                 else if (*src == 'r') {
843                     ch = '\r';
844                 } else {
845                     ch = *src;
846                 }
847             }
848             *dest++ = ch;
849         }
850         /* Remove trailing newline */
851         if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
852             dest--;
853         }
854         *dest = 0;
855
856         linenoiseHistoryAdd(buf);
857     }
858     fclose(fp);
859     return 0;
860 }
861
862 /* Provide access to the history buffer.
863  *
864  * If 'len' is not NULL, the length is stored in *len.
865  */
866 char **linenoiseHistory(int *len) {
867     if (len) {
868         *len = history_len;
869     }
870     return history;
871 }