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 * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
12 * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
14 * All rights reserved.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions are met:
19 * * Redistributions of source code must retain the above copyright notice,
20 * this list of conditions and the following disclaimer.
21 * * Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
24 * * Neither the name of Redis nor the names of its contributors may be used
25 * to endorse or promote products derived from this software without
26 * specific prior written permission.
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
29 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
32 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
36 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38 * POSSIBILITY OF SUCH DAMAGE.
41 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
42 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
45 * - Switch to gets() if $TERM is something we can't support.
46 * - Filter bogus Ctrl+<char> combinations.
51 * - History search like Ctrl+r in readline?
53 * List of escape sequences used by this program, we do everything just
54 * with three sequences. In order to be so cheap we may have some
55 * flickering effect with some slow terminal, but the lesser sequences
56 * the more compatible.
58 * CHA (Cursor Horizontal Absolute)
60 * Effect: moves cursor to column n
64 * Effect: if n is 0 or missing, clear from cursor to end of line
65 * Effect: if n is 1, clear from beginning of line to cursor
66 * Effect: if n is 2, clear entire line
68 * CUF (CUrsor Forward)
70 * Effect: moves cursor forward of n chars
81 #include <sys/types.h>
82 #include <sys/ioctl.h>
84 #include "linenoise.h"
86 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
87 #define LINENOISE_MAX_LINE 4096
88 static char *unsupported_term[] = {"dumb","cons25",NULL};
89 static linenoiseCompletionCallback *completionCallback = NULL;
91 static struct termios orig_termios; /* in order to restore at exit */
92 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
93 static int atexit_registered = 0; /* register atexit just 1 time */
94 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
95 static int history_len = 0;
96 char **history = NULL;
98 static void linenoiseAtExit(void);
99 int linenoiseHistoryAdd(const char *line);
101 static int isUnsupportedTerm(void) {
102 char *term = getenv("TERM");
105 if (term == NULL) return 0;
106 for (j = 0; unsupported_term[j]; j++)
107 if (!strcasecmp(term,unsupported_term[j])) return 1;
111 static void freeHistory(void) {
115 for (j = 0; j < history_len; j++)
121 static int enableRawMode(int fd) {
124 if (!isatty(STDIN_FILENO)) goto fatal;
125 if (!atexit_registered) {
126 atexit(linenoiseAtExit);
127 atexit_registered = 1;
129 if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
131 raw = orig_termios; /* modify the original mode */
132 /* input modes: no break, no CR to NL, no parity check, no strip char,
133 * no start/stop output control. */
134 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
135 /* output modes - disable post processing */
136 raw.c_oflag &= ~(OPOST);
137 /* control modes - set 8 bit chars */
138 raw.c_cflag |= (CS8);
139 /* local modes - choing off, canonical off, no extended functions,
140 * no signal chars (^Z,^C) */
141 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
142 /* control chars - set return condition: min number of bytes and timer.
143 * We want read to return every single byte, without timeout. */
144 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
146 /* put terminal in raw mode after flushing */
147 if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
156 static void disableRawMode(int fd) {
157 /* Don't even check the return value as it's too late. */
158 if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1)
162 /* At exit we'll try to fix the terminal to the initial conditions. */
163 static void linenoiseAtExit(void) {
164 disableRawMode(STDIN_FILENO);
168 static int getColumns(void) {
171 if (ioctl(1, TIOCGWINSZ, &ws) == -1) return 80;
175 static void refreshLine(int fd, const char *prompt, char *buf, size_t len, size_t pos, size_t cols) {
177 size_t plen = strlen(prompt);
179 while((plen+pos) >= cols) {
184 while (plen+len > cols) {
188 /* Cursor to left edge */
189 snprintf(seq,64,"\x1b[0G");
190 if (write(fd,seq,strlen(seq)) == -1) return;
191 /* Write the prompt and the current buffer content */
192 if (write(fd,prompt,strlen(prompt)) == -1) return;
193 if (write(fd,buf,len) == -1) return;
195 snprintf(seq,64,"\x1b[0K");
196 if (write(fd,seq,strlen(seq)) == -1) return;
197 /* Move cursor to original position. */
198 snprintf(seq,64,"\x1b[0G\x1b[%dC", (int)(pos+plen));
199 if (write(fd,seq,strlen(seq)) == -1) return;
203 fprintf(stderr, "\x7");
207 static void freeCompletions(linenoiseCompletions *lc) {
209 for (i = 0; i < lc->len; i++)
211 if (lc->cvec != NULL)
215 static int completeLine(int fd, const char *prompt, char *buf, size_t buflen, size_t *len, size_t *pos, size_t cols) {
216 linenoiseCompletions lc = { 0, NULL };
220 completionCallback(buf,&lc);
224 size_t stop = 0, i = 0;
228 /* Show completion or original buffer */
230 clen = strlen(lc.cvec[i]);
231 refreshLine(fd,prompt,lc.cvec[i],clen,clen,cols);
233 refreshLine(fd,prompt,buf,*len,*pos,cols);
236 nread = read(fd,&c,1);
238 freeCompletions(&lc);
244 i = (i+1) % (lc.len+1);
245 if (i == lc.len) beep();
247 case 27: /* escape */
248 /* Re-show original buffer */
250 refreshLine(fd,prompt,buf,*len,*pos,cols);
255 /* Update buffer and return */
257 nwritten = snprintf(buf,buflen,"%s",lc.cvec[i]);
258 *len = *pos = nwritten;
266 freeCompletions(&lc);
267 return c; /* Return last read character */
270 static int linenoisePrompt(int fd, char *buf, size_t buflen, const char *prompt) {
271 size_t plen = strlen(prompt);
274 size_t cols = getColumns();
275 int history_index = 0;
278 buflen--; /* Make sure there is always space for the nulterm */
280 /* The latest history entry is always our current buffer, that
281 * initially is just an empty string. */
282 linenoiseHistoryAdd("");
284 if (write(fd,prompt,plen) == -1) return -1;
288 char seq[2], seq2[2];
290 nread = read(fd,&c,1);
291 if (nread <= 0) return len;
293 /* Only autocomplete when the callback is set. It returns < 0 when
294 * there was an error reading from fd. Otherwise it will return the
295 * character that should be handled next. */
296 if (c == 9 && completionCallback != NULL) {
297 c = completeLine(fd,prompt,buf,buflen,&len,&pos,cols);
298 /* Return on errors */
299 if (c < 0) return len;
300 /* Read next character when 0 */
301 if (c == 0) continue;
308 free(history[history_len]);
309 return (len == 0 && c == 4) ? -1 : (int)len;
313 case 127: /* backspace */
315 if (pos > 0 && len > 0) {
316 memmove(buf+pos-1,buf+pos,len-pos);
320 refreshLine(fd,prompt,buf,len,pos,cols);
323 case 20: /* ctrl-t */
324 if (pos > 0 && pos < len) {
325 int aux = buf[pos-1];
326 buf[pos-1] = buf[pos];
328 if (pos != len-1) pos++;
329 refreshLine(fd,prompt,buf,len,pos,cols);
336 case 16: /* ctrl-p */
339 case 14: /* ctrl-n */
343 case 27: /* escape sequence */
344 if (read(fd,seq,2) == -1) break;
345 if (seq[0] == 91 && seq[1] == 68) {
350 refreshLine(fd,prompt,buf,len,pos,cols);
352 } else if (seq[0] == 91 && seq[1] == 67) {
357 refreshLine(fd,prompt,buf,len,pos,cols);
359 } else if (seq[0] == 91 && (seq[1] == 65 || seq[1] == 66)) {
361 /* up and down arrow: history */
362 if (history_len > 1) {
363 /* Update the current history entry before to
364 * overwrite it with tne next one. */
365 free(history[history_len-1-history_index]);
366 history[history_len-1-history_index] = strdup(buf);
367 /* Show the new entry */
368 history_index += (seq[1] == 65) ? 1 : -1;
369 if (history_index < 0) {
372 } else if (history_index >= history_len) {
373 history_index = history_len-1;
376 strncpy(buf,history[history_len-1-history_index],buflen);
378 len = pos = strlen(buf);
379 refreshLine(fd,prompt,buf,len,pos,cols);
381 } else if (seq[0] == 91 && seq[1] > 48 && seq[1] < 55) {
382 /* extended escape */
383 if (read(fd,seq2,2) == -1) break;
384 if (seq[1] == 51 && seq2[0] == 126) {
386 if (len > 0 && pos < len) {
387 memmove(buf+pos,buf+pos+1,len-pos-1);
390 refreshLine(fd,prompt,buf,len,pos,cols);
402 if (plen+len < cols) {
403 /* Avoid a full update of the line in the
405 if (write(fd,&c,1) == -1) return -1;
407 refreshLine(fd,prompt,buf,len,pos,cols);
410 memmove(buf+pos+1,buf+pos,len-pos);
415 refreshLine(fd,prompt,buf,len,pos,cols);
419 case 21: /* Ctrl+u, delete the whole line. */
422 refreshLine(fd,prompt,buf,len,pos,cols);
424 case 11: /* Ctrl+k, delete from current to end of line. */
427 refreshLine(fd,prompt,buf,len,pos,cols);
429 case 1: /* Ctrl+a, go to the start of the line */
431 refreshLine(fd,prompt,buf,len,pos,cols);
433 case 5: /* ctrl+e, go to the end of the line */
435 refreshLine(fd,prompt,buf,len,pos,cols);
442 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
443 int fd = STDIN_FILENO;
450 if (!isatty(STDIN_FILENO)) {
451 if (fgets(buf, buflen, stdin) == NULL) return -1;
453 if (count && buf[count-1] == '\n') {
458 if (enableRawMode(fd) == -1) return -1;
459 count = linenoisePrompt(fd, buf, buflen, prompt);
466 char *linenoise(const char *prompt) {
467 char buf[LINENOISE_MAX_LINE];
470 if (isUnsupportedTerm()) {
475 if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
477 while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
483 count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
484 if (count == -1) return NULL;
489 /* Register a callback function to be called for tab-completion. */
490 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
491 completionCallback = fn;
494 void linenoiseAddCompletion(linenoiseCompletions *lc, char *str) {
495 size_t len = strlen(str);
496 char *copy = malloc(len+1);
497 memcpy(copy,str,len+1);
498 lc->cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
499 lc->cvec[lc->len++] = copy;
502 /* Using a circular buffer is smarter, but a bit more complex to handle. */
503 int linenoiseHistoryAdd(const char *line) {
506 if (history_max_len == 0) return 0;
507 if (history == NULL) {
508 history = malloc(sizeof(char*)*history_max_len);
509 if (history == NULL) return 0;
510 memset(history,0,(sizeof(char*)*history_max_len));
512 linecopy = strdup(line);
513 if (!linecopy) return 0;
514 if (history_len == history_max_len) {
516 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
519 history[history_len] = linecopy;
524 int linenoiseHistorySetMaxLen(int len) {
527 if (len < 1) return 0;
529 int tocopy = history_len;
531 new = malloc(sizeof(char*)*len);
532 if (new == NULL) return 0;
533 if (len < tocopy) tocopy = len;
534 memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
538 history_max_len = len;
539 if (history_len > history_max_len)
540 history_len = history_max_len;
544 /* Save the history in the specified file. On success 0 is returned
545 * otherwise -1 is returned. */
546 int linenoiseHistorySave(char *filename) {
547 FILE *fp = fopen(filename,"w");
550 if (fp == NULL) return -1;
551 for (j = 0; j < history_len; j++)
552 fprintf(fp,"%s\n",history[j]);
557 /* Load the history from the specified file. If the file does not exist
558 * zero is returned and no operation is performed.
560 * If the file exists and the operation succeeded 0 is returned, otherwise
561 * on error -1 is returned. */
562 int linenoiseHistoryLoad(char *filename) {
563 FILE *fp = fopen(filename,"r");
564 char buf[LINENOISE_MAX_LINE];
566 if (fp == NULL) return -1;
568 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
571 p = strchr(buf,'\r');
572 if (!p) p = strchr(buf,'\n');
574 linenoiseHistoryAdd(buf);