OSDN Git Service

Working on README, put defs in joy.py
[joypy/Thun.git] / implementations / C / 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-2016, Salvatore Sanfilippo <antirez at gmail dot com>
14  * Copyright (c) 2010-2013, 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  * - Filter bogus Ctrl+<char> combinations.
49  * - Win32 support
50  *
51  * Bloat:
52  * - History search like Ctrl+r in readline?
53  *
54  * List of escape sequences used by this program, we do everything just
55  * with three sequences. In order to be so cheap we may have some
56  * flickering effect with some slow terminal, but the lesser sequences
57  * the more compatible.
58  *
59  * EL (Erase Line)
60  *    Sequence: ESC [ n K
61  *    Effect: if n is 0 or missing, clear from cursor to end of line
62  *    Effect: if n is 1, clear from beginning of line to cursor
63  *    Effect: if n is 2, clear entire line
64  *
65  * CUF (CUrsor Forward)
66  *    Sequence: ESC [ n C
67  *    Effect: moves cursor forward n chars
68  *
69  * CUB (CUrsor Backward)
70  *    Sequence: ESC [ n D
71  *    Effect: moves cursor backward n chars
72  *
73  * The following is used to get the terminal width if getting
74  * the width with the TIOCGWINSZ ioctl fails
75  *
76  * DSR (Device Status Report)
77  *    Sequence: ESC [ 6 n
78  *    Effect: reports the current cusor position as ESC [ n ; m R
79  *            where n is the row and m is the column
80  *
81  * When multi line mode is enabled, we also use an additional escape
82  * sequence. However multi line editing is disabled by default.
83  *
84  * CUU (Cursor Up)
85  *    Sequence: ESC [ n A
86  *    Effect: moves cursor up of n chars.
87  *
88  * CUD (Cursor Down)
89  *    Sequence: ESC [ n B
90  *    Effect: moves cursor down of n chars.
91  *
92  * When linenoiseClearScreen() is called, two additional escape sequences
93  * are used in order to clear the screen and position the cursor at home
94  * position.
95  *
96  * CUP (Cursor position)
97  *    Sequence: ESC [ H
98  *    Effect: moves the cursor to upper left corner
99  *
100  * ED (Erase display)
101  *    Sequence: ESC [ 2 J
102  *    Effect: clear the whole screen
103  *
104  */
105
106 #include <termios.h>
107 #include <unistd.h>
108 #include <stdlib.h>
109 #include <stdio.h>
110 #include <errno.h>
111 #include <string.h>
112 #include <stdlib.h>
113 #include <ctype.h>
114 #include <sys/stat.h>
115 #include <sys/types.h>
116 #include <sys/ioctl.h>
117 #include <unistd.h>
118 #include "linenoise.h"
119
120 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
121 #define LINENOISE_MAX_LINE 4096
122 static char *unsupported_term[] = {"dumb","cons25","emacs",NULL};
123 static linenoiseCompletionCallback *completionCallback = NULL;
124 static linenoiseHintsCallback *hintsCallback = NULL;
125 static linenoiseFreeHintsCallback *freeHintsCallback = NULL;
126
127 static struct termios orig_termios; /* In order to restore at exit.*/
128 static int maskmode = 0; /* Show "***" instead of input. For passwords. */
129 static int rawmode = 0; /* For atexit() function to check if restore is needed*/
130 static int mlmode = 0;  /* Multi line mode. Default is single line. */
131 static int atexit_registered = 0; /* Register atexit just 1 time. */
132 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
133 static int history_len = 0;
134 static char **history = NULL;
135
136 /* The linenoiseState structure represents the state during line editing.
137  * We pass this state to functions implementing specific editing
138  * functionalities. */
139 struct linenoiseState {
140     int ifd;            /* Terminal stdin file descriptor. */
141     int ofd;            /* Terminal stdout file descriptor. */
142     char *buf;          /* Edited line buffer. */
143     size_t buflen;      /* Edited line buffer size. */
144     const char *prompt; /* Prompt to display. */
145     size_t plen;        /* Prompt length. */
146     size_t pos;         /* Current cursor position. */
147     size_t oldpos;      /* Previous refresh cursor position. */
148     size_t len;         /* Current edited line length. */
149     size_t cols;        /* Number of columns in terminal. */
150     size_t maxrows;     /* Maximum num of rows used so far (multiline mode) */
151     int history_index;  /* The history index we are currently editing. */
152 };
153
154 enum KEY_ACTION{
155         KEY_NULL = 0,       /* NULL */
156         CTRL_A = 1,         /* Ctrl+a */
157         CTRL_B = 2,         /* Ctrl-b */
158         CTRL_C = 3,         /* Ctrl-c */
159         CTRL_D = 4,         /* Ctrl-d */
160         CTRL_E = 5,         /* Ctrl-e */
161         CTRL_F = 6,         /* Ctrl-f */
162         CTRL_H = 8,         /* Ctrl-h */
163         TAB = 9,            /* Tab */
164         CTRL_K = 11,        /* Ctrl+k */
165         CTRL_L = 12,        /* Ctrl+l */
166         ENTER = 13,         /* Enter */
167         CTRL_N = 14,        /* Ctrl-n */
168         CTRL_P = 16,        /* Ctrl-p */
169         CTRL_T = 20,        /* Ctrl-t */
170         CTRL_U = 21,        /* Ctrl+u */
171         CTRL_W = 23,        /* Ctrl+w */
172         ESC = 27,           /* Escape */
173         BACKSPACE =  127    /* Backspace */
174 };
175
176 static void linenoiseAtExit(void);
177 int linenoiseHistoryAdd(const char *line);
178 static void refreshLine(struct linenoiseState *l);
179
180 /* Debugging macro. */
181 #if 0
182 FILE *lndebug_fp = NULL;
183 #define lndebug(...) \
184     do { \
185         if (lndebug_fp == NULL) { \
186             lndebug_fp = fopen("/tmp/lndebug.txt","a"); \
187             fprintf(lndebug_fp, \
188             "[%d %d %d] p: %d, rows: %d, rpos: %d, max: %d, oldmax: %d\n", \
189             (int)l->len,(int)l->pos,(int)l->oldpos,plen,rows,rpos, \
190             (int)l->maxrows,old_rows); \
191         } \
192         fprintf(lndebug_fp, ", " __VA_ARGS__); \
193         fflush(lndebug_fp); \
194     } while (0)
195 #else
196 #define lndebug(fmt, ...)
197 #endif
198
199 /* ======================= Low level terminal handling ====================== */
200
201 /* Enable "mask mode". When it is enabled, instead of the input that
202  * the user is typing, the terminal will just display a corresponding
203  * number of asterisks, like "****". This is useful for passwords and other
204  * secrets that should not be displayed. */
205 void linenoiseMaskModeEnable(void) {
206     maskmode = 1;
207 }
208
209 /* Disable mask mode. */
210 void linenoiseMaskModeDisable(void) {
211     maskmode = 0;
212 }
213
214 /* Set if to use or not the multi line mode. */
215 void linenoiseSetMultiLine(int ml) {
216     mlmode = ml;
217 }
218
219 /* Return true if the terminal name is in the list of terminals we know are
220  * not able to understand basic escape sequences. */
221 static int isUnsupportedTerm(void) {
222     char *term = getenv("TERM");
223     int j;
224
225     if (term == NULL) return 0;
226     for (j = 0; unsupported_term[j]; j++)
227         if (!strcasecmp(term,unsupported_term[j])) return 1;
228     return 0;
229 }
230
231 /* Raw mode: 1960 magic shit. */
232 static int enableRawMode(int fd) {
233     struct termios raw;
234
235     if (!isatty(STDIN_FILENO)) goto fatal;
236     if (!atexit_registered) {
237         atexit(linenoiseAtExit);
238         atexit_registered = 1;
239     }
240     if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
241
242     raw = orig_termios;  /* modify the original mode */
243     /* input modes: no break, no CR to NL, no parity check, no strip char,
244      * no start/stop output control. */
245     raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
246     /* output modes - disable post processing */
247     raw.c_oflag &= ~(OPOST);
248     /* control modes - set 8 bit chars */
249     raw.c_cflag |= (CS8);
250     /* local modes - choing off, canonical off, no extended functions,
251      * no signal chars (^Z,^C) */
252     raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
253     /* control chars - set return condition: min number of bytes and timer.
254      * We want read to return every single byte, without timeout. */
255     raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
256
257     /* put terminal in raw mode after flushing */
258     if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
259     rawmode = 1;
260     return 0;
261
262 fatal:
263     errno = ENOTTY;
264     return -1;
265 }
266
267 static void disableRawMode(int fd) {
268     /* Don't even check the return value as it's too late. */
269     if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1)
270         rawmode = 0;
271 }
272
273 /* Use the ESC [6n escape sequence to query the horizontal cursor position
274  * and return it. On error -1 is returned, on success the position of the
275  * cursor. */
276 static int getCursorPosition(int ifd, int ofd) {
277     char buf[32];
278     int cols, rows;
279     unsigned int i = 0;
280
281     /* Report cursor location */
282     if (write(ofd, "\x1b[6n", 4) != 4) return -1;
283
284     /* Read the response: ESC [ rows ; cols R */
285     while (i < sizeof(buf)-1) {
286         if (read(ifd,buf+i,1) != 1) break;
287         if (buf[i] == 'R') break;
288         i++;
289     }
290     buf[i] = '\0';
291
292     /* Parse it. */
293     if (buf[0] != ESC || buf[1] != '[') return -1;
294     if (sscanf(buf+2,"%d;%d",&rows,&cols) != 2) return -1;
295     return cols;
296 }
297
298 /* Try to get the number of columns in the current terminal, or assume 80
299  * if it fails. */
300 static int getColumns(int ifd, int ofd) {
301     struct winsize ws;
302
303     if (ioctl(1, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
304         /* ioctl() failed. Try to query the terminal itself. */
305         int start, cols;
306
307         /* Get the initial position so we can restore it later. */
308         start = getCursorPosition(ifd,ofd);
309         if (start == -1) goto failed;
310
311         /* Go to right margin and get position. */
312         if (write(ofd,"\x1b[999C",6) != 6) goto failed;
313         cols = getCursorPosition(ifd,ofd);
314         if (cols == -1) goto failed;
315
316         /* Restore position. */
317         if (cols > start) {
318             char seq[32];
319             snprintf(seq,32,"\x1b[%dD",cols-start);
320             if (write(ofd,seq,strlen(seq)) == -1) {
321                 /* Can't recover... */
322             }
323         }
324         return cols;
325     } else {
326         return ws.ws_col;
327     }
328
329 failed:
330     return 80;
331 }
332
333 /* Clear the screen. Used to handle ctrl+l */
334 void linenoiseClearScreen(void) {
335     if (write(STDOUT_FILENO,"\x1b[H\x1b[2J",7) <= 0) {
336         /* nothing to do, just to avoid warning. */
337     }
338 }
339
340 /* Beep, used for completion when there is nothing to complete or when all
341  * the choices were already shown. */
342 static void linenoiseBeep(void) {
343     fprintf(stderr, "\x7");
344     fflush(stderr);
345 }
346
347 /* ============================== Completion ================================ */
348
349 /* Free a list of completion option populated by linenoiseAddCompletion(). */
350 static void freeCompletions(linenoiseCompletions *lc) {
351     size_t i;
352     for (i = 0; i < lc->len; i++)
353         free(lc->cvec[i]);
354     if (lc->cvec != NULL)
355         free(lc->cvec);
356 }
357
358 /* This is an helper function for linenoiseEdit() and is called when the
359  * user types the <tab> key in order to complete the string currently in the
360  * input.
361  *
362  * The state of the editing is encapsulated into the pointed linenoiseState
363  * structure as described in the structure definition. */
364 static int completeLine(struct linenoiseState *ls) {
365     linenoiseCompletions lc = { 0, NULL };
366     int nread, nwritten;
367     char c = 0;
368
369     completionCallback(ls->buf,&lc);
370     if (lc.len == 0) {
371         linenoiseBeep();
372     } else {
373         size_t stop = 0, i = 0;
374
375         while(!stop) {
376             /* Show completion or original buffer */
377             if (i < lc.len) {
378                 struct linenoiseState saved = *ls;
379
380                 ls->len = ls->pos = strlen(lc.cvec[i]);
381                 ls->buf = lc.cvec[i];
382                 refreshLine(ls);
383                 ls->len = saved.len;
384                 ls->pos = saved.pos;
385                 ls->buf = saved.buf;
386             } else {
387                 refreshLine(ls);
388             }
389
390             nread = read(ls->ifd,&c,1);
391             if (nread <= 0) {
392                 freeCompletions(&lc);
393                 return -1;
394             }
395
396             switch(c) {
397                 case 9: /* tab */
398                     i = (i+1) % (lc.len+1);
399                     if (i == lc.len) linenoiseBeep();
400                     break;
401                 case 27: /* escape */
402                     /* Re-show original buffer */
403                     if (i < lc.len) refreshLine(ls);
404                     stop = 1;
405                     break;
406                 default:
407                     /* Update buffer and return */
408                     if (i < lc.len) {
409                         nwritten = snprintf(ls->buf,ls->buflen,"%s",lc.cvec[i]);
410                         ls->len = ls->pos = nwritten;
411                     }
412                     stop = 1;
413                     break;
414             }
415         }
416     }
417
418     freeCompletions(&lc);
419     return c; /* Return last read character */
420 }
421
422 /* Register a callback function to be called for tab-completion. */
423 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
424     completionCallback = fn;
425 }
426
427 /* Register a hits function to be called to show hits to the user at the
428  * right of the prompt. */
429 void linenoiseSetHintsCallback(linenoiseHintsCallback *fn) {
430     hintsCallback = fn;
431 }
432
433 /* Register a function to free the hints returned by the hints callback
434  * registered with linenoiseSetHintsCallback(). */
435 void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *fn) {
436     freeHintsCallback = fn;
437 }
438
439 /* This function is used by the callback function registered by the user
440  * in order to add completion options given the input string when the
441  * user typed <tab>. See the example.c source code for a very easy to
442  * understand example. */
443 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
444     size_t len = strlen(str);
445     char *copy, **cvec;
446
447     copy = malloc(len+1);
448     if (copy == NULL) return;
449     memcpy(copy,str,len+1);
450     cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
451     if (cvec == NULL) {
452         free(copy);
453         return;
454     }
455     lc->cvec = cvec;
456     lc->cvec[lc->len++] = copy;
457 }
458
459 /* =========================== Line editing ================================= */
460
461 /* We define a very simple "append buffer" structure, that is an heap
462  * allocated string where we can append to. This is useful in order to
463  * write all the escape sequences in a buffer and flush them to the standard
464  * output in a single call, to avoid flickering effects. */
465 struct abuf {
466     char *b;
467     int len;
468 };
469
470 static void abInit(struct abuf *ab) {
471     ab->b = NULL;
472     ab->len = 0;
473 }
474
475 static void abAppend(struct abuf *ab, const char *s, int len) {
476     char *new = realloc(ab->b,ab->len+len);
477
478     if (new == NULL) return;
479     memcpy(new+ab->len,s,len);
480     ab->b = new;
481     ab->len += len;
482 }
483
484 static void abFree(struct abuf *ab) {
485     free(ab->b);
486 }
487
488 /* Helper of refreshSingleLine() and refreshMultiLine() to show hints
489  * to the right of the prompt. */
490 void refreshShowHints(struct abuf *ab, struct linenoiseState *l, int plen) {
491     char seq[64];
492     if (hintsCallback && plen+l->len < l->cols) {
493         int color = -1, bold = 0;
494         char *hint = hintsCallback(l->buf,&color,&bold);
495         if (hint) {
496             int hintlen = strlen(hint);
497             int hintmaxlen = l->cols-(plen+l->len);
498             if (hintlen > hintmaxlen) hintlen = hintmaxlen;
499             if (bold == 1 && color == -1) color = 37;
500             if (color != -1 || bold != 0)
501                 snprintf(seq,64,"\033[%d;%d;49m",bold,color);
502             else
503                 seq[0] = '\0';
504             abAppend(ab,seq,strlen(seq));
505             abAppend(ab,hint,hintlen);
506             if (color != -1 || bold != 0)
507                 abAppend(ab,"\033[0m",4);
508             /* Call the function to free the hint returned. */
509             if (freeHintsCallback) freeHintsCallback(hint);
510         }
511     }
512 }
513
514 /* Single line low level line refresh.
515  *
516  * Rewrite the currently edited line accordingly to the buffer content,
517  * cursor position, and number of columns of the terminal. */
518 static void refreshSingleLine(struct linenoiseState *l) {
519     char seq[64];
520     size_t plen = strlen(l->prompt);
521     int fd = l->ofd;
522     char *buf = l->buf;
523     size_t len = l->len;
524     size_t pos = l->pos;
525     struct abuf ab;
526
527     while((plen+pos) >= l->cols) {
528         buf++;
529         len--;
530         pos--;
531     }
532     while (plen+len > l->cols) {
533         len--;
534     }
535
536     abInit(&ab);
537     /* Cursor to left edge */
538     snprintf(seq,64,"\r");
539     abAppend(&ab,seq,strlen(seq));
540     /* Write the prompt and the current buffer content */
541     abAppend(&ab,l->prompt,strlen(l->prompt));
542     if (maskmode == 1) {
543         while (len--) abAppend(&ab,"*",1);
544     } else {
545         abAppend(&ab,buf,len);
546     }
547     /* Show hits if any. */
548     refreshShowHints(&ab,l,plen);
549     /* Erase to right */
550     snprintf(seq,64,"\x1b[0K");
551     abAppend(&ab,seq,strlen(seq));
552     /* Move cursor to original position. */
553     snprintf(seq,64,"\r\x1b[%dC", (int)(pos+plen));
554     abAppend(&ab,seq,strlen(seq));
555     if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */
556     abFree(&ab);
557 }
558
559 /* Multi line low level line refresh.
560  *
561  * Rewrite the currently edited line accordingly to the buffer content,
562  * cursor position, and number of columns of the terminal. */
563 static void refreshMultiLine(struct linenoiseState *l) {
564     char seq[64];
565     int plen = strlen(l->prompt);
566     int rows = (plen+l->len+l->cols-1)/l->cols; /* rows used by current buf. */
567     int rpos = (plen+l->oldpos+l->cols)/l->cols; /* cursor relative row. */
568     int rpos2; /* rpos after refresh. */
569     int col; /* colum position, zero-based. */
570     int old_rows = l->maxrows;
571     int fd = l->ofd, j;
572     struct abuf ab;
573
574     /* Update maxrows if needed. */
575     if (rows > (int)l->maxrows) l->maxrows = rows;
576
577     /* First step: clear all the lines used before. To do so start by
578      * going to the last row. */
579     abInit(&ab);
580     if (old_rows-rpos > 0) {
581         lndebug("go down %d", old_rows-rpos);
582         snprintf(seq,64,"\x1b[%dB", old_rows-rpos);
583         abAppend(&ab,seq,strlen(seq));
584     }
585
586     /* Now for every row clear it, go up. */
587     for (j = 0; j < old_rows-1; j++) {
588         lndebug("clear+up");
589         snprintf(seq,64,"\r\x1b[0K\x1b[1A");
590         abAppend(&ab,seq,strlen(seq));
591     }
592
593     /* Clean the top line. */
594     lndebug("clear");
595     snprintf(seq,64,"\r\x1b[0K");
596     abAppend(&ab,seq,strlen(seq));
597
598     /* Write the prompt and the current buffer content */
599     abAppend(&ab,l->prompt,strlen(l->prompt));
600     if (maskmode == 1) {
601         unsigned int i;
602         for (i = 0; i < l->len; i++) abAppend(&ab,"*",1);
603     } else {
604         abAppend(&ab,l->buf,l->len);
605     }
606
607     /* Show hits if any. */
608     refreshShowHints(&ab,l,plen);
609
610     /* If we are at the very end of the screen with our prompt, we need to
611      * emit a newline and move the prompt to the first column. */
612     if (l->pos &&
613         l->pos == l->len &&
614         (l->pos+plen) % l->cols == 0)
615     {
616         lndebug("<newline>");
617         abAppend(&ab,"\n",1);
618         snprintf(seq,64,"\r");
619         abAppend(&ab,seq,strlen(seq));
620         rows++;
621         if (rows > (int)l->maxrows) l->maxrows = rows;
622     }
623
624     /* Move cursor to right position. */
625     rpos2 = (plen+l->pos+l->cols)/l->cols; /* current cursor relative row. */
626     lndebug("rpos2 %d", rpos2);
627
628     /* Go up till we reach the expected positon. */
629     if (rows-rpos2 > 0) {
630         lndebug("go-up %d", rows-rpos2);
631         snprintf(seq,64,"\x1b[%dA", rows-rpos2);
632         abAppend(&ab,seq,strlen(seq));
633     }
634
635     /* Set column. */
636     col = (plen+(int)l->pos) % (int)l->cols;
637     lndebug("set col %d", 1+col);
638     if (col)
639         snprintf(seq,64,"\r\x1b[%dC", col);
640     else
641         snprintf(seq,64,"\r");
642     abAppend(&ab,seq,strlen(seq));
643
644     lndebug("\n");
645     l->oldpos = l->pos;
646
647     if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */
648     abFree(&ab);
649 }
650
651 /* Calls the two low level functions refreshSingleLine() or
652  * refreshMultiLine() according to the selected mode. */
653 static void refreshLine(struct linenoiseState *l) {
654     if (mlmode)
655         refreshMultiLine(l);
656     else
657         refreshSingleLine(l);
658 }
659
660 /* Insert the character 'c' at cursor current position.
661  *
662  * On error writing to the terminal -1 is returned, otherwise 0. */
663 int linenoiseEditInsert(struct linenoiseState *l, char c) {
664     if (l->len < l->buflen) {
665         if (l->len == l->pos) {
666             l->buf[l->pos] = c;
667             l->pos++;
668             l->len++;
669             l->buf[l->len] = '\0';
670             if ((!mlmode && l->plen+l->len < l->cols && !hintsCallback)) {
671                 /* Avoid a full update of the line in the
672                  * trivial case. */
673                 char d = (maskmode==1) ? '*' : c;
674                 if (write(l->ofd,&d,1) == -1) return -1;
675             } else {
676                 refreshLine(l);
677             }
678         } else {
679             memmove(l->buf+l->pos+1,l->buf+l->pos,l->len-l->pos);
680             l->buf[l->pos] = c;
681             l->len++;
682             l->pos++;
683             l->buf[l->len] = '\0';
684             refreshLine(l);
685         }
686     }
687     return 0;
688 }
689
690 /* Move cursor on the left. */
691 void linenoiseEditMoveLeft(struct linenoiseState *l) {
692     if (l->pos > 0) {
693         l->pos--;
694         refreshLine(l);
695     }
696 }
697
698 /* Move cursor on the right. */
699 void linenoiseEditMoveRight(struct linenoiseState *l) {
700     if (l->pos != l->len) {
701         l->pos++;
702         refreshLine(l);
703     }
704 }
705
706 /* Move cursor to the start of the line. */
707 void linenoiseEditMoveHome(struct linenoiseState *l) {
708     if (l->pos != 0) {
709         l->pos = 0;
710         refreshLine(l);
711     }
712 }
713
714 /* Move cursor to the end of the line. */
715 void linenoiseEditMoveEnd(struct linenoiseState *l) {
716     if (l->pos != l->len) {
717         l->pos = l->len;
718         refreshLine(l);
719     }
720 }
721
722 /* Substitute the currently edited line with the next or previous history
723  * entry as specified by 'dir'. */
724 #define LINENOISE_HISTORY_NEXT 0
725 #define LINENOISE_HISTORY_PREV 1
726 void linenoiseEditHistoryNext(struct linenoiseState *l, int dir) {
727     if (history_len > 1) {
728         /* Update the current history entry before to
729          * overwrite it with the next one. */
730         free(history[history_len - 1 - l->history_index]);
731         history[history_len - 1 - l->history_index] = strdup(l->buf);
732         /* Show the new entry */
733         l->history_index += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1;
734         if (l->history_index < 0) {
735             l->history_index = 0;
736             return;
737         } else if (l->history_index >= history_len) {
738             l->history_index = history_len-1;
739             return;
740         }
741         strncpy(l->buf,history[history_len - 1 - l->history_index],l->buflen);
742         l->buf[l->buflen-1] = '\0';
743         l->len = l->pos = strlen(l->buf);
744         refreshLine(l);
745     }
746 }
747
748 /* Delete the character at the right of the cursor without altering the cursor
749  * position. Basically this is what happens with the "Delete" keyboard key. */
750 void linenoiseEditDelete(struct linenoiseState *l) {
751     if (l->len > 0 && l->pos < l->len) {
752         memmove(l->buf+l->pos,l->buf+l->pos+1,l->len-l->pos-1);
753         l->len--;
754         l->buf[l->len] = '\0';
755         refreshLine(l);
756     }
757 }
758
759 /* Backspace implementation. */
760 void linenoiseEditBackspace(struct linenoiseState *l) {
761     if (l->pos > 0 && l->len > 0) {
762         memmove(l->buf+l->pos-1,l->buf+l->pos,l->len-l->pos);
763         l->pos--;
764         l->len--;
765         l->buf[l->len] = '\0';
766         refreshLine(l);
767     }
768 }
769
770 /* Delete the previosu word, maintaining the cursor at the start of the
771  * current word. */
772 void linenoiseEditDeletePrevWord(struct linenoiseState *l) {
773     size_t old_pos = l->pos;
774     size_t diff;
775
776     while (l->pos > 0 && l->buf[l->pos-1] == ' ')
777         l->pos--;
778     while (l->pos > 0 && l->buf[l->pos-1] != ' ')
779         l->pos--;
780     diff = old_pos - l->pos;
781     memmove(l->buf+l->pos,l->buf+old_pos,l->len-old_pos+1);
782     l->len -= diff;
783     refreshLine(l);
784 }
785
786 /* This function is the core of the line editing capability of linenoise.
787  * It expects 'fd' to be already in "raw mode" so that every key pressed
788  * will be returned ASAP to read().
789  *
790  * The resulting string is put into 'buf' when the user type enter, or
791  * when ctrl+d is typed.
792  *
793  * The function returns the length of the current buffer. */
794 static int linenoiseEdit(int stdin_fd, int stdout_fd, char *buf, size_t buflen, const char *prompt)
795 {
796     struct linenoiseState l;
797
798     /* Populate the linenoise state that we pass to functions implementing
799      * specific editing functionalities. */
800     l.ifd = stdin_fd;
801     l.ofd = stdout_fd;
802     l.buf = buf;
803     l.buflen = buflen;
804     l.prompt = prompt;
805     l.plen = strlen(prompt);
806     l.oldpos = l.pos = 0;
807     l.len = 0;
808     l.cols = getColumns(stdin_fd, stdout_fd);
809     l.maxrows = 0;
810     l.history_index = 0;
811
812     /* Buffer starts empty. */
813     l.buf[0] = '\0';
814     l.buflen--; /* Make sure there is always space for the nulterm */
815
816     /* The latest history entry is always our current buffer, that
817      * initially is just an empty string. */
818     linenoiseHistoryAdd("");
819
820     if (write(l.ofd,prompt,l.plen) == -1) return -1;
821     while(1) {
822         char c;
823         int nread;
824         char seq[3];
825
826         nread = read(l.ifd,&c,1);
827         if (nread <= 0) return l.len;
828
829         /* Only autocomplete when the callback is set. It returns < 0 when
830          * there was an error reading from fd. Otherwise it will return the
831          * character that should be handled next. */
832         if (c == 9 && completionCallback != NULL) {
833             c = completeLine(&l);
834             /* Return on errors */
835             if (c < 0) return l.len;
836             /* Read next character when 0 */
837             if (c == 0) continue;
838         }
839
840         switch(c) {
841         case ENTER:    /* enter */
842             history_len--;
843             free(history[history_len]);
844             if (mlmode) linenoiseEditMoveEnd(&l);
845             if (hintsCallback) {
846                 /* Force a refresh without hints to leave the previous
847                  * line as the user typed it after a newline. */
848                 linenoiseHintsCallback *hc = hintsCallback;
849                 hintsCallback = NULL;
850                 refreshLine(&l);
851                 hintsCallback = hc;
852             }
853             return (int)l.len;
854         case CTRL_C:     /* ctrl-c */
855             errno = EAGAIN;
856             return -1;
857         case BACKSPACE:   /* backspace */
858         case 8:     /* ctrl-h */
859             linenoiseEditBackspace(&l);
860             break;
861         case CTRL_D:     /* ctrl-d, remove char at right of cursor, or if the
862                             line is empty, act as end-of-file. */
863             if (l.len > 0) {
864                 linenoiseEditDelete(&l);
865             } else {
866                 history_len--;
867                 free(history[history_len]);
868                 return -1;
869             }
870             break;
871         case CTRL_T:    /* ctrl-t, swaps current character with previous. */
872             if (l.pos > 0 && l.pos < l.len) {
873                 int aux = buf[l.pos-1];
874                 buf[l.pos-1] = buf[l.pos];
875                 buf[l.pos] = aux;
876                 if (l.pos != l.len-1) l.pos++;
877                 refreshLine(&l);
878             }
879             break;
880         case CTRL_B:     /* ctrl-b */
881             linenoiseEditMoveLeft(&l);
882             break;
883         case CTRL_F:     /* ctrl-f */
884             linenoiseEditMoveRight(&l);
885             break;
886         case CTRL_P:    /* ctrl-p */
887             linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
888             break;
889         case CTRL_N:    /* ctrl-n */
890             linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
891             break;
892         case ESC:    /* escape sequence */
893             /* Read the next two bytes representing the escape sequence.
894              * Use two calls to handle slow terminals returning the two
895              * chars at different times. */
896             if (read(l.ifd,seq,1) == -1) break;
897             if (read(l.ifd,seq+1,1) == -1) break;
898
899             /* ESC [ sequences. */
900             if (seq[0] == '[') {
901                 if (seq[1] >= '0' && seq[1] <= '9') {
902                     /* Extended escape, read additional byte. */
903                     if (read(l.ifd,seq+2,1) == -1) break;
904                     if (seq[2] == '~') {
905                         switch(seq[1]) {
906                         case '3': /* Delete key. */
907                             linenoiseEditDelete(&l);
908                             break;
909                         }
910                     }
911                 } else {
912                     switch(seq[1]) {
913                     case 'A': /* Up */
914                         linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
915                         break;
916                     case 'B': /* Down */
917                         linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
918                         break;
919                     case 'C': /* Right */
920                         linenoiseEditMoveRight(&l);
921                         break;
922                     case 'D': /* Left */
923                         linenoiseEditMoveLeft(&l);
924                         break;
925                     case 'H': /* Home */
926                         linenoiseEditMoveHome(&l);
927                         break;
928                     case 'F': /* End*/
929                         linenoiseEditMoveEnd(&l);
930                         break;
931                     }
932                 }
933             }
934
935             /* ESC O sequences. */
936             else if (seq[0] == 'O') {
937                 switch(seq[1]) {
938                 case 'H': /* Home */
939                     linenoiseEditMoveHome(&l);
940                     break;
941                 case 'F': /* End*/
942                     linenoiseEditMoveEnd(&l);
943                     break;
944                 }
945             }
946             break;
947         default:
948             if (linenoiseEditInsert(&l,c)) return -1;
949             break;
950         case CTRL_U: /* Ctrl+u, delete the whole line. */
951             buf[0] = '\0';
952             l.pos = l.len = 0;
953             refreshLine(&l);
954             break;
955         case CTRL_K: /* Ctrl+k, delete from current to end of line. */
956             buf[l.pos] = '\0';
957             l.len = l.pos;
958             refreshLine(&l);
959             break;
960         case CTRL_A: /* Ctrl+a, go to the start of the line */
961             linenoiseEditMoveHome(&l);
962             break;
963         case CTRL_E: /* ctrl+e, go to the end of the line */
964             linenoiseEditMoveEnd(&l);
965             break;
966         case CTRL_L: /* ctrl+l, clear screen */
967             linenoiseClearScreen();
968             refreshLine(&l);
969             break;
970         case CTRL_W: /* ctrl+w, delete previous word */
971             linenoiseEditDeletePrevWord(&l);
972             break;
973         }
974     }
975     return l.len;
976 }
977
978 /* This special mode is used by linenoise in order to print scan codes
979  * on screen for debugging / development purposes. It is implemented
980  * by the linenoise_example program using the --keycodes option. */
981 void linenoisePrintKeyCodes(void) {
982     char quit[4];
983
984     printf("Linenoise key codes debugging mode.\n"
985             "Press keys to see scan codes. Type 'quit' at any time to exit.\n");
986     if (enableRawMode(STDIN_FILENO) == -1) return;
987     memset(quit,' ',4);
988     while(1) {
989         char c;
990         int nread;
991
992         nread = read(STDIN_FILENO,&c,1);
993         if (nread <= 0) continue;
994         memmove(quit,quit+1,sizeof(quit)-1); /* shift string to left. */
995         quit[sizeof(quit)-1] = c; /* Insert current char on the right. */
996         if (memcmp(quit,"quit",sizeof(quit)) == 0) break;
997
998         printf("'%c' %02x (%d) (type quit to exit)\n",
999             isprint(c) ? c : '?', (int)c, (int)c);
1000         printf("\r"); /* Go left edge manually, we are in raw mode. */
1001         fflush(stdout);
1002     }
1003     disableRawMode(STDIN_FILENO);
1004 }
1005
1006 /* This function calls the line editing function linenoiseEdit() using
1007  * the STDIN file descriptor set in raw mode. */
1008 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
1009     int count;
1010
1011     if (buflen == 0) {
1012         errno = EINVAL;
1013         return -1;
1014     }
1015
1016     if (enableRawMode(STDIN_FILENO) == -1) return -1;
1017     count = linenoiseEdit(STDIN_FILENO, STDOUT_FILENO, buf, buflen, prompt);
1018     disableRawMode(STDIN_FILENO);
1019     printf("\n");
1020     return count;
1021 }
1022
1023 /* This function is called when linenoise() is called with the standard
1024  * input file descriptor not attached to a TTY. So for example when the
1025  * program using linenoise is called in pipe or with a file redirected
1026  * to its standard input. In this case, we want to be able to return the
1027  * line regardless of its length (by default we are limited to 4k). */
1028 static char *linenoiseNoTTY(void) {
1029     char *line = NULL;
1030     size_t len = 0, maxlen = 0;
1031
1032     while(1) {
1033         if (len == maxlen) {
1034             if (maxlen == 0) maxlen = 16;
1035             maxlen *= 2;
1036             char *oldval = line;
1037             line = realloc(line,maxlen);
1038             if (line == NULL) {
1039                 if (oldval) free(oldval);
1040                 return NULL;
1041             }
1042         }
1043         int c = fgetc(stdin);
1044         if (c == EOF || c == '\n') {
1045             if (c == EOF && len == 0) {
1046                 free(line);
1047                 return NULL;
1048             } else {
1049                 line[len] = '\0';
1050                 return line;
1051             }
1052         } else {
1053             line[len] = c;
1054             len++;
1055         }
1056     }
1057 }
1058
1059 /* The high level function that is the main API of the linenoise library.
1060  * This function checks if the terminal has basic capabilities, just checking
1061  * for a blacklist of stupid terminals, and later either calls the line
1062  * editing function or uses dummy fgets() so that you will be able to type
1063  * something even in the most desperate of the conditions. */
1064 char *linenoise(const char *prompt) {
1065     char buf[LINENOISE_MAX_LINE];
1066     int count;
1067
1068     if (!isatty(STDIN_FILENO)) {
1069         /* Not a tty: read from file / pipe. In this mode we don't want any
1070          * limit to the line size, so we call a function to handle that. */
1071         return linenoiseNoTTY();
1072     } else if (isUnsupportedTerm()) {
1073         size_t len;
1074
1075         printf("%s",prompt);
1076         fflush(stdout);
1077         if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
1078         len = strlen(buf);
1079         while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
1080             len--;
1081             buf[len] = '\0';
1082         }
1083         return strdup(buf);
1084     } else {
1085         count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
1086         if (count == -1) return NULL;
1087         return strdup(buf);
1088     }
1089 }
1090
1091 /* This is just a wrapper the user may want to call in order to make sure
1092  * the linenoise returned buffer is freed with the same allocator it was
1093  * created with. Useful when the main program is using an alternative
1094  * allocator. */
1095 void linenoiseFree(void *ptr) {
1096     free(ptr);
1097 }
1098
1099 /* ================================ History ================================= */
1100
1101 /* Free the history, but does not reset it. Only used when we have to
1102  * exit() to avoid memory leaks are reported by valgrind & co. */
1103 static void freeHistory(void) {
1104     if (history) {
1105         int j;
1106
1107         for (j = 0; j < history_len; j++)
1108             free(history[j]);
1109         free(history);
1110     }
1111 }
1112
1113 /* At exit we'll try to fix the terminal to the initial conditions. */
1114 static void linenoiseAtExit(void) {
1115     disableRawMode(STDIN_FILENO);
1116     freeHistory();
1117 }
1118
1119 /* This is the API call to add a new entry in the linenoise history.
1120  * It uses a fixed array of char pointers that are shifted (memmoved)
1121  * when the history max length is reached in order to remove the older
1122  * entry and make room for the new one, so it is not exactly suitable for huge
1123  * histories, but will work well for a few hundred of entries.
1124  *
1125  * Using a circular buffer is smarter, but a bit more complex to handle. */
1126 int linenoiseHistoryAdd(const char *line) {
1127     char *linecopy;
1128
1129     if (history_max_len == 0) return 0;
1130
1131     /* Initialization on first call. */
1132     if (history == NULL) {
1133         history = malloc(sizeof(char*)*history_max_len);
1134         if (history == NULL) return 0;
1135         memset(history,0,(sizeof(char*)*history_max_len));
1136     }
1137
1138     /* Don't add duplicated lines. */
1139     if (history_len && !strcmp(history[history_len-1], line)) return 0;
1140
1141     /* Add an heap allocated copy of the line in the history.
1142      * If we reached the max length, remove the older line. */
1143     linecopy = strdup(line);
1144     if (!linecopy) return 0;
1145     if (history_len == history_max_len) {
1146         free(history[0]);
1147         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1148         history_len--;
1149     }
1150     history[history_len] = linecopy;
1151     history_len++;
1152     return 1;
1153 }
1154
1155 /* Set the maximum length for the history. This function can be called even
1156  * if there is already some history, the function will make sure to retain
1157  * just the latest 'len' elements if the new history length value is smaller
1158  * than the amount of items already inside the history. */
1159 int linenoiseHistorySetMaxLen(int len) {
1160     char **new;
1161
1162     if (len < 1) return 0;
1163     if (history) {
1164         int tocopy = history_len;
1165
1166         new = malloc(sizeof(char*)*len);
1167         if (new == NULL) return 0;
1168
1169         /* If we can't copy everything, free the elements we'll not use. */
1170         if (len < tocopy) {
1171             int j;
1172
1173             for (j = 0; j < tocopy-len; j++) free(history[j]);
1174             tocopy = len;
1175         }
1176         memset(new,0,sizeof(char*)*len);
1177         memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy);
1178         free(history);
1179         history = new;
1180     }
1181     history_max_len = len;
1182     if (history_len > history_max_len)
1183         history_len = history_max_len;
1184     return 1;
1185 }
1186
1187 /* Save the history in the specified file. On success 0 is returned
1188  * otherwise -1 is returned. */
1189 int linenoiseHistorySave(const char *filename) {
1190     mode_t old_umask = umask(S_IXUSR|S_IRWXG|S_IRWXO);
1191     FILE *fp;
1192     int j;
1193
1194     fp = fopen(filename,"w");
1195     umask(old_umask);
1196     if (fp == NULL) return -1;
1197     chmod(filename,S_IRUSR|S_IWUSR);
1198     for (j = 0; j < history_len; j++)
1199         fprintf(fp,"%s\n",history[j]);
1200     fclose(fp);
1201     return 0;
1202 }
1203
1204 /* Load the history from the specified file. If the file does not exist
1205  * zero is returned and no operation is performed.
1206  *
1207  * If the file exists and the operation succeeded 0 is returned, otherwise
1208  * on error -1 is returned. */
1209 int linenoiseHistoryLoad(const char *filename) {
1210     FILE *fp = fopen(filename,"r");
1211     char buf[LINENOISE_MAX_LINE];
1212
1213     if (fp == NULL) return -1;
1214
1215     while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1216         char *p;
1217
1218         p = strchr(buf,'\r');
1219         if (!p) p = strchr(buf,'\n');
1220         if (p) *p = '\0';
1221         linenoiseHistoryAdd(buf);
1222     }
1223     fclose(fp);
1224     return 0;
1225 }