]> git.saurik.com Git - redis.git/blame - deps/linenoise/linenoise.c
previouse INCR implementation restored, was actually faster for some reson not fully...
[redis.git] / deps / linenoise / linenoise.c
CommitLineData
cf87ebf2
MM
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>
bbac56c2 12 * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
13 *
cf87ebf2
MM
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
bbac56c2 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
cf87ebf2
MM
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>
ff405818 95#include "linenoise.h"
cf87ebf2 96
99628c1a 97#define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
cf87ebf2 98#define LINENOISE_MAX_LINE 4096
a737ada1 99static char *unsupported_term[] = {"dumb","cons25",NULL};
ff405818 100static linenoiseCompletionCallback *completionCallback = NULL;
cf87ebf2
MM
101
102static struct termios orig_termios; /* in order to restore at exit */
103static int rawmode = 0; /* for atexit() function to check if restore is needed*/
104static int atexit_registered = 0; /* register atexit just 1 time */
99628c1a 105static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
cf87ebf2
MM
106static int history_len = 0;
107char **history = NULL;
108
109static void linenoiseAtExit(void);
a737ada1 110int linenoiseHistoryAdd(const char *line);
111
112static 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}
cf87ebf2
MM
121
122static 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
132static 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
162fatal:
163 errno = ENOTTY;
164 return -1;
165}
166
167static 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. */
174static void linenoiseAtExit(void) {
175 disableRawMode(STDIN_FILENO);
176 freeHistory();
177}
178
179static int getColumns(void) {
180 struct winsize ws;
181
182 if (ioctl(1, TIOCGWINSZ, &ws) == -1) return 80;
183 return ws.ws_col;
184}
185
186static 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
ff405818
PN
213static void beep() {
214 fprintf(stderr, "\x7");
215 fflush(stderr);
216}
217
218static 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
226static 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 */
c54afb6d
PN
259 /* Re-show original buffer */
260 if (i < lc.len) {
261 refreshLine(fd,prompt,buf,*len,*pos,cols);
262 }
ff405818
PN
263 stop = 1;
264 break;
265 default:
c54afb6d 266 /* Update buffer and return */
ff405818
PN
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
bbac56c2 281void linenoiseClearScreen(void) {
282 write(STDIN_FILENO,"\x1b[H\x1b[2J",7);
283}
284
cf87ebf2
MM
285static int linenoisePrompt(int fd, char *buf, size_t buflen, const char *prompt) {
286 size_t plen = strlen(prompt);
287 size_t pos = 0;
288 size_t len = 0;
289 size_t cols = getColumns();
290 int history_index = 0;
291
292 buf[0] = '\0';
293 buflen--; /* Make sure there is always space for the nulterm */
294
295 /* The latest history entry is always our current buffer, that
296 * initially is just an empty string. */
297 linenoiseHistoryAdd("");
298
299 if (write(fd,prompt,plen) == -1) return -1;
300 while(1) {
301 char c;
302 int nread;
e902b579 303 char seq[2], seq2[2];
cf87ebf2
MM
304
305 nread = read(fd,&c,1);
306 if (nread <= 0) return len;
ff405818
PN
307
308 /* Only autocomplete when the callback is set. It returns < 0 when
309 * there was an error reading from fd. Otherwise it will return the
310 * character that should be handled next. */
311 if (c == 9 && completionCallback != NULL) {
312 c = completeLine(fd,prompt,buf,buflen,&len,&pos,cols);
313 /* Return on errors */
314 if (c < 0) return len;
315 /* Read next character when 0 */
316 if (c == 0) continue;
317 }
318
cf87ebf2
MM
319 switch(c) {
320 case 13: /* enter */
cf87ebf2
MM
321 case 4: /* ctrl-d */
322 history_len--;
99628c1a 323 free(history[history_len]);
324 return (len == 0 && c == 4) ? -1 : (int)len;
cf87ebf2
MM
325 case 3: /* ctrl-c */
326 errno = EAGAIN;
327 return -1;
328 case 127: /* backspace */
329 case 8: /* ctrl-h */
330 if (pos > 0 && len > 0) {
331 memmove(buf+pos-1,buf+pos,len-pos);
332 pos--;
333 len--;
334 buf[len] = '\0';
335 refreshLine(fd,prompt,buf,len,pos,cols);
336 }
337 break;
338 case 20: /* ctrl-t */
339 if (pos > 0 && pos < len) {
340 int aux = buf[pos-1];
341 buf[pos-1] = buf[pos];
342 buf[pos] = aux;
343 if (pos != len-1) pos++;
344 refreshLine(fd,prompt,buf,len,pos,cols);
345 }
346 break;
347 case 2: /* ctrl-b */
348 goto left_arrow;
349 case 6: /* ctrl-f */
350 goto right_arrow;
351 case 16: /* ctrl-p */
352 seq[1] = 65;
353 goto up_down_arrow;
354 case 14: /* ctrl-n */
355 seq[1] = 66;
356 goto up_down_arrow;
357 break;
358 case 27: /* escape sequence */
359 if (read(fd,seq,2) == -1) break;
360 if (seq[0] == 91 && seq[1] == 68) {
361left_arrow:
362 /* left arrow */
363 if (pos > 0) {
364 pos--;
365 refreshLine(fd,prompt,buf,len,pos,cols);
366 }
367 } else if (seq[0] == 91 && seq[1] == 67) {
368right_arrow:
369 /* right arrow */
370 if (pos != len) {
371 pos++;
372 refreshLine(fd,prompt,buf,len,pos,cols);
373 }
374 } else if (seq[0] == 91 && (seq[1] == 65 || seq[1] == 66)) {
375up_down_arrow:
376 /* up and down arrow: history */
377 if (history_len > 1) {
378 /* Update the current history entry before to
379 * overwrite it with tne next one. */
380 free(history[history_len-1-history_index]);
381 history[history_len-1-history_index] = strdup(buf);
382 /* Show the new entry */
383 history_index += (seq[1] == 65) ? 1 : -1;
384 if (history_index < 0) {
385 history_index = 0;
386 break;
387 } else if (history_index >= history_len) {
388 history_index = history_len-1;
389 break;
390 }
391 strncpy(buf,history[history_len-1-history_index],buflen);
392 buf[buflen] = '\0';
393 len = pos = strlen(buf);
394 refreshLine(fd,prompt,buf,len,pos,cols);
395 }
e902b579
PN
396 } else if (seq[0] == 91 && seq[1] > 48 && seq[1] < 55) {
397 /* extended escape */
398 if (read(fd,seq2,2) == -1) break;
399 if (seq[1] == 51 && seq2[0] == 126) {
400 /* delete */
401 if (len > 0 && pos < len) {
402 memmove(buf+pos,buf+pos+1,len-pos-1);
403 len--;
404 buf[len] = '\0';
405 refreshLine(fd,prompt,buf,len,pos,cols);
406 }
407 }
cf87ebf2
MM
408 }
409 break;
410 default:
411 if (len < buflen) {
412 if (len == pos) {
413 buf[pos] = c;
414 pos++;
415 len++;
416 buf[len] = '\0';
417 if (plen+len < cols) {
418 /* Avoid a full update of the line in the
419 * trivial case. */
420 if (write(fd,&c,1) == -1) return -1;
421 } else {
422 refreshLine(fd,prompt,buf,len,pos,cols);
423 }
424 } else {
425 memmove(buf+pos+1,buf+pos,len-pos);
426 buf[pos] = c;
427 len++;
428 pos++;
429 buf[len] = '\0';
430 refreshLine(fd,prompt,buf,len,pos,cols);
431 }
432 }
433 break;
434 case 21: /* Ctrl+u, delete the whole line. */
435 buf[0] = '\0';
436 pos = len = 0;
437 refreshLine(fd,prompt,buf,len,pos,cols);
438 break;
439 case 11: /* Ctrl+k, delete from current to end of line. */
440 buf[pos] = '\0';
441 len = pos;
442 refreshLine(fd,prompt,buf,len,pos,cols);
443 break;
444 case 1: /* Ctrl+a, go to the start of the line */
445 pos = 0;
446 refreshLine(fd,prompt,buf,len,pos,cols);
447 break;
448 case 5: /* ctrl+e, go to the end of the line */
449 pos = len;
450 refreshLine(fd,prompt,buf,len,pos,cols);
451 break;
bbac56c2 452 case 12: /* ctrl+l, clear screen */
453 linenoiseClearScreen();
454 refreshLine(fd,prompt,buf,len,pos,cols);
cf87ebf2
MM
455 }
456 }
457 return len;
458}
459
460static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
461 int fd = STDIN_FILENO;
462 int count;
463
464 if (buflen == 0) {
465 errno = EINVAL;
466 return -1;
467 }
a737ada1 468 if (!isatty(STDIN_FILENO)) {
469 if (fgets(buf, buflen, stdin) == NULL) return -1;
470 count = strlen(buf);
471 if (count && buf[count-1] == '\n') {
472 count--;
473 buf[count] = '\0';
474 }
475 } else {
476 if (enableRawMode(fd) == -1) return -1;
477 count = linenoisePrompt(fd, buf, buflen, prompt);
478 disableRawMode(fd);
479 printf("\n");
480 }
cf87ebf2
MM
481 return count;
482}
483
484char *linenoise(const char *prompt) {
485 char buf[LINENOISE_MAX_LINE];
486 int count;
487
a737ada1 488 if (isUnsupportedTerm()) {
489 size_t len;
490
491 printf("%s",prompt);
492 fflush(stdout);
493 if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
494 len = strlen(buf);
495 while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
496 len--;
497 buf[len] = '\0';
498 }
499 return strdup(buf);
500 } else {
501 count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
502 if (count == -1) return NULL;
503 return strdup(buf);
504 }
cf87ebf2
MM
505}
506
ff405818
PN
507/* Register a callback function to be called for tab-completion. */
508void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
509 completionCallback = fn;
510}
511
512void linenoiseAddCompletion(linenoiseCompletions *lc, char *str) {
513 size_t len = strlen(str);
514 char *copy = malloc(len+1);
515 memcpy(copy,str,len+1);
516 lc->cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
517 lc->cvec[lc->len++] = copy;
518}
519
cf87ebf2 520/* Using a circular buffer is smarter, but a bit more complex to handle. */
a737ada1 521int linenoiseHistoryAdd(const char *line) {
522 char *linecopy;
523
cf87ebf2 524 if (history_max_len == 0) return 0;
99628c1a 525 if (history == NULL) {
cf87ebf2
MM
526 history = malloc(sizeof(char*)*history_max_len);
527 if (history == NULL) return 0;
528 memset(history,0,(sizeof(char*)*history_max_len));
529 }
a737ada1 530 linecopy = strdup(line);
531 if (!linecopy) return 0;
cf87ebf2 532 if (history_len == history_max_len) {
99628c1a 533 free(history[0]);
cf87ebf2
MM
534 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
535 history_len--;
536 }
a737ada1 537 history[history_len] = linecopy;
cf87ebf2
MM
538 history_len++;
539 return 1;
540}
541
542int linenoiseHistorySetMaxLen(int len) {
543 char **new;
544
545 if (len < 1) return 0;
546 if (history) {
547 int tocopy = history_len;
548
549 new = malloc(sizeof(char*)*len);
550 if (new == NULL) return 0;
551 if (len < tocopy) tocopy = len;
552 memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
553 free(history);
554 history = new;
555 }
556 history_max_len = len;
557 if (history_len > history_max_len)
558 history_len = history_max_len;
559 return 1;
560}
99628c1a 561
562/* Save the history in the specified file. On success 0 is returned
563 * otherwise -1 is returned. */
564int linenoiseHistorySave(char *filename) {
565 FILE *fp = fopen(filename,"w");
566 int j;
567
568 if (fp == NULL) return -1;
569 for (j = 0; j < history_len; j++)
570 fprintf(fp,"%s\n",history[j]);
571 fclose(fp);
572 return 0;
573}
574
575/* Load the history from the specified file. If the file does not exist
576 * zero is returned and no operation is performed.
577 *
578 * If the file exists and the operation succeeded 0 is returned, otherwise
579 * on error -1 is returned. */
580int linenoiseHistoryLoad(char *filename) {
581 FILE *fp = fopen(filename,"r");
582 char buf[LINENOISE_MAX_LINE];
583
584 if (fp == NULL) return -1;
585
586 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
587 char *p;
588
589 p = strchr(buf,'\r');
590 if (!p) p = strchr(buf,'\n');
591 if (p) *p = '\0';
592 linenoiseHistoryAdd(buf);
593 }
594 fclose(fp);
595 return 0;
596}