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 * All rights reserved.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions are met:
17 * * Redistributions of source code must retain the above copyright notice,
18 * this list of conditions and the following disclaimer.
19 * * Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 * * Neither the name of Redis nor the names of its contributors may be used
23 * to endorse or promote products derived from this software without
24 * specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
27 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
30 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
39 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
40 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
43 * - Switch to gets() if $TERM is something we can't support.
44 * - Filter bogus Ctrl+<char> combinations.
49 * - History search like Ctrl+r in readline?
51 * List of escape sequences used by this program, we do everything just
52 * with three sequences. In order to be so cheap we may have some
53 * flickering effect with some slow terminal, but the lesser sequences
54 * the more compatible.
56 * CHA (Cursor Horizontal Absolute)
58 * Effect: moves cursor to column n
62 * Effect: if n is 0 or missing, clear from cursor to end of line
63 * Effect: if n is 1, clear from beginning of line to cursor
64 * Effect: if n is 2, clear entire line
66 * CUF (CUrsor Forward)
68 * Effect: moves cursor forward of n chars
79 #include <sys/types.h>
80 #include <sys/ioctl.h>
82 #include "linenoise.h"
84 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
85 #define LINENOISE_MAX_LINE 4096
86 static char *unsupported_term
[] = {"dumb","cons25",NULL
};
87 static linenoiseCompletionCallback
*completionCallback
= NULL
;
89 static struct termios orig_termios
; /* in order to restore at exit */
90 static int rawmode
= 0; /* for atexit() function to check if restore is needed*/
91 static int atexit_registered
= 0; /* register atexit just 1 time */
92 static int history_max_len
= LINENOISE_DEFAULT_HISTORY_MAX_LEN
;
93 static int history_len
= 0;
94 char **history
= NULL
;
96 static void linenoiseAtExit(void);
97 int linenoiseHistoryAdd(const char *line
);
99 static int isUnsupportedTerm(void) {
100 char *term
= getenv("TERM");
103 if (term
== NULL
) return 0;
104 for (j
= 0; unsupported_term
[j
]; j
++)
105 if (!strcasecmp(term
,unsupported_term
[j
])) return 1;
109 static void freeHistory(void) {
113 for (j
= 0; j
< history_len
; j
++)
119 static int enableRawMode(int fd
) {
122 if (!isatty(STDIN_FILENO
)) goto fatal
;
123 if (!atexit_registered
) {
124 atexit(linenoiseAtExit
);
125 atexit_registered
= 1;
127 if (tcgetattr(fd
,&orig_termios
) == -1) goto fatal
;
129 raw
= orig_termios
; /* modify the original mode */
130 /* input modes: no break, no CR to NL, no parity check, no strip char,
131 * no start/stop output control. */
132 raw
.c_iflag
&= ~(BRKINT
| ICRNL
| INPCK
| ISTRIP
| IXON
);
133 /* output modes - disable post processing */
134 raw
.c_oflag
&= ~(OPOST
);
135 /* control modes - set 8 bit chars */
136 raw
.c_cflag
|= (CS8
);
137 /* local modes - choing off, canonical off, no extended functions,
138 * no signal chars (^Z,^C) */
139 raw
.c_lflag
&= ~(ECHO
| ICANON
| IEXTEN
| ISIG
);
140 /* control chars - set return condition: min number of bytes and timer.
141 * We want read to return every single byte, without timeout. */
142 raw
.c_cc
[VMIN
] = 1; raw
.c_cc
[VTIME
] = 0; /* 1 byte, no timer */
144 /* put terminal in raw mode after flushing */
145 if (tcsetattr(fd
,TCSAFLUSH
,&raw
) < 0) goto fatal
;
154 static void disableRawMode(int fd
) {
155 /* Don't even check the return value as it's too late. */
156 if (rawmode
&& tcsetattr(fd
,TCSAFLUSH
,&orig_termios
) != -1)
160 /* At exit we'll try to fix the terminal to the initial conditions. */
161 static void linenoiseAtExit(void) {
162 disableRawMode(STDIN_FILENO
);
166 static int getColumns(void) {
169 if (ioctl(1, TIOCGWINSZ
, &ws
) == -1) return 80;
173 static void refreshLine(int fd
, const char *prompt
, char *buf
, size_t len
, size_t pos
, size_t cols
) {
175 size_t plen
= strlen(prompt
);
177 while((plen
+pos
) >= cols
) {
182 while (plen
+len
> cols
) {
186 /* Cursor to left edge */
187 snprintf(seq
,64,"\x1b[0G");
188 if (write(fd
,seq
,strlen(seq
)) == -1) return;
189 /* Write the prompt and the current buffer content */
190 if (write(fd
,prompt
,strlen(prompt
)) == -1) return;
191 if (write(fd
,buf
,len
) == -1) return;
193 snprintf(seq
,64,"\x1b[0K");
194 if (write(fd
,seq
,strlen(seq
)) == -1) return;
195 /* Move cursor to original position. */
196 snprintf(seq
,64,"\x1b[0G\x1b[%dC", (int)(pos
+plen
));
197 if (write(fd
,seq
,strlen(seq
)) == -1) return;
201 fprintf(stderr
, "\x7");
205 static void freeCompletions(linenoiseCompletions
*lc
) {
207 for (i
= 0; i
< lc
->len
; i
++)
209 if (lc
->cvec
!= NULL
)
213 static int completeLine(int fd
, const char *prompt
, char *buf
, size_t buflen
, size_t *len
, size_t *pos
, size_t cols
) {
214 linenoiseCompletions lc
= { 0, NULL
};
218 completionCallback(buf
,&lc
);
222 size_t stop
= 0, i
= 0;
226 /* Show completion or original buffer */
228 clen
= strlen(lc
.cvec
[i
]);
229 refreshLine(fd
,prompt
,lc
.cvec
[i
],clen
,clen
,cols
);
231 refreshLine(fd
,prompt
,buf
,*len
,*pos
,cols
);
234 nread
= read(fd
,&c
,1);
236 freeCompletions(&lc
);
242 i
= (i
+1) % (lc
.len
+1);
243 if (i
== lc
.len
) beep();
245 case 27: /* escape */
246 /* Re-show original buffer */
248 refreshLine(fd
,prompt
,buf
,*len
,*pos
,cols
);
253 /* Update buffer and return */
255 nwritten
= snprintf(buf
,buflen
,"%s",lc
.cvec
[i
]);
256 *len
= *pos
= nwritten
;
264 freeCompletions(&lc
);
265 return c
; /* Return last read character */
268 static int linenoisePrompt(int fd
, char *buf
, size_t buflen
, const char *prompt
) {
269 size_t plen
= strlen(prompt
);
272 size_t cols
= getColumns();
273 int history_index
= 0;
276 buflen
--; /* Make sure there is always space for the nulterm */
278 /* The latest history entry is always our current buffer, that
279 * initially is just an empty string. */
280 linenoiseHistoryAdd("");
282 if (write(fd
,prompt
,plen
) == -1) return -1;
286 char seq
[2], seq2
[2];
288 nread
= read(fd
,&c
,1);
289 if (nread
<= 0) return len
;
291 /* Only autocomplete when the callback is set. It returns < 0 when
292 * there was an error reading from fd. Otherwise it will return the
293 * character that should be handled next. */
294 if (c
== 9 && completionCallback
!= NULL
) {
295 c
= completeLine(fd
,prompt
,buf
,buflen
,&len
,&pos
,cols
);
296 /* Return on errors */
297 if (c
< 0) return len
;
298 /* Read next character when 0 */
299 if (c
== 0) continue;
306 free(history
[history_len
]);
307 return (len
== 0 && c
== 4) ? -1 : (int)len
;
311 case 127: /* backspace */
313 if (pos
> 0 && len
> 0) {
314 memmove(buf
+pos
-1,buf
+pos
,len
-pos
);
318 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
321 case 20: /* ctrl-t */
322 if (pos
> 0 && pos
< len
) {
323 int aux
= buf
[pos
-1];
324 buf
[pos
-1] = buf
[pos
];
326 if (pos
!= len
-1) pos
++;
327 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
334 case 16: /* ctrl-p */
337 case 14: /* ctrl-n */
341 case 27: /* escape sequence */
342 if (read(fd
,seq
,2) == -1) break;
343 if (seq
[0] == 91 && seq
[1] == 68) {
348 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
350 } else if (seq
[0] == 91 && seq
[1] == 67) {
355 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
357 } else if (seq
[0] == 91 && (seq
[1] == 65 || seq
[1] == 66)) {
359 /* up and down arrow: history */
360 if (history_len
> 1) {
361 /* Update the current history entry before to
362 * overwrite it with tne next one. */
363 free(history
[history_len
-1-history_index
]);
364 history
[history_len
-1-history_index
] = strdup(buf
);
365 /* Show the new entry */
366 history_index
+= (seq
[1] == 65) ? 1 : -1;
367 if (history_index
< 0) {
370 } else if (history_index
>= history_len
) {
371 history_index
= history_len
-1;
374 strncpy(buf
,history
[history_len
-1-history_index
],buflen
);
376 len
= pos
= strlen(buf
);
377 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
379 } else if (seq
[0] == 91 && seq
[1] > 48 && seq
[1] < 55) {
380 /* extended escape */
381 if (read(fd
,seq2
,2) == -1) break;
382 if (seq
[1] == 51 && seq2
[0] == 126) {
384 if (len
> 0 && pos
< len
) {
385 memmove(buf
+pos
,buf
+pos
+1,len
-pos
-1);
388 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
400 if (plen
+len
< cols
) {
401 /* Avoid a full update of the line in the
403 if (write(fd
,&c
,1) == -1) return -1;
405 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
408 memmove(buf
+pos
+1,buf
+pos
,len
-pos
);
413 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
417 case 21: /* Ctrl+u, delete the whole line. */
420 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
422 case 11: /* Ctrl+k, delete from current to end of line. */
425 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
427 case 1: /* Ctrl+a, go to the start of the line */
429 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
431 case 5: /* ctrl+e, go to the end of the line */
433 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
440 static int linenoiseRaw(char *buf
, size_t buflen
, const char *prompt
) {
441 int fd
= STDIN_FILENO
;
448 if (!isatty(STDIN_FILENO
)) {
449 if (fgets(buf
, buflen
, stdin
) == NULL
) return -1;
451 if (count
&& buf
[count
-1] == '\n') {
456 if (enableRawMode(fd
) == -1) return -1;
457 count
= linenoisePrompt(fd
, buf
, buflen
, prompt
);
464 char *linenoise(const char *prompt
) {
465 char buf
[LINENOISE_MAX_LINE
];
468 if (isUnsupportedTerm()) {
473 if (fgets(buf
,LINENOISE_MAX_LINE
,stdin
) == NULL
) return NULL
;
475 while(len
&& (buf
[len
-1] == '\n' || buf
[len
-1] == '\r')) {
481 count
= linenoiseRaw(buf
,LINENOISE_MAX_LINE
,prompt
);
482 if (count
== -1) return NULL
;
487 /* Register a callback function to be called for tab-completion. */
488 void linenoiseSetCompletionCallback(linenoiseCompletionCallback
*fn
) {
489 completionCallback
= fn
;
492 void linenoiseAddCompletion(linenoiseCompletions
*lc
, char *str
) {
493 size_t len
= strlen(str
);
494 char *copy
= malloc(len
+1);
495 memcpy(copy
,str
,len
+1);
496 lc
->cvec
= realloc(lc
->cvec
,sizeof(char*)*(lc
->len
+1));
497 lc
->cvec
[lc
->len
++] = copy
;
500 /* Using a circular buffer is smarter, but a bit more complex to handle. */
501 int linenoiseHistoryAdd(const char *line
) {
504 if (history_max_len
== 0) return 0;
505 if (history
== NULL
) {
506 history
= malloc(sizeof(char*)*history_max_len
);
507 if (history
== NULL
) return 0;
508 memset(history
,0,(sizeof(char*)*history_max_len
));
510 linecopy
= strdup(line
);
511 if (!linecopy
) return 0;
512 if (history_len
== history_max_len
) {
514 memmove(history
,history
+1,sizeof(char*)*(history_max_len
-1));
517 history
[history_len
] = linecopy
;
522 int linenoiseHistorySetMaxLen(int len
) {
525 if (len
< 1) return 0;
527 int tocopy
= history_len
;
529 new = malloc(sizeof(char*)*len
);
530 if (new == NULL
) return 0;
531 if (len
< tocopy
) tocopy
= len
;
532 memcpy(new,history
+(history_max_len
-tocopy
), sizeof(char*)*tocopy
);
536 history_max_len
= len
;
537 if (history_len
> history_max_len
)
538 history_len
= history_max_len
;
542 /* Save the history in the specified file. On success 0 is returned
543 * otherwise -1 is returned. */
544 int linenoiseHistorySave(char *filename
) {
545 FILE *fp
= fopen(filename
,"w");
548 if (fp
== NULL
) return -1;
549 for (j
= 0; j
< history_len
; j
++)
550 fprintf(fp
,"%s\n",history
[j
]);
555 /* Load the history from the specified file. If the file does not exist
556 * zero is returned and no operation is performed.
558 * If the file exists and the operation succeeded 0 is returned, otherwise
559 * on error -1 is returned. */
560 int linenoiseHistoryLoad(char *filename
) {
561 FILE *fp
= fopen(filename
,"r");
562 char buf
[LINENOISE_MAX_LINE
];
564 if (fp
== NULL
) return -1;
566 while (fgets(buf
,LINENOISE_MAX_LINE
,fp
) != NULL
) {
569 p
= strchr(buf
,'\r');
570 if (!p
) p
= strchr(buf
,'\n');
572 linenoiseHistoryAdd(buf
);