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 /* This is fd_printf() on some systems, but use a different
216 * name to avoid conflicts
218 static void fd_printf(int fd, const char *format, ...)
224 va_start(args, format);
225 n = vsnprintf(buf, sizeof(buf), format, args);
230 static int utf8_getchars(char *buf, int c)
233 return utf8_fromunicode(buf, c);
241 * Returns the unicode character at the given offset,
244 static int get_char(struct current *current, int pos)
246 if (pos >= 0 && pos < current->chars) {
248 int i = utf8_index(current->buf, pos);
249 utf8_tounicode(current->buf + i, &c);
255 static void refreshLine(const char *prompt, struct current *current) {
260 const char *buf = current->buf;
261 int chars = current->chars;
262 int pos = current->pos;
267 /* Should intercept SIGWINCH. For now, just get the size every time */
268 current->cols = getColumns();
270 plen = strlen(prompt);
271 pchars = utf8_strlen(prompt, plen);
273 /* Account for a line which is too long to fit in the window.
274 * Note that control chars require an extra column
277 /* How many cols are required to the left of 'pos'?
278 * The prompt, plus one extra for each control char
280 n = pchars + utf8_strlen(buf, current->len);
282 for (i = 0; i < pos; i++) {
283 b += utf8_tounicode(buf + b, &ch);
289 /* If too many are need, strip chars off the front of 'buf'
290 * until it fits. Note that if the current char is a control character,
291 * we need one extra col.
293 if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
297 while (n >= current->cols) {
298 b = utf8_tounicode(buf, &ch);
308 /* Cursor to left edge, then the prompt */
309 fd_printf(current->fd, "\x1b[0G");
310 write(current->fd, prompt, plen);
312 /* Now the current buffer content */
314 /* Need special handling for control characters.
315 * If we hit 'cols', stop.
317 b = 0; /* unwritted bytes */
318 n = 0; /* How many control chars were written */
319 for (i = 0; i < chars; i++) {
321 int w = utf8_tounicode(buf + b, &ch);
325 if (pchars + i + n >= current->cols) {
329 /* A control character, so write the buffer so far */
330 write(current->fd, buf, b);
333 fd_printf(current->fd, "\033[7m^%c\033[0m", ch + '@');
342 write(current->fd, buf, b);
344 /* Erase to right, move cursor to original position */
345 fd_printf(current->fd, "\x1b[0K" "\x1b[0G\x1b[%dC", pos + pchars + backup);
348 static void set_current(struct current *current, const char *str)
350 strncpy(current->buf, str, current->bufmax);
351 current->buf[current->bufmax - 1] = 0;
352 current->len = strlen(current->buf);
353 current->pos = current->chars = utf8_strlen(current->buf, current->len);
356 static int has_room(struct current *current, int bytes)
358 return current->len + bytes < current->bufmax - 1;
361 static int remove_char(struct current *current, int pos)
363 if (pos >= 0 && pos < current->chars) {
365 p1 = utf8_index(current->buf, pos);
366 p2 = p1 + utf8_index(current->buf + p1, 1);
367 /* Move the null char too */
368 memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
369 current->len -= (p2 - p1);
371 if (current->pos > pos) {
379 static int insert_char(struct current *current, int pos, int ch)
382 int n = utf8_getchars(buf, ch);
384 if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
386 p1 = utf8_index(current->buf, pos);
388 memmove(current->buf + p2, current->buf + p1, current->len - p1);
389 memcpy(current->buf + p1, buf, n);
392 if (current->pos >= pos) {
400 #ifndef NO_COMPLETION
401 static linenoiseCompletionCallback *completionCallback = NULL;
404 fprintf(stderr, "\x7");
408 static void freeCompletions(linenoiseCompletions *lc) {
410 for (i = 0; i < lc->len; i++)
415 static int completeLine(const char *prompt, struct current *current) {
416 linenoiseCompletions lc = { 0, NULL };
419 completionCallback(current->buf,&lc);
423 size_t stop = 0, i = 0;
426 /* Show completion or original buffer */
428 struct current tmp = *current;
429 tmp.buf = lc.cvec[i];
430 tmp.pos = tmp.len = strlen(tmp.buf);
431 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
432 refreshLine(prompt, &tmp);
434 refreshLine(prompt, current);
437 c = fd_read(current->fd);
444 i = (i+1) % (lc.len+1);
445 if (i == lc.len) beep();
447 case 27: /* escape */
448 /* Re-show original buffer */
450 refreshLine(prompt, current);
455 /* Update buffer and return */
457 set_current(current,lc.cvec[i]);
465 freeCompletions(&lc);
466 return c; /* Return last read character */
469 /* Register a callback function to be called for tab-completion. */
470 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
471 completionCallback = fn;
474 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
475 lc->cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
476 lc->cvec[lc->len++] = strdup(str);
481 /* XXX: Optimise this later */
482 static int remove_chars(struct current *current, int pos, int n)
485 while (n-- && remove_char(current, pos)) {
492 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
494 * A timeout of -1 means to wait forever.
496 * Returns -1 if no char is received within the time or an error occurs.
498 static int fd_read_char(int fd, int timeout)
506 if (poll(&p, 1, timeout) == 0) {
510 if (read(fd, &c, 1) != 1) {
517 * Reads a complete utf-8 character
518 * and returns the unicode value, or -1 on error.
520 static int fd_read(int fd)
528 if (read(fd, &buf[0], 1) != 1) {
531 n = utf8_charlen(buf[0]);
532 if (n < 1 || n > 3) {
535 for (i = 1; i < n; i++) {
536 if (read(fd, &buf[i], 1) != 1) {
541 /* decode and return the character */
542 utf8_tounicode(buf, &c);
545 return fd_read_char(fd, -1);
549 /* Use -ve numbers here to co-exist with normal unicode chars */
556 SPECIAL_DELETE = -24,
560 * If escape (27) was received, reads subsequent
561 * chars to determine if this is a known special key.
563 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
565 * If no additional char is received within a short time,
568 static int check_special(int fd)
570 int c = fd_read_char(fd, 50);
577 c2 = fd_read_char(fd, 50);
581 if (c == '[' || c == 'O') {
582 /* Potential arrow key */
589 return SPECIAL_RIGHT;
594 if (c == '[' && c2 >= '1' && c2 <= '6') {
595 /* extended escape */
596 int c3 = fd_read_char(fd, 50);
597 if (c2 == '3' && c3 == '~') {
598 /* delete char under cursor */
599 return SPECIAL_DELETE;
601 while (c3 != -1 && c3 != '~') {
602 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
603 c3 = fd_read_char(fd, 50);
610 #define ctrl(C) ((C) - '@')
612 static int linenoisePrompt(const char *prompt, struct current *current) {
613 int history_index = 0;
615 /* The latest history entry is always our current buffer, that
616 * initially is just an empty string. */
617 linenoiseHistoryAdd("");
619 set_current(current, "");
620 refreshLine(prompt, current);
623 int c = fd_read(current->fd);
625 #ifndef NO_COMPLETION
626 /* Only autocomplete when the callback is set. It returns < 0 when
627 * there was an error reading from fd. Otherwise it will return the
628 * character that should be handled next. */
629 if (c == 9 && completionCallback != NULL) {
630 c = completeLine(prompt, current);
631 /* Return on errors */
632 if (c < 0) return current->len;
633 /* Read next character when 0 */
634 if (c == 0) continue;
639 if (c == -1) return current->len;
641 case '\r': /* enter */
643 free(history[history_len]);
645 case ctrl('C'): /* ctrl-c */
648 case 127: /* backspace */
650 if (remove_char(current, current->pos - 1)) {
651 refreshLine(prompt, current);
654 case ctrl('D'): /* ctrl-d */
655 if (current->len == 0) {
656 /* Empty line, so EOF */
658 free(history[history_len]);
661 /* Otherwise delete char to right of cursor */
662 if (remove_char(current, current->pos)) {
663 refreshLine(prompt, current);
666 case ctrl('W'): /* ctrl-w */
667 /* eat any spaces on the left */
669 int pos = current->pos;
670 while (pos > 0 && get_char(current, pos - 1) == ' ') {
674 /* now eat any non-spaces on the left */
675 while (pos > 0 && get_char(current, pos - 1) != ' ') {
679 if (remove_chars(current, pos, current->pos - pos)) {
680 refreshLine(prompt, current);
684 case ctrl('R'): /* ctrl-r */
686 /* Display the reverse-i-search prompt and process chars */
691 int searchpos = history_len - 1;
696 const char *p = NULL;
700 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
701 refreshLine(rprompt, current);
702 c = fd_read(current->fd);
703 if (c == ctrl('H') || c == 127) {
705 int p = utf8_index(rbuf, --rchars);
712 c = check_special(current->fd);
714 if (c == ctrl('P') || c == SPECIAL_UP) {
715 /* Search for the previous (earlier) match */
721 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
722 /* Search for the next (later) match */
723 if (searchpos < history_len) {
730 if (rlen >= (int)sizeof(rbuf) + 3) {
734 n = utf8_getchars(rbuf + rlen, c);
739 /* Adding a new char resets the search location */
740 searchpos = history_len - 1;
743 /* Exit from incremental search mode */
747 /* Now search through the history for a match */
748 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
749 p = strstr(history[searchpos], rbuf);
752 if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
753 /* But it is identical, so skip it */
756 /* Copy the matching line and set the cursor position */
757 set_current(current,history[searchpos]);
758 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
763 /* No match, so don't add it */
769 if (c == ctrl('G') || c == ctrl('C')) {
770 /* ctrl-g terminates the search with no effect */
771 set_current(current, "");
774 else if (c == ctrl('J')) {
775 /* ctrl-j terminates the search leaving the buffer in place */
778 /* Go process the char normally */
779 refreshLine(prompt, current);
783 case ctrl('T'): /* ctrl-t */
784 if (current->pos > 0 && current->pos < current->chars) {
785 c = get_char(current, current->pos);
786 remove_char(current, current->pos);
787 insert_char(current, current->pos - 1, c);
788 refreshLine(prompt, current);
791 case ctrl('V'): /* ctrl-v */
792 if (has_room(current, 3)) {
793 /* Insert the ^V first */
794 if (insert_char(current, current->pos, c)) {
795 refreshLine(prompt, current);
796 /* Now wait for the next char. Can insert anything except \0 */
797 c = fd_read(current->fd);
799 /* Remove the ^V first */
800 remove_char(current, current->pos - 1);
802 /* Insert the actual char */
803 insert_char(current, current->pos, c);
805 refreshLine(prompt, current);
809 case ctrl('B'): /* ctrl-b */
810 case ctrl('F'): /* ctrl-f */
811 case ctrl('P'): /* ctrl-p */
812 case ctrl('N'): /* ctrl-n */
813 case 27: { /* escape sequence */
816 c = check_special(current->fd);
821 if (current->pos > 0) {
823 refreshLine(prompt, current);
828 if (current->pos < current->chars) {
830 refreshLine(prompt, current);
838 if (history_len > 1) {
839 /* Update the current history entry before to
840 * overwrite it with tne next one. */
841 free(history[history_len-1-history_index]);
842 history[history_len-1-history_index] = strdup(current->buf);
843 /* Show the new entry */
844 history_index += dir;
845 if (history_index < 0) {
848 } else if (history_index >= history_len) {
849 history_index = history_len-1;
852 set_current(current, history[history_len-1-history_index]);
853 refreshLine(prompt, current);
858 if (remove_char(current, current->pos)) {
859 refreshLine(prompt, current);
866 /* Only tab is allowed without ^V */
867 if (c == '\t' || c >= ' ') {
868 if (insert_char(current, current->pos, c)) {
869 refreshLine(prompt, current);
873 case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
874 if (remove_chars(current, 0, current->pos)) {
875 refreshLine(prompt, current);
878 case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
879 if (remove_chars(current, current->pos, current->chars - current->pos)) {
880 refreshLine(prompt, current);
883 case ctrl('A'): /* Ctrl+a, go to the start of the line */
885 refreshLine(prompt, current);
887 case ctrl('E'): /* ctrl+e, go to the end of the line */
888 current->pos = current->chars;
889 refreshLine(prompt, current);
891 case ctrl('L'): /* Ctrl+L, clear screen */
893 fd_printf(current->fd, "\x1b[H\x1b[2J");
894 refreshLine(prompt, current);
901 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
902 int fd = STDIN_FILENO;
909 if (!isatty(STDIN_FILENO)) {
910 if (fgets(buf, buflen, stdin) == NULL) return -1;
912 if (count && buf[count-1] == '\n') {
917 struct current current;
919 if (enableRawMode(fd) == -1) return -1;
923 current.bufmax = buflen;
929 count = linenoisePrompt(prompt, ¤t);
937 char *linenoise(const char *prompt) {
938 char buf[LINENOISE_MAX_LINE];
941 if (isUnsupportedTerm()) {
946 if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
948 while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
954 count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
955 if (count == -1) return NULL;
960 /* Using a circular buffer is smarter, but a bit more complex to handle. */
961 int linenoiseHistoryAdd(const char *line) {
964 if (history_max_len == 0) return 0;
965 if (history == NULL) {
966 history = malloc(sizeof(char*)*history_max_len);
967 if (history == NULL) return 0;
968 memset(history,0,(sizeof(char*)*history_max_len));
970 linecopy = strdup(line);
971 if (!linecopy) return 0;
972 if (history_len == history_max_len) {
974 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
977 history[history_len] = linecopy;
982 int linenoiseHistorySetMaxLen(int len) {
985 if (len < 1) return 0;
987 int tocopy = history_len;
989 new = malloc(sizeof(char*)*len);
990 if (new == NULL) return 0;
991 if (len < tocopy) tocopy = len;
992 memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
996 history_max_len = len;
997 if (history_len > history_max_len)
998 history_len = history_max_len;
1002 /* Save the history in the specified file. On success 0 is returned
1003 * otherwise -1 is returned. */
1004 int linenoiseHistorySave(char *filename) {
1005 FILE *fp = fopen(filename,"w");
1008 if (fp == NULL) return -1;
1009 for (j = 0; j < history_len; j++) {
1010 const char *str = history[j];
1011 /* Need to encode backslash, nl and cr */
1016 else if (*str == '\n') {
1019 else if (*str == '\r') {
1034 /* Load the history from the specified file. If the file does not exist
1035 * zero is returned and no operation is performed.
1037 * If the file exists and the operation succeeded 0 is returned, otherwise
1038 * on error -1 is returned. */
1039 int linenoiseHistoryLoad(char *filename) {
1040 FILE *fp = fopen(filename,"r");
1041 char buf[LINENOISE_MAX_LINE];
1043 if (fp == NULL) return -1;
1045 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1048 /* Decode backslash escaped values */
1049 for (src = dest = buf; *src; src++) {
1057 else if (*src == 'r') {
1065 /* Remove trailing newline */
1066 if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1071 linenoiseHistoryAdd(buf);
1077 /* Provide access to the history buffer.
1079 * If 'len' is not NULL, the length is stored in *len.
1081 char **linenoiseHistory(int *len) {