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
72 * The following are used to clear the screen: ESC [ H ESC [ 2 J
73 * This is actually composed of two sequences:
77 * Effect: moves the cursor to upper left corner
79 * ED2 (Clear entire screen)
81 * Effect: clear the whole screen
92 #include <sys/types.h>
93 #include <sys/ioctl.h>
95 #include "linenoise.h"
97 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
98 #define LINENOISE_MAX_LINE 4096
99 static char *unsupported_term[] = {"dumb","cons25",NULL};
100 static linenoiseCompletionCallback *completionCallback = NULL;
102 static struct termios orig_termios; /* in order to restore at exit */
103 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
104 static int atexit_registered = 0; /* register atexit just 1 time */
105 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
106 static int history_len = 0;
107 char **history = NULL;
109 static void linenoiseAtExit(void);
110 int linenoiseHistoryAdd(const char *line);
112 static int isUnsupportedTerm(void) {
113 char *term = getenv("TERM");
116 if (term == NULL) return 0;
117 for (j = 0; unsupported_term[j]; j++)
118 if (!strcasecmp(term,unsupported_term[j])) return 1;
122 static void freeHistory(void) {
126 for (j = 0; j < history_len; j++)
132 static int enableRawMode(int fd) {
135 if (!isatty(STDIN_FILENO)) goto fatal;
136 if (!atexit_registered) {
137 atexit(linenoiseAtExit);
138 atexit_registered = 1;
140 if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
142 raw = orig_termios; /* modify the original mode */
143 /* input modes: no break, no CR to NL, no parity check, no strip char,
144 * no start/stop output control. */
145 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
146 /* output modes - disable post processing */
147 raw.c_oflag &= ~(OPOST);
148 /* control modes - set 8 bit chars */
149 raw.c_cflag |= (CS8);
150 /* local modes - choing off, canonical off, no extended functions,
151 * no signal chars (^Z,^C) */
152 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
153 /* control chars - set return condition: min number of bytes and timer.
154 * We want read to return every single byte, without timeout. */
155 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
157 /* put terminal in raw mode after flushing */
158 if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
167 static void disableRawMode(int fd) {
168 /* Don't even check the return value as it's too late. */
169 if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1)
173 /* At exit we'll try to fix the terminal to the initial conditions. */
174 static void linenoiseAtExit(void) {
175 disableRawMode(STDIN_FILENO);
179 static int getColumns(void) {
182 if (ioctl(1, TIOCGWINSZ, &ws) == -1) return 80;
186 static void refreshLine(int fd, const char *prompt, char *buf, size_t len, size_t pos, size_t cols) {
188 size_t plen = strlen(prompt);
190 while((plen+pos) >= cols) {
195 while (plen+len > cols) {
199 /* Cursor to left edge */
200 snprintf(seq,64,"\x1b[0G");
201 if (write(fd,seq,strlen(seq)) == -1) return;
202 /* Write the prompt and the current buffer content */
203 if (write(fd,prompt,strlen(prompt)) == -1) return;
204 if (write(fd,buf,len) == -1) return;
206 snprintf(seq,64,"\x1b[0K");
207 if (write(fd,seq,strlen(seq)) == -1) return;
208 /* Move cursor to original position. */
209 snprintf(seq,64,"\x1b[0G\x1b[%dC", (int)(pos+plen));
210 if (write(fd,seq,strlen(seq)) == -1) return;
214 fprintf(stderr, "\x7");
218 static void freeCompletions(linenoiseCompletions *lc) {
220 for (i = 0; i < lc->len; i++)
222 if (lc->cvec != NULL)
226 static int completeLine(int fd, const char *prompt, char *buf, size_t buflen, size_t *len, size_t *pos, size_t cols) {
227 linenoiseCompletions lc = { 0, NULL };
231 completionCallback(buf,&lc);
235 size_t stop = 0, i = 0;
239 /* Show completion or original buffer */
241 clen = strlen(lc.cvec[i]);
242 refreshLine(fd,prompt,lc.cvec[i],clen,clen,cols);
244 refreshLine(fd,prompt,buf,*len,*pos,cols);
247 nread = read(fd,&c,1);
249 freeCompletions(&lc);
255 i = (i+1) % (lc.len+1);
256 if (i == lc.len) beep();
258 case 27: /* escape */
259 /* Re-show original buffer */
261 refreshLine(fd,prompt,buf,*len,*pos,cols);
266 /* Update buffer and return */
268 nwritten = snprintf(buf,buflen,"%s",lc.cvec[i]);
269 *len = *pos = nwritten;
277 freeCompletions(&lc);
278 return c; /* Return last read character */
281 void linenoiseClearScreen(void) {
282 if (write(STDIN_FILENO,"\x1b[H\x1b[2J",7) <= 0) {
283 /* nothing to do, just to avoid warning. */
287 static int linenoisePrompt(int fd, char *buf, size_t buflen, const char *prompt) {
288 size_t plen = strlen(prompt);
291 size_t cols = getColumns();
292 int history_index = 0;
295 buflen--; /* Make sure there is always space for the nulterm */
297 /* The latest history entry is always our current buffer, that
298 * initially is just an empty string. */
299 linenoiseHistoryAdd("");
301 if (write(fd,prompt,plen) == -1) return -1;
305 char seq[2], seq2[2];
307 nread = read(fd,&c,1);
308 if (nread <= 0) return len;
310 /* Only autocomplete when the callback is set. It returns < 0 when
311 * there was an error reading from fd. Otherwise it will return the
312 * character that should be handled next. */
313 if (c == 9 && completionCallback != NULL) {
314 c = completeLine(fd,prompt,buf,buflen,&len,&pos,cols);
315 /* Return on errors */
316 if (c < 0) return len;
317 /* Read next character when 0 */
318 if (c == 0) continue;
324 free(history[history_len]);
329 case 127: /* backspace */
331 if (pos > 0 && len > 0) {
332 memmove(buf+pos-1,buf+pos,len-pos);
336 refreshLine(fd,prompt,buf,len,pos,cols);
339 case 4: /* ctrl-d, remove char at right of cursor */
340 if (len > 1 && pos < (len-1)) {
341 memmove(buf+pos,buf+pos+1,len-pos);
344 refreshLine(fd,prompt,buf,len,pos,cols);
345 } else if (len == 0) {
347 free(history[history_len]);
351 case 20: /* ctrl-t */
352 if (pos > 0 && pos < len) {
353 int aux = buf[pos-1];
354 buf[pos-1] = buf[pos];
356 if (pos != len-1) pos++;
357 refreshLine(fd,prompt,buf,len,pos,cols);
364 case 16: /* ctrl-p */
367 case 14: /* ctrl-n */
371 case 27: /* escape sequence */
372 if (read(fd,seq,2) == -1) break;
373 if (seq[0] == 91 && seq[1] == 68) {
378 refreshLine(fd,prompt,buf,len,pos,cols);
380 } else if (seq[0] == 91 && seq[1] == 67) {
385 refreshLine(fd,prompt,buf,len,pos,cols);
387 } else if (seq[0] == 91 && (seq[1] == 65 || seq[1] == 66)) {
389 /* up and down arrow: history */
390 if (history_len > 1) {
391 /* Update the current history entry before to
392 * overwrite it with tne next one. */
393 free(history[history_len-1-history_index]);
394 history[history_len-1-history_index] = strdup(buf);
395 /* Show the new entry */
396 history_index += (seq[1] == 65) ? 1 : -1;
397 if (history_index < 0) {
400 } else if (history_index >= history_len) {
401 history_index = history_len-1;
404 strncpy(buf,history[history_len-1-history_index],buflen);
406 len = pos = strlen(buf);
407 refreshLine(fd,prompt,buf,len,pos,cols);
409 } else if (seq[0] == 91 && seq[1] > 48 && seq[1] < 55) {
410 /* extended escape */
411 if (read(fd,seq2,2) == -1) break;
412 if (seq[1] == 51 && seq2[0] == 126) {
414 if (len > 0 && pos < len) {
415 memmove(buf+pos,buf+pos+1,len-pos-1);
418 refreshLine(fd,prompt,buf,len,pos,cols);
430 if (plen+len < cols) {
431 /* Avoid a full update of the line in the
433 if (write(fd,&c,1) == -1) return -1;
435 refreshLine(fd,prompt,buf,len,pos,cols);
438 memmove(buf+pos+1,buf+pos,len-pos);
443 refreshLine(fd,prompt,buf,len,pos,cols);
447 case 21: /* Ctrl+u, delete the whole line. */
450 refreshLine(fd,prompt,buf,len,pos,cols);
452 case 11: /* Ctrl+k, delete from current to end of line. */
455 refreshLine(fd,prompt,buf,len,pos,cols);
457 case 1: /* Ctrl+a, go to the start of the line */
459 refreshLine(fd,prompt,buf,len,pos,cols);
461 case 5: /* ctrl+e, go to the end of the line */
463 refreshLine(fd,prompt,buf,len,pos,cols);
465 case 12: /* ctrl+l, clear screen */
466 linenoiseClearScreen();
467 refreshLine(fd,prompt,buf,len,pos,cols);
473 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
474 int fd = STDIN_FILENO;
481 if (!isatty(STDIN_FILENO)) {
482 if (fgets(buf, buflen, stdin) == NULL) return -1;
484 if (count && buf[count-1] == '\n') {
489 if (enableRawMode(fd) == -1) return -1;
490 count = linenoisePrompt(fd, buf, buflen, prompt);
497 char *linenoise(const char *prompt) {
498 char buf[LINENOISE_MAX_LINE];
501 if (isUnsupportedTerm()) {
506 if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
508 while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
514 count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
515 if (count == -1) return NULL;
520 /* Register a callback function to be called for tab-completion. */
521 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
522 completionCallback = fn;
525 void linenoiseAddCompletion(linenoiseCompletions *lc, char *str) {
526 size_t len = strlen(str);
527 char *copy = malloc(len+1);
528 memcpy(copy,str,len+1);
529 lc->cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
530 lc->cvec[lc->len++] = copy;
533 /* Using a circular buffer is smarter, but a bit more complex to handle. */
534 int linenoiseHistoryAdd(const char *line) {
537 if (history_max_len == 0) return 0;
538 if (history == NULL) {
539 history = malloc(sizeof(char*)*history_max_len);
540 if (history == NULL) return 0;
541 memset(history,0,(sizeof(char*)*history_max_len));
543 linecopy = strdup(line);
544 if (!linecopy) return 0;
545 if (history_len == history_max_len) {
547 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
550 history[history_len] = linecopy;
555 int linenoiseHistorySetMaxLen(int len) {
558 if (len < 1) return 0;
560 int tocopy = history_len;
562 new = malloc(sizeof(char*)*len);
563 if (new == NULL) return 0;
564 if (len < tocopy) tocopy = len;
565 memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
569 history_max_len = len;
570 if (history_len > history_max_len)
571 history_len = history_max_len;
575 /* Save the history in the specified file. On success 0 is returned
576 * otherwise -1 is returned. */
577 int linenoiseHistorySave(char *filename) {
578 FILE *fp = fopen(filename,"w");
581 if (fp == NULL) return -1;
582 for (j = 0; j < history_len; j++)
583 fprintf(fp,"%s\n",history[j]);
588 /* Load the history from the specified file. If the file does not exist
589 * zero is returned and no operation is performed.
591 * If the file exists and the operation succeeded 0 is returned, otherwise
592 * on error -1 is returned. */
593 int linenoiseHistoryLoad(char *filename) {
594 FILE *fp = fopen(filename,"r");
595 char buf[LINENOISE_MAX_LINE];
597 if (fp == NULL) return -1;
599 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
602 p = strchr(buf,'\r');
603 if (!p) p = strchr(buf,'\n');
605 linenoiseHistoryAdd(buf);