]>
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
84 static char *unsupported_term
[] = {"dumb","cons25",NULL
};
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
;
93 static void linenoiseAtExit(void);
94 int linenoiseHistoryAdd(const char *line
);
96 static int isUnsupportedTerm(void) {
97 char *term
= getenv("TERM");
100 if (term
== NULL
) return 0;
101 for (j
= 0; unsupported_term
[j
]; j
++)
102 if (!strcasecmp(term
,unsupported_term
[j
])) return 1;
106 static void freeHistory(void) {
110 for (j
= 0; j
< history_len
; j
++)
116 static int enableRawMode(int fd
) {
119 if (!isatty(STDIN_FILENO
)) goto fatal
;
120 if (!atexit_registered
) {
121 atexit(linenoiseAtExit
);
122 atexit_registered
= 1;
124 if (tcgetattr(fd
,&orig_termios
) == -1) goto fatal
;
126 raw
= orig_termios
; /* modify the original mode */
127 /* input modes: no break, no CR to NL, no parity check, no strip char,
128 * no start/stop output control. */
129 raw
.c_iflag
&= ~(BRKINT
| ICRNL
| INPCK
| ISTRIP
| IXON
);
130 /* output modes - disable post processing */
131 raw
.c_oflag
&= ~(OPOST
);
132 /* control modes - set 8 bit chars */
133 raw
.c_cflag
|= (CS8
);
134 /* local modes - choing off, canonical off, no extended functions,
135 * no signal chars (^Z,^C) */
136 raw
.c_lflag
&= ~(ECHO
| ICANON
| IEXTEN
| ISIG
);
137 /* control chars - set return condition: min number of bytes and timer.
138 * We want read to return every single byte, without timeout. */
139 raw
.c_cc
[VMIN
] = 1; raw
.c_cc
[VTIME
] = 0; /* 1 byte, no timer */
141 /* put terminal in raw mode after flushing */
142 if (tcsetattr(fd
,TCSAFLUSH
,&raw
) < 0) goto fatal
;
151 static void disableRawMode(int fd
) {
152 /* Don't even check the return value as it's too late. */
153 if (rawmode
&& tcsetattr(fd
,TCSAFLUSH
,&orig_termios
) != -1)
157 /* At exit we'll try to fix the terminal to the initial conditions. */
158 static void linenoiseAtExit(void) {
159 disableRawMode(STDIN_FILENO
);
163 static int getColumns(void) {
166 if (ioctl(1, TIOCGWINSZ
, &ws
) == -1) return 80;
170 static void refreshLine(int fd
, const char *prompt
, char *buf
, size_t len
, size_t pos
, size_t cols
) {
172 size_t plen
= strlen(prompt
);
174 while((plen
+pos
) >= cols
) {
179 while (plen
+len
> cols
) {
183 /* Cursor to left edge */
184 snprintf(seq
,64,"\x1b[0G");
185 if (write(fd
,seq
,strlen(seq
)) == -1) return;
186 /* Write the prompt and the current buffer content */
187 if (write(fd
,prompt
,strlen(prompt
)) == -1) return;
188 if (write(fd
,buf
,len
) == -1) return;
190 snprintf(seq
,64,"\x1b[0K");
191 if (write(fd
,seq
,strlen(seq
)) == -1) return;
192 /* Move cursor to original position. */
193 snprintf(seq
,64,"\x1b[0G\x1b[%dC", (int)(pos
+plen
));
194 if (write(fd
,seq
,strlen(seq
)) == -1) return;
197 static int linenoisePrompt(int fd
, char *buf
, size_t buflen
, const char *prompt
) {
198 size_t plen
= strlen(prompt
);
201 size_t cols
= getColumns();
202 int history_index
= 0;
205 buflen
--; /* Make sure there is always space for the nulterm */
207 /* The latest history entry is always our current buffer, that
208 * initially is just an empty string. */
209 linenoiseHistoryAdd("");
211 if (write(fd
,prompt
,plen
) == -1) return -1;
217 nread
= read(fd
,&c
,1);
218 if (nread
<= 0) return len
;
225 return (len
== 0) ? -1 : (int)len
;
229 case 127: /* backspace */
231 if (pos
> 0 && len
> 0) {
232 memmove(buf
+pos
-1,buf
+pos
,len
-pos
);
236 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
239 case 20: /* ctrl-t */
240 if (pos
> 0 && pos
< len
) {
241 int aux
= buf
[pos
-1];
242 buf
[pos
-1] = buf
[pos
];
244 if (pos
!= len
-1) pos
++;
245 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
252 case 16: /* ctrl-p */
255 case 14: /* ctrl-n */
259 case 27: /* escape sequence */
260 if (read(fd
,seq
,2) == -1) break;
261 if (seq
[0] == 91 && seq
[1] == 68) {
266 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
268 } else if (seq
[0] == 91 && seq
[1] == 67) {
273 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
275 } else if (seq
[0] == 91 && (seq
[1] == 65 || seq
[1] == 66)) {
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) {
288 } else if (history_index
>= history_len
) {
289 history_index
= history_len
-1;
292 strncpy(buf
,history
[history_len
-1-history_index
],buflen
);
294 len
= pos
= strlen(buf
);
295 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
306 if (plen
+len
< cols
) {
307 /* Avoid a full update of the line in the
309 if (write(fd
,&c
,1) == -1) return -1;
311 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
314 memmove(buf
+pos
+1,buf
+pos
,len
-pos
);
319 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
323 case 21: /* Ctrl+u, delete the whole line. */
326 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
328 case 11: /* Ctrl+k, delete from current to end of line. */
331 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
333 case 1: /* Ctrl+a, go to the start of the line */
335 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
337 case 5: /* ctrl+e, go to the end of the line */
339 refreshLine(fd
,prompt
,buf
,len
,pos
,cols
);
346 static int linenoiseRaw(char *buf
, size_t buflen
, const char *prompt
) {
347 int fd
= STDIN_FILENO
;
354 if (!isatty(STDIN_FILENO
)) {
355 if (fgets(buf
, buflen
, stdin
) == NULL
) return -1;
357 if (count
&& buf
[count
-1] == '\n') {
362 if (enableRawMode(fd
) == -1) return -1;
363 count
= linenoisePrompt(fd
, buf
, buflen
, prompt
);
370 char *linenoise(const char *prompt
) {
371 char buf
[LINENOISE_MAX_LINE
];
374 if (isUnsupportedTerm()) {
379 if (fgets(buf
,LINENOISE_MAX_LINE
,stdin
) == NULL
) return NULL
;
381 while(len
&& (buf
[len
-1] == '\n' || buf
[len
-1] == '\r')) {
387 count
= linenoiseRaw(buf
,LINENOISE_MAX_LINE
,prompt
);
388 if (count
== -1) return NULL
;
393 /* Using a circular buffer is smarter, but a bit more complex to handle. */
394 int linenoiseHistoryAdd(const char *line
) {
397 if (history_max_len
== 0) return 0;
399 history
= malloc(sizeof(char*)*history_max_len
);
400 if (history
== NULL
) return 0;
401 memset(history
,0,(sizeof(char*)*history_max_len
));
403 linecopy
= strdup(line
);
404 if (!linecopy
) return 0;
405 if (history_len
== history_max_len
) {
406 memmove(history
,history
+1,sizeof(char*)*(history_max_len
-1));
409 history
[history_len
] = linecopy
;
414 int linenoiseHistorySetMaxLen(int len
) {
417 if (len
< 1) return 0;
419 int tocopy
= history_len
;
421 new = malloc(sizeof(char*)*len
);
422 if (new == NULL
) return 0;
423 if (len
< tocopy
) tocopy
= len
;
424 memcpy(new,history
+(history_max_len
-tocopy
), sizeof(char*)*tocopy
);
428 history_max_len
= len
;
429 if (history_len
> history_max_len
)
430 history_len
= history_max_len
;