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 write(STDIN_FILENO
,"\x1b[H\x1b[2J",7);
285 static int linenoisePrompt(int fd
, char *buf
, size_t buflen
, const char *prompt
) {
286 size_t plen
= strlen(prompt
);
289 size_t cols
= getColumns();
290 int history_index
= 0;
293 buflen
--; /* Make sure there is always space for the nulterm */
295 /* The latest history entry is always our current buffer, that
296 * initially is just an empty string. */
297 linenoiseHistoryAdd("");
299 if (write(fd
,prompt
,plen
) == -1) return -1;
303 char seq
[2], seq2
[2];
305 nread
= read(fd
,&c
,1);
306 if (nread
<= 0) return len
;
308 /* Only autocomplete when the callback is set. It returns < 0 when
309 * there was an error reading from fd. Otherwise it will return the
310 * character that should be handled next. */
311 if (c
== 9 && completionCallback
!= NULL
) {
312 c
= completeLine(fd
,prompt
,buf
,buflen
,&len
,&pos
,cols
);
313 /* Return on errors */
314 if (c
< 0) return len
;
315 /* Read next character when 0 */
316 if (c
== 0) continue;
323 free(history
[history_len
]);
324 return (len
== 0 && c
== 4) ? -1 : (int)len
;
328 case 127: /* backspace */
330 if (pos
> 0 && len
> 0) {
331 memmove(buf
+pos
-1,buf
+pos
,len
-pos
);
335 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
338 case 20: /* ctrl-t */
339 if (pos
> 0 && pos
< len
) {
340 int aux
= buf
[pos
-1];
341 buf
[pos
-1] = buf
[pos
];
343 if (pos
!= len
-1) pos
++;
344 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
351 case 16: /* ctrl-p */
354 case 14: /* ctrl-n */
358 case 27: /* escape sequence */
359 if (read(fd
,seq
,2) == -1) break;
360 if (seq
[0] == 91 && seq
[1] == 68) {
365 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
367 } else if (seq
[0] == 91 && seq
[1] == 67) {
372 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
374 } else if (seq
[0] == 91 && (seq
[1] == 65 || seq
[1] == 66)) {
376 /* up and down arrow: history */
377 if (history_len
> 1) {
378 /* Update the current history entry before to
379 * overwrite it with tne next one. */
380 free(history
[history_len
-1-history_index
]);
381 history
[history_len
-1-history_index
] = strdup(buf
);
382 /* Show the new entry */
383 history_index
+= (seq
[1] == 65) ? 1 : -1;
384 if (history_index
< 0) {
387 } else if (history_index
>= history_len
) {
388 history_index
= history_len
-1;
391 strncpy(buf
,history
[history_len
-1-history_index
],buflen
);
393 len
= pos
= strlen(buf
);
394 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
396 } else if (seq
[0] == 91 && seq
[1] > 48 && seq
[1] < 55) {
397 /* extended escape */
398 if (read(fd
,seq2
,2) == -1) break;
399 if (seq
[1] == 51 && seq2
[0] == 126) {
401 if (len
> 0 && pos
< len
) {
402 memmove(buf
+pos
,buf
+pos
+1,len
-pos
-1);
405 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
417 if (plen
+len
< cols
) {
418 /* Avoid a full update of the line in the
420 if (write(fd
,&c
,1) == -1) return -1;
422 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
425 memmove(buf
+pos
+1,buf
+pos
,len
-pos
);
430 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
434 case 21: /* Ctrl+u, delete the whole line. */
437 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
439 case 11: /* Ctrl+k, delete from current to end of line. */
442 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
444 case 1: /* Ctrl+a, go to the start of the line */
446 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
448 case 5: /* ctrl+e, go to the end of the line */
450 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
452 case 12: /* ctrl+l, clear screen */
453 linenoiseClearScreen();
454 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
460 static int linenoiseRaw(char *buf
, size_t buflen
, const char *prompt
) {
461 int fd
= STDIN_FILENO
;
468 if (!isatty(STDIN_FILENO
)) {
469 if (fgets(buf
, buflen
, stdin
) == NULL
) return -1;
471 if (count
&& buf
[count
-1] == '\n') {
476 if (enableRawMode(fd
) == -1) return -1;
477 count
= linenoisePrompt(fd
, buf
, buflen
, prompt
);
484 char *linenoise(const char *prompt
) {
485 char buf
[LINENOISE_MAX_LINE
];
488 if (isUnsupportedTerm()) {
493 if (fgets(buf
,LINENOISE_MAX_LINE
,stdin
) == NULL
) return NULL
;
495 while(len
&& (buf
[len
-1] == '\n' || buf
[len
-1] == '\r')) {
501 count
= linenoiseRaw(buf
,LINENOISE_MAX_LINE
,prompt
);
502 if (count
== -1) return NULL
;
507 /* Register a callback function to be called for tab-completion. */
508 void linenoiseSetCompletionCallback(linenoiseCompletionCallback
*fn
) {
509 completionCallback
= fn
;
512 void linenoiseAddCompletion(linenoiseCompletions
*lc
, char *str
) {
513 size_t len
= strlen(str
);
514 char *copy
= malloc(len
+1);
515 memcpy(copy
,str
,len
+1);
516 lc
->cvec
= realloc(lc
->cvec
,sizeof(char*)*(lc
->len
+1));
517 lc
->cvec
[lc
->len
++] = copy
;
520 /* Using a circular buffer is smarter, but a bit more complex to handle. */
521 int linenoiseHistoryAdd(const char *line
) {
524 if (history_max_len
== 0) return 0;
525 if (history
== NULL
) {
526 history
= malloc(sizeof(char*)*history_max_len
);
527 if (history
== NULL
) return 0;
528 memset(history
,0,(sizeof(char*)*history_max_len
));
530 linecopy
= strdup(line
);
531 if (!linecopy
) return 0;
532 if (history_len
== history_max_len
) {
534 memmove(history
,history
+1,sizeof(char*)*(history_max_len
-1));
537 history
[history_len
] = linecopy
;
542 int linenoiseHistorySetMaxLen(int len
) {
545 if (len
< 1) return 0;
547 int tocopy
= history_len
;
549 new = malloc(sizeof(char*)*len
);
550 if (new == NULL
) return 0;
551 if (len
< tocopy
) tocopy
= len
;
552 memcpy(new,history
+(history_max_len
-tocopy
), sizeof(char*)*tocopy
);
556 history_max_len
= len
;
557 if (history_len
> history_max_len
)
558 history_len
= history_max_len
;
562 /* Save the history in the specified file. On success 0 is returned
563 * otherwise -1 is returned. */
564 int linenoiseHistorySave(char *filename
) {
565 FILE *fp
= fopen(filename
,"w");
568 if (fp
== NULL
) return -1;
569 for (j
= 0; j
< history_len
; j
++)
570 fprintf(fp
,"%s\n",history
[j
]);
575 /* Load the history from the specified file. If the file does not exist
576 * zero is returned and no operation is performed.
578 * If the file exists and the operation succeeded 0 is returned, otherwise
579 * on error -1 is returned. */
580 int linenoiseHistoryLoad(char *filename
) {
581 FILE *fp
= fopen(filename
,"r");
582 char buf
[LINENOISE_MAX_LINE
];
584 if (fp
== NULL
) return -1;
586 while (fgets(buf
,LINENOISE_MAX_LINE
,fp
) != NULL
) {
589 p
= strchr(buf
,'\r');
590 if (!p
) p
= strchr(buf
,'\n');
592 linenoiseHistoryAdd(buf
);