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