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