xref: /illumos-gate/usr/src/boot/common/linenoise/linenoise.c (revision 22028508fd28d36ff74dc02c5774a8ba1f0db045)
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
put_bytes(const char * s,int len)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. */
linenoiseSetMultiLine(int ml)176 void linenoiseSetMultiLine(int ml) {
177     mlmode = ml;
178 }
179 
180 /* Clear the screen. Used to handle ctrl+l */
linenoiseClearScreen(void)181 void linenoiseClearScreen(void) {
182     if (put_bytes("\x1b[H\x1b[J", 6) <= 0) {
183         /* nothing to do, just to avoid warning. */
184     }
185 }
186 
187 static int
getColumns(void)188 getColumns(void)
189 {
190 	char *columns = getenv("screen-#cols");
191 	if (columns == NULL)
192 		return (80);
193 	return (strtol(columns, NULL, 0));
194 }
195 
196 /* Beep, used for completion when there is nothing to complete or when all
197  * the choices were already shown. */
linenoiseBeep(void)198 static void linenoiseBeep(void) {
199     put_bytes("\x7", 1);
200 }
201 
202 /* ============================== Completion ================================ */
203 
204 /* Free a list of completion option populated by linenoiseAddCompletion(). */
freeCompletions(linenoiseCompletions * lc)205 static void freeCompletions(linenoiseCompletions *lc) {
206     size_t i;
207     for (i = 0; i < lc->len; i++)
208         free(lc->cvec[i]);
209     if (lc->cvec != NULL)
210         free(lc->cvec);
211 }
212 
213 /* This is an helper function for linenoiseEdit() and is called when the
214  * user types the <tab> key in order to complete the string currently in the
215  * input.
216  *
217  * The state of the editing is encapsulated into the pointed linenoiseState
218  * structure as described in the structure definition. */
completeLine(struct linenoiseState * ls)219 static int completeLine(struct linenoiseState *ls) {
220     linenoiseCompletions lc = { 0, NULL };
221     int nwritten;
222     char c = 0;
223 
224     completionCallback(ls->buf,&lc);
225     if (lc.len == 0) {
226         linenoiseBeep();
227     } else {
228         size_t stop = 0, i = 0;
229 
230         while(!stop) {
231             /* Show completion or original buffer */
232             if (i < lc.len) {
233                 struct linenoiseState saved = *ls;
234 
235                 ls->len = ls->pos = strlen(lc.cvec[i]);
236                 ls->buf = lc.cvec[i];
237                 refreshLine(ls);
238                 ls->len = saved.len;
239                 ls->pos = saved.pos;
240                 ls->buf = saved.buf;
241             } else {
242                 refreshLine(ls);
243             }
244 
245             c = getchar();
246             if (c <= 0) {
247                 freeCompletions(&lc);
248                 return -1;
249             }
250 
251             switch(c) {
252                 case 9: /* tab */
253                     i = (i+1) % (lc.len+1);
254                     if (i == lc.len) linenoiseBeep();
255                     break;
256                 case 27: /* escape */
257                     /* Re-show original buffer */
258                     if (i < lc.len) refreshLine(ls);
259                     stop = 1;
260                     break;
261                 default:
262                     /* Update buffer and return */
263                     if (i < lc.len) {
264                         nwritten = snprintf(ls->buf,ls->buflen,"%s",lc.cvec[i]);
265                         ls->len = ls->pos = nwritten;
266                     }
267                     stop = 1;
268                     break;
269             }
270         }
271     }
272 
273     freeCompletions(&lc);
274     return c; /* Return last read character */
275 }
276 
277 /* Register a callback function to be called for tab-completion. */
linenoiseSetCompletionCallback(linenoiseCompletionCallback * fn)278 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
279     completionCallback = fn;
280 }
281 
282 /* This function is used by the callback function registered by the user
283  * in order to add completion options given the input string when the
284  * user typed <tab>. See the example.c source code for a very easy to
285  * understand example. */
linenoiseAddCompletion(linenoiseCompletions * lc,const char * str)286 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
287     size_t len = strlen(str);
288     char *copy, **cvec;
289 
290     copy = malloc(len+1);
291     if (copy == NULL) return;
292     memcpy(copy,str,len+1);
293     cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
294     if (cvec == NULL) {
295         free(copy);
296         return;
297     }
298     lc->cvec = cvec;
299     lc->cvec[lc->len++] = copy;
300 }
301 
302 /* =========================== Line editing ================================= */
303 
304 /* We define a very simple "append buffer" structure, that is an heap
305  * allocated string where we can append to. This is useful in order to
306  * write all the escape sequences in a buffer and flush them to the standard
307  * output in a single call, to avoid flickering effects. */
308 struct abuf {
309     char *b;
310     int len;
311 };
312 
abInit(struct abuf * ab)313 static void abInit(struct abuf *ab) {
314     ab->b = NULL;
315     ab->len = 0;
316 }
317 
abAppend(struct abuf * ab,const char * s,int len)318 static void abAppend(struct abuf *ab, const char *s, int len) {
319     char *new = malloc(ab->len+len);
320 
321     if (new == NULL) return;
322     memcpy(new, ab->b, ab->len);
323     memcpy(new+ab->len,s,len);
324     free(ab->b);
325     ab->b = new;
326     ab->len += len;
327 }
328 
abFree(struct abuf * ab)329 static void abFree(struct abuf *ab) {
330     free(ab->b);
331 }
332 
333 /* Single line low level line refresh.
334  *
335  * Rewrite the currently edited line accordingly to the buffer content,
336  * cursor position, and number of columns of the terminal. */
refreshSingleLine(struct linenoiseState * l)337 static void refreshSingleLine(struct linenoiseState *l) {
338     char seq[64];
339     size_t plen = strlen(l->prompt);
340     char *buf = l->buf;
341     size_t len = l->len;
342     size_t pos = l->pos;
343     struct abuf ab;
344 
345     while((plen+pos) >= l->cols) {
346         buf++;
347         len--;
348         pos--;
349     }
350     while (plen+len > l->cols) {
351         len--;
352     }
353 
354     abInit(&ab);
355     /* Cursor to left edge */
356     snprintf(seq,64,"\r");
357     abAppend(&ab,seq,strlen(seq));
358     /* Write the prompt and the current buffer content */
359     abAppend(&ab,l->prompt,strlen(l->prompt));
360     abAppend(&ab,buf,len);
361     /* Erase to right */
362     snprintf(seq,64,"\x1b[K");
363     abAppend(&ab,seq,strlen(seq));
364     /* Move cursor to original position. */
365     snprintf(seq,64,"\r\x1b[%dC", (int)(pos+plen));
366     abAppend(&ab,seq,strlen(seq));
367     put_bytes(ab.b, ab.len);
368 
369     abFree(&ab);
370 }
371 
372 /* Multi line low level line refresh.
373  *
374  * Rewrite the currently edited line accordingly to the buffer content,
375  * cursor position, and number of columns of the terminal. */
refreshMultiLine(struct linenoiseState * l)376 static void refreshMultiLine(struct linenoiseState *l) {
377     char seq[64];
378     int plen = strlen(l->prompt);
379     int rows = (plen+l->len+l->cols)/l->cols; /* rows used by current buf. */
380     int rpos = (plen+l->oldpos+l->cols)/l->cols; /* cursor relative row. */
381     int rpos2; /* rpos after refresh. */
382     int col; /* colum position, zero-based. */
383     int old_rows = l->maxrows;
384     int j;
385     struct abuf ab;
386 
387     /* Update maxrows if needed. */
388     if (rows > (int)l->maxrows) l->maxrows = rows;
389 
390     /* First step: clear all the lines used before. To do so start by
391      * going to the last row. */
392     abInit(&ab);
393     if (old_rows-rpos > 0) {
394         snprintf(seq,64,"\x1b[%dB", old_rows-rpos);
395         abAppend(&ab,seq,strlen(seq));
396     }
397 
398     /* Now for every row clear it, go up. */
399     for (j = 0; j < old_rows-1; j++) {
400         snprintf(seq,64,"\r\x1b[0K\x1b[1A");
401         abAppend(&ab,seq,strlen(seq));
402     }
403 
404     /* Clean the top line. */
405     snprintf(seq,64,"\r\x1b[0K");
406     abAppend(&ab,seq,strlen(seq));
407 
408     /* Write the prompt and the current buffer content */
409     abAppend(&ab,l->prompt,strlen(l->prompt));
410     abAppend(&ab,l->buf,l->len);
411 
412     /* If we are at the very end of the screen with our prompt, we need to
413      * emit a newline and move the prompt to the first column. */
414     if (l->pos &&
415         l->pos == l->len &&
416         (l->pos+plen) % l->cols == 0)
417     {
418         abAppend(&ab,"\n",1);
419         snprintf(seq,64,"\r");
420         abAppend(&ab,seq,strlen(seq));
421         rows++;
422         if (rows > (int)l->maxrows) l->maxrows = rows;
423     }
424 
425     /* Move cursor to right position. */
426     rpos2 = (plen+l->pos+l->cols)/l->cols; /* current cursor relative row. */
427 
428     /* Go up till we reach the expected positon. */
429     if (rows-rpos2 > 0) {
430         snprintf(seq,64,"\x1b[%dA", rows-rpos2);
431         abAppend(&ab,seq,strlen(seq));
432     }
433 
434     /* Set column. */
435     col = (plen+(int)l->pos) % (int)l->cols;
436     if (col)
437         snprintf(seq,64,"\r\x1b[%dC", col);
438     else
439         snprintf(seq,64,"\r");
440     abAppend(&ab,seq,strlen(seq));
441 
442     l->oldpos = l->pos;
443 
444     put_bytes(ab.b, ab.len);
445     abFree(&ab);
446 }
447 
448 /* Calls the two low level functions refreshSingleLine() or
449  * refreshMultiLine() according to the selected mode. */
refreshLine(struct linenoiseState * l)450 static void refreshLine(struct linenoiseState *l) {
451     if (mlmode)
452         refreshMultiLine(l);
453     else
454         refreshSingleLine(l);
455 }
456 
457 /* Insert the character 'c' at cursor current position.
458  *
459  * On error writing to the terminal -1 is returned, otherwise 0. */
460 static int
linenoiseEditInsert(struct linenoiseState * l,char c)461 linenoiseEditInsert(struct linenoiseState *l, char c) {
462     if (l->len < l->buflen) {
463         if (l->len == l->pos) {
464             l->buf[l->pos] = c;
465             l->pos++;
466             l->len++;
467             l->buf[l->len] = '\0';
468             if ((!mlmode && l->plen+l->len < l->cols) /* || mlmode */) {
469                 /* Avoid a full update of the line in the
470                  * trivial case. */
471                 putchar(c);
472             } else {
473                 refreshLine(l);
474             }
475         } else {
476             memmove(l->buf+l->pos+1,l->buf+l->pos,l->len-l->pos);
477             l->buf[l->pos] = c;
478             l->len++;
479             l->pos++;
480             l->buf[l->len] = '\0';
481             refreshLine(l);
482         }
483     }
484     return 0;
485 }
486 
487 /* Move cursor on the left. */
488 static void
linenoiseEditMoveLeft(struct linenoiseState * l)489 linenoiseEditMoveLeft(struct linenoiseState *l) {
490     if (l->pos > 0) {
491         l->pos--;
492         refreshLine(l);
493     }
494 }
495 
496 /* Move cursor on the right. */
497 static void
linenoiseEditMoveRight(struct linenoiseState * l)498 linenoiseEditMoveRight(struct linenoiseState *l) {
499     if (l->pos != l->len) {
500         l->pos++;
501         refreshLine(l);
502     }
503 }
504 
505 /* Move cursor to the start of the line. */
506 static void
linenoiseEditMoveHome(struct linenoiseState * l)507 linenoiseEditMoveHome(struct linenoiseState *l) {
508     if (l->pos != 0) {
509         l->pos = 0;
510         refreshLine(l);
511     }
512 }
513 
514 /* Move cursor to the end of the line. */
515 static void
linenoiseEditMoveEnd(struct linenoiseState * l)516 linenoiseEditMoveEnd(struct linenoiseState *l) {
517     if (l->pos != l->len) {
518         l->pos = l->len;
519         refreshLine(l);
520     }
521 }
522 
523 /* Substitute the currently edited line with the next or previous history
524  * entry as specified by 'dir'. */
525 #define LINENOISE_HISTORY_NEXT 0
526 #define LINENOISE_HISTORY_PREV 1
527 static void
linenoiseEditHistoryNext(struct linenoiseState * l,int dir)528 linenoiseEditHistoryNext(struct linenoiseState *l, int dir) {
529     if (history_len > 1) {
530         /* Update the current history entry before to
531          * overwrite it with the next one. */
532         free(history[history_len - 1 - l->history_index]);
533         history[history_len - 1 - l->history_index] = strdup(l->buf);
534         /* Show the new entry */
535         l->history_index += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1;
536         if (l->history_index < 0) {
537             l->history_index = 0;
538             return;
539         } else if (l->history_index >= history_len) {
540             l->history_index = history_len-1;
541             return;
542         }
543         strncpy(l->buf,history[history_len - 1 - l->history_index],l->buflen);
544         l->buf[l->buflen-1] = '\0';
545         l->len = l->pos = strlen(l->buf);
546         refreshLine(l);
547     }
548 }
549 
550 /* Delete the character at the right of the cursor without altering the cursor
551  * position. Basically this is what happens with the "Delete" keyboard key. */
552 static void
linenoiseEditDelete(struct linenoiseState * l)553 linenoiseEditDelete(struct linenoiseState *l) {
554     if (l->len > 0 && l->pos < l->len) {
555         memmove(l->buf+l->pos,l->buf+l->pos+1,l->len-l->pos-1);
556         l->len--;
557         l->buf[l->len] = '\0';
558         refreshLine(l);
559     }
560 }
561 
562 /* Backspace implementation. */
563 static void
linenoiseEditBackspace(struct linenoiseState * l)564 linenoiseEditBackspace(struct linenoiseState *l) {
565     if (l->pos > 0 && l->len > 0) {
566         memmove(l->buf+l->pos-1,l->buf+l->pos,l->len-l->pos);
567         l->pos--;
568         l->len--;
569         l->buf[l->len] = '\0';
570         refreshLine(l);
571     }
572 }
573 
574 /* Delete the previosu word, maintaining the cursor at the start of the
575  * current word. */
576 static void
linenoiseEditDeletePrevWord(struct linenoiseState * l)577 linenoiseEditDeletePrevWord(struct linenoiseState *l) {
578     size_t old_pos = l->pos;
579     size_t diff;
580 
581     while (l->pos > 0 && l->buf[l->pos-1] == ' ')
582         l->pos--;
583     while (l->pos > 0 && l->buf[l->pos-1] != ' ')
584         l->pos--;
585     diff = old_pos - l->pos;
586     memmove(l->buf+l->pos,l->buf+old_pos,l->len-old_pos+1);
587     l->len -= diff;
588     refreshLine(l);
589 }
590 
591 /* This function is the core of the line editing capability of linenoise.
592  * It expects 'fd' to be already in "raw mode" so that every key pressed
593  * will be returned ASAP to read().
594  *
595  * The resulting string is put into 'buf' when the user type enter, or
596  * when ctrl+d is typed.
597  *
598  * The function returns the length of the current buffer. */
linenoiseEdit(char * buf,size_t buflen,const char * prompt)599 static int linenoiseEdit(char *buf, size_t buflen, const char *prompt)
600 {
601     struct linenoiseState l;
602 
603     /* Populate the linenoise state that we pass to functions implementing
604      * specific editing functionalities. */
605     l.buf = buf;
606     l.buflen = buflen;
607     l.prompt = prompt;
608     l.plen = strlen(prompt);
609     l.oldpos = l.pos = 0;
610     l.len = 0;
611     l.cols = getColumns();
612     l.maxrows = 0;
613     l.history_index = 0;
614 
615     /* Buffer starts empty. */
616     l.buf[0] = '\0';
617     l.buflen--; /* Make sure there is always space for the nulterm */
618 
619     /* The latest history entry is always our current buffer, that
620      * initially is just an empty string. */
621     linenoiseHistoryAdd("");
622 
623     printf ("%s", prompt);
624     while(1) {
625         char c;
626         char seq[3];
627 
628         c = getchar();
629 	if (c == -1)
630 		continue;
631 
632         /* Only autocomplete when the callback is set. It returns < 0 when
633          * there was an error reading from fd. Otherwise it will return the
634          * character that should be handled next. */
635         if (c == 9 && completionCallback != NULL) {
636             c = completeLine(&l);
637             /* Return on errors */
638             if (c < 0) return l.len;
639             /* Read next character when 0 */
640             if (c == 0) continue;
641         }
642 
643         switch(c) {
644         case ENTER:    /* enter */
645             history_len--;
646             free(history[history_len]);
647             if (mlmode) linenoiseEditMoveEnd(&l);
648             return (int)l.len;
649         case CTRL_C:     /* ctrl-c */
650             buf[0] = '\0';
651             l.pos = l.len = 0;
652             refreshLine(&l);
653 	    break;
654         case BACKSPACE:   /* backspace */
655         case 8:     /* ctrl-h */
656             linenoiseEditBackspace(&l);
657             break;
658         case CTRL_D:     /* ctrl-d, remove char at right of cursor. */
659             if (l.len > 0) {
660                 linenoiseEditDelete(&l);
661             }
662             break;
663         case CTRL_T:    /* ctrl-t, swaps current character with previous. */
664             if (l.pos > 0 && l.pos < l.len) {
665                 int aux = buf[l.pos-1];
666                 buf[l.pos-1] = buf[l.pos];
667                 buf[l.pos] = aux;
668                 if (l.pos != l.len-1) l.pos++;
669                 refreshLine(&l);
670             }
671             break;
672         case CTRL_B:     /* ctrl-b */
673             linenoiseEditMoveLeft(&l);
674             break;
675         case CTRL_F:     /* ctrl-f */
676             linenoiseEditMoveRight(&l);
677             break;
678         case CTRL_P:    /* ctrl-p */
679             linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
680             break;
681         case CTRL_N:    /* ctrl-n */
682             linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
683             break;
684         case ESC:    /* escape sequence */
685             /* Read the next two bytes representing the escape sequence.
686              * Use two calls to handle slow terminals returning the two
687              * chars at different times. */
688             seq[0] = getchar();
689             seq[1] = getchar();
690 
691             /* ESC [ sequences. */
692             if (seq[0] == '[') {
693                 if (seq[1] >= '0' && seq[1] <= '9') {
694                     /* Extended escape, read additional byte. */
695                     seq[2] = getchar();
696                     if (seq[2] == '~') {
697                         switch(seq[1]) {
698                         case '3': /* Delete key. */
699                             linenoiseEditDelete(&l);
700                             break;
701                         }
702                     }
703                 } else {
704                     switch(seq[1]) {
705                     case 'A': /* Up */
706                         linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
707                         break;
708                     case 'B': /* Down */
709                         linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
710                         break;
711                     case 'C': /* Right */
712                         linenoiseEditMoveRight(&l);
713                         break;
714                     case 'D': /* Left */
715                         linenoiseEditMoveLeft(&l);
716                         break;
717                     case 'H': /* Home */
718                         linenoiseEditMoveHome(&l);
719                         break;
720                     case 'F': /* End*/
721                         linenoiseEditMoveEnd(&l);
722                         break;
723                     }
724                 }
725             }
726 
727             /* ESC O sequences. */
728             else if (seq[0] == 'O') {
729                 switch(seq[1]) {
730                 case 'H': /* Home */
731                     linenoiseEditMoveHome(&l);
732                     break;
733                 case 'F': /* End*/
734                     linenoiseEditMoveEnd(&l);
735                     break;
736                 }
737             }
738             break;
739         default:
740             if (linenoiseEditInsert(&l,c)) return -1;
741             break;
742         case CTRL_U: /* Ctrl+u, delete the whole line. */
743             buf[0] = '\0';
744             l.pos = l.len = 0;
745             refreshLine(&l);
746             break;
747         case CTRL_K: /* Ctrl+k, delete from current to end of line. */
748             buf[l.pos] = '\0';
749             l.len = l.pos;
750             refreshLine(&l);
751             break;
752         case CTRL_A: /* Ctrl+a, go to the start of the line */
753             linenoiseEditMoveHome(&l);
754             break;
755         case CTRL_E: /* ctrl+e, go to the end of the line */
756             linenoiseEditMoveEnd(&l);
757             break;
758         case CTRL_L: /* ctrl+l, clear screen */
759             linenoiseClearScreen();
760             refreshLine(&l);
761             break;
762         case CTRL_W: /* ctrl+w, delete previous word */
763             linenoiseEditDeletePrevWord(&l);
764             break;
765         }
766     }
767     return l.len;
768 }
769 
770 /* The high level function that is the main API of the linenoise library.
771  * This function checks if the terminal has basic capabilities, just checking
772  * for a blacklist of stupid terminals, and later either calls the line
773  * editing function or uses dummy fgets() so that you will be able to type
774  * something even in the most desperate of the conditions. */
linenoise(const char * prompt)775 char *linenoise(const char *prompt) {
776     char buf[LINENOISE_MAX_LINE];
777     int count;
778 
779     cons_mode(C_MODERAW);
780     count = linenoiseEdit(buf,LINENOISE_MAX_LINE,prompt);
781     cons_mode(0);
782     printf("\n");
783     if (count == -1) return NULL;
784     return strdup(buf);
785 }
786 
787 /* ================================ History ================================= */
788 
789 /* This is the API call to add a new entry in the linenoise history.
790  * It uses a fixed array of char pointers that are shifted (memmoved)
791  * when the history max length is reached in order to remove the older
792  * entry and make room for the new one, so it is not exactly suitable for huge
793  * histories, but will work well for a few hundred of entries.
794  *
795  * Using a circular buffer is smarter, but a bit more complex to handle. */
linenoiseHistoryAdd(const char * line)796 int linenoiseHistoryAdd(const char *line) {
797     char *linecopy;
798 
799     if (history_max_len == 0) return 0;
800 
801     /* Initialization on first call. */
802     if (history == NULL) {
803         history = malloc(sizeof(char*)*history_max_len);
804         if (history == NULL) return 0;
805         memset(history,0,(sizeof(char*)*history_max_len));
806     }
807 
808     /* Don't add duplicated lines. */
809     if (history_len && !strcmp(history[history_len-1], line)) return 0;
810 
811     /* Add an heap allocated copy of the line in the history.
812      * If we reached the max length, remove the older line. */
813     linecopy = strdup(line);
814     if (!linecopy) return 0;
815     if (history_len == history_max_len) {
816         free(history[0]);
817         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
818         history_len--;
819     }
820     history[history_len] = linecopy;
821     history_len++;
822     return 1;
823 }
824 
825 /* Set the maximum length for the history. This function can be called even
826  * if there is already some history, the function will make sure to retain
827  * just the latest 'len' elements if the new history length value is smaller
828  * than the amount of items already inside the history. */
linenoiseHistorySetMaxLen(int len)829 int linenoiseHistorySetMaxLen(int len) {
830     char **new;
831 
832     if (len < 1) return 0;
833     if (history) {
834         int tocopy = history_len;
835 
836         new = malloc(sizeof(char*)*len);
837         if (new == NULL) return 0;
838 
839         /* If we can't copy everything, free the elements we'll not use. */
840         if (len < tocopy) {
841             int j;
842 
843             for (j = 0; j < tocopy-len; j++) free(history[j]);
844             tocopy = len;
845         }
846         memset(new,0,sizeof(char*)*len);
847         memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy);
848         free(history);
849         history = new;
850     }
851     history_max_len = len;
852     if (history_len > history_max_len)
853         history_len = history_max_len;
854     return 1;
855 }
856