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
48 * - Switch to gets() if $TERM is something we can't support.
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>
110 #include "linenoise.h"
112 #include "linenoise.h"
114 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
115 #define LINENOISE_MAX_LINE 4096
116 static char *unsupported_term[] = {"dumb","cons25",NULL};
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;
125 static void linenoiseAtExit(void);
126 static int fd_read(int fd);
128 static int isUnsupportedTerm(void) {
129 char *term = getenv("TERM");
132 if (term == NULL) return 0;
133 for (j = 0; unsupported_term[j]; j++)
134 if (!strcasecmp(term,unsupported_term[j])) return 1;
138 static void freeHistory(void) {
142 for (j = 0; j < history_len; j++)
148 static int enableRawMode(int fd) {
151 if (!isatty(STDIN_FILENO)) goto fatal;
152 if (!atexit_registered) {
153 atexit(linenoiseAtExit);
154 atexit_registered = 1;
156 if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
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 */
173 /* put terminal in raw mode after flushing */
174 if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
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)
189 /* At exit we'll try to fix the terminal to the initial conditions. */
190 static void linenoiseAtExit(void) {
191 disableRawMode(STDIN_FILENO);
195 static int getColumns(void) {
198 if (ioctl(1, TIOCGWINSZ, &ws) == -1) return 80;
202 /* Structure to contain the status of the current (being edited) line */
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 */
212 /* This is fd_printf() on some systems, but use a different
213 * name to avoid conflicts
215 static void fd_printf(int fd, const char *format, ...)
221 va_start(args, format);
222 n = vsnprintf(buf, sizeof(buf), format, args);
227 static void refreshLine(const char *prompt, struct current *c) {
228 size_t plen = strlen(prompt);
231 const char *buf = c->buf;
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);
238 while((plen+pos) >= c->cols) {
243 while (plen+len > c->cols) {
247 /* Cursor to left edge, then the prompt */
248 fd_printf(c->fd, "\x1b[0G");
249 write(c->fd, prompt, strlen(prompt));
251 /* Now the current buffer content */
252 /* Need special handling for control characters */
254 for (i = 0; i < len; i++) {
255 if (buf[i] >= 0 && buf[i] < ' ') {
256 write(c->fd, buf + p, i - p);
258 fd_printf(c->fd, "\033[7m^%c\033[0m", buf[i] + '@');
264 write(c->fd, buf + p, i - p);
266 /* Erase to right, move cursor to original position */
267 fd_printf(c->fd, "\x1b[0K" "\x1b[0G\x1b[%dC", (int)(pos+plen+extra));
270 static void set_current(struct current *current, const char *str)
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;
278 static int has_room(struct current *current, int chars)
280 return current->len + chars < current->bufmax - 1;
283 static int remove_char(struct current *current, int pos)
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) {
290 /* Move the null char too */
291 memmove(current->buf + pos, current->buf + pos + 1, current->len - pos);
298 static int insert_char(struct current *current, int pos, int ch)
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;
304 if (current->pos >= pos) {
312 #ifndef NO_COMPLETION
313 static linenoiseCompletionCallback *completionCallback = NULL;
316 fprintf(stderr, "\x7");
320 static void freeCompletions(linenoiseCompletions *lc) {
322 for (i = 0; i < lc->len; i++)
327 static int completeLine(const char *prompt, struct current *current) {
328 linenoiseCompletions lc = { 0, NULL };
331 completionCallback(current->buf,&lc);
335 size_t stop = 0, i = 0;
338 /* Show completion or original buffer */
340 struct current tmp = *current;
341 tmp.buf = lc.cvec[i];
342 tmp.pos = tmp.len = strlen(tmp.buf);
343 refreshLine(prompt, &tmp);
345 refreshLine(prompt, current);
348 c = fd_read(current->fd);
355 i = (i+1) % (lc.len+1);
356 if (i == lc.len) beep();
358 case 27: /* escape */
359 /* Re-show original buffer */
361 refreshLine(prompt, current);
366 /* Update buffer and return */
368 set_current(current,lc.cvec[i]);
376 freeCompletions(&lc);
377 return c; /* Return last read character */
380 /* Register a callback function to be called for tab-completion. */
381 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
382 completionCallback = fn;
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);
392 /* XXX: Optimise this later */
393 static int remove_chars(struct current *current, int pos, int n)
396 while (n-- && remove_char(current, pos)) {
402 static int fd_read(int fd)
405 if (read(fd, &c, 1) != 1) {
412 #define ctrl(C) ((C) - '@')
415 static int linenoisePrompt(const char *prompt, struct current *current) {
416 size_t plen = strlen(prompt);
417 int history_index = 0;
419 /* The latest history entry is always our current buffer, that
420 * initially is just an empty string. */
421 linenoiseHistoryAdd("");
423 set_current(current, "");
424 refreshLine(prompt, current);
431 c = fd_read(current->fd);
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;
447 if (c < 0) return current->len;
449 case '\r': /* enter */
451 free(history[history_len]);
453 case ctrl('C'): /* ctrl-c */
456 case 127: /* backspace */
458 if (remove_char(current, current->pos - 1)) {
459 refreshLine(prompt, current);
462 case ctrl('D'): /* ctrl-d */
463 if (current->len == 0) {
464 /* Empty line, so EOF */
466 free(history[history_len]);
469 /* Otherwise delete char to right of cursor */
470 if (remove_char(current, current->pos)) {
471 refreshLine(prompt, current);
474 case ctrl('W'): /* ctrl-w */
475 /* eat any spaces on the left */
477 int pos = current->pos;
478 while (pos > 0 && current->buf[pos - 1] == ' ') {
482 /* now eat any non-spaces on the left */
483 while (pos > 0 && current->buf[pos - 1] != ' ') {
487 if (remove_chars(current, pos, current->pos - pos)) {
488 refreshLine(prompt, current);
492 case ctrl('R'): /* ctrl-r */
494 /* Display the reverse-i-search prompt and process chars */
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) {
509 if (c >= ' ' && c <= '~') {
510 if (i < (int)sizeof(rbuf)) {
512 const char *p = NULL;
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);
519 /* Found a match. Copy it */
520 set_current(current,history[j]);
521 current->pos = p - history[j];
526 /* No match, so don't add it */
534 if (c == ctrl('G')) {
535 /* ctrl-g terminates the search with no effect */
536 set_current(current, "");
539 else if (c == ctrl('J')) {
540 /* ctrl-j terminates the search leaving the buffer in place */
543 /* Go process the char normally */
544 refreshLine(prompt, current);
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);
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);
565 /* Replace the ^V with the actual char */
566 current->buf[current->pos - 1] = c;
569 remove_char(current, current->pos);
571 refreshLine(prompt, current);
575 case ctrl('B'): /* ctrl-b */
577 case ctrl('F'): /* ctrl-f */
579 case ctrl('P'): /* ctrl-p */
582 case ctrl('N'): /* ctrl-n */
586 case 27: /* escape sequence */
587 c = fd_read(current->fd);
591 c2 = fd_read(current->fd);
595 ext = (c == 91 || c == 79);
596 if (ext && c2 == 68) {
599 if (current->pos > 0) {
601 refreshLine(prompt, current);
603 } else if (ext && c2 == 67) {
606 if (current->pos < current->len) {
608 refreshLine(prompt, current);
610 } else if (ext && (c2 == 65 || c2 == 66)) {
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) {
623 } else if (history_index >= history_len) {
624 history_index = history_len-1;
627 set_current(current, history[history_len-1-history_index]);
628 refreshLine(prompt, current);
630 } else if (c == 91 && c2 > 48 && c2 < 55) {
631 /* extended escape */
632 c = fd_read(current->fd);
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);
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) {
652 write(current->fd, &ch, 1);
655 refreshLine(prompt, current);
660 case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
661 if (remove_chars(current, 0, current->pos)) {
662 refreshLine(prompt, current);
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);
670 case ctrl('A'): /* Ctrl+a, go to the start of the line */
672 refreshLine(prompt, current);
674 case ctrl('E'): /* ctrl+e, go to the end of the line */
675 current->pos = current->len;
676 refreshLine(prompt, current);
678 case ctrl('L'): /* Ctrl+L, clear screen */
680 fd_printf(current->fd, "\x1b[H\x1b[2J");
681 refreshLine(prompt, current);
688 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
689 int fd = STDIN_FILENO;
696 if (!isatty(STDIN_FILENO)) {
697 if (fgets(buf, buflen, stdin) == NULL) return -1;
699 if (count && buf[count-1] == '\n') {
704 struct current current;
706 if (enableRawMode(fd) == -1) return -1;
710 current.bufmax = buflen;
713 current.cols = getColumns();
715 count = linenoisePrompt(prompt, ¤t);
722 char *linenoise(const char *prompt) {
723 char buf[LINENOISE_MAX_LINE];
726 if (isUnsupportedTerm()) {
731 if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
733 while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
739 count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
740 if (count == -1) return NULL;
745 /* Using a circular buffer is smarter, but a bit more complex to handle. */
746 int linenoiseHistoryAdd(const char *line) {
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));
755 linecopy = strdup(line);
756 if (!linecopy) return 0;
757 if (history_len == history_max_len) {
759 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
762 history[history_len] = linecopy;
767 int linenoiseHistorySetMaxLen(int len) {
770 if (len < 1) return 0;
772 int tocopy = history_len;
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);
781 history_max_len = len;
782 if (history_len > history_max_len)
783 history_len = history_max_len;
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");
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 */
801 else if (*str == '\n') {
804 else if (*str == '\r') {
819 /* Load the history from the specified file. If the file does not exist
820 * zero is returned and no operation is performed.
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];
828 if (fp == NULL) return -1;
830 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
833 /* Decode backslash escaped values */
834 for (src = dest = buf; *src; src++) {
842 else if (*src == 'r') {
850 /* Remove trailing newline */
851 if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
856 linenoiseHistoryAdd(buf);
862 /* Provide access to the history buffer.
864 * If 'len' is not NULL, the length is stored in *len.
866 char **linenoiseHistory(int *len) {