xref: /illumos-gate/usr/src/boot/common/linenoise/linenoise.c (revision d4a88d1b9c69d0caaaddaf0e455bcae63d371258)
1 /* linenoise.c -- VERSION 1.0
2  *
3  * Guerrilla line editing library against the idea that a line editing lib
4  * needs to be 20,000 lines of C code.
5  *
6  * You can find the latest source code at:
7  *
8  *   http://github.com/antirez/linenoise
9  *
10  * Does a number of crazy assumptions that happen to be true in 99.9999% of
11  * the 2010 UNIX computers around.
12  *
13  * ------------------------------------------------------------------------
14  *
15  * Copyright (c) 2010-2014, Salvatore Sanfilippo <antirez at gmail dot com>
16  * Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
17  *
18  * All rights reserved.
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions are
22  * met:
23  *
24  *  *  Redistributions of source code must retain the above copyright
25  *     notice, this list of conditions and the following disclaimer.
26  *
27  *  *  Redistributions in binary form must reproduce the above copyright
28  *     notice, this list of conditions and the following disclaimer in the
29  *     documentation and/or other materials provided with the distribution.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42  *
43  * ------------------------------------------------------------------------
44  *
45  * References:
46  * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
47  * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
48  *
49  * Todo list:
50  * - Filter bogus Ctrl+<char> combinations.
51  * - Win32 support
52  *
53  * Bloat:
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  * EL (Erase Line)
62  *    Sequence: ESC [ n K
63  *    Effect: if n is 0 or missing, clear from cursor to end of line
64  *    Effect: if n is 1, clear from beginning of line to cursor
65  *    Effect: if n is 2, clear entire line
66  *
67  * CUF (CUrsor Forward)
68  *    Sequence: ESC [ n C
69  *    Effect: moves cursor forward n chars
70  *
71  * CUB (CUrsor Backward)
72  *    Sequence: ESC [ n D
73  *    Effect: moves cursor backward n chars
74  *
75  * The following is used to get the terminal width if getting
76  * the width with the TIOCGWINSZ ioctl fails
77  *
78  * DSR (Device Status Report)
79  *    Sequence: ESC [ 6 n
80  *    Effect: reports the current cusor position as ESC [ n ; m R
81  *            where n is the row and m is the column
82  *
83  * When multi line mode is enabled, we also use an additional escape
84  * sequence. However multi line editing is disabled by default.
85  *
86  * CUU (Cursor Up)
87  *    Sequence: ESC [ n A
88  *    Effect: moves cursor up of n chars.
89  *
90  * CUD (Cursor Down)
91  *    Sequence: ESC [ n B
92  *    Effect: moves cursor down of n chars.
93  *
94  * When linenoiseClearScreen() is called, two additional escape sequences
95  * are used in order to clear the screen and position the cursor at home
96  * position.
97  *
98  * CUP (Cursor position)
99  *    Sequence: ESC [ H
100  *    Effect: moves the cursor to upper left corner
101  *
102  * ED (Erase display)
103  *    Sequence: ESC [ 2 J
104  *    Effect: clear the whole screen
105  *
106  */
107 
108 #include <stand.h>
109 #include "linenoise.h"
110 #include "bootstrap.h"
111 
112 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
113 #define LINENOISE_MAX_LINE 256
114 static linenoiseCompletionCallback *completionCallback = NULL;
115 
116 static int mlmode = 1;  /* Multi line mode. Default is single line. */
117 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
118 static int history_len = 0;
119 static char **history = NULL;
120 
121 /* The linenoiseState structure represents the state during line editing.
122  * We pass this state to functions implementing specific editing
123  * functionalities. */
124 struct linenoiseState {
125     char *buf;          /* Edited line buffer. */
126     size_t buflen;      /* Edited line buffer size. */
127     const char *prompt; /* Prompt to display. */
128     size_t plen;        /* Prompt length. */
129     size_t pos;         /* Current cursor position. */
130     size_t oldpos;      /* Previous refresh cursor position. */
131     size_t len;         /* Current edited line length. */
132     size_t cols;        /* Number of columns in terminal. */
133     size_t maxrows;     /* Maximum num of rows used so far (multiline mode) */
134     int history_index;  /* The history index we are currently editing. */
135 };
136 
137 enum KEY_ACTION{
138 	KEY_NULL = 0,	    /* NULL */
139 	CTRL_A = 1,         /* Ctrl+a */
140 	CTRL_B = 2,         /* Ctrl-b */
141 	CTRL_C = 3,         /* Ctrl-c */
142 	CTRL_D = 4,         /* Ctrl-d */
143 	CTRL_E = 5,         /* Ctrl-e */
144 	CTRL_F = 6,         /* Ctrl-f */
145 	CTRL_H = 8,         /* Ctrl-h */
146 	TAB = 9,            /* Tab */
147 	CTRL_K = 11,        /* Ctrl+k */
148 	CTRL_L = 12,        /* Ctrl+l */
149 	ENTER = 13,         /* Enter */
150 	CTRL_N = 14,        /* Ctrl-n */
151 	CTRL_P = 16,        /* Ctrl-p */
152 	CTRL_T = 20,        /* Ctrl-t */
153 	CTRL_U = 21,        /* Ctrl+u */
154 	CTRL_W = 23,        /* Ctrl+w */
155 	ESC = 27,           /* Escape */
156 	BACKSPACE =  127    /* Backspace */
157 };
158 
159 static void refreshLine(struct linenoiseState *l);
160 
161 /* ======================= Low level terminal handling ====================== */
162 
163 static int
164 put_bytes(const char *s, int len)
165 {
166     int i;
167     if (s == NULL)
168 	return -1;
169 
170     for (i = 0; i < len; i++)
171 	putchar(s[i]);
172     return (i);
173 }
174 
175 /* Set if to use or not the multi line mode. */
176 void linenoiseSetMultiLine(int ml) {
177     mlmode = ml;
178 }
179 
180 /* Clear the screen. Used to handle ctrl+l */
181 void linenoiseClearScreen(void)
182 {
183     if (put_bytes("\x1b[H\x1b[J", 6) <= 0) {
184         /* nothing to do, just to avoid warning. */
185     }
186 }
187 
188 static int
189 getColumns(void)
190 {
191 	char *columns = getenv("screen-#cols");
192 	if (columns == NULL)
193 		return (80);
194 	return (strtol(columns, NULL, 0));
195 }
196 
197 /* Beep, used for completion when there is nothing to complete or when all
198  * the choices were already shown. */
199 static void linenoiseBeep(void)
200 {
201     (void) put_bytes("\x7", 1);
202 }
203 
204 /* ============================== Completion ================================ */
205 
206 /* Free a list of completion option populated by linenoiseAddCompletion(). */
207 static void freeCompletions(linenoiseCompletions *lc) {
208     size_t i;
209     for (i = 0; i < lc->len; i++)
210         free(lc->cvec[i]);
211     if (lc->cvec != NULL)
212         free(lc->cvec);
213 }
214 
215 /* This is an helper function for linenoiseEdit() and is called when the
216  * user types the <tab> key in order to complete the string currently in the
217  * input.
218  *
219  * The state of the editing is encapsulated into the pointed linenoiseState
220  * structure as described in the structure definition. */
221 static int completeLine(struct linenoiseState *ls) {
222     linenoiseCompletions lc = { 0, NULL };
223     int nwritten;
224     char c = 0;
225 
226     completionCallback(ls->buf,&lc);
227     if (lc.len == 0) {
228         linenoiseBeep();
229     } else {
230         size_t stop = 0, i = 0;
231 
232         while(!stop) {
233             /* Show completion or original buffer */
234             if (i < lc.len) {
235                 struct linenoiseState saved = *ls;
236 
237                 ls->len = ls->pos = strlen(lc.cvec[i]);
238                 ls->buf = lc.cvec[i];
239                 refreshLine(ls);
240                 ls->len = saved.len;
241                 ls->pos = saved.pos;
242                 ls->buf = saved.buf;
243             } else {
244                 refreshLine(ls);
245             }
246 
247             c = getchar();
248             if (c <= 0) {
249                 freeCompletions(&lc);
250                 return -1;
251             }
252 
253             switch(c) {
254                 case 9: /* tab */
255                     i = (i+1) % (lc.len+1);
256                     if (i == lc.len) linenoiseBeep();
257                     break;
258                 case 27: /* escape */
259                     /* Re-show original buffer */
260                     if (i < lc.len) refreshLine(ls);
261                     stop = 1;
262                     break;
263                 default:
264                     /* Update buffer and return */
265                     if (i < lc.len) {
266                         nwritten = snprintf(ls->buf,ls->buflen,"%s",lc.cvec[i]);
267                         ls->len = ls->pos = nwritten;
268                     }
269                     stop = 1;
270                     break;
271             }
272         }
273     }
274 
275     freeCompletions(&lc);
276     return c; /* Return last read character */
277 }
278 
279 /* Register a callback function to be called for tab-completion. */
280 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
281     completionCallback = fn;
282 }
283 
284 /* This function is used by the callback function registered by the user
285  * in order to add completion options given the input string when the
286  * user typed <tab>. See the example.c source code for a very easy to
287  * understand example. */
288 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
289     size_t len = strlen(str);
290     char *copy, **cvec;
291 
292     copy = malloc(len+1);
293     if (copy == NULL) return;
294     memcpy(copy,str,len+1);
295     cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
296     if (cvec == NULL) {
297         free(copy);
298         return;
299     }
300     lc->cvec = cvec;
301     lc->cvec[lc->len++] = copy;
302 }
303 
304 /* =========================== Line editing ================================= */
305 
306 /* We define a very simple "append buffer" structure, that is an heap
307  * allocated string where we can append to. This is useful in order to
308  * write all the escape sequences in a buffer and flush them to the standard
309  * output in a single call, to avoid flickering effects. */
310 struct abuf {
311     char *b;
312     int len;
313 };
314 
315 static void abInit(struct abuf *ab) {
316     ab->b = NULL;
317     ab->len = 0;
318 }
319 
320 static void abAppend(struct abuf *ab, const char *s, int len) {
321     char *new = malloc(ab->len+len);
322 
323     if (new == NULL) return;
324     memcpy(new, ab->b, ab->len);
325     memcpy(new+ab->len,s,len);
326     free(ab->b);
327     ab->b = new;
328     ab->len += len;
329 }
330 
331 static void abFree(struct abuf *ab) {
332     free(ab->b);
333 }
334 
335 /* Single line low level line refresh.
336  *
337  * Rewrite the currently edited line accordingly to the buffer content,
338  * cursor position, and number of columns of the terminal. */
339 static void refreshSingleLine(struct linenoiseState *l) {
340     char seq[64];
341     size_t plen = strlen(l->prompt);
342     char *buf = l->buf;
343     size_t len = l->len;
344     size_t pos = l->pos;
345     struct abuf ab;
346 
347     while((plen+pos) >= l->cols) {
348         buf++;
349         len--;
350         pos--;
351     }
352     while (plen+len > l->cols) {
353         len--;
354     }
355 
356     abInit(&ab);
357     /* Cursor to left edge */
358     (void) snprintf(seq,64,"\r");
359     abAppend(&ab,seq,strlen(seq));
360     /* Write the prompt and the current buffer content */
361     abAppend(&ab,l->prompt,strlen(l->prompt));
362     abAppend(&ab,buf,len);
363     /* Erase to right */
364     (void) snprintf(seq,64,"\x1b[K");
365     abAppend(&ab,seq,strlen(seq));
366     /* Move cursor to original position. */
367     (void) snprintf(seq,64,"\r\x1b[%dC", (int)(pos+plen));
368     abAppend(&ab,seq,strlen(seq));
369     (void) put_bytes(ab.b, ab.len);
370 
371     abFree(&ab);
372 }
373 
374 /* Multi line low level line refresh.
375  *
376  * Rewrite the currently edited line accordingly to the buffer content,
377  * cursor position, and number of columns of the terminal. */
378 static void refreshMultiLine(struct linenoiseState *l) {
379     char seq[64];
380     int plen = strlen(l->prompt);
381     int rows = (plen+l->len+l->cols)/l->cols; /* rows used by current buf. */
382     int rpos = (plen+l->oldpos+l->cols)/l->cols; /* cursor relative row. */
383     int rpos2; /* rpos after refresh. */
384     int col; /* colum position, zero-based. */
385     int old_rows = l->maxrows;
386     int j;
387     struct abuf ab;
388 
389     /* Update maxrows if needed. */
390     if (rows > (int)l->maxrows) l->maxrows = rows;
391 
392     /* First step: clear all the lines used before. To do so start by
393      * going to the last row. */
394     abInit(&ab);
395     if (old_rows-rpos > 0) {
396         (void) snprintf(seq,64,"\x1b[%dB", old_rows-rpos);
397         abAppend(&ab,seq,strlen(seq));
398     }
399 
400     /* Now for every row clear it, go up. */
401     for (j = 0; j < old_rows-1; j++) {
402         (void) snprintf(seq,64,"\r\x1b[0K\x1b[1A");
403         abAppend(&ab,seq,strlen(seq));
404     }
405 
406     /* Clean the top line. */
407     (void) snprintf(seq,64,"\r\x1b[0K");
408     abAppend(&ab,seq,strlen(seq));
409 
410     /* Write the prompt and the current buffer content */
411     abAppend(&ab,l->prompt,strlen(l->prompt));
412     abAppend(&ab,l->buf,l->len);
413 
414     /* If we are at the very end of the screen with our prompt, we need to
415      * emit a newline and move the prompt to the first column. */
416     if (l->pos &&
417         l->pos == l->len &&
418         (l->pos+plen) % l->cols == 0)
419     {
420         abAppend(&ab,"\n",1);
421         (void) snprintf(seq,64,"\r");
422         abAppend(&ab,seq,strlen(seq));
423         rows++;
424         if (rows > (int)l->maxrows) l->maxrows = rows;
425     }
426 
427     /* Move cursor to right position. */
428     rpos2 = (plen+l->pos+l->cols)/l->cols; /* current cursor relative row. */
429 
430     /* Go up till we reach the expected positon. */
431     if (rows-rpos2 > 0) {
432         (void) snprintf(seq,64,"\x1b[%dA", rows-rpos2);
433         abAppend(&ab,seq,strlen(seq));
434     }
435 
436     /* Set column. */
437     col = (plen+(int)l->pos) % (int)l->cols;
438     if (col)
439         (void) snprintf(seq,64,"\r\x1b[%dC", col);
440     else
441         (void) snprintf(seq,64,"\r");
442     abAppend(&ab,seq,strlen(seq));
443 
444     l->oldpos = l->pos;
445 
446     (void) put_bytes(ab.b, ab.len);
447     abFree(&ab);
448 }
449 
450 /* Calls the two low level functions refreshSingleLine() or
451  * refreshMultiLine() according to the selected mode. */
452 static void refreshLine(struct linenoiseState *l) {
453     if (mlmode)
454         refreshMultiLine(l);
455     else
456         refreshSingleLine(l);
457 }
458 
459 /* Insert the character 'c' at cursor current position.
460  *
461  * On error writing to the terminal -1 is returned, otherwise 0. */
462 static int
463 linenoiseEditInsert(struct linenoiseState *l, char c) {
464     if (l->len < l->buflen) {
465         if (l->len == l->pos) {
466             l->buf[l->pos] = c;
467             l->pos++;
468             l->len++;
469             l->buf[l->len] = '\0';
470             if ((!mlmode && l->plen+l->len < l->cols) /* || mlmode */) {
471                 /* Avoid a full update of the line in the
472                  * trivial case. */
473                 putchar(c);
474             } else {
475                 refreshLine(l);
476             }
477         } else {
478             memmove(l->buf+l->pos+1,l->buf+l->pos,l->len-l->pos);
479             l->buf[l->pos] = c;
480             l->len++;
481             l->pos++;
482             l->buf[l->len] = '\0';
483             refreshLine(l);
484         }
485     }
486     return 0;
487 }
488 
489 /* Move cursor on the left. */
490 static void
491 linenoiseEditMoveLeft(struct linenoiseState *l) {
492     if (l->pos > 0) {
493         l->pos--;
494         refreshLine(l);
495     }
496 }
497 
498 /* Move cursor on the right. */
499 static void
500 linenoiseEditMoveRight(struct linenoiseState *l) {
501     if (l->pos != l->len) {
502         l->pos++;
503         refreshLine(l);
504     }
505 }
506 
507 /* Move cursor to the start of the line. */
508 static void
509 linenoiseEditMoveHome(struct linenoiseState *l) {
510     if (l->pos != 0) {
511         l->pos = 0;
512         refreshLine(l);
513     }
514 }
515 
516 /* Move cursor to the end of the line. */
517 static void
518 linenoiseEditMoveEnd(struct linenoiseState *l) {
519     if (l->pos != l->len) {
520         l->pos = l->len;
521         refreshLine(l);
522     }
523 }
524 
525 /* Substitute the currently edited line with the next or previous history
526  * entry as specified by 'dir'. */
527 #define LINENOISE_HISTORY_NEXT 0
528 #define LINENOISE_HISTORY_PREV 1
529 static void
530 linenoiseEditHistoryNext(struct linenoiseState *l, int dir) {
531     if (history_len > 1) {
532         /* Update the current history entry before to
533          * overwrite it with the next one. */
534         free(history[history_len - 1 - l->history_index]);
535         history[history_len - 1 - l->history_index] = strdup(l->buf);
536         /* Show the new entry */
537         l->history_index += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1;
538         if (l->history_index < 0) {
539             l->history_index = 0;
540             return;
541         } else if (l->history_index >= history_len) {
542             l->history_index = history_len-1;
543             return;
544         }
545         (void) strncpy(l->buf, history[history_len - 1 - l->history_index],
546 	    l->buflen);
547         l->buf[l->buflen-1] = '\0';
548         l->len = l->pos = strlen(l->buf);
549         refreshLine(l);
550     }
551 }
552 
553 /* Delete the character at the right of the cursor without altering the cursor
554  * position. Basically this is what happens with the "Delete" keyboard key. */
555 static void
556 linenoiseEditDelete(struct linenoiseState *l) {
557     if (l->len > 0 && l->pos < l->len) {
558         memmove(l->buf+l->pos,l->buf+l->pos+1,l->len-l->pos-1);
559         l->len--;
560         l->buf[l->len] = '\0';
561         refreshLine(l);
562     }
563 }
564 
565 /* Backspace implementation. */
566 static void
567 linenoiseEditBackspace(struct linenoiseState *l) {
568     if (l->pos > 0 && l->len > 0) {
569         memmove(l->buf+l->pos-1,l->buf+l->pos,l->len-l->pos);
570         l->pos--;
571         l->len--;
572         l->buf[l->len] = '\0';
573         refreshLine(l);
574     }
575 }
576 
577 /* Delete the previosu word, maintaining the cursor at the start of the
578  * current word. */
579 static void
580 linenoiseEditDeletePrevWord(struct linenoiseState *l) {
581     size_t old_pos = l->pos;
582     size_t diff;
583 
584     while (l->pos > 0 && l->buf[l->pos-1] == ' ')
585         l->pos--;
586     while (l->pos > 0 && l->buf[l->pos-1] != ' ')
587         l->pos--;
588     diff = old_pos - l->pos;
589     memmove(l->buf+l->pos,l->buf+old_pos,l->len-old_pos+1);
590     l->len -= diff;
591     refreshLine(l);
592 }
593 
594 /* This function is the core of the line editing capability of linenoise.
595  * It expects 'fd' to be already in "raw mode" so that every key pressed
596  * will be returned ASAP to read().
597  *
598  * The resulting string is put into 'buf' when the user type enter, or
599  * when ctrl+d is typed.
600  *
601  * The function returns the length of the current buffer. */
602 static int linenoiseEdit(char *buf, size_t buflen, const char *prompt)
603 {
604     struct linenoiseState l;
605 
606     /* Populate the linenoise state that we pass to functions implementing
607      * specific editing functionalities. */
608     l.buf = buf;
609     l.buflen = buflen;
610     l.prompt = prompt;
611     l.plen = strlen(prompt);
612     l.oldpos = l.pos = 0;
613     l.len = 0;
614     l.cols = getColumns();
615     l.maxrows = 0;
616     l.history_index = 0;
617 
618     /* Buffer starts empty. */
619     l.buf[0] = '\0';
620     l.buflen--; /* Make sure there is always space for the nulterm */
621 
622     /* The latest history entry is always our current buffer, that
623      * initially is just an empty string. */
624     (void) linenoiseHistoryAdd("");
625 
626     printf ("%s", prompt);
627     while(1) {
628         char c;
629         char seq[3];
630 
631         c = getchar();
632 	if (c == -1)
633 		continue;
634 
635         /* Only autocomplete when the callback is set. It returns < 0 when
636          * there was an error reading from fd. Otherwise it will return the
637          * character that should be handled next. */
638         if (c == 9 && completionCallback != NULL) {
639             c = completeLine(&l);
640             /* Return on errors */
641             if (c < 0) return l.len;
642             /* Read next character when 0 */
643             if (c == 0) continue;
644         }
645 
646         switch(c) {
647         case ENTER:    /* enter */
648             history_len--;
649             free(history[history_len]);
650             if (mlmode) linenoiseEditMoveEnd(&l);
651             return (int)l.len;
652         case CTRL_C:     /* ctrl-c */
653             buf[0] = '\0';
654             l.pos = l.len = 0;
655             refreshLine(&l);
656 	    break;
657         case BACKSPACE:   /* backspace */
658         case 8:     /* ctrl-h */
659             linenoiseEditBackspace(&l);
660             break;
661         case CTRL_D:     /* ctrl-d, remove char at right of cursor. */
662             if (l.len > 0) {
663                 linenoiseEditDelete(&l);
664             }
665             break;
666         case CTRL_T:    /* ctrl-t, swaps current character with previous. */
667             if (l.pos > 0 && l.pos < l.len) {
668                 int aux = buf[l.pos-1];
669                 buf[l.pos-1] = buf[l.pos];
670                 buf[l.pos] = aux;
671                 if (l.pos != l.len-1) l.pos++;
672                 refreshLine(&l);
673             }
674             break;
675         case CTRL_B:     /* ctrl-b */
676             linenoiseEditMoveLeft(&l);
677             break;
678         case CTRL_F:     /* ctrl-f */
679             linenoiseEditMoveRight(&l);
680             break;
681         case CTRL_P:    /* ctrl-p */
682             linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
683             break;
684         case CTRL_N:    /* ctrl-n */
685             linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
686             break;
687         case ESC:    /* escape sequence */
688             /* Read the next two bytes representing the escape sequence.
689              * Use two calls to handle slow terminals returning the two
690              * chars at different times. */
691             seq[0] = getchar();
692             seq[1] = getchar();
693 
694             /* ESC [ sequences. */
695             if (seq[0] == '[') {
696                 if (seq[1] >= '0' && seq[1] <= '9') {
697                     /* Extended escape, read additional byte. */
698                     seq[2] = getchar();
699                     if (seq[2] == '~') {
700                         switch(seq[1]) {
701                         case '3': /* Delete key. */
702                             linenoiseEditDelete(&l);
703                             break;
704                         }
705                     }
706                 } else {
707                     switch(seq[1]) {
708                     case 'A': /* Up */
709                         linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
710                         break;
711                     case 'B': /* Down */
712                         linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
713                         break;
714                     case 'C': /* Right */
715                         linenoiseEditMoveRight(&l);
716                         break;
717                     case 'D': /* Left */
718                         linenoiseEditMoveLeft(&l);
719                         break;
720                     case 'H': /* Home */
721                         linenoiseEditMoveHome(&l);
722                         break;
723                     case 'F': /* End*/
724                         linenoiseEditMoveEnd(&l);
725                         break;
726                     }
727                 }
728             }
729 
730             /* ESC O sequences. */
731             else if (seq[0] == 'O') {
732                 switch(seq[1]) {
733                 case 'H': /* Home */
734                     linenoiseEditMoveHome(&l);
735                     break;
736                 case 'F': /* End*/
737                     linenoiseEditMoveEnd(&l);
738                     break;
739                 }
740             }
741             break;
742         default:
743             if (linenoiseEditInsert(&l,c)) return -1;
744             break;
745         case CTRL_U: /* Ctrl+u, delete the whole line. */
746             buf[0] = '\0';
747             l.pos = l.len = 0;
748             refreshLine(&l);
749             break;
750         case CTRL_K: /* Ctrl+k, delete from current to end of line. */
751             buf[l.pos] = '\0';
752             l.len = l.pos;
753             refreshLine(&l);
754             break;
755         case CTRL_A: /* Ctrl+a, go to the start of the line */
756             linenoiseEditMoveHome(&l);
757             break;
758         case CTRL_E: /* ctrl+e, go to the end of the line */
759             linenoiseEditMoveEnd(&l);
760             break;
761         case CTRL_L: /* ctrl+l, clear screen */
762             linenoiseClearScreen();
763             refreshLine(&l);
764             break;
765         case CTRL_W: /* ctrl+w, delete previous word */
766             linenoiseEditDeletePrevWord(&l);
767             break;
768         }
769     }
770     return l.len;
771 }
772 
773 /* The high level function that is the main API of the linenoise library.
774  * This function checks if the terminal has basic capabilities, just checking
775  * for a blacklist of stupid terminals, and later either calls the line
776  * editing function or uses dummy fgets() so that you will be able to type
777  * something even in the most desperate of the conditions. */
778 char *linenoise(const char *prompt) {
779     char buf[LINENOISE_MAX_LINE];
780     int count;
781 
782     cons_mode(C_MODERAW);
783     count = linenoiseEdit(buf,LINENOISE_MAX_LINE,prompt);
784     cons_mode(0);
785     printf("\n");
786     if (count == -1) return NULL;
787     return strdup(buf);
788 }
789 
790 /* ================================ History ================================= */
791 
792 /* This is the API call to add a new entry in the linenoise history.
793  * It uses a fixed array of char pointers that are shifted (memmoved)
794  * when the history max length is reached in order to remove the older
795  * entry and make room for the new one, so it is not exactly suitable for huge
796  * histories, but will work well for a few hundred of entries.
797  *
798  * Using a circular buffer is smarter, but a bit more complex to handle. */
799 int linenoiseHistoryAdd(const char *line) {
800     char *linecopy;
801 
802     if (history_max_len == 0) return 0;
803 
804     /* Initialization on first call. */
805     if (history == NULL) {
806         history = malloc(sizeof(char*)*history_max_len);
807         if (history == NULL) return 0;
808         memset(history,0,(sizeof(char*)*history_max_len));
809     }
810 
811     /* Don't add duplicated lines. */
812     if (history_len && !strcmp(history[history_len-1], line)) return 0;
813 
814     /* Add an heap allocated copy of the line in the history.
815      * If we reached the max length, remove the older line. */
816     linecopy = strdup(line);
817     if (!linecopy) return 0;
818     if (history_len == history_max_len) {
819         free(history[0]);
820         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
821         history_len--;
822     }
823     history[history_len] = linecopy;
824     history_len++;
825     return 1;
826 }
827 
828 /* Set the maximum length for the history. This function can be called even
829  * if there is already some history, the function will make sure to retain
830  * just the latest 'len' elements if the new history length value is smaller
831  * than the amount of items already inside the history. */
832 int linenoiseHistorySetMaxLen(int len) {
833     char **new;
834 
835     if (len < 1) return 0;
836     if (history) {
837         int tocopy = history_len;
838 
839         new = malloc(sizeof(char*)*len);
840         if (new == NULL) return 0;
841 
842         /* If we can't copy everything, free the elements we'll not use. */
843         if (len < tocopy) {
844             int j;
845 
846             for (j = 0; j < tocopy-len; j++) free(history[j]);
847             tocopy = len;
848         }
849         memset(new,0,sizeof(char*)*len);
850         memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy);
851         free(history);
852         history = new;
853     }
854     history_max_len = len;
855     if (history_len > history_max_len)
856         history_len = history_max_len;
857     return 1;
858 }
859