]> git.saurik.com Git - redis.git/blob - linenoise.c
use long long reply type for HINCRBY
[redis.git] / 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 "fmacros.h"
73 #include <termios.h>
74 #include <unistd.h>
75 #include <stdlib.h>
76 #include <stdio.h>
77 #include <errno.h>
78 #include <string.h>
79 #include <stdlib.h>
80 #include <sys/types.h>
81 #include <sys/ioctl.h>
82 #include <unistd.h>
83
84 #define LINENOISE_MAX_LINE 4096
85
86 static struct termios orig_termios; /* in order to restore at exit */
87 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
88 static int atexit_registered = 0; /* register atexit just 1 time */
89 static int history_max_len = 100;
90 static int history_len = 0;
91 char **history = NULL;
92
93 static void linenoiseAtExit(void);
94 int linenoiseHistoryAdd(char *line);
95
96 static void freeHistory(void) {
97 if (history) {
98 int j;
99
100 for (j = 0; j < history_len; j++)
101 free(history[j]);
102 free(history);
103 }
104 }
105
106 static int enableRawMode(int fd) {
107 struct termios raw;
108
109 if (!isatty(STDIN_FILENO)) goto fatal;
110 if (!atexit_registered) {
111 atexit(linenoiseAtExit);
112 atexit_registered = 1;
113 }
114 if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
115
116 raw = orig_termios; /* modify the original mode */
117 /* input modes: no break, no CR to NL, no parity check, no strip char,
118 * no start/stop output control. */
119 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
120 /* output modes - disable post processing */
121 raw.c_oflag &= ~(OPOST);
122 /* control modes - set 8 bit chars */
123 raw.c_cflag |= (CS8);
124 /* local modes - choing off, canonical off, no extended functions,
125 * no signal chars (^Z,^C) */
126 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
127 /* control chars - set return condition: min number of bytes and timer.
128 * We want read to return every single byte, without timeout. */
129 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
130
131 /* put terminal in raw mode after flushing */
132 if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
133 rawmode = 1;
134 return 0;
135
136 fatal:
137 errno = ENOTTY;
138 return -1;
139 }
140
141 static void disableRawMode(int fd) {
142 /* Don't even check the return value as it's too late. */
143 if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1)
144 rawmode = 0;
145 }
146
147 /* At exit we'll try to fix the terminal to the initial conditions. */
148 static void linenoiseAtExit(void) {
149 disableRawMode(STDIN_FILENO);
150 freeHistory();
151 }
152
153 static int getColumns(void) {
154 struct winsize ws;
155
156 if (ioctl(1, TIOCGWINSZ, &ws) == -1) return 80;
157 return ws.ws_col;
158 }
159
160 static void refreshLine(int fd, const char *prompt, char *buf, size_t len, size_t pos, size_t cols) {
161 char seq[64];
162 size_t plen = strlen(prompt);
163
164 while((plen+pos) >= cols) {
165 buf++;
166 len--;
167 pos--;
168 }
169 while (plen+len > cols) {
170 len--;
171 }
172
173 /* Cursor to left edge */
174 snprintf(seq,64,"\x1b[0G");
175 if (write(fd,seq,strlen(seq)) == -1) return;
176 /* Write the prompt and the current buffer content */
177 if (write(fd,prompt,strlen(prompt)) == -1) return;
178 if (write(fd,buf,len) == -1) return;
179 /* Erase to right */
180 snprintf(seq,64,"\x1b[0K");
181 if (write(fd,seq,strlen(seq)) == -1) return;
182 /* Move cursor to original position. */
183 snprintf(seq,64,"\x1b[0G\x1b[%dC", (int)(pos+plen));
184 if (write(fd,seq,strlen(seq)) == -1) return;
185 }
186
187 static int linenoisePrompt(int fd, char *buf, size_t buflen, const char *prompt) {
188 size_t plen = strlen(prompt);
189 size_t pos = 0;
190 size_t len = 0;
191 size_t cols = getColumns();
192 int history_index = 0;
193
194 buf[0] = '\0';
195 buflen--; /* Make sure there is always space for the nulterm */
196
197 /* The latest history entry is always our current buffer, that
198 * initially is just an empty string. */
199 linenoiseHistoryAdd("");
200
201 if (write(fd,prompt,plen) == -1) return -1;
202 while(1) {
203 char c;
204 int nread;
205 char seq[2];
206
207 nread = read(fd,&c,1);
208 if (nread <= 0) return len;
209 switch(c) {
210 case 13: /* enter */
211 history_len--;
212 return len;
213 case 4: /* ctrl-d */
214 history_len--;
215 return (len == 0) ? -1 : (int)len;
216 case 3: /* ctrl-c */
217 errno = EAGAIN;
218 return -1;
219 case 127: /* backspace */
220 case 8: /* ctrl-h */
221 if (pos > 0 && len > 0) {
222 memmove(buf+pos-1,buf+pos,len-pos);
223 pos--;
224 len--;
225 buf[len] = '\0';
226 refreshLine(fd,prompt,buf,len,pos,cols);
227 }
228 break;
229 case 20: /* ctrl-t */
230 if (pos > 0 && pos < len) {
231 int aux = buf[pos-1];
232 buf[pos-1] = buf[pos];
233 buf[pos] = aux;
234 if (pos != len-1) pos++;
235 refreshLine(fd,prompt,buf,len,pos,cols);
236 }
237 break;
238 case 2: /* ctrl-b */
239 goto left_arrow;
240 case 6: /* ctrl-f */
241 goto right_arrow;
242 case 16: /* ctrl-p */
243 seq[1] = 65;
244 goto up_down_arrow;
245 case 14: /* ctrl-n */
246 seq[1] = 66;
247 goto up_down_arrow;
248 break;
249 case 27: /* escape sequence */
250 if (read(fd,seq,2) == -1) break;
251 if (seq[0] == 91 && seq[1] == 68) {
252 left_arrow:
253 /* left arrow */
254 if (pos > 0) {
255 pos--;
256 refreshLine(fd,prompt,buf,len,pos,cols);
257 }
258 } else if (seq[0] == 91 && seq[1] == 67) {
259 right_arrow:
260 /* right arrow */
261 if (pos != len) {
262 pos++;
263 refreshLine(fd,prompt,buf,len,pos,cols);
264 }
265 } else if (seq[0] == 91 && (seq[1] == 65 || seq[1] == 66)) {
266 up_down_arrow:
267 /* up and down arrow: history */
268 if (history_len > 1) {
269 /* Update the current history entry before to
270 * overwrite it with tne next one. */
271 free(history[history_len-1-history_index]);
272 history[history_len-1-history_index] = strdup(buf);
273 /* Show the new entry */
274 history_index += (seq[1] == 65) ? 1 : -1;
275 if (history_index < 0) {
276 history_index = 0;
277 break;
278 } else if (history_index >= history_len) {
279 history_index = history_len-1;
280 break;
281 }
282 strncpy(buf,history[history_len-1-history_index],buflen);
283 buf[buflen] = '\0';
284 len = pos = strlen(buf);
285 refreshLine(fd,prompt,buf,len,pos,cols);
286 }
287 }
288 break;
289 default:
290 if (len < buflen) {
291 if (len == pos) {
292 buf[pos] = c;
293 pos++;
294 len++;
295 buf[len] = '\0';
296 if (plen+len < cols) {
297 /* Avoid a full update of the line in the
298 * trivial case. */
299 if (write(fd,&c,1) == -1) return -1;
300 } else {
301 refreshLine(fd,prompt,buf,len,pos,cols);
302 }
303 } else {
304 memmove(buf+pos+1,buf+pos,len-pos);
305 buf[pos] = c;
306 len++;
307 pos++;
308 buf[len] = '\0';
309 refreshLine(fd,prompt,buf,len,pos,cols);
310 }
311 }
312 break;
313 case 21: /* Ctrl+u, delete the whole line. */
314 buf[0] = '\0';
315 pos = len = 0;
316 refreshLine(fd,prompt,buf,len,pos,cols);
317 break;
318 case 11: /* Ctrl+k, delete from current to end of line. */
319 buf[pos] = '\0';
320 len = pos;
321 refreshLine(fd,prompt,buf,len,pos,cols);
322 break;
323 case 1: /* Ctrl+a, go to the start of the line */
324 pos = 0;
325 refreshLine(fd,prompt,buf,len,pos,cols);
326 break;
327 case 5: /* ctrl+e, go to the end of the line */
328 pos = len;
329 refreshLine(fd,prompt,buf,len,pos,cols);
330 break;
331 }
332 }
333 return len;
334 }
335
336 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
337 int fd = STDIN_FILENO;
338 int count;
339
340 if (buflen == 0) {
341 errno = EINVAL;
342 return -1;
343 }
344 if (enableRawMode(fd) == -1) return -1;
345 count = linenoisePrompt(fd, buf, buflen, prompt);
346 disableRawMode(fd);
347 printf("\n");
348 return count;
349 }
350
351 char *linenoise(const char *prompt) {
352 char buf[LINENOISE_MAX_LINE];
353 int count;
354
355 count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
356 if (count == -1) return NULL;
357 return strdup(buf);
358 }
359
360 /* Using a circular buffer is smarter, but a bit more complex to handle. */
361 int linenoiseHistoryAdd(char *line) {
362 if (history_max_len == 0) return 0;
363 if (history == 0) {
364 history = malloc(sizeof(char*)*history_max_len);
365 if (history == NULL) return 0;
366 memset(history,0,(sizeof(char*)*history_max_len));
367 }
368 line = strdup(line);
369 if (!line) return 0;
370 if (history_len == history_max_len) {
371 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
372 history_len--;
373 }
374 history[history_len] = line;
375 history_len++;
376 return 1;
377 }
378
379 int linenoiseHistorySetMaxLen(int len) {
380 char **new;
381
382 if (len < 1) return 0;
383 if (history) {
384 int tocopy = history_len;
385
386 new = malloc(sizeof(char*)*len);
387 if (new == NULL) return 0;
388 if (len < tocopy) tocopy = len;
389 memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
390 free(history);
391 history = new;
392 }
393 history_max_len = len;
394 if (history_len > history_max_len)
395 history_len = history_max_len;
396 return 1;
397 }