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:
87 * Effect: Uses some standout mode such as reverse video
91 * Effect: Exit standout mode
101 #include <sys/types.h>
102 #include <sys/ioctl.h>
104 #include "linenoise.h"
106 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
107 #define LINENOISE_MAX_LINE 4096
108 static char *unsupported_term[] = {"dumb","cons25",NULL};
109 static linenoiseCompletionCallback *completionCallback = NULL;
111 static struct termios orig_termios; /* in order to restore at exit */
112 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
113 static int atexit_registered = 0; /* register atexit just 1 time */
114 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
115 static int history_len = 0;
116 char **history = NULL;
118 static void linenoiseAtExit(void);
119 int linenoiseHistoryAdd(const char *line);
121 static int isUnsupportedTerm(void) {
122 char *term = getenv("TERM");
125 if (term == NULL) return 0;
126 for (j = 0; unsupported_term[j]; j++)
127 if (!strcasecmp(term,unsupported_term[j])) return 1;
131 static void freeHistory(void) {
135 for (j = 0; j < history_len; j++)
141 static int enableRawMode(int fd) {
144 if (!isatty(STDIN_FILENO)) goto fatal;
145 if (!atexit_registered) {
146 atexit(linenoiseAtExit);
147 atexit_registered = 1;
149 if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
151 raw = orig_termios; /* modify the original mode */
152 /* input modes: no break, no CR to NL, no parity check, no strip char,
153 * no start/stop output control. */
154 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
155 /* output modes - disable post processing */
156 raw.c_oflag &= ~(OPOST);
157 /* control modes - set 8 bit chars */
158 raw.c_cflag |= (CS8);
159 /* local modes - choing off, canonical off, no extended functions,
160 * no signal chars (^Z,^C) */
161 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
162 /* control chars - set return condition: min number of bytes and timer.
163 * We want read to return every single byte, without timeout. */
164 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
166 /* put terminal in raw mode after flushing */
167 if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
176 static void disableRawMode(int fd) {
177 /* Don't even check the return value as it's too late. */
178 if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1)
182 /* At exit we'll try to fix the terminal to the initial conditions. */
183 static void linenoiseAtExit(void) {
184 disableRawMode(STDIN_FILENO);
188 static int getColumns(void) {
191 if (ioctl(1, TIOCGWINSZ, &ws) == -1) return 80;
195 static void refreshLine(int fd, const char *prompt, char *buf, size_t len, size_t pos, size_t cols) {
197 size_t plen = strlen(prompt);
201 while((plen+pos) >= cols) {
206 while (plen+len > cols) {
210 /* Cursor to left edge */
211 snprintf(seq,64,"\x1b[0G");
212 if (write(fd,seq,strlen(seq)) == -1) return;
213 /* Write the prompt and the current buffer content */
214 if (write(fd,prompt,strlen(prompt)) == -1) return;
215 /* Need special handling for control characters */
217 for (i = 0; i < len; i++) {
219 write(fd, buf + p, i - p);
221 snprintf(seq,64,"\033[7m^%c\033[0m", buf[i] + '@');
222 if (write(fd,seq,strlen(seq)) == -1) return;
228 write(fd, buf + p, i - p);
230 snprintf(seq,64,"\x1b[0K");
231 if (write(fd,seq,strlen(seq)) == -1) return;
232 /* Move cursor to original position. */
233 snprintf(seq,64,"\x1b[0G\x1b[%dC", (int)(pos+plen+extra));
234 if (write(fd,seq,strlen(seq)) == -1) return;
238 fprintf(stderr, "\x7");
242 static void freeCompletions(linenoiseCompletions *lc) {
244 for (i = 0; i < lc->len; i++)
246 if (lc->cvec != NULL)
250 static int completeLine(int fd, const char *prompt, char *buf, size_t buflen, size_t *len, size_t *pos, size_t cols) {
251 linenoiseCompletions lc = { 0, NULL };
255 completionCallback(buf,&lc);
259 size_t stop = 0, i = 0;
263 /* Show completion or original buffer */
265 clen = strlen(lc.cvec[i]);
266 refreshLine(fd,prompt,lc.cvec[i],clen,clen,cols);
268 refreshLine(fd,prompt,buf,*len,*pos,cols);
271 nread = read(fd,&c,1);
273 freeCompletions(&lc);
279 i = (i+1) % (lc.len+1);
280 if (i == lc.len) beep();
282 case 27: /* escape */
283 /* Re-show original buffer */
285 refreshLine(fd,prompt,buf,*len,*pos,cols);
290 /* Update buffer and return */
292 nwritten = snprintf(buf,buflen,"%s",lc.cvec[i]);
293 *len = *pos = nwritten;
301 freeCompletions(&lc);
302 return c; /* Return last read character */
305 void linenoiseClearScreen(void) {
306 if (write(STDIN_FILENO,"\x1b[H\x1b[2J",7) <= 0) {
307 /* nothing to do, just to avoid warning. */
311 static int linenoisePrompt(int fd, char *buf, size_t buflen, const char *prompt) {
312 size_t plen = strlen(prompt);
315 size_t cols = getColumns();
316 int history_index = 0;
319 buflen--; /* Make sure there is always space for the nulterm */
321 /* The latest history entry is always our current buffer, that
322 * initially is just an empty string. */
323 linenoiseHistoryAdd("");
325 if (write(fd,prompt,plen) == -1) return -1;
330 char seq[2], seq2[2];
332 nread = read(fd,&c,1);
334 if (nread <= 0) return len;
336 /* Only autocomplete when the callback is set. It returns < 0 when
337 * there was an error reading from fd. Otherwise it will return the
338 * character that should be handled next. */
339 if (c == 9 && completionCallback != NULL) {
340 c = completeLine(fd,prompt,buf,buflen,&len,&pos,cols);
341 /* Return on errors */
342 if (c < 0) return len;
343 /* Read next character when 0 */
344 if (c == 0) continue;
350 free(history[history_len]);
355 case 127: /* backspace */
357 if (pos > 0 && len > 0) {
358 memmove(buf+pos-1,buf+pos,len-pos);
362 refreshLine(fd,prompt,buf,len,pos,cols);
365 case 4: /* ctrl-d, remove char at right of cursor */
366 if (len > 1 && pos < (len-1)) {
367 memmove(buf+pos,buf+pos+1,len-pos);
370 refreshLine(fd,prompt,buf,len,pos,cols);
371 } else if (len == 0) {
373 free(history[history_len]);
376 case 23: /* ctrl-w */
377 /* eat any spaces on the left */
380 while (pos > 0 && len > 0 && buf[pos - 1] == ' ') {
385 /* now eat any non-spaces on the left */
386 while (pos > 0 && len > 0 && buf[pos - 1] != ' ') {
391 memmove(buf+pos,buf+pos+n,len-pos);
392 refreshLine(fd,prompt,buf,len,pos,cols);
395 case 18: /* ctrl-r */
397 /* Display the reverse-i-search prompt and process chars */
403 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
404 refreshLine(fd,rprompt,buf,len,pos,cols);
405 nread = read(fd,&c,1);
407 if (c == 8 || c == 127) {
414 /* ctrl-g terminates the search with no effect */
420 if (c >= ' ' && c <= '~') {
421 if (i < (int)sizeof(rbuf)) {
423 const char *p = NULL;
426 /* Now search back through the history for a match */
427 for (j = history_len - 1; j > 0; j--) {
428 p = strstr(history[j], rbuf);
430 /* Found a match. Copy it */
431 strncpy(buf,history[j],buflen);
434 pos = p - history[j];
439 /* No match, so don't add it */
448 /* Go process the char normally */
449 refreshLine(fd,prompt,buf,len,pos,cols);
453 case 20: /* ctrl-t */
454 if (pos > 0 && pos < len) {
455 int aux = buf[pos-1];
456 buf[pos-1] = buf[pos];
458 if (pos != len-1) pos++;
459 refreshLine(fd,prompt,buf,len,pos,cols);
466 case 16: /* ctrl-p */
469 case 14: /* ctrl-n */
473 case 27: /* escape sequence */
474 if (read(fd,seq,2) == -1) break;
475 ext = (seq[0] == 91 || seq[0] == 79);
476 if (ext && seq[1] == 68) {
481 refreshLine(fd,prompt,buf,len,pos,cols);
483 } else if (ext && seq[1] == 67) {
488 refreshLine(fd,prompt,buf,len,pos,cols);
490 } else if (ext && (seq[1] == 65 || seq[1] == 66)) {
492 /* up and down arrow: history */
493 if (history_len > 1) {
494 /* Update the current history entry before to
495 * overwrite it with tne next one. */
496 free(history[history_len-1-history_index]);
497 history[history_len-1-history_index] = strdup(buf);
498 /* Show the new entry */
499 history_index += (seq[1] == 65) ? 1 : -1;
500 if (history_index < 0) {
503 } else if (history_index >= history_len) {
504 history_index = history_len-1;
507 strncpy(buf,history[history_len-1-history_index],buflen);
509 len = pos = strlen(buf);
510 refreshLine(fd,prompt,buf,len,pos,cols);
512 } else if (seq[0] == 91 && seq[1] > 48 && seq[1] < 55) {
513 /* extended escape */
514 if (read(fd,seq2,2) == -1) break;
515 if (seq[1] == 51 && seq2[0] == 126) {
517 if (len > 0 && pos < len) {
518 memmove(buf+pos,buf+pos+1,len-pos-1);
521 refreshLine(fd,prompt,buf,len,pos,cols);
527 /* Note that the only control character currently permitted is tab */
528 if (len < buflen && (c == '\t' || c >= ' ')) {
529 if (len == pos && c >= ' ') {
534 if (plen+len < cols) {
535 /* Avoid a full update of the line in the
537 if (write(fd,&c,1) == -1) return -1;
539 refreshLine(fd,prompt,buf,len,pos,cols);
542 memmove(buf+pos+1,buf+pos,len-pos);
547 refreshLine(fd,prompt,buf,len,pos,cols);
551 case 21: /* Ctrl+u, delete the whole line. */
554 refreshLine(fd,prompt,buf,len,pos,cols);
556 case 11: /* Ctrl+k, delete from current to end of line. */
559 refreshLine(fd,prompt,buf,len,pos,cols);
561 case 1: /* Ctrl+a, go to the start of the line */
563 refreshLine(fd,prompt,buf,len,pos,cols);
565 case 5: /* ctrl+e, go to the end of the line */
567 refreshLine(fd,prompt,buf,len,pos,cols);
569 case 12: /* ctrl+l, clear screen */
570 linenoiseClearScreen();
571 refreshLine(fd,prompt,buf,len,pos,cols);
577 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
578 int fd = STDIN_FILENO;
585 if (!isatty(STDIN_FILENO)) {
586 if (fgets(buf, buflen, stdin) == NULL) return -1;
588 if (count && buf[count-1] == '\n') {
593 if (enableRawMode(fd) == -1) return -1;
594 count = linenoisePrompt(fd, buf, buflen, prompt);
601 char *linenoise(const char *prompt) {
602 char buf[LINENOISE_MAX_LINE];
605 if (isUnsupportedTerm()) {
610 if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
612 while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
618 count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
619 if (count == -1) return NULL;
624 /* Register a callback function to be called for tab-completion. */
625 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
626 completionCallback = fn;
629 void linenoiseAddCompletion(linenoiseCompletions *lc, char *str) {
630 size_t len = strlen(str);
631 char *copy = malloc(len+1);
632 memcpy(copy,str,len+1);
633 lc->cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
634 lc->cvec[lc->len++] = copy;
637 /* Using a circular buffer is smarter, but a bit more complex to handle. */
638 int linenoiseHistoryAdd(const char *line) {
641 if (history_max_len == 0) return 0;
642 if (history == NULL) {
643 history = malloc(sizeof(char*)*history_max_len);
644 if (history == NULL) return 0;
645 memset(history,0,(sizeof(char*)*history_max_len));
647 linecopy = strdup(line);
648 if (!linecopy) return 0;
649 if (history_len == history_max_len) {
651 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
654 history[history_len] = linecopy;
659 int linenoiseHistorySetMaxLen(int len) {
662 if (len < 1) return 0;
664 int tocopy = history_len;
666 new = malloc(sizeof(char*)*len);
667 if (new == NULL) return 0;
668 if (len < tocopy) tocopy = len;
669 memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
673 history_max_len = len;
674 if (history_len > history_max_len)
675 history_len = history_max_len;
679 /* Save the history in the specified file. On success 0 is returned
680 * otherwise -1 is returned. */
681 int linenoiseHistorySave(char *filename) {
682 FILE *fp = fopen(filename,"w");
685 if (fp == NULL) return -1;
686 for (j = 0; j < history_len; j++)
687 fprintf(fp,"%s\n",history[j]);
692 /* Load the history from the specified file. If the file does not exist
693 * zero is returned and no operation is performed.
695 * If the file exists and the operation succeeded 0 is returned, otherwise
696 * on error -1 is returned. */
697 int linenoiseHistoryLoad(char *filename) {
698 FILE *fp = fopen(filename,"r");
699 char buf[LINENOISE_MAX_LINE];
701 if (fp == NULL) return -1;
703 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
706 p = strchr(buf,'\r');
707 if (!p) p = strchr(buf,'\n');
709 linenoiseHistoryAdd(buf);