]> git.lizzy.rs Git - linenoise.git/blob - linenoise.c
Fix arrow keys on some terminals
[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         int ext;
309         char seq[2], seq2[2];
310
311         nread = read(fd,&c,1);
312         if (nread <= 0) return len;
313
314         /* Only autocomplete when the callback is set. It returns < 0 when
315          * there was an error reading from fd. Otherwise it will return the
316          * character that should be handled next. */
317         if (c == 9 && completionCallback != NULL) {
318             c = completeLine(fd,prompt,buf,buflen,&len,&pos,cols);
319             /* Return on errors */
320             if (c < 0) return len;
321             /* Read next character when 0 */
322             if (c == 0) continue;
323         }
324
325         switch(c) {
326         case 13:    /* enter */
327             history_len--;
328             free(history[history_len]);
329             return (int)len;
330         case 3:     /* ctrl-c */
331             errno = EAGAIN;
332             return -1;
333         case 127:   /* backspace */
334         case 8:     /* ctrl-h */
335             if (pos > 0 && len > 0) {
336                 memmove(buf+pos-1,buf+pos,len-pos);
337                 pos--;
338                 len--;
339                 buf[len] = '\0';
340                 refreshLine(fd,prompt,buf,len,pos,cols);
341             }
342             break;
343         case 4:     /* ctrl-d, remove char at right of cursor */
344             if (len > 1 && pos < (len-1)) {
345                 memmove(buf+pos,buf+pos+1,len-pos);
346                 len--;
347                 buf[len] = '\0';
348                 refreshLine(fd,prompt,buf,len,pos,cols);
349             } else if (len == 0) {
350                 history_len--;
351                 free(history[history_len]);
352                 return -1;
353             }
354             break;
355         case 20:    /* ctrl-t */
356             if (pos > 0 && pos < len) {
357                 int aux = buf[pos-1];
358                 buf[pos-1] = buf[pos];
359                 buf[pos] = aux;
360                 if (pos != len-1) pos++;
361                 refreshLine(fd,prompt,buf,len,pos,cols);
362             }
363             break;
364         case 2:     /* ctrl-b */
365             goto left_arrow;
366         case 6:     /* ctrl-f */
367             goto right_arrow;
368         case 16:    /* ctrl-p */
369             seq[1] = 65;
370             goto up_down_arrow;
371         case 14:    /* ctrl-n */
372             seq[1] = 66;
373             goto up_down_arrow;
374             break;
375         case 27:    /* escape sequence */
376             if (read(fd,seq,2) == -1) break;
377             ext = (seq[0] == 91 || seq[0] == 79);
378             if (ext && seq[1] == 68) {
379 left_arrow:
380                 /* left arrow */
381                 if (pos > 0) {
382                     pos--;
383                     refreshLine(fd,prompt,buf,len,pos,cols);
384                 }
385             } else if (ext && seq[1] == 67) {
386 right_arrow:
387                 /* right arrow */
388                 if (pos != len) {
389                     pos++;
390                     refreshLine(fd,prompt,buf,len,pos,cols);
391                 }
392             } else if (ext && (seq[1] == 65 || seq[1] == 66)) {
393 up_down_arrow:
394                 /* up and down arrow: history */
395                 if (history_len > 1) {
396                     /* Update the current history entry before to
397                      * overwrite it with tne next one. */
398                     free(history[history_len-1-history_index]);
399                     history[history_len-1-history_index] = strdup(buf);
400                     /* Show the new entry */
401                     history_index += (seq[1] == 65) ? 1 : -1;
402                     if (history_index < 0) {
403                         history_index = 0;
404                         break;
405                     } else if (history_index >= history_len) {
406                         history_index = history_len-1;
407                         break;
408                     }
409                     strncpy(buf,history[history_len-1-history_index],buflen);
410                     buf[buflen] = '\0';
411                     len = pos = strlen(buf);
412                     refreshLine(fd,prompt,buf,len,pos,cols);
413                 }
414             } else if (seq[0] == 91 && seq[1] > 48 && seq[1] < 55) {
415                 /* extended escape */
416                 if (read(fd,seq2,2) == -1) break;
417                 if (seq[1] == 51 && seq2[0] == 126) {
418                     /* delete */
419                     if (len > 0 && pos < len) {
420                         memmove(buf+pos,buf+pos+1,len-pos-1);
421                         len--;
422                         buf[len] = '\0';
423                         refreshLine(fd,prompt,buf,len,pos,cols);
424                     }
425                 }
426             }
427             break;
428         default:
429             if (len < buflen) {
430                 if (len == pos) {
431                     buf[pos] = c;
432                     pos++;
433                     len++;
434                     buf[len] = '\0';
435                     if (plen+len < cols) {
436                         /* Avoid a full update of the line in the
437                          * trivial case. */
438                         if (write(fd,&c,1) == -1) return -1;
439                     } else {
440                         refreshLine(fd,prompt,buf,len,pos,cols);
441                     }
442                 } else {
443                     memmove(buf+pos+1,buf+pos,len-pos);
444                     buf[pos] = c;
445                     len++;
446                     pos++;
447                     buf[len] = '\0';
448                     refreshLine(fd,prompt,buf,len,pos,cols);
449                 }
450             }
451             break;
452         case 21: /* Ctrl+u, delete the whole line. */
453             buf[0] = '\0';
454             pos = len = 0;
455             refreshLine(fd,prompt,buf,len,pos,cols);
456             break;
457         case 11: /* Ctrl+k, delete from current to end of line. */
458             buf[pos] = '\0';
459             len = pos;
460             refreshLine(fd,prompt,buf,len,pos,cols);
461             break;
462         case 1: /* Ctrl+a, go to the start of the line */
463             pos = 0;
464             refreshLine(fd,prompt,buf,len,pos,cols);
465             break;
466         case 5: /* ctrl+e, go to the end of the line */
467             pos = len;
468             refreshLine(fd,prompt,buf,len,pos,cols);
469             break;
470         case 12: /* ctrl+l, clear screen */
471             linenoiseClearScreen();
472             refreshLine(fd,prompt,buf,len,pos,cols);
473         }
474     }
475     return len;
476 }
477
478 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
479     int fd = STDIN_FILENO;
480     int count;
481
482     if (buflen == 0) {
483         errno = EINVAL;
484         return -1;
485     }
486     if (!isatty(STDIN_FILENO)) {
487         if (fgets(buf, buflen, stdin) == NULL) return -1;
488         count = strlen(buf);
489         if (count && buf[count-1] == '\n') {
490             count--;
491             buf[count] = '\0';
492         }
493     } else {
494         if (enableRawMode(fd) == -1) return -1;
495         count = linenoisePrompt(fd, buf, buflen, prompt);
496         disableRawMode(fd);
497         printf("\n");
498     }
499     return count;
500 }
501
502 char *linenoise(const char *prompt) {
503     char buf[LINENOISE_MAX_LINE];
504     int count;
505
506     if (isUnsupportedTerm()) {
507         size_t len;
508
509         printf("%s",prompt);
510         fflush(stdout);
511         if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
512         len = strlen(buf);
513         while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
514             len--;
515             buf[len] = '\0';
516         }
517         return strdup(buf);
518     } else {
519         count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
520         if (count == -1) return NULL;
521         return strdup(buf);
522     }
523 }
524
525 /* Register a callback function to be called for tab-completion. */
526 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
527     completionCallback = fn;
528 }
529
530 void linenoiseAddCompletion(linenoiseCompletions *lc, char *str) {
531     size_t len = strlen(str);
532     char *copy = malloc(len+1);
533     memcpy(copy,str,len+1);
534     lc->cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
535     lc->cvec[lc->len++] = copy;
536 }
537
538 /* Using a circular buffer is smarter, but a bit more complex to handle. */
539 int linenoiseHistoryAdd(const char *line) {
540     char *linecopy;
541
542     if (history_max_len == 0) return 0;
543     if (history == NULL) {
544         history = malloc(sizeof(char*)*history_max_len);
545         if (history == NULL) return 0;
546         memset(history,0,(sizeof(char*)*history_max_len));
547     }
548     linecopy = strdup(line);
549     if (!linecopy) return 0;
550     if (history_len == history_max_len) {
551         free(history[0]);
552         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
553         history_len--;
554     }
555     history[history_len] = linecopy;
556     history_len++;
557     return 1;
558 }
559
560 int linenoiseHistorySetMaxLen(int len) {
561     char **new;
562
563     if (len < 1) return 0;
564     if (history) {
565         int tocopy = history_len;
566
567         new = malloc(sizeof(char*)*len);
568         if (new == NULL) return 0;
569         if (len < tocopy) tocopy = len;
570         memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
571         free(history);
572         history = new;
573     }
574     history_max_len = len;
575     if (history_len > history_max_len)
576         history_len = history_max_len;
577     return 1;
578 }
579
580 /* Save the history in the specified file. On success 0 is returned
581  * otherwise -1 is returned. */
582 int linenoiseHistorySave(char *filename) {
583     FILE *fp = fopen(filename,"w");
584     int j;
585     
586     if (fp == NULL) return -1;
587     for (j = 0; j < history_len; j++)
588         fprintf(fp,"%s\n",history[j]);
589     fclose(fp);
590     return 0;
591 }
592
593 /* Load the history from the specified file. If the file does not exist
594  * zero is returned and no operation is performed.
595  *
596  * If the file exists and the operation succeeded 0 is returned, otherwise
597  * on error -1 is returned. */
598 int linenoiseHistoryLoad(char *filename) {
599     FILE *fp = fopen(filename,"r");
600     char buf[LINENOISE_MAX_LINE];
601     
602     if (fp == NULL) return -1;
603
604     while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
605         char *p;
606         
607         p = strchr(buf,'\r');
608         if (!p) p = strchr(buf,'\n');
609         if (p) *p = '\0';
610         linenoiseHistoryAdd(buf);
611     }
612     fclose(fp);
613     return 0;
614 }