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