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 * ------------------------------------------------------------------------
13 * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
14 * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
16 * All rights reserved.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
22 * * Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
25 * * Redistributions in binary form must reproduce the above copyright
26 * notice, this list of conditions and the following disclaimer in the
27 * documentation and/or other materials provided with the distribution.
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41 * ------------------------------------------------------------------------
44 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
45 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
48 * - Switch to gets() if $TERM is something we can't support.
49 * - Filter bogus Ctrl+<char> combinations.
54 * - History search like Ctrl+r in readline?
56 * List of escape sequences used by this program, we do everything just
57 * with three sequences. In order to be so cheap we may have some
58 * flickering effect with some slow terminal, but the lesser sequences
59 * the more compatible.
61 * CHA (Cursor Horizontal Absolute)
63 * Effect: moves cursor to column n
67 * Effect: if n is 0 or missing, clear from cursor to end of line
68 * Effect: if n is 1, clear from beginning of line to cursor
69 * Effect: if n is 2, clear entire line
71 * CUF (CUrsor Forward)
73 * Effect: moves cursor forward of n chars
75 * The following are used to clear the screen: ESC [ H ESC [ 2 J
76 * This is actually composed of two sequences:
80 * Effect: moves the cursor to upper left corner
82 * ED2 (Clear entire screen)
84 * Effect: clear the whole screen
95 #include <sys/types.h>
96 #include <sys/ioctl.h>
98 #include "linenoise.h"
100 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
101 #define LINENOISE_MAX_LINE 4096
102 static char *unsupported_term
[] = {"dumb","cons25",NULL
};
103 static linenoiseCompletionCallback
*completionCallback
= NULL
;
105 static struct termios orig_termios
; /* in order to restore at exit */
106 static int rawmode
= 0; /* for atexit() function to check if restore is needed*/
107 static int atexit_registered
= 0; /* register atexit just 1 time */
108 static int history_max_len
= LINENOISE_DEFAULT_HISTORY_MAX_LEN
;
109 static int history_len
= 0;
110 char **history
= NULL
;
112 static void linenoiseAtExit(void);
113 int linenoiseHistoryAdd(const char *line
);
115 static int isUnsupportedTerm(void) {
116 char *term
= getenv("TERM");
119 if (term
== NULL
) return 0;
120 for (j
= 0; unsupported_term
[j
]; j
++)
121 if (!strcasecmp(term
,unsupported_term
[j
])) return 1;
125 static void freeHistory(void) {
129 for (j
= 0; j
< history_len
; j
++)
135 static int enableRawMode(int fd
) {
138 if (!isatty(STDIN_FILENO
)) goto fatal
;
139 if (!atexit_registered
) {
140 atexit(linenoiseAtExit
);
141 atexit_registered
= 1;
143 if (tcgetattr(fd
,&orig_termios
) == -1) goto fatal
;
145 raw
= orig_termios
; /* modify the original mode */
146 /* input modes: no break, no CR to NL, no parity check, no strip char,
147 * no start/stop output control. */
148 raw
.c_iflag
&= ~(BRKINT
| ICRNL
| INPCK
| ISTRIP
| IXON
);
149 /* output modes - disable post processing */
150 raw
.c_oflag
&= ~(OPOST
);
151 /* control modes - set 8 bit chars */
152 raw
.c_cflag
|= (CS8
);
153 /* local modes - choing off, canonical off, no extended functions,
154 * no signal chars (^Z,^C) */
155 raw
.c_lflag
&= ~(ECHO
| ICANON
| IEXTEN
| ISIG
);
156 /* control chars - set return condition: min number of bytes and timer.
157 * We want read to return every single byte, without timeout. */
158 raw
.c_cc
[VMIN
] = 1; raw
.c_cc
[VTIME
] = 0; /* 1 byte, no timer */
160 /* put terminal in raw mode after flushing */
161 if (tcsetattr(fd
,TCSAFLUSH
,&raw
) < 0) goto fatal
;
170 static void disableRawMode(int fd
) {
171 /* Don't even check the return value as it's too late. */
172 if (rawmode
&& tcsetattr(fd
,TCSAFLUSH
,&orig_termios
) != -1)
176 /* At exit we'll try to fix the terminal to the initial conditions. */
177 static void linenoiseAtExit(void) {
178 disableRawMode(STDIN_FILENO
);
182 static int getColumns(void) {
185 if (ioctl(1, TIOCGWINSZ
, &ws
) == -1) return 80;
189 static void refreshLine(int fd
, const char *prompt
, char *buf
, size_t len
, size_t pos
, size_t cols
) {
191 size_t plen
= strlen(prompt
);
193 while((plen
+pos
) >= cols
) {
198 while (plen
+len
> cols
) {
202 /* Cursor to left edge */
203 snprintf(seq
,64,"\x1b[0G");
204 if (write(fd
,seq
,strlen(seq
)) == -1) return;
205 /* Write the prompt and the current buffer content */
206 if (write(fd
,prompt
,strlen(prompt
)) == -1) return;
207 if (write(fd
,buf
,len
) == -1) return;
209 snprintf(seq
,64,"\x1b[0K");
210 if (write(fd
,seq
,strlen(seq
)) == -1) return;
211 /* Move cursor to original position. */
212 snprintf(seq
,64,"\x1b[0G\x1b[%dC", (int)(pos
+plen
));
213 if (write(fd
,seq
,strlen(seq
)) == -1) return;
217 fprintf(stderr
, "\x7");
221 static void freeCompletions(linenoiseCompletions
*lc
) {
223 for (i
= 0; i
< lc
->len
; i
++)
225 if (lc
->cvec
!= NULL
)
229 static int completeLine(int fd
, const char *prompt
, char *buf
, size_t buflen
, size_t *len
, size_t *pos
, size_t cols
) {
230 linenoiseCompletions lc
= { 0, NULL
};
234 completionCallback(buf
,&lc
);
238 size_t stop
= 0, i
= 0;
242 /* Show completion or original buffer */
244 clen
= strlen(lc
.cvec
[i
]);
245 refreshLine(fd
,prompt
,lc
.cvec
[i
],clen
,clen
,cols
);
247 refreshLine(fd
,prompt
,buf
,*len
,*pos
,cols
);
250 nread
= read(fd
,&c
,1);
252 freeCompletions(&lc
);
258 i
= (i
+1) % (lc
.len
+1);
259 if (i
== lc
.len
) beep();
261 case 27: /* escape */
262 /* Re-show original buffer */
264 refreshLine(fd
,prompt
,buf
,*len
,*pos
,cols
);
269 /* Update buffer and return */
271 nwritten
= snprintf(buf
,buflen
,"%s",lc
.cvec
[i
]);
272 *len
= *pos
= nwritten
;
280 freeCompletions(&lc
);
281 return c
; /* Return last read character */
284 void linenoiseClearScreen(void) {
285 if (write(STDIN_FILENO
,"\x1b[H\x1b[2J",7) <= 0) {
286 /* nothing to do, just to avoid warning. */
290 static int linenoisePrompt(int fd
, char *buf
, size_t buflen
, const char *prompt
) {
291 size_t plen
= strlen(prompt
);
294 size_t cols
= getColumns();
295 int history_index
= 0;
300 buflen
--; /* Make sure there is always space for the nulterm */
302 /* The latest history entry is always our current buffer, that
303 * initially is just an empty string. */
304 linenoiseHistoryAdd("");
306 if (write(fd
,prompt
,plen
) == -1) return -1;
310 char seq
[2], seq2
[2];
312 nread
= read(fd
,&c
,1);
313 if (nread
<= 0) return len
;
315 /* Only autocomplete when the callback is set. It returns < 0 when
316 * there was an error reading from fd. Otherwise it will return the
317 * character that should be handled next. */
318 if (c
== 9 && completionCallback
!= NULL
) {
319 c
= completeLine(fd
,prompt
,buf
,buflen
,&len
,&pos
,cols
);
320 /* Return on errors */
321 if (c
< 0) return len
;
322 /* Read next character when 0 */
323 if (c
== 0) continue;
329 free(history
[history_len
]);
334 case 127: /* backspace */
336 if (pos
> 0 && len
> 0) {
337 memmove(buf
+pos
-1,buf
+pos
,len
-pos
);
341 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
344 case 4: /* ctrl-d, remove char at right of cursor */
345 if (len
> 1 && pos
< (len
-1)) {
346 memmove(buf
+pos
,buf
+pos
+1,len
-pos
);
349 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
350 } else if (len
== 0) {
352 free(history
[history_len
]);
356 case 20: /* ctrl-t */
357 if (pos
> 0 && pos
< len
) {
358 int aux
= buf
[pos
-1];
359 buf
[pos
-1] = buf
[pos
];
361 if (pos
!= len
-1) pos
++;
362 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
369 case 16: /* ctrl-p */
372 case 14: /* ctrl-n */
376 case 27: /* escape sequence */
377 if (read(fd
,seq
,2) == -1) break;
378 if (seq
[0] == 91 && seq
[1] == 68) {
383 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
385 } else if (seq
[0] == 91 && seq
[1] == 67) {
390 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
392 } else if (seq
[0] == 91 && (seq
[1] == 65 || seq
[1] == 66)) {
394 /* up and down arrow: history */
395 if (history_len
> 1) {
396 /* Update the current history entry before to
397 * overwrite it with tne next one. */
398 free(history
[history_len
-1-history_index
]);
399 history
[history_len
-1-history_index
] = strdup(buf
);
400 /* Show the new entry */
401 history_index
+= (seq
[1] == 65) ? 1 : -1;
402 if (history_index
< 0) {
405 } else if (history_index
>= history_len
) {
406 history_index
= history_len
-1;
409 strncpy(buf
,history
[history_len
-1-history_index
],buflen
);
411 len
= pos
= strlen(buf
);
412 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
414 } else if (seq
[0] == 91 && seq
[1] > 48 && seq
[1] < 55) {
415 /* extended escape */
416 if (read(fd
,seq2
,2) == -1) break;
417 if (seq
[1] == 51 && seq2
[0] == 126) {
419 if (len
> 0 && pos
< len
) {
420 memmove(buf
+pos
,buf
+pos
+1,len
-pos
-1);
423 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
435 if (plen
+len
< cols
) {
436 /* Avoid a full update of the line in the
438 if (write(fd
,&c
,1) == -1) return -1;
440 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
443 memmove(buf
+pos
+1,buf
+pos
,len
-pos
);
448 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
452 case 21: /* Ctrl+u, delete the whole line. */
455 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
457 case 11: /* Ctrl+k, delete from current to end of line. */
460 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
462 case 1: /* Ctrl+a, go to the start of the line */
464 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
466 case 5: /* ctrl+e, go to the end of the line */
468 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
470 case 12: /* ctrl+l, clear screen */
471 linenoiseClearScreen();
472 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
474 case 23: /* ctrl+w, delete previous word */
476 while (pos
> 0 && buf
[pos
-1] == ' ')
478 while (pos
> 0 && buf
[pos
-1] != ' ')
480 diff
= old_pos
- pos
;
481 memmove(&buf
[pos
], &buf
[old_pos
], len
-old_pos
+1);
483 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
490 static int linenoiseRaw(char *buf
, size_t buflen
, const char *prompt
) {
491 int fd
= STDIN_FILENO
;
498 if (!isatty(STDIN_FILENO
)) {
499 if (fgets(buf
, buflen
, stdin
) == NULL
) return -1;
501 if (count
&& buf
[count
-1] == '\n') {
506 if (enableRawMode(fd
) == -1) return -1;
507 count
= linenoisePrompt(fd
, buf
, buflen
, prompt
);
514 char *linenoise(const char *prompt
) {
515 char buf
[LINENOISE_MAX_LINE
];
518 if (isUnsupportedTerm()) {
523 if (fgets(buf
,LINENOISE_MAX_LINE
,stdin
) == NULL
) return NULL
;
525 while(len
&& (buf
[len
-1] == '\n' || buf
[len
-1] == '\r')) {
531 count
= linenoiseRaw(buf
,LINENOISE_MAX_LINE
,prompt
);
532 if (count
== -1) return NULL
;
537 /* Register a callback function to be called for tab-completion. */
538 void linenoiseSetCompletionCallback(linenoiseCompletionCallback
*fn
) {
539 completionCallback
= fn
;
542 void linenoiseAddCompletion(linenoiseCompletions
*lc
, char *str
) {
543 size_t len
= strlen(str
);
544 char *copy
= malloc(len
+1);
545 memcpy(copy
,str
,len
+1);
546 lc
->cvec
= realloc(lc
->cvec
,sizeof(char*)*(lc
->len
+1));
547 lc
->cvec
[lc
->len
++] = copy
;
550 /* Using a circular buffer is smarter, but a bit more complex to handle. */
551 int linenoiseHistoryAdd(const char *line
) {
554 if (history_max_len
== 0) return 0;
555 if (history
== NULL
) {
556 history
= malloc(sizeof(char*)*history_max_len
);
557 if (history
== NULL
) return 0;
558 memset(history
,0,(sizeof(char*)*history_max_len
));
560 linecopy
= strdup(line
);
561 if (!linecopy
) return 0;
562 if (history_len
== history_max_len
) {
564 memmove(history
,history
+1,sizeof(char*)*(history_max_len
-1));
567 history
[history_len
] = linecopy
;
572 int linenoiseHistorySetMaxLen(int len
) {
575 if (len
< 1) return 0;
577 int tocopy
= history_len
;
579 new = malloc(sizeof(char*)*len
);
580 if (new == NULL
) return 0;
581 if (len
< tocopy
) tocopy
= len
;
582 memcpy(new,history
+(history_max_len
-tocopy
), sizeof(char*)*tocopy
);
586 history_max_len
= len
;
587 if (history_len
> history_max_len
)
588 history_len
= history_max_len
;
592 /* Save the history in the specified file. On success 0 is returned
593 * otherwise -1 is returned. */
594 int linenoiseHistorySave(char *filename
) {
595 FILE *fp
= fopen(filename
,"w");
598 if (fp
== NULL
) return -1;
599 for (j
= 0; j
< history_len
; j
++)
600 fprintf(fp
,"%s\n",history
[j
]);
605 /* Load the history from the specified file. If the file does not exist
606 * zero is returned and no operation is performed.
608 * If the file exists and the operation succeeded 0 is returned, otherwise
609 * on error -1 is returned. */
610 int linenoiseHistoryLoad(char *filename
) {
611 FILE *fp
= fopen(filename
,"r");
612 char buf
[LINENOISE_MAX_LINE
];
614 if (fp
== NULL
) return -1;
616 while (fgets(buf
,LINENOISE_MAX_LINE
,fp
) != NULL
) {
619 p
= strchr(buf
,'\r');
620 if (!p
) p
= strchr(buf
,'\n');
622 linenoiseHistoryAdd(buf
);