]> git.saurik.com Git - redis.git/blob - deps/linenoise/linenoise.c
Merge remote branch 'jonahharris/syslog'
[redis.git] / deps / linenoise / linenoise.c
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.
3 *
4 * You can find the latest source code at:
5 *
6 * http://github.com/antirez/linenoise
7 *
8 * Does a number of crazy assumptions that happen to be true in 99.9999% of
9 * the 2010 UNIX computers around.
10 *
11 * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
12 * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
13 *
14 * All rights reserved.
15 *
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions are met:
18 *
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.
27 *
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.
39 *
40 * References:
41 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
42 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
43 *
44 * Todo list:
45 * - Switch to gets() if $TERM is something we can't support.
46 * - Filter bogus Ctrl+<char> combinations.
47 * - Win32 support
48 *
49 * Bloat:
50 * - Completion?
51 * - History search like Ctrl+r in readline?
52 *
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.
57 *
58 * CHA (Cursor Horizontal Absolute)
59 * Sequence: ESC [ n G
60 * Effect: moves cursor to column n
61 *
62 * EL (Erase Line)
63 * Sequence: ESC [ n K
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
67 *
68 * CUF (CUrsor Forward)
69 * Sequence: ESC [ n C
70 * Effect: moves cursor forward of n chars
71 *
72 * The following are used to clear the screen: ESC [ H ESC [ 2 J
73 * This is actually composed of two sequences:
74 *
75 * cursorhome
76 * Sequence: ESC [ H
77 * Effect: moves the cursor to upper left corner
78 *
79 * ED2 (Clear entire screen)
80 * Sequence: ESC [ 2 J
81 * Effect: clear the whole screen
82 *
83 */
84
85 #include <termios.h>
86 #include <unistd.h>
87 #include <stdlib.h>
88 #include <stdio.h>
89 #include <errno.h>
90 #include <string.h>
91 #include <stdlib.h>
92 #include <sys/types.h>
93 #include <sys/ioctl.h>
94 #include <unistd.h>
95 #include "linenoise.h"
96
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;
101
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;
108
109 static void linenoiseAtExit(void);
110 int linenoiseHistoryAdd(const char *line);
111
112 static int isUnsupportedTerm(void) {
113 char *term = getenv("TERM");
114 int j;
115
116 if (term == NULL) return 0;
117 for (j = 0; unsupported_term[j]; j++)
118 if (!strcasecmp(term,unsupported_term[j])) return 1;
119 return 0;
120 }
121
122 static void freeHistory(void) {
123 if (history) {
124 int j;
125
126 for (j = 0; j < history_len; j++)
127 free(history[j]);
128 free(history);
129 }
130 }
131
132 static int enableRawMode(int fd) {
133 struct termios raw;
134
135 if (!isatty(STDIN_FILENO)) goto fatal;
136 if (!atexit_registered) {
137 atexit(linenoiseAtExit);
138 atexit_registered = 1;
139 }
140 if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
141
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 */
156
157 /* put terminal in raw mode after flushing */
158 if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
159 rawmode = 1;
160 return 0;
161
162 fatal:
163 errno = ENOTTY;
164 return -1;
165 }
166
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)
170 rawmode = 0;
171 }
172
173 /* At exit we'll try to fix the terminal to the initial conditions. */
174 static void linenoiseAtExit(void) {
175 disableRawMode(STDIN_FILENO);
176 freeHistory();
177 }
178
179 static int getColumns(void) {
180 struct winsize ws;
181
182 if (ioctl(1, TIOCGWINSZ, &ws) == -1) return 80;
183 return ws.ws_col;
184 }
185
186 static void refreshLine(int fd, const char *prompt, char *buf, size_t len, size_t pos, size_t cols) {
187 char seq[64];
188 size_t plen = strlen(prompt);
189
190 while((plen+pos) >= cols) {
191 buf++;
192 len--;
193 pos--;
194 }
195 while (plen+len > cols) {
196 len--;
197 }
198
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;
205 /* Erase to right */
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;
211 }
212
213 static void beep() {
214 fprintf(stderr, "\x7");
215 fflush(stderr);
216 }
217
218 static void freeCompletions(linenoiseCompletions *lc) {
219 size_t i;
220 for (i = 0; i < lc->len; i++)
221 free(lc->cvec[i]);
222 if (lc->cvec != NULL)
223 free(lc->cvec);
224 }
225
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 };
228 int nread, nwritten;
229 char c = 0;
230
231 completionCallback(buf,&lc);
232 if (lc.len == 0) {
233 beep();
234 } else {
235 size_t stop = 0, i = 0;
236 size_t clen;
237
238 while(!stop) {
239 /* Show completion or original buffer */
240 if (i < lc.len) {
241 clen = strlen(lc.cvec[i]);
242 refreshLine(fd,prompt,lc.cvec[i],clen,clen,cols);
243 } else {
244 refreshLine(fd,prompt,buf,*len,*pos,cols);
245 }
246
247 nread = read(fd,&c,1);
248 if (nread <= 0) {
249 freeCompletions(&lc);
250 return -1;
251 }
252
253 switch(c) {
254 case 9: /* tab */
255 i = (i+1) % (lc.len+1);
256 if (i == lc.len) beep();
257 break;
258 case 27: /* escape */
259 /* Re-show original buffer */
260 if (i < lc.len) {
261 refreshLine(fd,prompt,buf,*len,*pos,cols);
262 }
263 stop = 1;
264 break;
265 default:
266 /* Update buffer and return */
267 if (i < lc.len) {
268 nwritten = snprintf(buf,buflen,"%s",lc.cvec[i]);
269 *len = *pos = nwritten;
270 }
271 stop = 1;
272 break;
273 }
274 }
275 }
276
277 freeCompletions(&lc);
278 return c; /* Return last read character */
279 }
280
281 void linenoiseClearScreen(void) {
282 if (write(STDIN_FILENO,"\x1b[H\x1b[2J",7) <= 0) {
283 /* nothing to do, just to avoid warning. */
284 }
285 }
286
287 static int linenoisePrompt(int fd, char *buf, size_t buflen, const char *prompt) {
288 size_t plen = strlen(prompt);
289 size_t pos = 0;
290 size_t len = 0;
291 size_t cols = getColumns();
292 int history_index = 0;
293
294 buf[0] = '\0';
295 buflen--; /* Make sure there is always space for the nulterm */
296
297 /* The latest history entry is always our current buffer, that
298 * initially is just an empty string. */
299 linenoiseHistoryAdd("");
300
301 if (write(fd,prompt,plen) == -1) return -1;
302 while(1) {
303 char c;
304 int nread;
305 char seq[2], seq2[2];
306
307 nread = read(fd,&c,1);
308 if (nread <= 0) return len;
309
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;
319 }
320
321 switch(c) {
322 case 13: /* enter */
323 case 4: /* ctrl-d */
324 history_len--;
325 free(history[history_len]);
326 return (len == 0 && c == 4) ? -1 : (int)len;
327 case 3: /* ctrl-c */
328 errno = EAGAIN;
329 return -1;
330 case 127: /* backspace */
331 case 8: /* ctrl-h */
332 if (pos > 0 && len > 0) {
333 memmove(buf+pos-1,buf+pos,len-pos);
334 pos--;
335 len--;
336 buf[len] = '\0';
337 refreshLine(fd,prompt,buf,len,pos,cols);
338 }
339 break;
340 case 20: /* ctrl-t */
341 if (pos > 0 && pos < len) {
342 int aux = buf[pos-1];
343 buf[pos-1] = buf[pos];
344 buf[pos] = aux;
345 if (pos != len-1) pos++;
346 refreshLine(fd,prompt,buf,len,pos,cols);
347 }
348 break;
349 case 2: /* ctrl-b */
350 goto left_arrow;
351 case 6: /* ctrl-f */
352 goto right_arrow;
353 case 16: /* ctrl-p */
354 seq[1] = 65;
355 goto up_down_arrow;
356 case 14: /* ctrl-n */
357 seq[1] = 66;
358 goto up_down_arrow;
359 break;
360 case 27: /* escape sequence */
361 if (read(fd,seq,2) == -1) break;
362 if (seq[0] == 91 && seq[1] == 68) {
363 left_arrow:
364 /* left arrow */
365 if (pos > 0) {
366 pos--;
367 refreshLine(fd,prompt,buf,len,pos,cols);
368 }
369 } else if (seq[0] == 91 && seq[1] == 67) {
370 right_arrow:
371 /* right arrow */
372 if (pos != len) {
373 pos++;
374 refreshLine(fd,prompt,buf,len,pos,cols);
375 }
376 } else if (seq[0] == 91 && (seq[1] == 65 || seq[1] == 66)) {
377 up_down_arrow:
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) {
387 history_index = 0;
388 break;
389 } else if (history_index >= history_len) {
390 history_index = history_len-1;
391 break;
392 }
393 strncpy(buf,history[history_len-1-history_index],buflen);
394 buf[buflen] = '\0';
395 len = pos = strlen(buf);
396 refreshLine(fd,prompt,buf,len,pos,cols);
397 }
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) {
402 /* delete */
403 if (len > 0 && pos < len) {
404 memmove(buf+pos,buf+pos+1,len-pos-1);
405 len--;
406 buf[len] = '\0';
407 refreshLine(fd,prompt,buf,len,pos,cols);
408 }
409 }
410 }
411 break;
412 default:
413 if (len < buflen) {
414 if (len == pos) {
415 buf[pos] = c;
416 pos++;
417 len++;
418 buf[len] = '\0';
419 if (plen+len < cols) {
420 /* Avoid a full update of the line in the
421 * trivial case. */
422 if (write(fd,&c,1) == -1) return -1;
423 } else {
424 refreshLine(fd,prompt,buf,len,pos,cols);
425 }
426 } else {
427 memmove(buf+pos+1,buf+pos,len-pos);
428 buf[pos] = c;
429 len++;
430 pos++;
431 buf[len] = '\0';
432 refreshLine(fd,prompt,buf,len,pos,cols);
433 }
434 }
435 break;
436 case 21: /* Ctrl+u, delete the whole line. */
437 buf[0] = '\0';
438 pos = len = 0;
439 refreshLine(fd,prompt,buf,len,pos,cols);
440 break;
441 case 11: /* Ctrl+k, delete from current to end of line. */
442 buf[pos] = '\0';
443 len = pos;
444 refreshLine(fd,prompt,buf,len,pos,cols);
445 break;
446 case 1: /* Ctrl+a, go to the start of the line */
447 pos = 0;
448 refreshLine(fd,prompt,buf,len,pos,cols);
449 break;
450 case 5: /* ctrl+e, go to the end of the line */
451 pos = len;
452 refreshLine(fd,prompt,buf,len,pos,cols);
453 break;
454 case 12: /* ctrl+l, clear screen */
455 linenoiseClearScreen();
456 refreshLine(fd,prompt,buf,len,pos,cols);
457 }
458 }
459 return len;
460 }
461
462 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
463 int fd = STDIN_FILENO;
464 int count;
465
466 if (buflen == 0) {
467 errno = EINVAL;
468 return -1;
469 }
470 if (!isatty(STDIN_FILENO)) {
471 if (fgets(buf, buflen, stdin) == NULL) return -1;
472 count = strlen(buf);
473 if (count && buf[count-1] == '\n') {
474 count--;
475 buf[count] = '\0';
476 }
477 } else {
478 if (enableRawMode(fd) == -1) return -1;
479 count = linenoisePrompt(fd, buf, buflen, prompt);
480 disableRawMode(fd);
481 printf("\n");
482 }
483 return count;
484 }
485
486 char *linenoise(const char *prompt) {
487 char buf[LINENOISE_MAX_LINE];
488 int count;
489
490 if (isUnsupportedTerm()) {
491 size_t len;
492
493 printf("%s",prompt);
494 fflush(stdout);
495 if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
496 len = strlen(buf);
497 while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
498 len--;
499 buf[len] = '\0';
500 }
501 return strdup(buf);
502 } else {
503 count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
504 if (count == -1) return NULL;
505 return strdup(buf);
506 }
507 }
508
509 /* Register a callback function to be called for tab-completion. */
510 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
511 completionCallback = fn;
512 }
513
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;
520 }
521
522 /* Using a circular buffer is smarter, but a bit more complex to handle. */
523 int linenoiseHistoryAdd(const char *line) {
524 char *linecopy;
525
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));
531 }
532 linecopy = strdup(line);
533 if (!linecopy) return 0;
534 if (history_len == history_max_len) {
535 free(history[0]);
536 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
537 history_len--;
538 }
539 history[history_len] = linecopy;
540 history_len++;
541 return 1;
542 }
543
544 int linenoiseHistorySetMaxLen(int len) {
545 char **new;
546
547 if (len < 1) return 0;
548 if (history) {
549 int tocopy = history_len;
550
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);
555 free(history);
556 history = new;
557 }
558 history_max_len = len;
559 if (history_len > history_max_len)
560 history_len = history_max_len;
561 return 1;
562 }
563
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");
568 int j;
569
570 if (fp == NULL) return -1;
571 for (j = 0; j < history_len; j++)
572 fprintf(fp,"%s\n",history[j]);
573 fclose(fp);
574 return 0;
575 }
576
577 /* Load the history from the specified file. If the file does not exist
578 * zero is returned and no operation is performed.
579 *
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];
585
586 if (fp == NULL) return -1;
587
588 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
589 char *p;
590
591 p = strchr(buf,'\r');
592 if (!p) p = strchr(buf,'\n');
593 if (p) *p = '\0';
594 linenoiseHistoryAdd(buf);
595 }
596 fclose(fp);
597 return 0;
598 }