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.
49 * - Filter bogus Ctrl+<char> combinations.
54 * - History search like Ctrl+r in readline?
56 * List of escape sequences used by this program, we do everything just
57 * with three sequences. In order to be so cheap we may have some
58 * flickering effect with some slow terminal, but the lesser sequences
59 * the more compatible.
61 * CHA (Cursor Horizontal Absolute)
63 * Effect: moves cursor to column n
67 * Effect: if n is 0 or missing, clear from cursor to end of line
68 * Effect: if n is 1, clear from beginning of line to cursor
69 * Effect: if n is 2, clear entire line
71 * CUF (CUrsor Forward)
73 * Effect: moves cursor forward of n chars
75 * The following are used to clear the screen: ESC [ H ESC [ 2 J
76 * This is actually composed of two sequences:
80 * Effect: moves the cursor to upper left corner
82 * ED2 (Clear entire screen)
84 * Effect: clear the whole screen
95 #include <sys/types.h>
96 #include <sys/ioctl.h>
98 #include "linenoise.h"
100 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
101 #define LINENOISE_MAX_LINE 4096
102 static char *unsupported_term[] = {"dumb","cons25",NULL};
103 static linenoiseCompletionCallback *completionCallback = NULL;
105 static struct termios orig_termios; /* in order to restore at exit */
106 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
107 static int atexit_registered = 0; /* register atexit just 1 time */
108 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
109 static int history_len = 0;
110 char **history = NULL;
112 static void linenoiseAtExit(void);
113 int linenoiseHistoryAdd(const char *line);
115 static int isUnsupportedTerm(void) {
116 char *term = getenv("TERM");
119 if (term == NULL) return 0;
120 for (j = 0; unsupported_term[j]; j++)
121 if (!strcasecmp(term,unsupported_term[j])) return 1;
125 static void freeHistory(void) {
129 for (j = 0; j < history_len; j++)
135 static int enableRawMode(int fd) {
138 if (!isatty(STDIN_FILENO)) goto fatal;
139 if (!atexit_registered) {
140 atexit(linenoiseAtExit);
141 atexit_registered = 1;
143 if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
145 raw = orig_termios; /* modify the original mode */
146 /* input modes: no break, no CR to NL, no parity check, no strip char,
147 * no start/stop output control. */
148 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
149 /* output modes - disable post processing */
150 raw.c_oflag &= ~(OPOST);
151 /* control modes - set 8 bit chars */
152 raw.c_cflag |= (CS8);
153 /* local modes - choing off, canonical off, no extended functions,
154 * no signal chars (^Z,^C) */
155 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
156 /* control chars - set return condition: min number of bytes and timer.
157 * We want read to return every single byte, without timeout. */
158 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
160 /* put terminal in raw mode after flushing */
161 if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
170 static void disableRawMode(int fd) {
171 /* Don't even check the return value as it's too late. */
172 if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1)
176 /* At exit we'll try to fix the terminal to the initial conditions. */
177 static void linenoiseAtExit(void) {
178 disableRawMode(STDIN_FILENO);
182 static int getColumns(void) {
185 if (ioctl(1, TIOCGWINSZ, &ws) == -1) return 80;
189 static void refreshLine(int fd, const char *prompt, char *buf, size_t len, size_t pos, size_t cols) {
191 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 if (write(fd,buf,len) == -1) return;
209 snprintf(seq,64,"\x1b[0K");
210 if (write(fd,seq,strlen(seq)) == -1) return;
211 /* Move cursor to original position. */
212 snprintf(seq,64,"\x1b[0G\x1b[%dC", (int)(pos+plen));
213 if (write(fd,seq,strlen(seq)) == -1) return;
217 fprintf(stderr, "\x7");
221 static void freeCompletions(linenoiseCompletions *lc) {
223 for (i = 0; i < lc->len; i++)
225 if (lc->cvec != NULL)
229 static int completeLine(int fd, const char *prompt, char *buf, size_t buflen, size_t *len, size_t *pos, size_t cols) {
230 linenoiseCompletions lc = { 0, NULL };
234 completionCallback(buf,&lc);
238 size_t stop = 0, i = 0;
242 /* Show completion or original buffer */
244 clen = strlen(lc.cvec[i]);
245 refreshLine(fd,prompt,lc.cvec[i],clen,clen,cols);
247 refreshLine(fd,prompt,buf,*len,*pos,cols);
250 nread = read(fd,&c,1);
252 freeCompletions(&lc);
258 i = (i+1) % (lc.len+1);
259 if (i == lc.len) beep();
261 case 27: /* escape */
262 /* Re-show original buffer */
264 refreshLine(fd,prompt,buf,*len,*pos,cols);
269 /* Update buffer and return */
271 nwritten = snprintf(buf,buflen,"%s",lc.cvec[i]);
272 *len = *pos = nwritten;
280 freeCompletions(&lc);
281 return c; /* Return last read character */
284 void linenoiseClearScreen(void) {
285 if (write(STDIN_FILENO,"\x1b[H\x1b[2J",7) <= 0) {
286 /* nothing to do, just to avoid warning. */
290 static int linenoisePrompt(int fd, char *buf, size_t buflen, const char *prompt) {
291 size_t plen = strlen(prompt);
294 size_t cols = getColumns();
295 int history_index = 0;
298 buflen--; /* Make sure there is always space for the nulterm */
300 /* The latest history entry is always our current buffer, that
301 * initially is just an empty string. */
302 linenoiseHistoryAdd("");
304 if (write(fd,prompt,plen) == -1) return -1;
308 char seq[2], seq2[2];
310 nread = read(fd,&c,1);
311 if (nread <= 0) return len;
313 /* Only autocomplete when the callback is set. It returns < 0 when
314 * there was an error reading from fd. Otherwise it will return the
315 * character that should be handled next. */
316 if (c == 9 && completionCallback != NULL) {
317 c = completeLine(fd,prompt,buf,buflen,&len,&pos,cols);
318 /* Return on errors */
319 if (c < 0) return len;
320 /* Read next character when 0 */
321 if (c == 0) continue;
327 free(history[history_len]);
332 case 127: /* backspace */
334 if (pos > 0 && len > 0) {
335 memmove(buf+pos-1,buf+pos,len-pos);
339 refreshLine(fd,prompt,buf,len,pos,cols);
342 case 4: /* ctrl-d, remove char at right of cursor */
343 if (len > 1 && pos < (len-1)) {
344 memmove(buf+pos,buf+pos+1,len-pos);
347 refreshLine(fd,prompt,buf,len,pos,cols);
348 } else if (len == 0) {
350 free(history[history_len]);
354 case 20: /* ctrl-t */
355 if (pos > 0 && pos < len) {
356 int aux = buf[pos-1];
357 buf[pos-1] = buf[pos];
359 if (pos != len-1) pos++;
360 refreshLine(fd,prompt,buf,len,pos,cols);
367 case 16: /* ctrl-p */
370 case 14: /* ctrl-n */
374 case 27: /* escape sequence */
375 if (read(fd,seq,2) == -1) break;
376 if (seq[0] == 91 && seq[1] == 68) {
381 refreshLine(fd,prompt,buf,len,pos,cols);
383 } else if (seq[0] == 91 && seq[1] == 67) {
388 refreshLine(fd,prompt,buf,len,pos,cols);
390 } else if (seq[0] == 91 && (seq[1] == 65 || seq[1] == 66)) {
392 /* up and down arrow: history */
393 if (history_len > 1) {
394 /* Update the current history entry before to
395 * overwrite it with tne next one. */
396 free(history[history_len-1-history_index]);
397 history[history_len-1-history_index] = strdup(buf);
398 /* Show the new entry */
399 history_index += (seq[1] == 65) ? 1 : -1;
400 if (history_index < 0) {
403 } else if (history_index >= history_len) {
404 history_index = history_len-1;
407 strncpy(buf,history[history_len-1-history_index],buflen);
409 len = pos = strlen(buf);
410 refreshLine(fd,prompt,buf,len,pos,cols);
412 } else if (seq[0] == 91 && seq[1] > 48 && seq[1] < 55) {
413 /* extended escape */
414 if (read(fd,seq2,2) == -1) break;
415 if (seq[1] == 51 && seq2[0] == 126) {
417 if (len > 0 && pos < len) {
418 memmove(buf+pos,buf+pos+1,len-pos-1);
421 refreshLine(fd,prompt,buf,len,pos,cols);
433 if (plen+len < cols) {
434 /* Avoid a full update of the line in the
436 if (write(fd,&c,1) == -1) return -1;
438 refreshLine(fd,prompt,buf,len,pos,cols);
441 memmove(buf+pos+1,buf+pos,len-pos);
446 refreshLine(fd,prompt,buf,len,pos,cols);
450 case 21: /* Ctrl+u, delete the whole line. */
453 refreshLine(fd,prompt,buf,len,pos,cols);
455 case 11: /* Ctrl+k, delete from current to end of line. */
458 refreshLine(fd,prompt,buf,len,pos,cols);
460 case 1: /* Ctrl+a, go to the start of the line */
462 refreshLine(fd,prompt,buf,len,pos,cols);
464 case 5: /* ctrl+e, go to the end of the line */
466 refreshLine(fd,prompt,buf,len,pos,cols);
468 case 12: /* ctrl+l, clear screen */
469 linenoiseClearScreen();
470 refreshLine(fd,prompt,buf,len,pos,cols);
476 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
477 int fd = STDIN_FILENO;
484 if (!isatty(STDIN_FILENO)) {
485 if (fgets(buf, buflen, stdin) == NULL) return -1;
487 if (count && buf[count-1] == '\n') {
492 if (enableRawMode(fd) == -1) return -1;
493 count = linenoisePrompt(fd, buf, buflen, prompt);
500 char *linenoise(const char *prompt) {
501 char buf[LINENOISE_MAX_LINE];
504 if (isUnsupportedTerm()) {
509 if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
511 while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
517 count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
518 if (count == -1) return NULL;
523 /* Register a callback function to be called for tab-completion. */
524 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
525 completionCallback = fn;
528 void linenoiseAddCompletion(linenoiseCompletions *lc, char *str) {
529 size_t len = strlen(str);
530 char *copy = malloc(len+1);
531 memcpy(copy,str,len+1);
532 lc->cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
533 lc->cvec[lc->len++] = copy;
536 /* Using a circular buffer is smarter, but a bit more complex to handle. */
537 int linenoiseHistoryAdd(const char *line) {
540 if (history_max_len == 0) return 0;
541 if (history == NULL) {
542 history = malloc(sizeof(char*)*history_max_len);
543 if (history == NULL) return 0;
544 memset(history,0,(sizeof(char*)*history_max_len));
546 linecopy = strdup(line);
547 if (!linecopy) return 0;
548 if (history_len == history_max_len) {
550 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
553 history[history_len] = linecopy;
558 int linenoiseHistorySetMaxLen(int len) {
561 if (len < 1) return 0;
563 int tocopy = history_len;
565 new = malloc(sizeof(char*)*len);
566 if (new == NULL) return 0;
567 if (len < tocopy) tocopy = len;
568 memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
572 history_max_len = len;
573 if (history_len > history_max_len)
574 history_len = history_max_len;
578 /* Save the history in the specified file. On success 0 is returned
579 * otherwise -1 is returned. */
580 int linenoiseHistorySave(char *filename) {
581 FILE *fp = fopen(filename,"w");
584 if (fp == NULL) return -1;
585 for (j = 0; j < history_len; j++)
586 fprintf(fp,"%s\n",history[j]);
591 /* Load the history from the specified file. If the file does not exist
592 * zero is returned and no operation is performed.
594 * If the file exists and the operation succeeded 0 is returned, otherwise
595 * on error -1 is returned. */
596 int linenoiseHistoryLoad(char *filename) {
597 FILE *fp = fopen(filename,"r");
598 char buf[LINENOISE_MAX_LINE];
600 if (fp == NULL) return -1;
602 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
605 p = strchr(buf,'\r');
606 if (!p) p = strchr(buf,'\n');
608 linenoiseHistoryAdd(buf);