]> git.saurik.com Git - redis.git/blob - deps/linenoise/linenoise.c
Use safe dictionary iterator from KEYS
[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 history_len--;
324 free(history[history_len]);
325 return (int)len;
326 case 3: /* ctrl-c */
327 errno = EAGAIN;
328 return -1;
329 case 127: /* backspace */
330 case 8: /* ctrl-h */
331 if (pos > 0 && len > 0) {
332 memmove(buf+pos-1,buf+pos,len-pos);
333 pos--;
334 len--;
335 buf[len] = '\0';
336 refreshLine(fd,prompt,buf,len,pos,cols);
337 }
338 break;
339 case 4: /* ctrl-d, remove char at right of cursor */
340 if (len > 1 && pos < (len-1)) {
341 memmove(buf+pos,buf+pos+1,len-pos);
342 len--;
343 buf[len] = '\0';
344 refreshLine(fd,prompt,buf,len,pos,cols);
345 } else if (len == 0) {
346 history_len--;
347 free(history[history_len]);
348 return -1;
349 }
350 break;
351 case 20: /* ctrl-t */
352 if (pos > 0 && pos < len) {
353 int aux = buf[pos-1];
354 buf[pos-1] = buf[pos];
355 buf[pos] = aux;
356 if (pos != len-1) pos++;
357 refreshLine(fd,prompt,buf,len,pos,cols);
358 }
359 break;
360 case 2: /* ctrl-b */
361 goto left_arrow;
362 case 6: /* ctrl-f */
363 goto right_arrow;
364 case 16: /* ctrl-p */
365 seq[1] = 65;
366 goto up_down_arrow;
367 case 14: /* ctrl-n */
368 seq[1] = 66;
369 goto up_down_arrow;
370 break;
371 case 27: /* escape sequence */
372 if (read(fd,seq,2) == -1) break;
373 if (seq[0] == 91 && seq[1] == 68) {
374 left_arrow:
375 /* left arrow */
376 if (pos > 0) {
377 pos--;
378 refreshLine(fd,prompt,buf,len,pos,cols);
379 }
380 } else if (seq[0] == 91 && seq[1] == 67) {
381 right_arrow:
382 /* right arrow */
383 if (pos != len) {
384 pos++;
385 refreshLine(fd,prompt,buf,len,pos,cols);
386 }
387 } else if (seq[0] == 91 && (seq[1] == 65 || seq[1] == 66)) {
388 up_down_arrow:
389 /* up and down arrow: history */
390 if (history_len > 1) {
391 /* Update the current history entry before to
392 * overwrite it with tne next one. */
393 free(history[history_len-1-history_index]);
394 history[history_len-1-history_index] = strdup(buf);
395 /* Show the new entry */
396 history_index += (seq[1] == 65) ? 1 : -1;
397 if (history_index < 0) {
398 history_index = 0;
399 break;
400 } else if (history_index >= history_len) {
401 history_index = history_len-1;
402 break;
403 }
404 strncpy(buf,history[history_len-1-history_index],buflen);
405 buf[buflen] = '\0';
406 len = pos = strlen(buf);
407 refreshLine(fd,prompt,buf,len,pos,cols);
408 }
409 } else if (seq[0] == 91 && seq[1] > 48 && seq[1] < 55) {
410 /* extended escape */
411 if (read(fd,seq2,2) == -1) break;
412 if (seq[1] == 51 && seq2[0] == 126) {
413 /* delete */
414 if (len > 0 && pos < len) {
415 memmove(buf+pos,buf+pos+1,len-pos-1);
416 len--;
417 buf[len] = '\0';
418 refreshLine(fd,prompt,buf,len,pos,cols);
419 }
420 }
421 }
422 break;
423 default:
424 if (len < buflen) {
425 if (len == pos) {
426 buf[pos] = c;
427 pos++;
428 len++;
429 buf[len] = '\0';
430 if (plen+len < cols) {
431 /* Avoid a full update of the line in the
432 * trivial case. */
433 if (write(fd,&c,1) == -1) return -1;
434 } else {
435 refreshLine(fd,prompt,buf,len,pos,cols);
436 }
437 } else {
438 memmove(buf+pos+1,buf+pos,len-pos);
439 buf[pos] = c;
440 len++;
441 pos++;
442 buf[len] = '\0';
443 refreshLine(fd,prompt,buf,len,pos,cols);
444 }
445 }
446 break;
447 case 21: /* Ctrl+u, delete the whole line. */
448 buf[0] = '\0';
449 pos = len = 0;
450 refreshLine(fd,prompt,buf,len,pos,cols);
451 break;
452 case 11: /* Ctrl+k, delete from current to end of line. */
453 buf[pos] = '\0';
454 len = pos;
455 refreshLine(fd,prompt,buf,len,pos,cols);
456 break;
457 case 1: /* Ctrl+a, go to the start of the line */
458 pos = 0;
459 refreshLine(fd,prompt,buf,len,pos,cols);
460 break;
461 case 5: /* ctrl+e, go to the end of the line */
462 pos = len;
463 refreshLine(fd,prompt,buf,len,pos,cols);
464 break;
465 case 12: /* ctrl+l, clear screen */
466 linenoiseClearScreen();
467 refreshLine(fd,prompt,buf,len,pos,cols);
468 }
469 }
470 return len;
471 }
472
473 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
474 int fd = STDIN_FILENO;
475 int count;
476
477 if (buflen == 0) {
478 errno = EINVAL;
479 return -1;
480 }
481 if (!isatty(STDIN_FILENO)) {
482 if (fgets(buf, buflen, stdin) == NULL) return -1;
483 count = strlen(buf);
484 if (count && buf[count-1] == '\n') {
485 count--;
486 buf[count] = '\0';
487 }
488 } else {
489 if (enableRawMode(fd) == -1) return -1;
490 count = linenoisePrompt(fd, buf, buflen, prompt);
491 disableRawMode(fd);
492 printf("\n");
493 }
494 return count;
495 }
496
497 char *linenoise(const char *prompt) {
498 char buf[LINENOISE_MAX_LINE];
499 int count;
500
501 if (isUnsupportedTerm()) {
502 size_t len;
503
504 printf("%s",prompt);
505 fflush(stdout);
506 if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
507 len = strlen(buf);
508 while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
509 len--;
510 buf[len] = '\0';
511 }
512 return strdup(buf);
513 } else {
514 count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
515 if (count == -1) return NULL;
516 return strdup(buf);
517 }
518 }
519
520 /* Register a callback function to be called for tab-completion. */
521 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
522 completionCallback = fn;
523 }
524
525 void linenoiseAddCompletion(linenoiseCompletions *lc, char *str) {
526 size_t len = strlen(str);
527 char *copy = malloc(len+1);
528 memcpy(copy,str,len+1);
529 lc->cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
530 lc->cvec[lc->len++] = copy;
531 }
532
533 /* Using a circular buffer is smarter, but a bit more complex to handle. */
534 int linenoiseHistoryAdd(const char *line) {
535 char *linecopy;
536
537 if (history_max_len == 0) return 0;
538 if (history == NULL) {
539 history = malloc(sizeof(char*)*history_max_len);
540 if (history == NULL) return 0;
541 memset(history,0,(sizeof(char*)*history_max_len));
542 }
543 linecopy = strdup(line);
544 if (!linecopy) return 0;
545 if (history_len == history_max_len) {
546 free(history[0]);
547 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
548 history_len--;
549 }
550 history[history_len] = linecopy;
551 history_len++;
552 return 1;
553 }
554
555 int linenoiseHistorySetMaxLen(int len) {
556 char **new;
557
558 if (len < 1) return 0;
559 if (history) {
560 int tocopy = history_len;
561
562 new = malloc(sizeof(char*)*len);
563 if (new == NULL) return 0;
564 if (len < tocopy) tocopy = len;
565 memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
566 free(history);
567 history = new;
568 }
569 history_max_len = len;
570 if (history_len > history_max_len)
571 history_len = history_max_len;
572 return 1;
573 }
574
575 /* Save the history in the specified file. On success 0 is returned
576 * otherwise -1 is returned. */
577 int linenoiseHistorySave(char *filename) {
578 FILE *fp = fopen(filename,"w");
579 int j;
580
581 if (fp == NULL) return -1;
582 for (j = 0; j < history_len; j++)
583 fprintf(fp,"%s\n",history[j]);
584 fclose(fp);
585 return 0;
586 }
587
588 /* Load the history from the specified file. If the file does not exist
589 * zero is returned and no operation is performed.
590 *
591 * If the file exists and the operation succeeded 0 is returned, otherwise
592 * on error -1 is returned. */
593 int linenoiseHistoryLoad(char *filename) {
594 FILE *fp = fopen(filename,"r");
595 char buf[LINENOISE_MAX_LINE];
596
597 if (fp == NULL) return -1;
598
599 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
600 char *p;
601
602 p = strchr(buf,'\r');
603 if (!p) p = strchr(buf,'\n');
604 if (p) *p = '\0';
605 linenoiseHistoryAdd(buf);
606 }
607 fclose(fp);
608 return 0;
609 }