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
93 #include <sys/types.h>
94 #include <sys/ioctl.h>
96 #include "linenoise.h"
98 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
99 #define LINENOISE_MAX_LINE 4096
100 static char *unsupported_term[] = {"dumb","cons25",NULL};
101 static linenoiseCompletionCallback *completionCallback = NULL;
103 static struct termios orig_termios; /* in order to restore at exit */
104 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
105 static int atexit_registered = 0; /* register atexit just 1 time */
106 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
107 static int history_len = 0;
108 char **history = NULL;
110 static void linenoiseAtExit(void);
111 int linenoiseHistoryAdd(const char *line);
113 static int isUnsupportedTerm(void) {
114 char *term = getenv("TERM");
117 if (term == NULL) return 0;
118 for (j = 0; unsupported_term[j]; j++)
119 if (!strcasecmp(term,unsupported_term[j])) return 1;
123 static void freeHistory(void) {
127 for (j = 0; j < history_len; j++)
133 static int enableRawMode(int fd) {
136 if (!isatty(STDIN_FILENO)) goto fatal;
137 if (!atexit_registered) {
138 atexit(linenoiseAtExit);
139 atexit_registered = 1;
141 if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
143 raw = orig_termios; /* modify the original mode */
144 /* input modes: no break, no CR to NL, no parity check, no strip char,
145 * no start/stop output control. */
146 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
147 /* output modes - disable post processing */
148 raw.c_oflag &= ~(OPOST);
149 /* control modes - set 8 bit chars */
150 raw.c_cflag |= (CS8);
151 /* local modes - choing off, canonical off, no extended functions,
152 * no signal chars (^Z,^C) */
153 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
154 /* control chars - set return condition: min number of bytes and timer.
155 * We want read to return every single byte, without timeout. */
156 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
158 /* put terminal in raw mode after flushing */
159 if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
168 static void disableRawMode(int fd) {
169 /* Don't even check the return value as it's too late. */
170 if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1)
174 /* At exit we'll try to fix the terminal to the initial conditions. */
175 static void linenoiseAtExit(void) {
176 disableRawMode(STDIN_FILENO);
180 static int getColumns(void) {
183 if (ioctl(1, TIOCGWINSZ, &ws) == -1) return 80;
187 static void refreshLine(int fd, const char *prompt, char *buf, size_t len, size_t pos, size_t cols) {
189 size_t plen = strlen(prompt);
193 while((plen+pos) >= cols) {
198 while (plen+len > cols) {
202 /* Cursor to left edge */
203 snprintf(seq,64,"\x1b[0G");
204 if (write(fd,seq,strlen(seq)) == -1) return;
205 /* Write the prompt and the current buffer content */
206 if (write(fd,prompt,strlen(prompt)) == -1) return;
207 /* Need special handling for control characters */
209 for (i = 0; i < len; i++) {
211 write(fd, buf + p, i - p);
214 seq[1] = buf[i] + '@';
221 write(fd, buf + p, i - p);
223 snprintf(seq,64,"\x1b[0K");
224 if (write(fd,seq,strlen(seq)) == -1) return;
225 /* Move cursor to original position. */
226 snprintf(seq,64,"\x1b[0G\x1b[%dC", (int)(pos+plen+extra));
227 if (write(fd,seq,strlen(seq)) == -1) return;
231 fprintf(stderr, "\x7");
235 static void freeCompletions(linenoiseCompletions *lc) {
237 for (i = 0; i < lc->len; i++)
239 if (lc->cvec != NULL)
243 static int completeLine(int fd, const char *prompt, char *buf, size_t buflen, size_t *len, size_t *pos, size_t cols) {
244 linenoiseCompletions lc = { 0, NULL };
248 completionCallback(buf,&lc);
252 size_t stop = 0, i = 0;
256 /* Show completion or original buffer */
258 clen = strlen(lc.cvec[i]);
259 refreshLine(fd,prompt,lc.cvec[i],clen,clen,cols);
261 refreshLine(fd,prompt,buf,*len,*pos,cols);
264 nread = read(fd,&c,1);
266 freeCompletions(&lc);
272 i = (i+1) % (lc.len+1);
273 if (i == lc.len) beep();
275 case 27: /* escape */
276 /* Re-show original buffer */
278 refreshLine(fd,prompt,buf,*len,*pos,cols);
283 /* Update buffer and return */
285 nwritten = snprintf(buf,buflen,"%s",lc.cvec[i]);
286 *len = *pos = nwritten;
294 freeCompletions(&lc);
295 return c; /* Return last read character */
298 void linenoiseClearScreen(void) {
299 if (write(STDIN_FILENO,"\x1b[H\x1b[2J",7) <= 0) {
300 /* nothing to do, just to avoid warning. */
304 static int linenoisePrompt(int fd, char *buf, size_t buflen, const char *prompt) {
305 size_t plen = strlen(prompt);
308 size_t cols = getColumns();
309 int history_index = 0;
312 buflen--; /* Make sure there is always space for the nulterm */
314 /* The latest history entry is always our current buffer, that
315 * initially is just an empty string. */
316 linenoiseHistoryAdd("");
318 if (write(fd,prompt,plen) == -1) return -1;
323 char seq[2], seq2[2];
325 nread = read(fd,&c,1);
327 if (nread <= 0) return len;
329 /* Only autocomplete when the callback is set. It returns < 0 when
330 * there was an error reading from fd. Otherwise it will return the
331 * character that should be handled next. */
332 if (c == 9 && completionCallback != NULL) {
333 c = completeLine(fd,prompt,buf,buflen,&len,&pos,cols);
334 /* Return on errors */
335 if (c < 0) return len;
336 /* Read next character when 0 */
337 if (c == 0) continue;
343 free(history[history_len]);
348 case 127: /* backspace */
350 if (pos > 0 && len > 0) {
351 memmove(buf+pos-1,buf+pos,len-pos);
355 refreshLine(fd,prompt,buf,len,pos,cols);
358 case 4: /* ctrl-d, remove char at right of cursor */
359 if (len > 1 && pos < (len-1)) {
360 memmove(buf+pos,buf+pos+1,len-pos);
363 refreshLine(fd,prompt,buf,len,pos,cols);
364 } else if (len == 0) {
366 free(history[history_len]);
369 case 23: /* ctrl-w */
370 /* eat any spaces on the left */
373 while (pos > 0 && len > 0 && buf[pos - 1] == ' ') {
378 /* now eat any non-spaces on the left */
379 while (pos > 0 && len > 0 && buf[pos - 1] != ' ') {
384 memmove(buf+pos,buf+pos+n,len-pos);
385 refreshLine(fd,prompt,buf,len,pos,cols);
388 case 18: /* ctrl-r */
390 /* Display the reverse-i-search prompt and process chars */
396 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
397 refreshLine(fd,rprompt,buf,len,pos,cols);
398 nread = read(fd,&c,1);
400 if (c == 8 || c == 127) {
407 /* ctrl-g terminates the search with no effect */
413 if (c >= ' ' && c <= '~') {
414 if (i < (int)sizeof(rbuf)) {
416 const char *p = NULL;
419 /* Now search back through the history for a match */
420 for (j = history_len - 1; j > 0; j--) {
421 p = strstr(history[j], rbuf);
423 /* Found a match. Copy it */
424 strncpy(buf,history[j],buflen);
427 pos = p - history[j];
432 /* No match, so don't add it */
441 /* Go process the char normally */
442 refreshLine(fd,prompt,buf,len,pos,cols);
446 case 20: /* ctrl-t */
447 if (pos > 0 && pos < len) {
448 int aux = buf[pos-1];
449 buf[pos-1] = buf[pos];
451 if (pos != len-1) pos++;
452 refreshLine(fd,prompt,buf,len,pos,cols);
459 case 16: /* ctrl-p */
462 case 14: /* ctrl-n */
466 case 27: /* escape sequence */
467 if (read(fd,seq,2) == -1) break;
468 ext = (seq[0] == 91 || seq[0] == 79);
469 if (ext && seq[1] == 68) {
474 refreshLine(fd,prompt,buf,len,pos,cols);
476 } else if (ext && seq[1] == 67) {
481 refreshLine(fd,prompt,buf,len,pos,cols);
483 } else if (ext && (seq[1] == 65 || seq[1] == 66)) {
485 /* up and down arrow: history */
486 if (history_len > 1) {
487 /* Update the current history entry before to
488 * overwrite it with tne next one. */
489 free(history[history_len-1-history_index]);
490 history[history_len-1-history_index] = strdup(buf);
491 /* Show the new entry */
492 history_index += (seq[1] == 65) ? 1 : -1;
493 if (history_index < 0) {
496 } else if (history_index >= history_len) {
497 history_index = history_len-1;
500 strncpy(buf,history[history_len-1-history_index],buflen);
502 len = pos = strlen(buf);
503 refreshLine(fd,prompt,buf,len,pos,cols);
505 } else if (seq[0] == 91 && seq[1] > 48 && seq[1] < 55) {
506 /* extended escape */
507 if (read(fd,seq2,2) == -1) break;
508 if (seq[1] == 51 && seq2[0] == 126) {
510 if (len > 0 && pos < len) {
511 memmove(buf+pos,buf+pos+1,len-pos-1);
514 refreshLine(fd,prompt,buf,len,pos,cols);
520 /* Note that the only control character currently permitted is tab */
521 if (len < buflen && (c == '\t' || c >= ' ')) {
522 if (len == pos && c >= ' ') {
527 if (plen+len < cols) {
528 /* Avoid a full update of the line in the
530 if (write(fd,&c,1) == -1) return -1;
532 refreshLine(fd,prompt,buf,len,pos,cols);
535 memmove(buf+pos+1,buf+pos,len-pos);
540 refreshLine(fd,prompt,buf,len,pos,cols);
544 case 21: /* Ctrl+u, delete the whole line. */
547 refreshLine(fd,prompt,buf,len,pos,cols);
549 case 11: /* Ctrl+k, delete from current to end of line. */
552 refreshLine(fd,prompt,buf,len,pos,cols);
554 case 1: /* Ctrl+a, go to the start of the line */
556 refreshLine(fd,prompt,buf,len,pos,cols);
558 case 5: /* ctrl+e, go to the end of the line */
560 refreshLine(fd,prompt,buf,len,pos,cols);
562 case 12: /* ctrl+l, clear screen */
563 linenoiseClearScreen();
564 refreshLine(fd,prompt,buf,len,pos,cols);
570 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
571 int fd = STDIN_FILENO;
578 if (!isatty(STDIN_FILENO)) {
579 if (fgets(buf, buflen, stdin) == NULL) return -1;
581 if (count && buf[count-1] == '\n') {
586 if (enableRawMode(fd) == -1) return -1;
587 count = linenoisePrompt(fd, buf, buflen, prompt);
594 char *linenoise(const char *prompt) {
595 char buf[LINENOISE_MAX_LINE];
598 if (isUnsupportedTerm()) {
603 if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
605 while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
611 count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
612 if (count == -1) return NULL;
617 /* Register a callback function to be called for tab-completion. */
618 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
619 completionCallback = fn;
622 void linenoiseAddCompletion(linenoiseCompletions *lc, char *str) {
623 size_t len = strlen(str);
624 char *copy = malloc(len+1);
625 memcpy(copy,str,len+1);
626 lc->cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
627 lc->cvec[lc->len++] = copy;
630 /* Using a circular buffer is smarter, but a bit more complex to handle. */
631 int linenoiseHistoryAdd(const char *line) {
634 if (history_max_len == 0) return 0;
635 if (history == NULL) {
636 history = malloc(sizeof(char*)*history_max_len);
637 if (history == NULL) return 0;
638 memset(history,0,(sizeof(char*)*history_max_len));
640 linecopy = strdup(line);
641 if (!linecopy) return 0;
642 if (history_len == history_max_len) {
644 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
647 history[history_len] = linecopy;
652 int linenoiseHistorySetMaxLen(int len) {
655 if (len < 1) return 0;
657 int tocopy = history_len;
659 new = malloc(sizeof(char*)*len);
660 if (new == NULL) return 0;
661 if (len < tocopy) tocopy = len;
662 memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
666 history_max_len = len;
667 if (history_len > history_max_len)
668 history_len = history_max_len;
672 /* Save the history in the specified file. On success 0 is returned
673 * otherwise -1 is returned. */
674 int linenoiseHistorySave(char *filename) {
675 FILE *fp = fopen(filename,"w");
678 if (fp == NULL) return -1;
679 for (j = 0; j < history_len; j++)
680 fprintf(fp,"%s\n",history[j]);
685 /* Load the history from the specified file. If the file does not exist
686 * zero is returned and no operation is performed.
688 * If the file exists and the operation succeeded 0 is returned, otherwise
689 * on error -1 is returned. */
690 int linenoiseHistoryLoad(char *filename) {
691 FILE *fp = fopen(filename,"r");
692 char buf[LINENOISE_MAX_LINE];
694 if (fp == NULL) return -1;
696 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
699 p = strchr(buf,'\r');
700 if (!p) p = strchr(buf,'\n');
702 linenoiseHistoryAdd(buf);