]> git.lizzy.rs Git - linenoise.git/blob - linenoise.c
0ebef2e910f8772cfc9c35a7d5d858c227bccef5
[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  * 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 #include "linenoise.h"
83
84 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
85 #define LINENOISE_MAX_LINE 4096
86 static char *unsupported_term[] = {"dumb","cons25",NULL};
87 static linenoiseCompletionCallback *completionCallback = NULL;
88
89 static struct termios orig_termios; /* in order to restore at exit */
90 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
91 static int atexit_registered = 0; /* register atexit just 1 time */
92 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
93 static int history_len = 0;
94 char **history = NULL;
95
96 static void linenoiseAtExit(void);
97 int linenoiseHistoryAdd(const char *line);
98
99 static int isUnsupportedTerm(void) {
100     char *term = getenv("TERM");
101     int j;
102
103     if (term == NULL) return 0;
104     for (j = 0; unsupported_term[j]; j++)
105         if (!strcasecmp(term,unsupported_term[j])) return 1;
106     return 0;
107 }
108
109 static void freeHistory(void) {
110     if (history) {
111         int j;
112
113         for (j = 0; j < history_len; j++)
114             free(history[j]);
115         free(history);
116     }
117 }
118
119 static int enableRawMode(int fd) {
120     struct termios raw;
121
122     if (!isatty(STDIN_FILENO)) goto fatal;
123     if (!atexit_registered) {
124         atexit(linenoiseAtExit);
125         atexit_registered = 1;
126     }
127     if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
128
129     raw = orig_termios;  /* modify the original mode */
130     /* input modes: no break, no CR to NL, no parity check, no strip char,
131      * no start/stop output control. */
132     raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
133     /* output modes - disable post processing */
134     raw.c_oflag &= ~(OPOST);
135     /* control modes - set 8 bit chars */
136     raw.c_cflag |= (CS8);
137     /* local modes - choing off, canonical off, no extended functions,
138      * no signal chars (^Z,^C) */
139     raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
140     /* control chars - set return condition: min number of bytes and timer.
141      * We want read to return every single byte, without timeout. */
142     raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
143
144     /* put terminal in raw mode after flushing */
145     if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
146     rawmode = 1;
147     return 0;
148
149 fatal:
150     errno = ENOTTY;
151     return -1;
152 }
153
154 static void disableRawMode(int fd) {
155     /* Don't even check the return value as it's too late. */
156     if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1)
157         rawmode = 0;
158 }
159
160 /* At exit we'll try to fix the terminal to the initial conditions. */
161 static void linenoiseAtExit(void) {
162     disableRawMode(STDIN_FILENO);
163     freeHistory();
164 }
165
166 static int getColumns(void) {
167     struct winsize ws;
168
169     if (ioctl(1, TIOCGWINSZ, &ws) == -1) return 80;
170     return ws.ws_col;
171 }
172
173 static 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
200 static void beep() {
201     fprintf(stderr, "\x7");
202     fflush(stderr);
203 }
204
205 static void freeCompletions(linenoiseCompletions *lc) {
206     size_t i;
207     for (i = 0; i < lc->len; i++)
208         free(lc->cvec[i]);
209     if (lc->cvec != NULL)
210         free(lc->cvec);
211 }
212
213 static int completeLine(int fd, const char *prompt, char *buf, size_t buflen, size_t *len, size_t *pos, size_t cols) {
214     linenoiseCompletions lc = { 0, NULL };
215     int nread, nwritten;
216     char c = 0;
217
218     completionCallback(buf,&lc);
219     if (lc.len == 0) {
220         beep();
221     } else {
222         size_t stop = 0, i = 0;
223         size_t clen;
224
225         while(!stop) {
226             /* Show completion or original buffer */
227             if (i < lc.len) {
228                 clen = strlen(lc.cvec[i]);
229                 refreshLine(fd,prompt,lc.cvec[i],clen,clen,cols);
230             } else {
231                 refreshLine(fd,prompt,buf,*len,*pos,cols);
232             }
233
234             nread = read(fd,&c,1);
235             if (nread <= 0) {
236                 freeCompletions(&lc);
237                 return -1;
238             }
239
240             switch(c) {
241                 case 9: /* tab */
242                     i = (i+1) % (lc.len+1);
243                     if (i == lc.len) beep();
244                     break;
245                 case 27: /* escape */
246                     stop = 1;
247                     break;
248                 default:
249                     /* update buffer and return */
250                     if (i < lc.len) {
251                         nwritten = snprintf(buf,buflen,"%s",lc.cvec[i]);
252                         *len = *pos = nwritten;
253                     }
254                     stop = 1;
255                     break;
256             }
257         }
258     }
259
260     freeCompletions(&lc);
261     return c; /* Return last read character */
262 }
263
264 static int linenoisePrompt(int fd, char *buf, size_t buflen, const char *prompt) {
265     size_t plen = strlen(prompt);
266     size_t pos = 0;
267     size_t len = 0;
268     size_t cols = getColumns();
269     int history_index = 0;
270
271     buf[0] = '\0';
272     buflen--; /* Make sure there is always space for the nulterm */
273
274     /* The latest history entry is always our current buffer, that
275      * initially is just an empty string. */
276     linenoiseHistoryAdd("");
277     
278     if (write(fd,prompt,plen) == -1) return -1;
279     while(1) {
280         char c;
281         int nread;
282         char seq[2], seq2[2];
283
284         nread = read(fd,&c,1);
285         if (nread <= 0) return len;
286
287         /* Only autocomplete when the callback is set. It returns < 0 when
288          * there was an error reading from fd. Otherwise it will return the
289          * character that should be handled next. */
290         if (c == 9 && completionCallback != NULL) {
291             c = completeLine(fd,prompt,buf,buflen,&len,&pos,cols);
292             /* Return on errors */
293             if (c < 0) return len;
294             /* Read next character when 0 */
295             if (c == 0) continue;
296         }
297
298         switch(c) {
299         case 13:    /* enter */
300         case 4:     /* ctrl-d */
301             history_len--;
302             free(history[history_len]);
303             return (len == 0 && c == 4) ? -1 : (int)len;
304         case 3:     /* ctrl-c */
305             errno = EAGAIN;
306             return -1;
307         case 127:   /* backspace */
308         case 8:     /* ctrl-h */
309             if (pos > 0 && len > 0) {
310                 memmove(buf+pos-1,buf+pos,len-pos);
311                 pos--;
312                 len--;
313                 buf[len] = '\0';
314                 refreshLine(fd,prompt,buf,len,pos,cols);
315             }
316             break;
317         case 20:    /* ctrl-t */
318             if (pos > 0 && pos < len) {
319                 int aux = buf[pos-1];
320                 buf[pos-1] = buf[pos];
321                 buf[pos] = aux;
322                 if (pos != len-1) pos++;
323                 refreshLine(fd,prompt,buf,len,pos,cols);
324             }
325             break;
326         case 2:     /* ctrl-b */
327             goto left_arrow;
328         case 6:     /* ctrl-f */
329             goto right_arrow;
330         case 16:    /* ctrl-p */
331             seq[1] = 65;
332             goto up_down_arrow;
333         case 14:    /* ctrl-n */
334             seq[1] = 66;
335             goto up_down_arrow;
336             break;
337         case 27:    /* escape sequence */
338             if (read(fd,seq,2) == -1) break;
339             if (seq[0] == 91 && seq[1] == 68) {
340 left_arrow:
341                 /* left arrow */
342                 if (pos > 0) {
343                     pos--;
344                     refreshLine(fd,prompt,buf,len,pos,cols);
345                 }
346             } else if (seq[0] == 91 && seq[1] == 67) {
347 right_arrow:
348                 /* right arrow */
349                 if (pos != len) {
350                     pos++;
351                     refreshLine(fd,prompt,buf,len,pos,cols);
352                 }
353             } else if (seq[0] == 91 && (seq[1] == 65 || seq[1] == 66)) {
354 up_down_arrow:
355                 /* up and down arrow: history */
356                 if (history_len > 1) {
357                     /* Update the current history entry before to
358                      * overwrite it with tne next one. */
359                     free(history[history_len-1-history_index]);
360                     history[history_len-1-history_index] = strdup(buf);
361                     /* Show the new entry */
362                     history_index += (seq[1] == 65) ? 1 : -1;
363                     if (history_index < 0) {
364                         history_index = 0;
365                         break;
366                     } else if (history_index >= history_len) {
367                         history_index = history_len-1;
368                         break;
369                     }
370                     strncpy(buf,history[history_len-1-history_index],buflen);
371                     buf[buflen] = '\0';
372                     len = pos = strlen(buf);
373                     refreshLine(fd,prompt,buf,len,pos,cols);
374                 }
375             } else if (seq[0] == 91 && seq[1] > 48 && seq[1] < 55) {
376                 /* extended escape */
377                 if (read(fd,seq2,2) == -1) break;
378                 if (seq[1] == 51 && seq2[0] == 126) {
379                     /* delete */
380                     if (len > 0 && pos < len) {
381                         memmove(buf+pos,buf+pos+1,len-pos-1);
382                         len--;
383                         buf[len] = '\0';
384                         refreshLine(fd,prompt,buf,len,pos,cols);
385                     }
386                 }
387             }
388             break;
389         default:
390             if (len < buflen) {
391                 if (len == pos) {
392                     buf[pos] = c;
393                     pos++;
394                     len++;
395                     buf[len] = '\0';
396                     if (plen+len < cols) {
397                         /* Avoid a full update of the line in the
398                          * trivial case. */
399                         if (write(fd,&c,1) == -1) return -1;
400                     } else {
401                         refreshLine(fd,prompt,buf,len,pos,cols);
402                     }
403                 } else {
404                     memmove(buf+pos+1,buf+pos,len-pos);
405                     buf[pos] = c;
406                     len++;
407                     pos++;
408                     buf[len] = '\0';
409                     refreshLine(fd,prompt,buf,len,pos,cols);
410                 }
411             }
412             break;
413         case 21: /* Ctrl+u, delete the whole line. */
414             buf[0] = '\0';
415             pos = len = 0;
416             refreshLine(fd,prompt,buf,len,pos,cols);
417             break;
418         case 11: /* Ctrl+k, delete from current to end of line. */
419             buf[pos] = '\0';
420             len = pos;
421             refreshLine(fd,prompt,buf,len,pos,cols);
422             break;
423         case 1: /* Ctrl+a, go to the start of the line */
424             pos = 0;
425             refreshLine(fd,prompt,buf,len,pos,cols);
426             break;
427         case 5: /* ctrl+e, go to the end of the line */
428             pos = len;
429             refreshLine(fd,prompt,buf,len,pos,cols);
430             break;
431         }
432     }
433     return len;
434 }
435
436 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
437     int fd = STDIN_FILENO;
438     int count;
439
440     if (buflen == 0) {
441         errno = EINVAL;
442         return -1;
443     }
444     if (!isatty(STDIN_FILENO)) {
445         if (fgets(buf, buflen, stdin) == NULL) return -1;
446         count = strlen(buf);
447         if (count && buf[count-1] == '\n') {
448             count--;
449             buf[count] = '\0';
450         }
451     } else {
452         if (enableRawMode(fd) == -1) return -1;
453         count = linenoisePrompt(fd, buf, buflen, prompt);
454         disableRawMode(fd);
455         printf("\n");
456     }
457     return count;
458 }
459
460 char *linenoise(const char *prompt) {
461     char buf[LINENOISE_MAX_LINE];
462     int count;
463
464     if (isUnsupportedTerm()) {
465         size_t len;
466
467         printf("%s",prompt);
468         fflush(stdout);
469         if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
470         len = strlen(buf);
471         while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
472             len--;
473             buf[len] = '\0';
474         }
475         return strdup(buf);
476     } else {
477         count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
478         if (count == -1) return NULL;
479         return strdup(buf);
480     }
481 }
482
483 /* Register a callback function to be called for tab-completion. */
484 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
485     completionCallback = fn;
486 }
487
488 void linenoiseAddCompletion(linenoiseCompletions *lc, char *str) {
489     size_t len = strlen(str);
490     char *copy = malloc(len+1);
491     memcpy(copy,str,len+1);
492     lc->cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
493     lc->cvec[lc->len++] = copy;
494 }
495
496 /* Using a circular buffer is smarter, but a bit more complex to handle. */
497 int linenoiseHistoryAdd(const char *line) {
498     char *linecopy;
499
500     if (history_max_len == 0) return 0;
501     if (history == NULL) {
502         history = malloc(sizeof(char*)*history_max_len);
503         if (history == NULL) return 0;
504         memset(history,0,(sizeof(char*)*history_max_len));
505     }
506     linecopy = strdup(line);
507     if (!linecopy) return 0;
508     if (history_len == history_max_len) {
509         free(history[0]);
510         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
511         history_len--;
512     }
513     history[history_len] = linecopy;
514     history_len++;
515     return 1;
516 }
517
518 int linenoiseHistorySetMaxLen(int len) {
519     char **new;
520
521     if (len < 1) return 0;
522     if (history) {
523         int tocopy = history_len;
524
525         new = malloc(sizeof(char*)*len);
526         if (new == NULL) return 0;
527         if (len < tocopy) tocopy = len;
528         memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
529         free(history);
530         history = new;
531     }
532     history_max_len = len;
533     if (history_len > history_max_len)
534         history_len = history_max_len;
535     return 1;
536 }
537
538 /* Save the history in the specified file. On success 0 is returned
539  * otherwise -1 is returned. */
540 int linenoiseHistorySave(char *filename) {
541     FILE *fp = fopen(filename,"w");
542     int j;
543     
544     if (fp == NULL) return -1;
545     for (j = 0; j < history_len; j++)
546         fprintf(fp,"%s\n",history[j]);
547     fclose(fp);
548     return 0;
549 }
550
551 /* Load the history from the specified file. If the file does not exist
552  * zero is returned and no operation is performed.
553  *
554  * If the file exists and the operation succeeded 0 is returned, otherwise
555  * on error -1 is returned. */
556 int linenoiseHistoryLoad(char *filename) {
557     FILE *fp = fopen(filename,"r");
558     char buf[LINENOISE_MAX_LINE];
559     
560     if (fp == NULL) return -1;
561
562     while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
563         char *p;
564         
565         p = strchr(buf,'\r');
566         if (!p) p = strchr(buf,'\n');
567         if (p) *p = '\0';
568         linenoiseHistoryAdd(buf);
569     }
570     fclose(fp);
571     return 0;
572 }