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
100 #include <sys/ioctl.h>
101 #include <sys/poll.h>
109 #include <sys/types.h>
112 #include "linenoise.h"
115 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
116 #define LINENOISE_MAX_LINE 4096
118 #define ctrl(C) ((C) - '@')
120 /* Use -ve numbers here to co-exist with normal unicode chars */
127 SPECIAL_DELETE = -24,
132 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
133 static int history_len = 0;
134 static char **history = NULL;
136 /* Structure to contain the status of the current (being edited) line */
138 char *buf; /* Current buffer. Always null terminated */
139 int bufmax; /* Size of the buffer, including space for the null termination */
140 int len; /* Number of bytes in 'buf' */
141 int chars; /* Number of chars in 'buf' (utf-8 chars) */
142 int pos; /* Cursor position, measured in chars */
143 int cols; /* Size of the window, in chars */
145 int fd; /* Terminal fd */
148 static int fd_read(struct current *current);
149 static int getWindowSize(struct current *current);
151 void linenoiseHistoryFree(void) {
155 for (j = 0; j < history_len; j++)
162 static void linenoiseAtExit(void);
163 static struct termios orig_termios; /* in order to restore at exit */
164 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
165 static int atexit_registered = 0; /* register atexit just 1 time */
167 static const char *unsupported_term[] = {"dumb","cons25",NULL};
169 static int isUnsupportedTerm(void) {
170 char *term = getenv("TERM");
174 for (j = 0; unsupported_term[j]; j++) {
175 if (strcasecmp(term, unsupported_term[j]) == 0) {
183 static int enableRawMode(struct current *current) {
186 current->fd = STDIN_FILENO;
188 if (!isatty(current->fd) || isUnsupportedTerm() ||
189 tcgetattr(current->fd, &orig_termios) == -1) {
195 if (!atexit_registered) {
196 atexit(linenoiseAtExit);
197 atexit_registered = 1;
200 raw = orig_termios; /* modify the original mode */
201 /* input modes: no break, no CR to NL, no parity check, no strip char,
202 * no start/stop output control. */
203 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
204 /* output modes - disable post processing */
205 raw.c_oflag &= ~(OPOST);
206 /* control modes - set 8 bit chars */
207 raw.c_cflag |= (CS8);
208 /* local modes - choing off, canonical off, no extended functions,
209 * no signal chars (^Z,^C) */
210 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
211 /* control chars - set return condition: min number of bytes and timer.
212 * We want read to return every single byte, without timeout. */
213 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
215 /* put terminal in raw mode after flushing */
216 if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
225 static void disableRawMode(struct current *current) {
226 /* Don't even check the return value as it's too late. */
227 if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
231 /* At exit we'll try to fix the terminal to the initial conditions. */
232 static void linenoiseAtExit(void) {
234 tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
236 linenoiseHistoryFree();
239 /* gcc/glibc insists that we care about the return code of write! */
240 #define IGNORE_RC(EXPR) if (EXPR) {}
242 /* This is fdprintf() on some systems, but use a different
243 * name to avoid conflicts
245 static void fd_printf(int fd, const char *format, ...)
251 va_start(args, format);
252 n = vsnprintf(buf, sizeof(buf), format, args);
254 IGNORE_RC(write(fd, buf, n));
257 static void clearScreen(struct current *current)
259 fd_printf(current->fd, "\x1b[H\x1b[2J");
262 static void cursorToLeft(struct current *current)
264 fd_printf(current->fd, "\x1b[1G");
267 static int outputChars(struct current *current, const char *buf, int len)
269 return write(current->fd, buf, len);
272 static void outputControlChar(struct current *current, char ch)
274 fd_printf(current->fd, "\033[7m^%c\033[0m", ch);
277 static void eraseEol(struct current *current)
279 fd_printf(current->fd, "\x1b[0K");
282 static void setCursorPos(struct current *current, int x)
284 fd_printf(current->fd, "\x1b[1G\x1b[%dC", x);
288 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
290 * A timeout of -1 means to wait forever.
292 * Returns -1 if no char is received within the time or an error occurs.
294 static int fd_read_char(int fd, int timeout)
302 if (poll(&p, 1, timeout) == 0) {
306 if (read(fd, &c, 1) != 1) {
313 * Reads a complete utf-8 character
314 * and returns the unicode value, or -1 on error.
316 static int fd_read(struct current *current)
324 if (read(current->fd, &buf[0], 1) != 1) {
327 n = utf8_charlen(buf[0]);
328 if (n < 1 || n > 3) {
331 for (i = 1; i < n; i++) {
332 if (read(current->fd, &buf[i], 1) != 1) {
337 /* decode and return the character */
338 utf8_tounicode(buf, &c);
341 return fd_read_char(current->fd, -1);
345 static int getWindowSize(struct current *current)
349 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
350 current->cols = ws.ws_col;
354 /* Failed to query the window size. Perhaps we are on a serial terminal.
355 * Try to query the width by sending the cursor as far to the right
356 * and reading back the cursor position.
357 * Note that this is only done once per call to linenoise rather than
358 * every time the line is refreshed for efficiency reasons.
360 if (current->cols == 0) {
363 /* Move cursor far right and report cursor position */
364 fd_printf(current->fd, "\x1b[999G" "\x1b[6n");
366 /* Parse the response: ESC [ rows ; cols R */
367 if (fd_read_char(current->fd, 100) == 0x1b && fd_read_char(current->fd, 100) == '[') {
370 int ch = fd_read_char(current->fd, 100);
375 else if (ch == 'R') {
377 if (n != 0 && n < 1000) {
382 else if (ch >= 0 && ch <= '9') {
383 n = n * 10 + ch - '0';
395 * If escape (27) was received, reads subsequent
396 * chars to determine if this is a known special key.
398 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
400 * If no additional char is received within a short time,
403 static int check_special(int fd)
405 int c = fd_read_char(fd, 50);
412 c2 = fd_read_char(fd, 50);
416 if (c == '[' || c == 'O') {
417 /* Potential arrow key */
424 return SPECIAL_RIGHT;
433 if (c == '[' && c2 >= '1' && c2 <= '6') {
434 /* extended escape */
435 int c3 = fd_read_char(fd, 50);
436 if (c2 == '3' && c3 == '~') {
437 /* delete char under cursor */
438 return SPECIAL_DELETE;
440 while (c3 != -1 && c3 != '~') {
441 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
442 c3 = fd_read_char(fd, 50);
449 static int utf8_getchars(char *buf, int c)
452 return utf8_fromunicode(buf, c);
460 * Returns the unicode character at the given offset,
463 static int get_char(struct current *current, int pos)
465 if (pos >= 0 && pos < current->chars) {
467 int i = utf8_index(current->buf, pos);
468 (void)utf8_tounicode(current->buf + i, &c);
474 static void refreshLine(const char *prompt, struct current *current)
480 const char *buf = current->buf;
481 int chars = current->chars;
482 int pos = current->pos;
487 /* Should intercept SIGWINCH. For now, just get the size every time */
488 getWindowSize(current);
490 plen = strlen(prompt);
491 pchars = utf8_strlen(prompt, plen);
493 /* Account for a line which is too long to fit in the window.
494 * Note that control chars require an extra column
497 /* How many cols are required to the left of 'pos'?
498 * The prompt, plus one extra for each control char
500 n = pchars + utf8_strlen(buf, current->len);
502 for (i = 0; i < pos; i++) {
503 b += utf8_tounicode(buf + b, &ch);
509 /* If too many are need, strip chars off the front of 'buf'
510 * until it fits. Note that if the current char is a control character,
511 * we need one extra col.
513 if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
517 while (n >= current->cols) {
518 b = utf8_tounicode(buf, &ch);
528 /* Cursor to left edge, then the prompt */
529 cursorToLeft(current);
530 outputChars(current, prompt, plen);
532 /* Now the current buffer content */
534 /* Need special handling for control characters.
535 * If we hit 'cols', stop.
537 b = 0; /* unwritted bytes */
538 n = 0; /* How many control chars were written */
539 for (i = 0; i < chars; i++) {
541 int w = utf8_tounicode(buf + b, &ch);
545 if (pchars + i + n >= current->cols) {
549 /* A control character, so write the buffer so far */
550 outputChars(current, buf, b);
553 outputControlChar(current, ch + '@');
562 outputChars(current, buf, b);
564 /* Erase to right, move cursor to original position */
566 setCursorPos(current, pos + pchars + backup);
569 static void set_current(struct current *current, const char *str)
571 strncpy(current->buf, str, current->bufmax);
572 current->buf[current->bufmax - 1] = 0;
573 current->len = strlen(current->buf);
574 current->pos = current->chars = utf8_strlen(current->buf, current->len);
577 static int has_room(struct current *current, int bytes)
579 return current->len + bytes < current->bufmax - 1;
583 * Removes the char at 'pos'.
585 * Returns 1 if the line needs to be refreshed, 2 if not
586 * and 0 if nothing was removed
588 static int remove_char(struct current *current, int pos)
590 if (pos >= 0 && pos < current->chars) {
593 p1 = utf8_index(current->buf, pos);
594 p2 = p1 + utf8_index(current->buf + p1, 1);
596 /* optimise remove char in the case of removing the last char */
597 if (current->pos == pos + 1 && current->pos == current->chars) {
598 if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
600 fd_printf(current->fd, "\b \b");
604 /* Move the null char too */
605 memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
606 current->len -= (p2 - p1);
609 if (current->pos > pos) {
618 * Insert 'ch' at position 'pos'
620 * Returns 1 if the line needs to be refreshed, 2 if not
621 * and 0 if nothing was inserted (no room)
623 static int insert_char(struct current *current, int pos, int ch)
626 int n = utf8_getchars(buf, ch);
628 if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
631 p1 = utf8_index(current->buf, pos);
634 /* optimise the case where adding a single char to the end and no scrolling is needed */
635 if (current->pos == pos && current->chars == pos) {
636 if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
637 IGNORE_RC(write(current->fd, buf, n));
642 memmove(current->buf + p2, current->buf + p1, current->len - p1);
643 memcpy(current->buf + p1, buf, n);
647 if (current->pos >= pos) {
656 * Returns 0 if no chars were removed or non-zero otherwise.
658 static int remove_chars(struct current *current, int pos, int n)
661 while (n-- && remove_char(current, pos)) {
667 #ifndef NO_COMPLETION
668 static linenoiseCompletionCallback *completionCallback = NULL;
671 fprintf(stderr, "\x7");
675 static void freeCompletions(linenoiseCompletions *lc) {
677 for (i = 0; i < lc->len; i++)
682 static int completeLine(struct current *current) {
683 linenoiseCompletions lc = { 0, NULL };
686 completionCallback(current->buf,&lc);
690 size_t stop = 0, i = 0;
693 /* Show completion or original buffer */
695 struct current tmp = *current;
696 tmp.buf = lc.cvec[i];
697 tmp.pos = tmp.len = strlen(tmp.buf);
698 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
699 refreshLine(current->prompt, &tmp);
701 refreshLine(current->prompt, current);
704 c = fd_read(current);
711 i = (i+1) % (lc.len+1);
712 if (i == lc.len) beep();
714 case 27: /* escape */
715 /* Re-show original buffer */
717 refreshLine(current->prompt, current);
722 /* Update buffer and return */
724 set_current(current,lc.cvec[i]);
732 freeCompletions(&lc);
733 return c; /* Return last read character */
736 /* Register a callback function to be called for tab-completion. */
737 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
738 completionCallback = fn;
741 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
742 lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
743 lc->cvec[lc->len++] = strdup(str);
748 static int linenoisePrompt(struct current *current) {
749 int history_index = 0;
751 /* The latest history entry is always our current buffer, that
752 * initially is just an empty string. */
753 linenoiseHistoryAdd("");
755 set_current(current, "");
756 refreshLine(current->prompt, current);
760 int c = fd_read(current);
762 #ifndef NO_COMPLETION
763 /* Only autocomplete when the callback is set. It returns < 0 when
764 * there was an error reading from fd. Otherwise it will return the
765 * character that should be handled next. */
766 if (c == 9 && completionCallback != NULL) {
767 c = completeLine(current);
768 /* Return on errors */
769 if (c < 0) return current->len;
770 /* Read next character when 0 */
771 if (c == 0) continue;
776 if (c == -1) return current->len;
777 if (c == 27) { /* escape sequence */
778 c = check_special(current->fd);
781 case '\r': /* enter */
783 free(history[history_len]);
785 case ctrl('C'): /* ctrl-c */
788 case 127: /* backspace */
790 if (remove_char(current, current->pos - 1) == 1) {
791 refreshLine(current->prompt, current);
794 case ctrl('D'): /* ctrl-d */
795 if (current->len == 0) {
796 /* Empty line, so EOF */
798 free(history[history_len]);
801 /* Otherwise delete char to right of cursor */
802 if (remove_char(current, current->pos)) {
803 refreshLine(current->prompt, current);
806 case ctrl('W'): /* ctrl-w */
807 /* eat any spaces on the left */
809 int pos = current->pos;
810 while (pos > 0 && get_char(current, pos - 1) == ' ') {
814 /* now eat any non-spaces on the left */
815 while (pos > 0 && get_char(current, pos - 1) != ' ') {
819 if (remove_chars(current, pos, current->pos - pos)) {
820 refreshLine(current->prompt, current);
824 case ctrl('R'): /* ctrl-r */
826 /* Display the reverse-i-search prompt and process chars */
831 int searchpos = history_len - 1;
836 const char *p = NULL;
840 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
841 refreshLine(rprompt, current);
842 c = fd_read(current);
843 if (c == ctrl('H') || c == 127) {
845 int p = utf8_index(rbuf, --rchars);
852 c = check_special(current->fd);
854 if (c == ctrl('P') || c == SPECIAL_UP) {
855 /* Search for the previous (earlier) match */
861 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
862 /* Search for the next (later) match */
863 if (searchpos < history_len) {
870 if (rlen >= (int)sizeof(rbuf) + 3) {
874 n = utf8_getchars(rbuf + rlen, c);
879 /* Adding a new char resets the search location */
880 searchpos = history_len - 1;
883 /* Exit from incremental search mode */
887 /* Now search through the history for a match */
888 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
889 p = strstr(history[searchpos], rbuf);
892 if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
893 /* But it is identical, so skip it */
896 /* Copy the matching line and set the cursor position */
897 set_current(current,history[searchpos]);
898 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
903 /* No match, so don't add it */
909 if (c == ctrl('G') || c == ctrl('C')) {
910 /* ctrl-g terminates the search with no effect */
911 set_current(current, "");
914 else if (c == ctrl('J')) {
915 /* ctrl-j terminates the search leaving the buffer in place */
918 /* Go process the char normally */
919 refreshLine(current->prompt, current);
923 case ctrl('T'): /* ctrl-t */
924 if (current->pos > 0 && current->pos < current->chars) {
925 c = get_char(current, current->pos);
926 remove_char(current, current->pos);
927 insert_char(current, current->pos - 1, c);
928 refreshLine(current->prompt, current);
931 case ctrl('V'): /* ctrl-v */
932 if (has_room(current, 3)) {
933 /* Insert the ^V first */
934 if (insert_char(current, current->pos, c)) {
935 refreshLine(current->prompt, current);
936 /* Now wait for the next char. Can insert anything except \0 */
937 c = fd_read(current);
939 /* Remove the ^V first */
940 remove_char(current, current->pos - 1);
942 /* Insert the actual char */
943 insert_char(current, current->pos, c);
945 refreshLine(current->prompt, current);
951 if (current->pos > 0) {
953 refreshLine(current->prompt, current);
958 if (current->pos < current->chars) {
960 refreshLine(current->prompt, current);
968 if (history_len > 1) {
969 /* Update the current history entry before to
970 * overwrite it with tne next one. */
971 free(history[history_len-1-history_index]);
972 history[history_len-1-history_index] = strdup(current->buf);
973 /* Show the new entry */
974 history_index += dir;
975 if (history_index < 0) {
978 } else if (history_index >= history_len) {
979 history_index = history_len-1;
982 set_current(current, history[history_len-1-history_index]);
983 refreshLine(current->prompt, current);
988 if (remove_char(current, current->pos) == 1) {
989 refreshLine(current->prompt, current);
994 refreshLine(current->prompt, current);
997 current->pos = current->chars;
998 refreshLine(current->prompt, current);
1001 /* Only tab is allowed without ^V */
1002 if (c == '\t' || c >= ' ') {
1003 if (insert_char(current, current->pos, c) == 1) {
1004 refreshLine(current->prompt, current);
1008 case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
1009 if (remove_chars(current, 0, current->pos)) {
1010 refreshLine(current->prompt, current);
1013 case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
1014 if (remove_chars(current, current->pos, current->chars - current->pos)) {
1015 refreshLine(current->prompt, current);
1018 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1020 refreshLine(current->prompt, current);
1022 case ctrl('E'): /* ctrl+e, go to the end of the line */
1023 current->pos = current->chars;
1024 refreshLine(current->prompt, current);
1026 case ctrl('L'): /* Ctrl+L, clear screen */
1028 clearScreen(current);
1029 /* Force recalc of window size for serial terminals */
1031 refreshLine(current->prompt, current);
1035 return current->len;
1038 char *linenoise(const char *prompt)
1041 struct current current;
1042 char buf[LINENOISE_MAX_LINE];
1044 if (enableRawMode(¤t) == -1) {
1045 printf("%s", prompt);
1047 if (fgets(buf, sizeof(buf), stdin) == NULL) {
1050 count = strlen(buf);
1051 if (count && buf[count-1] == '\n') {
1059 current.bufmax = sizeof(buf);
1063 current.prompt = prompt;
1065 count = linenoisePrompt(¤t);
1066 disableRawMode(¤t);
1075 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1076 int linenoiseHistoryAdd(const char *line) {
1079 if (history_max_len == 0) return 0;
1080 if (history == NULL) {
1081 history = (char **)malloc(sizeof(char*)*history_max_len);
1082 if (history == NULL) return 0;
1083 memset(history,0,(sizeof(char*)*history_max_len));
1085 linecopy = strdup(line);
1086 if (!linecopy) return 0;
1087 if (history_len == history_max_len) {
1089 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1092 history[history_len] = linecopy;
1097 int linenoiseHistorySetMaxLen(int len) {
1100 if (len < 1) return 0;
1102 int tocopy = history_len;
1104 newHistory = (char **)malloc(sizeof(char*)*len);
1105 if (newHistory == NULL) return 0;
1106 if (len < tocopy) tocopy = len;
1107 memcpy(newHistory,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
1109 history = newHistory;
1111 history_max_len = len;
1112 if (history_len > history_max_len)
1113 history_len = history_max_len;
1117 /* Save the history in the specified file. On success 0 is returned
1118 * otherwise -1 is returned. */
1119 int linenoiseHistorySave(const char *filename) {
1120 FILE *fp = fopen(filename,"w");
1123 if (fp == NULL) return -1;
1124 for (j = 0; j < history_len; j++) {
1125 const char *str = history[j];
1126 /* Need to encode backslash, nl and cr */
1131 else if (*str == '\n') {
1134 else if (*str == '\r') {
1149 /* Load the history from the specified file. If the file does not exist
1150 * zero is returned and no operation is performed.
1152 * If the file exists and the operation succeeded 0 is returned, otherwise
1153 * on error -1 is returned. */
1154 int linenoiseHistoryLoad(const char *filename) {
1155 FILE *fp = fopen(filename,"r");
1156 char buf[LINENOISE_MAX_LINE];
1158 if (fp == NULL) return -1;
1160 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1163 /* Decode backslash escaped values */
1164 for (src = dest = buf; *src; src++) {
1172 else if (*src == 'r') {
1180 /* Remove trailing newline */
1181 if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1186 linenoiseHistoryAdd(buf);
1192 /* Provide access to the history buffer.
1194 * If 'len' is not NULL, the length is stored in *len.
1196 char **linenoiseHistory(int *len) {