]>
git.saurik.com Git - redis.git/blob - 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.
4 * You can find the latest source code at:
6 * http://github.com/antirez/linenoise
8 * Does a number of crazy assumptions that happen to be true in 99.9999% of
9 * the 2010 UNIX computers around.
11 * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
12 * All rights reserved.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions are met:
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.
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.
39 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
40 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
43 * - Switch to gets() if $TERM is something we can't support.
44 * - Filter bogus Ctrl+<char> combinations.
49 * - History search like Ctrl+r in readline?
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.
56 * CHA (Cursor Horizontal Absolute)
58 * Effect: moves cursor to column n
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
66 * CUF (CUrsor Forward)
68 * Effect: moves cursor forward of n chars
79 #include <sys/types.h>
80 #include <sys/ioctl.h>
83 #define LINENOISE_MAX_LINE 4096
85 static struct termios orig_termios
; /* in order to restore at exit */
86 static int rawmode
= 0; /* for atexit() function to check if restore is needed*/
87 static int atexit_registered
= 0; /* register atexit just 1 time */
88 static int history_max_len
= 100;
89 static int history_len
= 0;
90 char **history
= NULL
;
92 static void linenoiseAtExit(void);
93 int linenoiseHistoryAdd(char *line
);
95 static void freeHistory(void) {
99 for (j
= 0; j
< history_len
; j
++)
105 static int enableRawMode(int fd
) {
108 if (!isatty(STDIN_FILENO
)) goto fatal
;
109 if (!atexit_registered
) {
110 atexit(linenoiseAtExit
);
111 atexit_registered
= 1;
113 if (tcgetattr(fd
,&orig_termios
) == -1) goto fatal
;
115 raw
= orig_termios
; /* modify the original mode */
116 /* input modes: no break, no CR to NL, no parity check, no strip char,
117 * no start/stop output control. */
118 raw
.c_iflag
&= ~(BRKINT
| ICRNL
| INPCK
| ISTRIP
| IXON
);
119 /* output modes - disable post processing */
120 raw
.c_oflag
&= ~(OPOST
);
121 /* control modes - set 8 bit chars */
122 raw
.c_cflag
|= (CS8
);
123 /* local modes - choing off, canonical off, no extended functions,
124 * no signal chars (^Z,^C) */
125 raw
.c_lflag
&= ~(ECHO
| ICANON
| IEXTEN
| ISIG
);
126 /* control chars - set return condition: min number of bytes and timer.
127 * We want read to return every single byte, without timeout. */
128 raw
.c_cc
[VMIN
] = 1; raw
.c_cc
[VTIME
] = 0; /* 1 byte, no timer */
130 /* put terminal in raw mode after flushing */
131 if (tcsetattr(fd
,TCSAFLUSH
,&raw
) < 0) goto fatal
;
140 static void disableRawMode(int fd
) {
141 /* Don't even check the return value as it's too late. */
142 if (rawmode
&& tcsetattr(fd
,TCSAFLUSH
,&orig_termios
) != -1)
146 /* At exit we'll try to fix the terminal to the initial conditions. */
147 static void linenoiseAtExit(void) {
148 disableRawMode(STDIN_FILENO
);
152 static int getColumns(void) {
155 if (ioctl(1, TIOCGWINSZ
, &ws
) == -1) return 80;
159 static void refreshLine(int fd
, const char *prompt
, char *buf
, size_t len
, size_t pos
, size_t cols
) {
161 size_t plen
= strlen(prompt
);
163 while((plen
+pos
) >= cols
) {
168 while (plen
+len
> cols
) {
172 /* Cursor to left edge */
173 snprintf(seq
,64,"\x1b[0G");
174 if (write(fd
,seq
,strlen(seq
)) == -1) return;
175 /* Write the prompt and the current buffer content */
176 if (write(fd
,prompt
,strlen(prompt
)) == -1) return;
177 if (write(fd
,buf
,len
) == -1) return;
179 snprintf(seq
,64,"\x1b[0K");
180 if (write(fd
,seq
,strlen(seq
)) == -1) return;
181 /* Move cursor to original position. */
182 snprintf(seq
,64,"\x1b[0G\x1b[%dC", (int)(pos
+plen
));
183 if (write(fd
,seq
,strlen(seq
)) == -1) return;
186 static int linenoisePrompt(int fd
, char *buf
, size_t buflen
, const char *prompt
) {
187 size_t plen
= strlen(prompt
);
190 size_t cols
= getColumns();
191 int history_index
= 0;
194 buflen
--; /* Make sure there is always space for the nulterm */
196 /* The latest history entry is always our current buffer, that
197 * initially is just an empty string. */
198 linenoiseHistoryAdd("");
200 if (write(fd
,prompt
,plen
) == -1) return -1;
206 nread
= read(fd
,&c
,1);
207 if (nread
<= 0) return len
;
214 return (len
== 0) ? -1 : (int)len
;
218 case 127: /* backspace */
220 if (pos
> 0 && len
> 0) {
221 memmove(buf
+pos
-1,buf
+pos
,len
-pos
);
225 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
228 case 20: /* ctrl-t */
229 if (pos
> 0 && pos
< len
) {
230 int aux
= buf
[pos
-1];
231 buf
[pos
-1] = buf
[pos
];
233 if (pos
!= len
-1) pos
++;
234 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
241 case 16: /* ctrl-p */
244 case 14: /* ctrl-n */
248 case 27: /* escape sequence */
249 if (read(fd
,seq
,2) == -1) break;
250 if (seq
[0] == 91 && seq
[1] == 68) {
255 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
257 } else if (seq
[0] == 91 && seq
[1] == 67) {
262 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
264 } else if (seq
[0] == 91 && (seq
[1] == 65 || seq
[1] == 66)) {
266 /* up and down arrow: history */
267 if (history_len
> 1) {
268 /* Update the current history entry before to
269 * overwrite it with tne next one. */
270 free(history
[history_len
-1-history_index
]);
271 history
[history_len
-1-history_index
] = strdup(buf
);
272 /* Show the new entry */
273 history_index
+= (seq
[1] == 65) ? 1 : -1;
274 if (history_index
< 0) {
277 } else if (history_index
>= history_len
) {
278 history_index
= history_len
-1;
281 strncpy(buf
,history
[history_len
-1-history_index
],buflen
);
283 len
= pos
= strlen(buf
);
284 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
295 if (plen
+len
< cols
) {
296 /* Avoid a full update of the line in the
298 if (write(fd
,&c
,1) == -1) return -1;
300 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
303 memmove(buf
+pos
+1,buf
+pos
,len
-pos
);
308 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
312 case 21: /* Ctrl+u, delete the whole line. */
315 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
317 case 11: /* Ctrl+k, delete from current to end of line. */
320 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
322 case 1: /* Ctrl+a, go to the start of the line */
324 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
326 case 5: /* ctrl+e, go to the end of the line */
328 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
335 static int linenoiseRaw(char *buf
, size_t buflen
, const char *prompt
) {
336 int fd
= STDIN_FILENO
;
343 if (enableRawMode(fd
) == -1) return -1;
344 count
= linenoisePrompt(fd
, buf
, buflen
, prompt
);
350 char *linenoise(const char *prompt
) {
351 char buf
[LINENOISE_MAX_LINE
];
354 count
= linenoiseRaw(buf
,LINENOISE_MAX_LINE
,prompt
);
355 if (count
== -1) return NULL
;
359 /* Using a circular buffer is smarter, but a bit more complex to handle. */
360 int linenoiseHistoryAdd(char *line
) {
361 if (history_max_len
== 0) return 0;
363 history
= malloc(sizeof(char*)*history_max_len
);
364 if (history
== NULL
) return 0;
365 memset(history
,0,(sizeof(char*)*history_max_len
));
369 if (history_len
== history_max_len
) {
370 memmove(history
,history
+1,sizeof(char*)*(history_max_len
-1));
373 history
[history_len
] = line
;
378 int linenoiseHistorySetMaxLen(int len
) {
381 if (len
< 1) return 0;
383 int tocopy
= history_len
;
385 new = malloc(sizeof(char*)*len
);
386 if (new == NULL
) return 0;
387 if (len
< tocopy
) tocopy
= len
;
388 memcpy(new,history
+(history_max_len
-tocopy
), sizeof(char*)*tocopy
);
392 history_max_len
= len
;
393 if (history_len
> history_max_len
)
394 history_len
= history_max_len
;