]> git.saurik.com Git - redis.git/blob - deps/linenoise/linenoise.c
045862e7881b7f4c0026f94c86a88a1368428490
[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 * All rights reserved.
13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions are met:
16 *
17 * * Redistributions of source code must retain the above copyright notice,
18 * this list of conditions and the following disclaimer.
19 * * Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 * * Neither the name of Redis nor the names of its contributors may be used
23 * to endorse or promote products derived from this software without
24 * specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
27 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
30 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
37 *
38 * References:
39 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
40 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
41 *
42 * Todo list:
43 * - Switch to gets() if $TERM is something we can't support.
44 * - Filter bogus Ctrl+<char> combinations.
45 * - Win32 support
46 *
47 * Bloat:
48 * - Completion?
49 * - History search like Ctrl+r in readline?
50 *
51 * List of escape sequences used by this program, we do everything just
52 * with three sequences. In order to be so cheap we may have some
53 * flickering effect with some slow terminal, but the lesser sequences
54 * the more compatible.
55 *
56 * CHA (Cursor Horizontal Absolute)
57 * Sequence: ESC [ n G
58 * Effect: moves cursor to column n
59 *
60 * EL (Erase Line)
61 * Sequence: ESC [ n K
62 * Effect: if n is 0 or missing, clear from cursor to end of line
63 * Effect: if n is 1, clear from beginning of line to cursor
64 * Effect: if n is 2, clear entire line
65 *
66 * CUF (CUrsor Forward)
67 * Sequence: ESC [ n C
68 * Effect: moves cursor forward of n chars
69 *
70 */
71
72 #include <termios.h>
73 #include <unistd.h>
74 #include <stdlib.h>
75 #include <stdio.h>
76 #include <errno.h>
77 #include <string.h>
78 #include <stdlib.h>
79 #include <sys/types.h>
80 #include <sys/ioctl.h>
81 #include <unistd.h>
82
83 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
84 #define LINENOISE_MAX_LINE 4096
85 static char *unsupported_term[] = {"dumb","cons25",NULL};
86
87 static struct termios orig_termios; /* in order to restore at exit */
88 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
89 static int atexit_registered = 0; /* register atexit just 1 time */
90 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
91 static int history_len = 0;
92 char **history = NULL;
93
94 static void linenoiseAtExit(void);
95 int linenoiseHistoryAdd(const char *line);
96
97 static int isUnsupportedTerm(void) {
98 char *term = getenv("TERM");
99 int j;
100
101 if (term == NULL) return 0;
102 for (j = 0; unsupported_term[j]; j++)
103 if (!strcasecmp(term,unsupported_term[j])) return 1;
104 return 0;
105 }
106
107 static void freeHistory(void) {
108 if (history) {
109 int j;
110
111 for (j = 0; j < history_len; j++)
112 free(history[j]);
113 free(history);
114 }
115 }
116
117 static int enableRawMode(int fd) {
118 struct termios raw;
119
120 if (!isatty(STDIN_FILENO)) goto fatal;
121 if (!atexit_registered) {
122 atexit(linenoiseAtExit);
123 atexit_registered = 1;
124 }
125 if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
126
127 raw = orig_termios; /* modify the original mode */
128 /* input modes: no break, no CR to NL, no parity check, no strip char,
129 * no start/stop output control. */
130 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
131 /* output modes - disable post processing */
132 raw.c_oflag &= ~(OPOST);
133 /* control modes - set 8 bit chars */
134 raw.c_cflag |= (CS8);
135 /* local modes - choing off, canonical off, no extended functions,
136 * no signal chars (^Z,^C) */
137 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
138 /* control chars - set return condition: min number of bytes and timer.
139 * We want read to return every single byte, without timeout. */
140 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
141
142 /* put terminal in raw mode after flushing */
143 if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
144 rawmode = 1;
145 return 0;
146
147 fatal:
148 errno = ENOTTY;
149 return -1;
150 }
151
152 static void disableRawMode(int fd) {
153 /* Don't even check the return value as it's too late. */
154 if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1)
155 rawmode = 0;
156 }
157
158 /* At exit we'll try to fix the terminal to the initial conditions. */
159 static void linenoiseAtExit(void) {
160 disableRawMode(STDIN_FILENO);
161 freeHistory();
162 }
163
164 static int getColumns(void) {
165 struct winsize ws;
166
167 if (ioctl(1, TIOCGWINSZ, &ws) == -1) return 80;
168 return ws.ws_col;
169 }
170
171 static void refreshLine(int fd, const char *prompt, char *buf, size_t len, size_t pos, size_t cols) {
172 char seq[64];
173 size_t plen = strlen(prompt);
174
175 while((plen+pos) >= cols) {
176 buf++;
177 len--;
178 pos--;
179 }
180 while (plen+len > cols) {
181 len--;
182 }
183
184 /* Cursor to left edge */
185 snprintf(seq,64,"\x1b[0G");
186 if (write(fd,seq,strlen(seq)) == -1) return;
187 /* Write the prompt and the current buffer content */
188 if (write(fd,prompt,strlen(prompt)) == -1) return;
189 if (write(fd,buf,len) == -1) return;
190 /* Erase to right */
191 snprintf(seq,64,"\x1b[0K");
192 if (write(fd,seq,strlen(seq)) == -1) return;
193 /* Move cursor to original position. */
194 snprintf(seq,64,"\x1b[0G\x1b[%dC", (int)(pos+plen));
195 if (write(fd,seq,strlen(seq)) == -1) return;
196 }
197
198 static int linenoisePrompt(int fd, char *buf, size_t buflen, const char *prompt) {
199 size_t plen = strlen(prompt);
200 size_t pos = 0;
201 size_t len = 0;
202 size_t cols = getColumns();
203 int history_index = 0;
204
205 buf[0] = '\0';
206 buflen--; /* Make sure there is always space for the nulterm */
207
208 /* The latest history entry is always our current buffer, that
209 * initially is just an empty string. */
210 linenoiseHistoryAdd("");
211
212 if (write(fd,prompt,plen) == -1) return -1;
213 while(1) {
214 char c;
215 int nread;
216 char seq[2], seq2[2];
217
218 nread = read(fd,&c,1);
219 if (nread <= 0) return len;
220 switch(c) {
221 case 13: /* enter */
222 case 4: /* ctrl-d */
223 history_len--;
224 free(history[history_len]);
225 return (len == 0 && c == 4) ? -1 : (int)len;
226 case 3: /* ctrl-c */
227 errno = EAGAIN;
228 return -1;
229 case 127: /* backspace */
230 case 8: /* ctrl-h */
231 if (pos > 0 && len > 0) {
232 memmove(buf+pos-1,buf+pos,len-pos);
233 pos--;
234 len--;
235 buf[len] = '\0';
236 refreshLine(fd,prompt,buf,len,pos,cols);
237 }
238 break;
239 case 20: /* ctrl-t */
240 if (pos > 0 && pos < len) {
241 int aux = buf[pos-1];
242 buf[pos-1] = buf[pos];
243 buf[pos] = aux;
244 if (pos != len-1) pos++;
245 refreshLine(fd,prompt,buf,len,pos,cols);
246 }
247 break;
248 case 2: /* ctrl-b */
249 goto left_arrow;
250 case 6: /* ctrl-f */
251 goto right_arrow;
252 case 16: /* ctrl-p */
253 seq[1] = 65;
254 goto up_down_arrow;
255 case 14: /* ctrl-n */
256 seq[1] = 66;
257 goto up_down_arrow;
258 break;
259 case 27: /* escape sequence */
260 if (read(fd,seq,2) == -1) break;
261 if (seq[0] == 91 && seq[1] == 68) {
262 left_arrow:
263 /* left arrow */
264 if (pos > 0) {
265 pos--;
266 refreshLine(fd,prompt,buf,len,pos,cols);
267 }
268 } else if (seq[0] == 91 && seq[1] == 67) {
269 right_arrow:
270 /* right arrow */
271 if (pos != len) {
272 pos++;
273 refreshLine(fd,prompt,buf,len,pos,cols);
274 }
275 } else if (seq[0] == 91 && (seq[1] == 65 || seq[1] == 66)) {
276 up_down_arrow:
277 /* up and down arrow: history */
278 if (history_len > 1) {
279 /* Update the current history entry before to
280 * overwrite it with tne next one. */
281 free(history[history_len-1-history_index]);
282 history[history_len-1-history_index] = strdup(buf);
283 /* Show the new entry */
284 history_index += (seq[1] == 65) ? 1 : -1;
285 if (history_index < 0) {
286 history_index = 0;
287 break;
288 } else if (history_index >= history_len) {
289 history_index = history_len-1;
290 break;
291 }
292 strncpy(buf,history[history_len-1-history_index],buflen);
293 buf[buflen] = '\0';
294 len = pos = strlen(buf);
295 refreshLine(fd,prompt,buf,len,pos,cols);
296 }
297 } else if (seq[0] == 91 && seq[1] > 48 && seq[1] < 55) {
298 /* extended escape */
299 if (read(fd,seq2,2) == -1) break;
300 if (seq[1] == 51 && seq2[0] == 126) {
301 /* delete */
302 if (len > 0 && pos < len) {
303 memmove(buf+pos,buf+pos+1,len-pos-1);
304 len--;
305 buf[len] = '\0';
306 refreshLine(fd,prompt,buf,len,pos,cols);
307 }
308 }
309 }
310 break;
311 default:
312 if (len < buflen) {
313 if (len == pos) {
314 buf[pos] = c;
315 pos++;
316 len++;
317 buf[len] = '\0';
318 if (plen+len < cols) {
319 /* Avoid a full update of the line in the
320 * trivial case. */
321 if (write(fd,&c,1) == -1) return -1;
322 } else {
323 refreshLine(fd,prompt,buf,len,pos,cols);
324 }
325 } else {
326 memmove(buf+pos+1,buf+pos,len-pos);
327 buf[pos] = c;
328 len++;
329 pos++;
330 buf[len] = '\0';
331 refreshLine(fd,prompt,buf,len,pos,cols);
332 }
333 }
334 break;
335 case 21: /* Ctrl+u, delete the whole line. */
336 buf[0] = '\0';
337 pos = len = 0;
338 refreshLine(fd,prompt,buf,len,pos,cols);
339 break;
340 case 11: /* Ctrl+k, delete from current to end of line. */
341 buf[pos] = '\0';
342 len = pos;
343 refreshLine(fd,prompt,buf,len,pos,cols);
344 break;
345 case 1: /* Ctrl+a, go to the start of the line */
346 pos = 0;
347 refreshLine(fd,prompt,buf,len,pos,cols);
348 break;
349 case 5: /* ctrl+e, go to the end of the line */
350 pos = len;
351 refreshLine(fd,prompt,buf,len,pos,cols);
352 break;
353 }
354 }
355 return len;
356 }
357
358 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
359 int fd = STDIN_FILENO;
360 int count;
361
362 if (buflen == 0) {
363 errno = EINVAL;
364 return -1;
365 }
366 if (!isatty(STDIN_FILENO)) {
367 if (fgets(buf, buflen, stdin) == NULL) return -1;
368 count = strlen(buf);
369 if (count && buf[count-1] == '\n') {
370 count--;
371 buf[count] = '\0';
372 }
373 } else {
374 if (enableRawMode(fd) == -1) return -1;
375 count = linenoisePrompt(fd, buf, buflen, prompt);
376 disableRawMode(fd);
377 printf("\n");
378 }
379 return count;
380 }
381
382 char *linenoise(const char *prompt) {
383 char buf[LINENOISE_MAX_LINE];
384 int count;
385
386 if (isUnsupportedTerm()) {
387 size_t len;
388
389 printf("%s",prompt);
390 fflush(stdout);
391 if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
392 len = strlen(buf);
393 while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
394 len--;
395 buf[len] = '\0';
396 }
397 return strdup(buf);
398 } else {
399 count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
400 if (count == -1) return NULL;
401 return strdup(buf);
402 }
403 }
404
405 /* Using a circular buffer is smarter, but a bit more complex to handle. */
406 int linenoiseHistoryAdd(const char *line) {
407 char *linecopy;
408
409 if (history_max_len == 0) return 0;
410 if (history == NULL) {
411 history = malloc(sizeof(char*)*history_max_len);
412 if (history == NULL) return 0;
413 memset(history,0,(sizeof(char*)*history_max_len));
414 }
415 linecopy = strdup(line);
416 if (!linecopy) return 0;
417 if (history_len == history_max_len) {
418 free(history[0]);
419 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
420 history_len--;
421 }
422 history[history_len] = linecopy;
423 history_len++;
424 return 1;
425 }
426
427 int linenoiseHistorySetMaxLen(int len) {
428 char **new;
429
430 if (len < 1) return 0;
431 if (history) {
432 int tocopy = history_len;
433
434 new = malloc(sizeof(char*)*len);
435 if (new == NULL) return 0;
436 if (len < tocopy) tocopy = len;
437 memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
438 free(history);
439 history = new;
440 }
441 history_max_len = len;
442 if (history_len > history_max_len)
443 history_len = history_max_len;
444 return 1;
445 }
446
447 /* Save the history in the specified file. On success 0 is returned
448 * otherwise -1 is returned. */
449 int linenoiseHistorySave(char *filename) {
450 FILE *fp = fopen(filename,"w");
451 int j;
452
453 if (fp == NULL) return -1;
454 for (j = 0; j < history_len; j++)
455 fprintf(fp,"%s\n",history[j]);
456 fclose(fp);
457 return 0;
458 }
459
460 /* Load the history from the specified file. If the file does not exist
461 * zero is returned and no operation is performed.
462 *
463 * If the file exists and the operation succeeded 0 is returned, otherwise
464 * on error -1 is returned. */
465 int linenoiseHistoryLoad(char *filename) {
466 FILE *fp = fopen(filename,"r");
467 char buf[LINENOISE_MAX_LINE];
468
469 if (fp == NULL) return -1;
470
471 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
472 char *p;
473
474 p = strchr(buf,'\r');
475 if (!p) p = strchr(buf,'\n');
476 if (p) *p = '\0';
477 linenoiseHistoryAdd(buf);
478 }
479 fclose(fp);
480 return 0;
481 }