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 * 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.
59 * CHA (Cursor Horizontal Absolute)
61 * Effect: moves cursor to column n
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);
130 static int isUnsupportedTerm(void) {
131 char *term = getenv("TERM");
134 if (term == NULL) return 0;
135 for (j = 0; unsupported_term[j]; j++)
136 if (!strcasecmp(term,unsupported_term[j])) return 1;
140 static void freeHistory(void) {
144 for (j = 0; j < history_len; j++)
150 static int enableRawMode(int fd) {
153 if (!isatty(STDIN_FILENO)) goto fatal;
154 if (!atexit_registered) {
155 atexit(linenoiseAtExit);
156 atexit_registered = 1;
158 if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
160 raw = orig_termios; /* modify the original mode */
161 /* input modes: no break, no CR to NL, no parity check, no strip char,
162 * no start/stop output control. */
163 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
164 /* output modes - disable post processing */
165 raw.c_oflag &= ~(OPOST);
166 /* control modes - set 8 bit chars */
167 raw.c_cflag |= (CS8);
168 /* local modes - choing off, canonical off, no extended functions,
169 * no signal chars (^Z,^C) */
170 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
171 /* control chars - set return condition: min number of bytes and timer.
172 * We want read to return every single byte, without timeout. */
173 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
175 /* put terminal in raw mode after flushing */
176 if (tcsetattr(fd,TCSADRAIN,&raw) < 0) goto fatal;
185 static void disableRawMode(int fd) {
186 /* Don't even check the return value as it's too late. */
187 if (rawmode && tcsetattr(fd,TCSADRAIN,&orig_termios) != -1)
191 /* At exit we'll try to fix the terminal to the initial conditions. */
192 static void linenoiseAtExit(void) {
193 disableRawMode(STDIN_FILENO);
197 static int getColumns(void) {
200 if (ioctl(1, TIOCGWINSZ, &ws) == -1) return 80;
204 /* Structure to contain the status of the current (being edited) line */
206 int fd; /* Terminal fd */
207 char *buf; /* Current buffer. Always null terminated */
208 int bufmax; /* Size of the buffer, including space for the null termination */
209 int len; /* Number of bytes in 'buf' */
210 int chars; /* Number of chars in 'buf' (utf-8 chars) */
211 int pos; /* Cursor position, measured in chars */
212 int cols; /* Size of the window, in chars */
215 /* gcc/glibc insists that we care about the return code of write! */
216 #define IGNORE_RC(EXPR) ((EXPR) < 0 ? -1 : 0)
218 /* This is fd_printf() on some systems, but use a different
219 * name to avoid conflicts
221 static void fd_printf(int fd, const char *format, ...)
227 va_start(args, format);
228 n = vsnprintf(buf, sizeof(buf), format, args);
230 IGNORE_RC(write(fd, buf, n));
233 static int utf8_getchars(char *buf, int c)
236 return utf8_fromunicode(buf, c);
244 * Returns the unicode character at the given offset,
247 static int get_char(struct current *current, int pos)
249 if (pos >= 0 && pos < current->chars) {
251 int i = utf8_index(current->buf, pos);
252 (void)utf8_tounicode(current->buf + i, &c);
258 static void refreshLine(const char *prompt, struct current *current) {
263 const char *buf = current->buf;
264 int chars = current->chars;
265 int pos = current->pos;
270 /* Should intercept SIGWINCH. For now, just get the size every time */
271 current->cols = getColumns();
273 plen = strlen(prompt);
274 pchars = utf8_strlen(prompt, plen);
276 /* Account for a line which is too long to fit in the window.
277 * Note that control chars require an extra column
280 /* How many cols are required to the left of 'pos'?
281 * The prompt, plus one extra for each control char
283 n = pchars + utf8_strlen(buf, current->len);
285 for (i = 0; i < pos; i++) {
286 b += utf8_tounicode(buf + b, &ch);
292 /* If too many are need, strip chars off the front of 'buf'
293 * until it fits. Note that if the current char is a control character,
294 * we need one extra col.
296 if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
300 while (n >= current->cols) {
301 b = utf8_tounicode(buf, &ch);
311 /* Cursor to left edge, then the prompt */
312 fd_printf(current->fd, "\x1b[0G");
313 IGNORE_RC(write(current->fd, prompt, plen));
315 /* Now the current buffer content */
317 /* Need special handling for control characters.
318 * If we hit 'cols', stop.
320 b = 0; /* unwritted bytes */
321 n = 0; /* How many control chars were written */
322 for (i = 0; i < chars; i++) {
324 int w = utf8_tounicode(buf + b, &ch);
328 if (pchars + i + n >= current->cols) {
332 /* A control character, so write the buffer so far */
333 IGNORE_RC(write(current->fd, buf, b));
336 fd_printf(current->fd, "\033[7m^%c\033[0m", ch + '@');
345 IGNORE_RC(write(current->fd, buf, b));
347 /* Erase to right, move cursor to original position */
348 fd_printf(current->fd, "\x1b[0K" "\x1b[0G\x1b[%dC", pos + pchars + backup);
351 static void set_current(struct current *current, const char *str)
353 strncpy(current->buf, str, current->bufmax);
354 current->buf[current->bufmax - 1] = 0;
355 current->len = strlen(current->buf);
356 current->pos = current->chars = utf8_strlen(current->buf, current->len);
359 static int has_room(struct current *current, int bytes)
361 return current->len + bytes < current->bufmax - 1;
364 static int remove_char(struct current *current, int pos)
366 if (pos >= 0 && pos < current->chars) {
368 p1 = utf8_index(current->buf, pos);
369 p2 = p1 + utf8_index(current->buf + p1, 1);
370 /* Move the null char too */
371 memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
372 current->len -= (p2 - p1);
374 if (current->pos > pos) {
382 static int insert_char(struct current *current, int pos, int ch)
385 int n = utf8_getchars(buf, ch);
387 if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
389 p1 = utf8_index(current->buf, pos);
391 memmove(current->buf + p2, current->buf + p1, current->len - p1);
392 memcpy(current->buf + p1, buf, n);
395 if (current->pos >= pos) {
403 #ifndef NO_COMPLETION
404 static linenoiseCompletionCallback *completionCallback = NULL;
407 fprintf(stderr, "\x7");
411 static void freeCompletions(linenoiseCompletions *lc) {
413 for (i = 0; i < lc->len; i++)
418 static int completeLine(const char *prompt, struct current *current) {
419 linenoiseCompletions lc = { 0, NULL };
422 completionCallback(current->buf,&lc);
426 size_t stop = 0, i = 0;
429 /* Show completion or original buffer */
431 struct current tmp = *current;
432 tmp.buf = lc.cvec[i];
433 tmp.pos = tmp.len = strlen(tmp.buf);
434 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
435 refreshLine(prompt, &tmp);
437 refreshLine(prompt, current);
440 c = fd_read(current->fd);
447 i = (i+1) % (lc.len+1);
448 if (i == lc.len) beep();
450 case 27: /* escape */
451 /* Re-show original buffer */
453 refreshLine(prompt, current);
458 /* Update buffer and return */
460 set_current(current,lc.cvec[i]);
468 freeCompletions(&lc);
469 return c; /* Return last read character */
472 /* Register a callback function to be called for tab-completion. */
473 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
474 completionCallback = fn;
477 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
478 lc->cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
479 lc->cvec[lc->len++] = strdup(str);
484 /* XXX: Optimise this later */
485 static int remove_chars(struct current *current, int pos, int n)
488 while (n-- && remove_char(current, pos)) {
495 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
497 * A timeout of -1 means to wait forever.
499 * Returns -1 if no char is received within the time or an error occurs.
501 static int fd_read_char(int fd, int timeout)
509 if (poll(&p, 1, timeout) == 0) {
513 if (read(fd, &c, 1) != 1) {
520 * Reads a complete utf-8 character
521 * and returns the unicode value, or -1 on error.
523 static int fd_read(int fd)
531 if (read(fd, &buf[0], 1) != 1) {
534 n = utf8_charlen(buf[0]);
535 if (n < 1 || n > 3) {
538 for (i = 1; i < n; i++) {
539 if (read(fd, &buf[i], 1) != 1) {
544 /* decode and return the character */
545 utf8_tounicode(buf, &c);
548 return fd_read_char(fd, -1);
552 /* Use -ve numbers here to co-exist with normal unicode chars */
559 SPECIAL_DELETE = -24,
563 * If escape (27) was received, reads subsequent
564 * chars to determine if this is a known special key.
566 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
568 * If no additional char is received within a short time,
571 static int check_special(int fd)
573 int c = fd_read_char(fd, 50);
580 c2 = fd_read_char(fd, 50);
584 if (c == '[' || c == 'O') {
585 /* Potential arrow key */
592 return SPECIAL_RIGHT;
597 if (c == '[' && c2 >= '1' && c2 <= '6') {
598 /* extended escape */
599 int c3 = fd_read_char(fd, 50);
600 if (c2 == '3' && c3 == '~') {
601 /* delete char under cursor */
602 return SPECIAL_DELETE;
604 while (c3 != -1 && c3 != '~') {
605 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
606 c3 = fd_read_char(fd, 50);
613 #define ctrl(C) ((C) - '@')
615 static int linenoisePrompt(const char *prompt, struct current *current) {
616 int history_index = 0;
618 /* The latest history entry is always our current buffer, that
619 * initially is just an empty string. */
620 linenoiseHistoryAdd("");
622 set_current(current, "");
623 refreshLine(prompt, current);
626 int c = fd_read(current->fd);
628 #ifndef NO_COMPLETION
629 /* Only autocomplete when the callback is set. It returns < 0 when
630 * there was an error reading from fd. Otherwise it will return the
631 * character that should be handled next. */
632 if (c == 9 && completionCallback != NULL) {
633 c = completeLine(prompt, current);
634 /* Return on errors */
635 if (c < 0) return current->len;
636 /* Read next character when 0 */
637 if (c == 0) continue;
642 if (c == -1) return current->len;
644 case '\r': /* enter */
646 free(history[history_len]);
648 case ctrl('C'): /* ctrl-c */
651 case 127: /* backspace */
653 if (remove_char(current, current->pos - 1)) {
654 refreshLine(prompt, current);
657 case ctrl('D'): /* ctrl-d */
658 if (current->len == 0) {
659 /* Empty line, so EOF */
661 free(history[history_len]);
664 /* Otherwise delete char to right of cursor */
665 if (remove_char(current, current->pos)) {
666 refreshLine(prompt, current);
669 case ctrl('W'): /* ctrl-w */
670 /* eat any spaces on the left */
672 int pos = current->pos;
673 while (pos > 0 && get_char(current, pos - 1) == ' ') {
677 /* now eat any non-spaces on the left */
678 while (pos > 0 && get_char(current, pos - 1) != ' ') {
682 if (remove_chars(current, pos, current->pos - pos)) {
683 refreshLine(prompt, current);
687 case ctrl('R'): /* ctrl-r */
689 /* Display the reverse-i-search prompt and process chars */
694 int searchpos = history_len - 1;
699 const char *p = NULL;
703 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
704 refreshLine(rprompt, current);
705 c = fd_read(current->fd);
706 if (c == ctrl('H') || c == 127) {
708 int p = utf8_index(rbuf, --rchars);
715 c = check_special(current->fd);
717 if (c == ctrl('P') || c == SPECIAL_UP) {
718 /* Search for the previous (earlier) match */
724 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
725 /* Search for the next (later) match */
726 if (searchpos < history_len) {
733 if (rlen >= (int)sizeof(rbuf) + 3) {
737 n = utf8_getchars(rbuf + rlen, c);
742 /* Adding a new char resets the search location */
743 searchpos = history_len - 1;
746 /* Exit from incremental search mode */
750 /* Now search through the history for a match */
751 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
752 p = strstr(history[searchpos], rbuf);
755 if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
756 /* But it is identical, so skip it */
759 /* Copy the matching line and set the cursor position */
760 set_current(current,history[searchpos]);
761 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
766 /* No match, so don't add it */
772 if (c == ctrl('G') || c == ctrl('C')) {
773 /* ctrl-g terminates the search with no effect */
774 set_current(current, "");
777 else if (c == ctrl('J')) {
778 /* ctrl-j terminates the search leaving the buffer in place */
781 /* Go process the char normally */
782 refreshLine(prompt, current);
786 case ctrl('T'): /* ctrl-t */
787 if (current->pos > 0 && current->pos < current->chars) {
788 c = get_char(current, current->pos);
789 remove_char(current, current->pos);
790 insert_char(current, current->pos - 1, c);
791 refreshLine(prompt, current);
794 case ctrl('V'): /* ctrl-v */
795 if (has_room(current, 3)) {
796 /* Insert the ^V first */
797 if (insert_char(current, current->pos, c)) {
798 refreshLine(prompt, current);
799 /* Now wait for the next char. Can insert anything except \0 */
800 c = fd_read(current->fd);
802 /* Remove the ^V first */
803 remove_char(current, current->pos - 1);
805 /* Insert the actual char */
806 insert_char(current, current->pos, c);
808 refreshLine(prompt, current);
812 case ctrl('B'): /* ctrl-b */
813 case ctrl('F'): /* ctrl-f */
814 case ctrl('P'): /* ctrl-p */
815 case ctrl('N'): /* ctrl-n */
816 case 27: { /* escape sequence */
819 c = check_special(current->fd);
824 if (current->pos > 0) {
826 refreshLine(prompt, current);
831 if (current->pos < current->chars) {
833 refreshLine(prompt, current);
841 if (history_len > 1) {
842 /* Update the current history entry before to
843 * overwrite it with tne next one. */
844 free(history[history_len-1-history_index]);
845 history[history_len-1-history_index] = strdup(current->buf);
846 /* Show the new entry */
847 history_index += dir;
848 if (history_index < 0) {
851 } else if (history_index >= history_len) {
852 history_index = history_len-1;
855 set_current(current, history[history_len-1-history_index]);
856 refreshLine(prompt, current);
861 if (remove_char(current, current->pos)) {
862 refreshLine(prompt, current);
869 /* Only tab is allowed without ^V */
870 if (c == '\t' || c >= ' ') {
871 if (insert_char(current, current->pos, c)) {
872 refreshLine(prompt, current);
876 case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
877 if (remove_chars(current, 0, current->pos)) {
878 refreshLine(prompt, current);
881 case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
882 if (remove_chars(current, current->pos, current->chars - current->pos)) {
883 refreshLine(prompt, current);
886 case ctrl('A'): /* Ctrl+a, go to the start of the line */
888 refreshLine(prompt, current);
890 case ctrl('E'): /* ctrl+e, go to the end of the line */
891 current->pos = current->chars;
892 refreshLine(prompt, current);
894 case ctrl('L'): /* Ctrl+L, clear screen */
896 fd_printf(current->fd, "\x1b[H\x1b[2J");
897 refreshLine(prompt, current);
904 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
905 int fd = STDIN_FILENO;
912 if (!isatty(STDIN_FILENO)) {
913 if (fgets(buf, buflen, stdin) == NULL) return -1;
915 if (count && buf[count-1] == '\n') {
920 struct current current;
922 if (enableRawMode(fd) == -1) return -1;
926 current.bufmax = buflen;
932 count = linenoisePrompt(prompt, ¤t);
940 char *linenoise(const char *prompt) {
941 char buf[LINENOISE_MAX_LINE];
944 if (isUnsupportedTerm()) {
949 if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
951 while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
957 count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
958 if (count == -1) return NULL;
963 /* Using a circular buffer is smarter, but a bit more complex to handle. */
964 int linenoiseHistoryAdd(const char *line) {
967 if (history_max_len == 0) return 0;
968 if (history == NULL) {
969 history = malloc(sizeof(char*)*history_max_len);
970 if (history == NULL) return 0;
971 memset(history,0,(sizeof(char*)*history_max_len));
973 linecopy = strdup(line);
974 if (!linecopy) return 0;
975 if (history_len == history_max_len) {
977 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
980 history[history_len] = linecopy;
985 int linenoiseHistorySetMaxLen(int len) {
988 if (len < 1) return 0;
990 int tocopy = history_len;
992 new = malloc(sizeof(char*)*len);
993 if (new == NULL) return 0;
994 if (len < tocopy) tocopy = len;
995 memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
999 history_max_len = len;
1000 if (history_len > history_max_len)
1001 history_len = history_max_len;
1005 /* Save the history in the specified file. On success 0 is returned
1006 * otherwise -1 is returned. */
1007 int linenoiseHistorySave(char *filename) {
1008 FILE *fp = fopen(filename,"w");
1011 if (fp == NULL) return -1;
1012 for (j = 0; j < history_len; j++) {
1013 const char *str = history[j];
1014 /* Need to encode backslash, nl and cr */
1019 else if (*str == '\n') {
1022 else if (*str == '\r') {
1037 /* Load the history from the specified file. If the file does not exist
1038 * zero is returned and no operation is performed.
1040 * If the file exists and the operation succeeded 0 is returned, otherwise
1041 * on error -1 is returned. */
1042 int linenoiseHistoryLoad(char *filename) {
1043 FILE *fp = fopen(filename,"r");
1044 char buf[LINENOISE_MAX_LINE];
1046 if (fp == NULL) return -1;
1048 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1051 /* Decode backslash escaped values */
1052 for (src = dest = buf; *src; src++) {
1060 else if (*src == 'r') {
1068 /* Remove trailing newline */
1069 if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1074 linenoiseHistoryAdd(buf);
1080 /* Provide access to the history buffer.
1082 * If 'len' is not NULL, the length is stored in *len.
1084 char **linenoiseHistory(int *len) {