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.
4 * You can find the latest source code at:
6 * http://github.com/antirez/linenoise
8 * Does a number of crazy assumptions that happen to be true in 99.9999% of
9 * the 2010 UNIX computers around.
11 * ------------------------------------------------------------------------
13 * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
14 * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
16 * All rights reserved.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
22 * * Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
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.
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.
41 * ------------------------------------------------------------------------
44 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
45 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
49 * - Save and load history containing newlines
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.
59 * CHA (Cursor Horizontal Absolute)
61 * Effect: moves cursor to column n (1 based)
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
69 * CUF (CUrsor Forward)
71 * Effect: moves cursor forward of n chars
73 * The following are used to clear the screen: ESC [ H ESC [ 2 J
74 * This is actually composed of two sequences:
78 * Effect: moves the cursor to upper left corner
80 * ED2 (Clear entire screen)
82 * Effect: clear the whole screen
84 * == For highlighting control characters, we also use the following two ==
87 * Effect: Uses some standout mode such as reverse video
91 * Effect: Exit standout mode
93 * == Only used if TIOCGWINSZ fails ==
94 * DSR/CPR (Report cursor position)
96 * Effect: reports current cursor position as ESC [ NNN ; MMM R
107 #include <sys/types.h>
108 #include <sys/ioctl.h>
109 #include <sys/poll.h>
111 #include "linenoise.h"
113 #include "linenoise.h"
116 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
117 #define LINENOISE_MAX_LINE 4096
118 static char *unsupported_term[] = {"dumb","cons25",NULL};
120 static struct termios orig_termios; /* in order to restore at exit */
121 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
122 static int atexit_registered = 0; /* register atexit just 1 time */
123 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
124 static int history_len = 0;
125 static char **history = NULL;
127 static void linenoiseAtExit(void);
128 static int fd_read(int fd);
129 static void getColumns(int fd, int *cols);
131 static int isUnsupportedTerm(void) {
132 char *term = getenv("TERM");
135 if (term == NULL) return 0;
136 for (j = 0; unsupported_term[j]; j++)
137 if (!strcasecmp(term,unsupported_term[j])) return 1;
141 static void freeHistory(void) {
145 for (j = 0; j < history_len; j++)
151 static int enableRawMode(int fd) {
154 if (!isatty(STDIN_FILENO)) goto fatal;
155 if (!atexit_registered) {
156 atexit(linenoiseAtExit);
157 atexit_registered = 1;
159 if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
161 raw = orig_termios; /* modify the original mode */
162 /* input modes: no break, no CR to NL, no parity check, no strip char,
163 * no start/stop output control. */
164 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
165 /* output modes - disable post processing */
166 raw.c_oflag &= ~(OPOST);
167 /* control modes - set 8 bit chars */
168 raw.c_cflag |= (CS8);
169 /* local modes - choing off, canonical off, no extended functions,
170 * no signal chars (^Z,^C) */
171 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
172 /* control chars - set return condition: min number of bytes and timer.
173 * We want read to return every single byte, without timeout. */
174 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
176 /* put terminal in raw mode after flushing */
177 if (tcsetattr(fd,TCSADRAIN,&raw) < 0) goto fatal;
186 static void disableRawMode(int fd) {
187 /* Don't even check the return value as it's too late. */
188 if (rawmode && tcsetattr(fd,TCSADRAIN,&orig_termios) != -1)
192 /* At exit we'll try to fix the terminal to the initial conditions. */
193 static void linenoiseAtExit(void) {
194 disableRawMode(STDIN_FILENO);
198 /* Structure to contain the status of the current (being edited) line */
200 int fd; /* Terminal fd */
201 char *buf; /* Current buffer. Always null terminated */
202 int bufmax; /* Size of the buffer, including space for the null termination */
203 int len; /* Number of bytes in 'buf' */
204 int chars; /* Number of chars in 'buf' (utf-8 chars) */
205 int pos; /* Cursor position, measured in chars */
206 int cols; /* Size of the window, in chars */
210 /* gcc/glibc insists that we care about the return code of write! */
211 #define IGNORE_RC(EXPR) ((EXPR) < 0 ? -1 : 0)
213 /* This is fd_printf() on some systems, but use a different
214 * name to avoid conflicts
216 static void fd_printf(int fd, const char *format, ...)
222 va_start(args, format);
223 n = vsnprintf(buf, sizeof(buf), format, args);
225 IGNORE_RC(write(fd, buf, n));
228 static int utf8_getchars(char *buf, int c)
231 return utf8_fromunicode(buf, c);
239 * Returns the unicode character at the given offset,
242 static int get_char(struct current *current, int pos)
244 if (pos >= 0 && pos < current->chars) {
246 int i = utf8_index(current->buf, pos);
247 (void)utf8_tounicode(current->buf + i, &c);
253 static void refreshLine(const char *prompt, struct current *current) {
258 const char *buf = current->buf;
259 int chars = current->chars;
260 int pos = current->pos;
265 /* Should intercept SIGWINCH. For now, just get the size every time */
266 getColumns(current->fd, ¤t->cols);
268 plen = strlen(prompt);
269 pchars = utf8_strlen(prompt, plen);
271 /* Account for a line which is too long to fit in the window.
272 * Note that control chars require an extra column
275 /* How many cols are required to the left of 'pos'?
276 * The prompt, plus one extra for each control char
278 n = pchars + utf8_strlen(buf, current->len);
280 for (i = 0; i < pos; i++) {
281 b += utf8_tounicode(buf + b, &ch);
287 /* If too many are need, strip chars off the front of 'buf'
288 * until it fits. Note that if the current char is a control character,
289 * we need one extra col.
291 if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
295 while (n >= current->cols) {
296 b = utf8_tounicode(buf, &ch);
306 /* Cursor to left edge, then the prompt */
307 fd_printf(current->fd, "\x1b[1G");
308 IGNORE_RC(write(current->fd, prompt, plen));
310 /* Now the current buffer content */
312 /* Need special handling for control characters.
313 * If we hit 'cols', stop.
315 b = 0; /* unwritted bytes */
316 n = 0; /* How many control chars were written */
317 for (i = 0; i < chars; i++) {
319 int w = utf8_tounicode(buf + b, &ch);
323 if (pchars + i + n >= current->cols) {
327 /* A control character, so write the buffer so far */
328 IGNORE_RC(write(current->fd, buf, b));
331 fd_printf(current->fd, "\033[7m^%c\033[0m", ch + '@');
340 IGNORE_RC(write(current->fd, buf, b));
342 /* Erase to right, move cursor to original position */
343 fd_printf(current->fd, "\x1b[0K" "\x1b[1G\x1b[%dC", pos + pchars + backup);
346 static void set_current(struct current *current, const char *str)
348 strncpy(current->buf, str, current->bufmax);
349 current->buf[current->bufmax - 1] = 0;
350 current->len = strlen(current->buf);
351 current->pos = current->chars = utf8_strlen(current->buf, current->len);
354 static int has_room(struct current *current, int bytes)
356 return current->len + bytes < current->bufmax - 1;
360 * Removes the char at 'pos'.
362 * Returns 1 if the line needs to be refreshed, 2 if not
363 * and 0 if nothing was removed
365 static int remove_char(struct current *current, int pos)
367 if (pos >= 0 && pos < current->chars) {
370 p1 = utf8_index(current->buf, pos);
371 p2 = p1 + utf8_index(current->buf + p1, 1);
373 /* optimise remove char in the case of removing the last char */
374 if (current->pos == pos + 1 && current->pos == current->chars) {
375 if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
377 fd_printf(current->fd, "\b \b");
381 /* Move the null char too */
382 memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
383 current->len -= (p2 - p1);
386 if (current->pos > pos) {
395 * Insert 'ch' at position 'pos'
397 * Returns 1 if the line needs to be refreshed, 2 if not
398 * and 0 if nothing was inserted (no room)
400 static int insert_char(struct current *current, int pos, int ch)
403 int n = utf8_getchars(buf, ch);
405 if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
408 p1 = utf8_index(current->buf, pos);
411 /* optimise the case where adding a single char to the end and no scrolling is needed */
412 if (current->pos == pos && current->chars == pos) {
413 if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
414 IGNORE_RC(write(current->fd, buf, n));
419 memmove(current->buf + p2, current->buf + p1, current->len - p1);
420 memcpy(current->buf + p1, buf, n);
424 if (current->pos >= pos) {
432 #ifndef NO_COMPLETION
433 static linenoiseCompletionCallback *completionCallback = NULL;
436 fprintf(stderr, "\x7");
440 static void freeCompletions(linenoiseCompletions *lc) {
442 for (i = 0; i < lc->len; i++)
447 static int completeLine(struct current *current) {
448 linenoiseCompletions lc = { 0, NULL };
451 completionCallback(current->buf,&lc);
455 size_t stop = 0, i = 0;
458 /* Show completion or original buffer */
460 struct current tmp = *current;
461 tmp.buf = lc.cvec[i];
462 tmp.pos = tmp.len = strlen(tmp.buf);
463 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
464 refreshLine(current->prompt, &tmp);
466 refreshLine(current->prompt, current);
469 c = fd_read(current->fd);
476 i = (i+1) % (lc.len+1);
477 if (i == lc.len) beep();
479 case 27: /* escape */
480 /* Re-show original buffer */
482 refreshLine(current->prompt, current);
487 /* Update buffer and return */
489 set_current(current,lc.cvec[i]);
497 freeCompletions(&lc);
498 return c; /* Return last read character */
501 /* Register a callback function to be called for tab-completion. */
502 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
503 completionCallback = fn;
506 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
507 lc->cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
508 lc->cvec[lc->len++] = strdup(str);
514 * Returns 0 if no chars were removed or non-zero otherwise.
516 static int remove_chars(struct current *current, int pos, int n)
519 while (n-- && remove_char(current, pos)) {
526 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
528 * A timeout of -1 means to wait forever.
530 * Returns -1 if no char is received within the time or an error occurs.
532 static int fd_read_char(int fd, int timeout)
540 if (poll(&p, 1, timeout) == 0) {
544 if (read(fd, &c, 1) != 1) {
551 * Reads a complete utf-8 character
552 * and returns the unicode value, or -1 on error.
554 static int fd_read(int fd)
562 if (read(fd, &buf[0], 1) != 1) {
565 n = utf8_charlen(buf[0]);
566 if (n < 1 || n > 3) {
569 for (i = 1; i < n; i++) {
570 if (read(fd, &buf[i], 1) != 1) {
575 /* decode and return the character */
576 utf8_tounicode(buf, &c);
579 return fd_read_char(fd, -1);
583 static void getColumns(int fd, int *cols) {
586 if (ioctl(1, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
590 /* Failed to query the window size. Perhaps we are on a serial terminal.
591 * Try to query the width by sending the cursor as far to the right
592 * and reading back the cursor position.
593 * Note that this is only done once per call to linenoise rather than
594 * every time the line is refreshed for efficiency reasons.
599 /* Move cursor far right and report cursor position */
600 fd_printf(fd, "\x1b[999G" "\x1b[6n");
602 /* Parse the response: ESC [ rows ; cols R */
603 if (fd_read_char(fd, 100) == 0x1b && fd_read_char(fd, 100) == '[') {
606 int ch = fd_read_char(fd, 100);
611 else if (ch == 'R') {
613 if (n != 0 && n < 1000) {
618 else if (ch >= 0 && ch <= '9') {
619 n = n * 10 + ch - '0';
629 /* Use -ve numbers here to co-exist with normal unicode chars */
636 SPECIAL_DELETE = -24,
640 * If escape (27) was received, reads subsequent
641 * chars to determine if this is a known special key.
643 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
645 * If no additional char is received within a short time,
648 static int check_special(int fd)
650 int c = fd_read_char(fd, 50);
657 c2 = fd_read_char(fd, 50);
661 if (c == '[' || c == 'O') {
662 /* Potential arrow key */
669 return SPECIAL_RIGHT;
674 if (c == '[' && c2 >= '1' && c2 <= '6') {
675 /* extended escape */
676 int c3 = fd_read_char(fd, 50);
677 if (c2 == '3' && c3 == '~') {
678 /* delete char under cursor */
679 return SPECIAL_DELETE;
681 while (c3 != -1 && c3 != '~') {
682 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
683 c3 = fd_read_char(fd, 50);
690 #define ctrl(C) ((C) - '@')
692 static int linenoisePrompt(struct current *current) {
693 int history_index = 0;
695 /* The latest history entry is always our current buffer, that
696 * initially is just an empty string. */
697 linenoiseHistoryAdd("");
699 set_current(current, "");
700 refreshLine(current->prompt, current);
703 int c = fd_read(current->fd);
705 #ifndef NO_COMPLETION
706 /* Only autocomplete when the callback is set. It returns < 0 when
707 * there was an error reading from fd. Otherwise it will return the
708 * character that should be handled next. */
709 if (c == 9 && completionCallback != NULL) {
710 c = completeLine(current);
711 /* Return on errors */
712 if (c < 0) return current->len;
713 /* Read next character when 0 */
714 if (c == 0) continue;
719 if (c == -1) return current->len;
721 case '\r': /* enter */
723 free(history[history_len]);
725 case ctrl('C'): /* ctrl-c */
728 case 127: /* backspace */
730 if (remove_char(current, current->pos - 1) == 1) {
731 refreshLine(current->prompt, current);
734 case ctrl('D'): /* ctrl-d */
735 if (current->len == 0) {
736 /* Empty line, so EOF */
738 free(history[history_len]);
741 /* Otherwise delete char to right of cursor */
742 if (remove_char(current, current->pos)) {
743 refreshLine(current->prompt, current);
746 case ctrl('W'): /* ctrl-w */
747 /* eat any spaces on the left */
749 int pos = current->pos;
750 while (pos > 0 && get_char(current, pos - 1) == ' ') {
754 /* now eat any non-spaces on the left */
755 while (pos > 0 && get_char(current, pos - 1) != ' ') {
759 if (remove_chars(current, pos, current->pos - pos)) {
760 refreshLine(current->prompt, current);
764 case ctrl('R'): /* ctrl-r */
766 /* Display the reverse-i-search prompt and process chars */
771 int searchpos = history_len - 1;
776 const char *p = NULL;
780 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
781 refreshLine(rprompt, current);
782 c = fd_read(current->fd);
783 if (c == ctrl('H') || c == 127) {
785 int p = utf8_index(rbuf, --rchars);
792 c = check_special(current->fd);
794 if (c == ctrl('P') || c == SPECIAL_UP) {
795 /* Search for the previous (earlier) match */
801 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
802 /* Search for the next (later) match */
803 if (searchpos < history_len) {
810 if (rlen >= (int)sizeof(rbuf) + 3) {
814 n = utf8_getchars(rbuf + rlen, c);
819 /* Adding a new char resets the search location */
820 searchpos = history_len - 1;
823 /* Exit from incremental search mode */
827 /* Now search through the history for a match */
828 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
829 p = strstr(history[searchpos], rbuf);
832 if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
833 /* But it is identical, so skip it */
836 /* Copy the matching line and set the cursor position */
837 set_current(current,history[searchpos]);
838 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
843 /* No match, so don't add it */
849 if (c == ctrl('G') || c == ctrl('C')) {
850 /* ctrl-g terminates the search with no effect */
851 set_current(current, "");
854 else if (c == ctrl('J')) {
855 /* ctrl-j terminates the search leaving the buffer in place */
858 /* Go process the char normally */
859 refreshLine(current->prompt, current);
863 case ctrl('T'): /* ctrl-t */
864 if (current->pos > 0 && current->pos < current->chars) {
865 c = get_char(current, current->pos);
866 remove_char(current, current->pos);
867 insert_char(current, current->pos - 1, c);
868 refreshLine(current->prompt, current);
871 case ctrl('V'): /* ctrl-v */
872 if (has_room(current, 3)) {
873 /* Insert the ^V first */
874 if (insert_char(current, current->pos, c)) {
875 refreshLine(current->prompt, current);
876 /* Now wait for the next char. Can insert anything except \0 */
877 c = fd_read(current->fd);
879 /* Remove the ^V first */
880 remove_char(current, current->pos - 1);
882 /* Insert the actual char */
883 insert_char(current, current->pos, c);
885 refreshLine(current->prompt, current);
889 case ctrl('B'): /* ctrl-b */
890 case ctrl('F'): /* ctrl-f */
891 case ctrl('P'): /* ctrl-p */
892 case ctrl('N'): /* ctrl-n */
893 case 27: { /* escape sequence */
896 c = check_special(current->fd);
901 if (current->pos > 0) {
903 refreshLine(current->prompt, current);
908 if (current->pos < current->chars) {
910 refreshLine(current->prompt, current);
918 if (history_len > 1) {
919 /* Update the current history entry before to
920 * overwrite it with tne next one. */
921 free(history[history_len-1-history_index]);
922 history[history_len-1-history_index] = strdup(current->buf);
923 /* Show the new entry */
924 history_index += dir;
925 if (history_index < 0) {
928 } else if (history_index >= history_len) {
929 history_index = history_len-1;
932 set_current(current, history[history_len-1-history_index]);
933 refreshLine(current->prompt, current);
938 if (remove_char(current, current->pos) == 1) {
939 refreshLine(current->prompt, current);
946 /* Only tab is allowed without ^V */
947 if (c == '\t' || c >= ' ') {
948 if (insert_char(current, current->pos, c) == 1) {
949 refreshLine(current->prompt, current);
953 case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
954 if (remove_chars(current, 0, current->pos)) {
955 refreshLine(current->prompt, current);
958 case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
959 if (remove_chars(current, current->pos, current->chars - current->pos)) {
960 refreshLine(current->prompt, current);
963 case ctrl('A'): /* Ctrl+a, go to the start of the line */
965 refreshLine(current->prompt, current);
967 case ctrl('E'): /* ctrl+e, go to the end of the line */
968 current->pos = current->chars;
969 refreshLine(current->prompt, current);
971 case ctrl('L'): /* Ctrl+L, clear screen */
973 fd_printf(current->fd, "\x1b[H\x1b[2J");
974 /* Force recalc of window size for serial terminals */
976 refreshLine(current->prompt, current);
983 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
984 int fd = STDIN_FILENO;
991 if (!isatty(STDIN_FILENO)) {
992 if (fgets(buf, buflen, stdin) == NULL) return -1;
994 if (count && buf[count-1] == '\n') {
999 struct current current;
1001 if (enableRawMode(fd) == -1) return -1;
1005 current.bufmax = buflen;
1010 current.prompt = prompt;
1012 count = linenoisePrompt(¤t);
1020 char *linenoise(const char *prompt) {
1021 char buf[LINENOISE_MAX_LINE];
1024 if (isUnsupportedTerm()) {
1027 printf("%s",prompt);
1029 if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
1031 while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
1037 count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
1038 if (count == -1) return NULL;
1043 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1044 int linenoiseHistoryAdd(const char *line) {
1047 if (history_max_len == 0) return 0;
1048 if (history == NULL) {
1049 history = malloc(sizeof(char*)*history_max_len);
1050 if (history == NULL) return 0;
1051 memset(history,0,(sizeof(char*)*history_max_len));
1053 linecopy = strdup(line);
1054 if (!linecopy) return 0;
1055 if (history_len == history_max_len) {
1057 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1060 history[history_len] = linecopy;
1065 int linenoiseHistorySetMaxLen(int len) {
1068 if (len < 1) return 0;
1070 int tocopy = history_len;
1072 new = malloc(sizeof(char*)*len);
1073 if (new == NULL) return 0;
1074 if (len < tocopy) tocopy = len;
1075 memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
1079 history_max_len = len;
1080 if (history_len > history_max_len)
1081 history_len = history_max_len;
1085 /* Save the history in the specified file. On success 0 is returned
1086 * otherwise -1 is returned. */
1087 int linenoiseHistorySave(char *filename) {
1088 FILE *fp = fopen(filename,"w");
1091 if (fp == NULL) return -1;
1092 for (j = 0; j < history_len; j++) {
1093 const char *str = history[j];
1094 /* Need to encode backslash, nl and cr */
1099 else if (*str == '\n') {
1102 else if (*str == '\r') {
1117 /* Load the history from the specified file. If the file does not exist
1118 * zero is returned and no operation is performed.
1120 * If the file exists and the operation succeeded 0 is returned, otherwise
1121 * on error -1 is returned. */
1122 int linenoiseHistoryLoad(char *filename) {
1123 FILE *fp = fopen(filename,"r");
1124 char buf[LINENOISE_MAX_LINE];
1126 if (fp == NULL) return -1;
1128 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1131 /* Decode backslash escaped values */
1132 for (src = dest = buf; *src; src++) {
1140 else if (*src == 'r') {
1148 /* Remove trailing newline */
1149 if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1154 linenoiseHistoryAdd(buf);
1160 /* Provide access to the history buffer.
1162 * If 'len' is not NULL, the length is stored in *len.
1164 char **linenoiseHistory(int *len) {