linenoise.c revision 7fe202f160ca1926bc0277e3c276ad7b3f9b9aeb
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_MAX_LINE 4096
84static char *unsupported_term[] = {"dumb","cons25",NULL};
85
86static struct termios orig_termios; /* in order to restore at exit */
87static int rawmode = 0; /* for atexit() function to check if restore is needed*/
88static int atexit_registered = 0; /* register atexit just 1 time */
89static int history_max_len = 100;
90static int history_len = 0;
91char **history = NULL;
92
93static void linenoiseAtExit(void);
94int linenoiseHistoryAdd(const char *line);
95
96static int isUnsupportedTerm(void) {
97    char *term = getenv("TERM");
98    int j;
99
100    if (term == NULL) return 0;
101    for (j = 0; unsupported_term[j]; j++)
102        if (!strcasecmp(term,unsupported_term[j])) return 1;
103    return 0;
104}
105
106static void freeHistory(void) {
107    if (history) {
108        int j;
109
110        for (j = 0; j < history_len; j++)
111            free(history[j]);
112        free(history);
113    }
114}
115
116static int enableRawMode(int fd) {
117    struct termios raw;
118
119    if (!isatty(STDIN_FILENO)) goto fatal;
120    if (!atexit_registered) {
121        atexit(linenoiseAtExit);
122        atexit_registered = 1;
123    }
124    if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
125
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 */
140
141    /* put terminal in raw mode after flushing */
142    if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
143    rawmode = 1;
144    return 0;
145
146fatal:
147    errno = ENOTTY;
148    return -1;
149}
150
151static 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)
154        rawmode = 0;
155}
156
157/* At exit we'll try to fix the terminal to the initial conditions. */
158static void linenoiseAtExit(void) {
159    disableRawMode(STDIN_FILENO);
160    freeHistory();
161}
162
163static int getColumns(void) {
164    struct winsize ws;
165
166    if (ioctl(1, TIOCGWINSZ, &ws) == -1) return 80;
167    if (ws.ws_col == 0) {
168        return 80;
169    }
170    return ws.ws_col;
171}
172
173static void refreshLine(int fd, const char *prompt, char *buf, size_t len, size_t pos, size_t cols) {
174    char seq[64];
175    size_t plen = strlen(prompt);
176
177    while((plen+pos) >= cols) {
178        buf++;
179        len--;
180        pos--;
181    }
182    while (plen+len > cols) {
183        len--;
184    }
185
186    /* Cursor to left edge */
187    snprintf(seq,64,"\x1b[0G");
188    if (write(fd,seq,strlen(seq)) == -1) return;
189    /* Write the prompt and the current buffer content */
190    if (write(fd,prompt,strlen(prompt)) == -1) return;
191    if (write(fd,buf,len) == -1) return;
192    /* Erase to right */
193    snprintf(seq,64,"\x1b[0K");
194    if (write(fd,seq,strlen(seq)) == -1) return;
195    /* Move cursor to original position. */
196    snprintf(seq,64,"\x1b[0G\x1b[%dC", (int)(pos+plen));
197    if (write(fd,seq,strlen(seq)) == -1) return;
198}
199
200static int linenoisePrompt(int fd, char *buf, size_t buflen, const char *prompt) {
201    size_t plen = strlen(prompt);
202    size_t pos = 0;
203    size_t len = 0;
204    size_t cols = getColumns();
205    int history_index = 0;
206
207    buf[0] = '\0';
208    buflen--; /* Make sure there is always space for the nulterm */
209
210    /* The latest history entry is always our current buffer, that
211     * initially is just an empty string. */
212    linenoiseHistoryAdd("");
213
214    if (write(fd,prompt,plen) == -1) return -1;
215    while(1) {
216        char c;
217        int nread;
218        char seq[2];
219
220        nread = read(fd,&c,1);
221        if (nread <= 0) return len;
222        switch(c) {
223        case 10:    /* line feed. */
224        case 13:    /* enter */
225            history_len--;
226            return len;
227        case 4:     /* ctrl-d */
228            history_len--;
229            return (len == 0) ? -1 : (int)len;
230        case 3:     /* ctrl-c */
231            errno = EAGAIN;
232            return -1;
233        case 127:   /* backspace */
234        case 8:     /* ctrl-h */
235            if (pos > 0 && len > 0) {
236                memmove(buf+pos-1,buf+pos,len-pos);
237                pos--;
238                len--;
239                buf[len] = '\0';
240                refreshLine(fd,prompt,buf,len,pos,cols);
241            }
242            break;
243        case 20:    /* ctrl-t */
244            if (pos > 0 && pos < len) {
245                int aux = buf[pos-1];
246                buf[pos-1] = buf[pos];
247                buf[pos] = aux;
248                if (pos != len-1) pos++;
249                refreshLine(fd,prompt,buf,len,pos,cols);
250            }
251            break;
252        case 2:     /* ctrl-b */
253            goto left_arrow;
254        case 6:     /* ctrl-f */
255            goto right_arrow;
256        case 16:    /* ctrl-p */
257            seq[1] = 65;
258            goto up_down_arrow;
259        case 14:    /* ctrl-n */
260            seq[1] = 66;
261            goto up_down_arrow;
262            break;
263        case 27:    /* escape sequence */
264            if (read(fd,seq,2) == -1) break;
265            if (seq[0] == 91 && seq[1] == 68) {
266left_arrow:
267                /* left arrow */
268                if (pos > 0) {
269                    pos--;
270                    refreshLine(fd,prompt,buf,len,pos,cols);
271                }
272            } else if (seq[0] == 91 && seq[1] == 67) {
273right_arrow:
274                /* right arrow */
275                if (pos != len) {
276                    pos++;
277                    refreshLine(fd,prompt,buf,len,pos,cols);
278                }
279            } else if (seq[0] == 91 && (seq[1] == 65 || seq[1] == 66)) {
280up_down_arrow:
281                /* up and down arrow: history */
282                if (history_len > 1) {
283                    /* Update the current history entry before to
284                     * overwrite it with tne next one. */
285                    free(history[history_len-1-history_index]);
286                    history[history_len-1-history_index] = strdup(buf);
287                    /* Show the new entry */
288                    history_index += (seq[1] == 65) ? 1 : -1;
289                    if (history_index < 0) {
290                        history_index = 0;
291                        break;
292                    } else if (history_index >= history_len) {
293                        history_index = history_len-1;
294                        break;
295                    }
296                    strncpy(buf,history[history_len-1-history_index],buflen);
297                    buf[buflen] = '\0';
298                    len = pos = strlen(buf);
299                    refreshLine(fd,prompt,buf,len,pos,cols);
300                }
301            }
302            break;
303        default:
304            if (len < buflen) {
305                if (len == pos) {
306                    buf[pos] = c;
307                    pos++;
308                    len++;
309                    buf[len] = '\0';
310                    if (plen+len < cols) {
311                        /* Avoid a full update of the line in the
312                         * trivial case. */
313                        if (write(fd,&c,1) == -1) return -1;
314                    } else {
315                        refreshLine(fd,prompt,buf,len,pos,cols);
316                    }
317                } else {
318                    memmove(buf+pos+1,buf+pos,len-pos);
319                    buf[pos] = c;
320                    len++;
321                    pos++;
322                    buf[len] = '\0';
323                    refreshLine(fd,prompt,buf,len,pos,cols);
324                }
325            }
326            break;
327        case 21: /* Ctrl+u, delete the whole line. */
328            buf[0] = '\0';
329            pos = len = 0;
330            refreshLine(fd,prompt,buf,len,pos,cols);
331            break;
332        case 11: /* Ctrl+k, delete from current to end of line. */
333            buf[pos] = '\0';
334            len = pos;
335            refreshLine(fd,prompt,buf,len,pos,cols);
336            break;
337        case 1: /* Ctrl+a, go to the start of the line */
338            pos = 0;
339            refreshLine(fd,prompt,buf,len,pos,cols);
340            break;
341        case 5: /* ctrl+e, go to the end of the line */
342            pos = len;
343            refreshLine(fd,prompt,buf,len,pos,cols);
344            break;
345        }
346    }
347    return len;
348}
349
350static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
351    int fd = STDIN_FILENO;
352    int count;
353
354    if (buflen == 0) {
355        errno = EINVAL;
356        return -1;
357    }
358    if (!isatty(STDIN_FILENO)) {
359        if (fgets(buf, buflen, stdin) == NULL) return -1;
360        count = strlen(buf);
361        if (count && buf[count-1] == '\n') {
362            count--;
363            buf[count] = '\0';
364        }
365    } else {
366        if (enableRawMode(fd) == -1) return -1;
367        count = linenoisePrompt(fd, buf, buflen, prompt);
368        disableRawMode(fd);
369    }
370    return count;
371}
372
373char *linenoise(const char *prompt) {
374    char buf[LINENOISE_MAX_LINE];
375    int count;
376
377    if (isUnsupportedTerm()) {
378        size_t len;
379
380        printf("%s",prompt);
381        fflush(stdout);
382        if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
383        len = strlen(buf);
384        while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
385            len--;
386            buf[len] = '\0';
387        }
388        return strdup(buf);
389    } else {
390        count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
391        if (count == -1) return NULL;
392        return strdup(buf);
393    }
394}
395
396/* Using a circular buffer is smarter, but a bit more complex to handle. */
397int linenoiseHistoryAdd(const char *line) {
398    char *linecopy;
399
400    if (history_max_len == 0) return 0;
401    if (history == 0) {
402        history = malloc(sizeof(char*)*history_max_len);
403        if (history == NULL) return 0;
404        memset(history,0,(sizeof(char*)*history_max_len));
405    }
406    linecopy = strdup(line);
407    if (!linecopy) return 0;
408    if (history_len == history_max_len) {
409        memmove(history,history+1,sizeof(char*)*(history_max_len-1));
410        history_len--;
411    }
412    history[history_len] = linecopy;
413    history_len++;
414    return 1;
415}
416
417int linenoiseHistorySetMaxLen(int len) {
418    char **new;
419
420    if (len < 1) return 0;
421    if (history) {
422        int tocopy = history_len;
423
424        new = malloc(sizeof(char*)*len);
425        if (new == NULL) return 0;
426        if (len < tocopy) tocopy = len;
427        memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
428        free(history);
429        history = new;
430    }
431    history_max_len = len;
432    if (history_len > history_max_len)
433        history_len = history_max_len;
434    return 1;
435}
436