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;
325 free(history
[history_len
]);
326 return (len
== 0 && c
== 4) ? -1 : (int)len
;
330 case 127: /* backspace */
332 if (pos
> 0 && len
> 0) {
333 memmove(buf
+pos
-1,buf
+pos
,len
-pos
);
337 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
340 case 20: /* ctrl-t */
341 if (pos
> 0 && pos
< len
) {
342 int aux
= buf
[pos
-1];
343 buf
[pos
-1] = buf
[pos
];
345 if (pos
!= len
-1) pos
++;
346 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
353 case 16: /* ctrl-p */
356 case 14: /* ctrl-n */
360 case 27: /* escape sequence */
361 if (read(fd
,seq
,2) == -1) break;
362 if (seq
[0] == 91 && seq
[1] == 68) {
367 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
369 } else if (seq
[0] == 91 && seq
[1] == 67) {
374 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
376 } else if (seq
[0] == 91 && (seq
[1] == 65 || seq
[1] == 66)) {
378 /* up and down arrow: history */
379 if (history_len
> 1) {
380 /* Update the current history entry before to
381 * overwrite it with tne next one. */
382 free(history
[history_len
-1-history_index
]);
383 history
[history_len
-1-history_index
] = strdup(buf
);
384 /* Show the new entry */
385 history_index
+= (seq
[1] == 65) ? 1 : -1;
386 if (history_index
< 0) {
389 } else if (history_index
>= history_len
) {
390 history_index
= history_len
-1;
393 strncpy(buf
,history
[history_len
-1-history_index
],buflen
);
395 len
= pos
= strlen(buf
);
396 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
398 } else if (seq
[0] == 91 && seq
[1] > 48 && seq
[1] < 55) {
399 /* extended escape */
400 if (read(fd
,seq2
,2) == -1) break;
401 if (seq
[1] == 51 && seq2
[0] == 126) {
403 if (len
> 0 && pos
< len
) {
404 memmove(buf
+pos
,buf
+pos
+1,len
-pos
-1);
407 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
419 if (plen
+len
< cols
) {
420 /* Avoid a full update of the line in the
422 if (write(fd
,&c
,1) == -1) return -1;
424 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
427 memmove(buf
+pos
+1,buf
+pos
,len
-pos
);
432 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
436 case 21: /* Ctrl+u, delete the whole line. */
439 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
441 case 11: /* Ctrl+k, delete from current to end of line. */
444 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
446 case 1: /* Ctrl+a, go to the start of the line */
448 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
450 case 5: /* ctrl+e, go to the end of the line */
452 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
454 case 12: /* ctrl+l, clear screen */
455 linenoiseClearScreen();
456 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
462 static int linenoiseRaw(char *buf
, size_t buflen
, const char *prompt
) {
463 int fd
= STDIN_FILENO
;
470 if (!isatty(STDIN_FILENO
)) {
471 if (fgets(buf
, buflen
, stdin
) == NULL
) return -1;
473 if (count
&& buf
[count
-1] == '\n') {
478 if (enableRawMode(fd
) == -1) return -1;
479 count
= linenoisePrompt(fd
, buf
, buflen
, prompt
);
486 char *linenoise(const char *prompt
) {
487 char buf
[LINENOISE_MAX_LINE
];
490 if (isUnsupportedTerm()) {
495 if (fgets(buf
,LINENOISE_MAX_LINE
,stdin
) == NULL
) return NULL
;
497 while(len
&& (buf
[len
-1] == '\n' || buf
[len
-1] == '\r')) {
503 count
= linenoiseRaw(buf
,LINENOISE_MAX_LINE
,prompt
);
504 if (count
== -1) return NULL
;
509 /* Register a callback function to be called for tab-completion. */
510 void linenoiseSetCompletionCallback(linenoiseCompletionCallback
*fn
) {
511 completionCallback
= fn
;
514 void linenoiseAddCompletion(linenoiseCompletions
*lc
, char *str
) {
515 size_t len
= strlen(str
);
516 char *copy
= malloc(len
+1);
517 memcpy(copy
,str
,len
+1);
518 lc
->cvec
= realloc(lc
->cvec
,sizeof(char*)*(lc
->len
+1));
519 lc
->cvec
[lc
->len
++] = copy
;
522 /* Using a circular buffer is smarter, but a bit more complex to handle. */
523 int linenoiseHistoryAdd(const char *line
) {
526 if (history_max_len
== 0) return 0;
527 if (history
== NULL
) {
528 history
= malloc(sizeof(char*)*history_max_len
);
529 if (history
== NULL
) return 0;
530 memset(history
,0,(sizeof(char*)*history_max_len
));
532 linecopy
= strdup(line
);
533 if (!linecopy
) return 0;
534 if (history_len
== history_max_len
) {
536 memmove(history
,history
+1,sizeof(char*)*(history_max_len
-1));
539 history
[history_len
] = linecopy
;
544 int linenoiseHistorySetMaxLen(int len
) {
547 if (len
< 1) return 0;
549 int tocopy
= history_len
;
551 new = malloc(sizeof(char*)*len
);
552 if (new == NULL
) return 0;
553 if (len
< tocopy
) tocopy
= len
;
554 memcpy(new,history
+(history_max_len
-tocopy
), sizeof(char*)*tocopy
);
558 history_max_len
= len
;
559 if (history_len
> history_max_len
)
560 history_len
= history_max_len
;
564 /* Save the history in the specified file. On success 0 is returned
565 * otherwise -1 is returned. */
566 int linenoiseHistorySave(char *filename
) {
567 FILE *fp
= fopen(filename
,"w");
570 if (fp
== NULL
) return -1;
571 for (j
= 0; j
< history_len
; j
++)
572 fprintf(fp
,"%s\n",history
[j
]);
577 /* Load the history from the specified file. If the file does not exist
578 * zero is returned and no operation is performed.
580 * If the file exists and the operation succeeded 0 is returned, otherwise
581 * on error -1 is returned. */
582 int linenoiseHistoryLoad(char *filename
) {
583 FILE *fp
= fopen(filename
,"r");
584 char buf
[LINENOISE_MAX_LINE
];
586 if (fp
== NULL
) return -1;
588 while (fgets(buf
,LINENOISE_MAX_LINE
,fp
) != NULL
) {
591 p
= strchr(buf
,'\r');
592 if (!p
) p
= strchr(buf
,'\n');
594 linenoiseHistoryAdd(buf
);