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.
4 * You can find the latest source code at:
6 * http://github.com/antirez/linenoise
8 * Does a number of crazy assumptions that happen to be true in 99.9999% of
9 * the 2010 UNIX computers around.
11 * ------------------------------------------------------------------------
13 * Copyright (c) 2010-2016, Salvatore Sanfilippo <antirez at gmail dot com>
14 * Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
16 * All rights reserved.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
22 * * Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
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.
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.
41 * ------------------------------------------------------------------------
44 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
45 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
48 * - Filter bogus Ctrl+<char> combinations.
52 * - History search like Ctrl+r in readline?
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.
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
65 * CUF (CUrsor Forward)
67 * Effect: moves cursor forward n chars
69 * CUB (CUrsor Backward)
71 * Effect: moves cursor backward n chars
73 * The following is used to get the terminal width if getting
74 * the width with the TIOCGWINSZ ioctl fails
76 * DSR (Device Status Report)
78 * Effect: reports the current cusor position as ESC [ n ; m R
79 * where n is the row and m is the column
81 * When multi line mode is enabled, we also use an additional escape
82 * sequence. However multi line editing is disabled by default.
86 * Effect: moves cursor up of n chars.
90 * Effect: moves cursor down of n chars.
92 * When linenoiseClearScreen() is called, two additional escape sequences
93 * are used in order to clear the screen and position the cursor at home
96 * CUP (Cursor position)
98 * Effect: moves the cursor to upper left corner
101 * Sequence: ESC [ 2 J
102 * Effect: clear the whole screen
114 #include <sys/stat.h>
115 #include <sys/types.h>
116 #include <sys/ioctl.h>
118 #include "linenoise.h"
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;
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;
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. */
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 */
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 */
176 static void linenoiseAtExit(void);
177 int linenoiseHistoryAdd(const char *line);
178 static void refreshLine(struct linenoiseState *l);
180 /* Debugging macro. */
182 FILE *lndebug_fp = NULL;
183 #define lndebug(...) \
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); \
192 fprintf(lndebug_fp, ", " __VA_ARGS__); \
193 fflush(lndebug_fp); \
196 #define lndebug(fmt, ...)
199 /* ======================= Low level terminal handling ====================== */
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) {
209 /* Disable mask mode. */
210 void linenoiseMaskModeDisable(void) {
214 /* Set if to use or not the multi line mode. */
215 void linenoiseSetMultiLine(int ml) {
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");
225 if (term == NULL) return 0;
226 for (j = 0; unsupported_term[j]; j++)
227 if (!strcasecmp(term,unsupported_term[j])) return 1;
231 /* Raw mode: 1960 magic shit. */
232 static int enableRawMode(int fd) {
235 if (!isatty(STDIN_FILENO)) goto fatal;
236 if (!atexit_registered) {
237 atexit(linenoiseAtExit);
238 atexit_registered = 1;
240 if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
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 */
257 /* put terminal in raw mode after flushing */
258 if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
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)
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
276 static int getCursorPosition(int ifd, int ofd) {
281 /* Report cursor location */
282 if (write(ofd, "\x1b[6n", 4) != 4) return -1;
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;
293 if (buf[0] != ESC || buf[1] != '[') return -1;
294 if (sscanf(buf+2,"%d;%d",&rows,&cols) != 2) return -1;
298 /* Try to get the number of columns in the current terminal, or assume 80
300 static int getColumns(int ifd, int ofd) {
303 if (ioctl(1, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
304 /* ioctl() failed. Try to query the terminal itself. */
307 /* Get the initial position so we can restore it later. */
308 start = getCursorPosition(ifd,ofd);
309 if (start == -1) goto failed;
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;
316 /* Restore position. */
319 snprintf(seq,32,"\x1b[%dD",cols-start);
320 if (write(ofd,seq,strlen(seq)) == -1) {
321 /* Can't recover... */
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. */
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");
347 /* ============================== Completion ================================ */
349 /* Free a list of completion option populated by linenoiseAddCompletion(). */
350 static void freeCompletions(linenoiseCompletions *lc) {
352 for (i = 0; i < lc->len; i++)
354 if (lc->cvec != NULL)
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
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 };
369 completionCallback(ls->buf,&lc);
373 size_t stop = 0, i = 0;
376 /* Show completion or original buffer */
378 struct linenoiseState saved = *ls;
380 ls->len = ls->pos = strlen(lc.cvec[i]);
381 ls->buf = lc.cvec[i];
390 nread = read(ls->ifd,&c,1);
392 freeCompletions(&lc);
398 i = (i+1) % (lc.len+1);
399 if (i == lc.len) linenoiseBeep();
401 case 27: /* escape */
402 /* Re-show original buffer */
403 if (i < lc.len) refreshLine(ls);
407 /* Update buffer and return */
409 nwritten = snprintf(ls->buf,ls->buflen,"%s",lc.cvec[i]);
410 ls->len = ls->pos = nwritten;
418 freeCompletions(&lc);
419 return c; /* Return last read character */
422 /* Register a callback function to be called for tab-completion. */
423 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
424 completionCallback = fn;
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) {
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;
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);
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));
456 lc->cvec[lc->len++] = copy;
459 /* =========================== Line editing ================================= */
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. */
470 static void abInit(struct abuf *ab) {
475 static void abAppend(struct abuf *ab, const char *s, int len) {
476 char *new = realloc(ab->b,ab->len+len);
478 if (new == NULL) return;
479 memcpy(new+ab->len,s,len);
484 static void abFree(struct abuf *ab) {
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) {
492 if (hintsCallback && plen+l->len < l->cols) {
493 int color = -1, bold = 0;
494 char *hint = hintsCallback(l->buf,&color,&bold);
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);
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);
514 /* Single line low level line refresh.
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) {
520 size_t plen = strlen(l->prompt);
527 while((plen+pos) >= l->cols) {
532 while (plen+len > l->cols) {
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));
543 while (len--) abAppend(&ab,"*",1);
545 abAppend(&ab,buf,len);
547 /* Show hits if any. */
548 refreshShowHints(&ab,l,plen);
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. */
559 /* Multi line low level line refresh.
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) {
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;
574 /* Update maxrows if needed. */
575 if (rows > (int)l->maxrows) l->maxrows = rows;
577 /* First step: clear all the lines used before. To do so start by
578 * going to the last row. */
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));
586 /* Now for every row clear it, go up. */
587 for (j = 0; j < old_rows-1; j++) {
589 snprintf(seq,64,"\r\x1b[0K\x1b[1A");
590 abAppend(&ab,seq,strlen(seq));
593 /* Clean the top line. */
595 snprintf(seq,64,"\r\x1b[0K");
596 abAppend(&ab,seq,strlen(seq));
598 /* Write the prompt and the current buffer content */
599 abAppend(&ab,l->prompt,strlen(l->prompt));
602 for (i = 0; i < l->len; i++) abAppend(&ab,"*",1);
604 abAppend(&ab,l->buf,l->len);
607 /* Show hits if any. */
608 refreshShowHints(&ab,l,plen);
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. */
614 (l->pos+plen) % l->cols == 0)
616 lndebug("<newline>");
617 abAppend(&ab,"\n",1);
618 snprintf(seq,64,"\r");
619 abAppend(&ab,seq,strlen(seq));
621 if (rows > (int)l->maxrows) l->maxrows = rows;
624 /* Move cursor to right position. */
625 rpos2 = (plen+l->pos+l->cols)/l->cols; /* current cursor relative row. */
626 lndebug("rpos2 %d", rpos2);
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));
636 col = (plen+(int)l->pos) % (int)l->cols;
637 lndebug("set col %d", 1+col);
639 snprintf(seq,64,"\r\x1b[%dC", col);
641 snprintf(seq,64,"\r");
642 abAppend(&ab,seq,strlen(seq));
647 if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */
651 /* Calls the two low level functions refreshSingleLine() or
652 * refreshMultiLine() according to the selected mode. */
653 static void refreshLine(struct linenoiseState *l) {
657 refreshSingleLine(l);
660 /* Insert the character 'c' at cursor current position.
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) {
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
673 char d = (maskmode==1) ? '*' : c;
674 if (write(l->ofd,&d,1) == -1) return -1;
679 memmove(l->buf+l->pos+1,l->buf+l->pos,l->len-l->pos);
683 l->buf[l->len] = '\0';
690 /* Move cursor on the left. */
691 void linenoiseEditMoveLeft(struct linenoiseState *l) {
698 /* Move cursor on the right. */
699 void linenoiseEditMoveRight(struct linenoiseState *l) {
700 if (l->pos != l->len) {
706 /* Move cursor to the start of the line. */
707 void linenoiseEditMoveHome(struct linenoiseState *l) {
714 /* Move cursor to the end of the line. */
715 void linenoiseEditMoveEnd(struct linenoiseState *l) {
716 if (l->pos != l->len) {
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;
737 } else if (l->history_index >= history_len) {
738 l->history_index = history_len-1;
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);
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);
754 l->buf[l->len] = '\0';
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);
765 l->buf[l->len] = '\0';
770 /* Delete the previosu word, maintaining the cursor at the start of the
772 void linenoiseEditDeletePrevWord(struct linenoiseState *l) {
773 size_t old_pos = l->pos;
776 while (l->pos > 0 && l->buf[l->pos-1] == ' ')
778 while (l->pos > 0 && l->buf[l->pos-1] != ' ')
780 diff = old_pos - l->pos;
781 memmove(l->buf+l->pos,l->buf+old_pos,l->len-old_pos+1);
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().
790 * The resulting string is put into 'buf' when the user type enter, or
791 * when ctrl+d is typed.
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)
796 struct linenoiseState l;
798 /* Populate the linenoise state that we pass to functions implementing
799 * specific editing functionalities. */
805 l.plen = strlen(prompt);
806 l.oldpos = l.pos = 0;
808 l.cols = getColumns(stdin_fd, stdout_fd);
812 /* Buffer starts empty. */
814 l.buflen--; /* Make sure there is always space for the nulterm */
816 /* The latest history entry is always our current buffer, that
817 * initially is just an empty string. */
818 linenoiseHistoryAdd("");
820 if (write(l.ofd,prompt,l.plen) == -1) return -1;
826 nread = read(l.ifd,&c,1);
827 if (nread <= 0) return l.len;
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;
841 case ENTER: /* enter */
843 free(history[history_len]);
844 if (mlmode) linenoiseEditMoveEnd(&l);
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;
854 case CTRL_C: /* ctrl-c */
857 case BACKSPACE: /* backspace */
859 linenoiseEditBackspace(&l);
861 case CTRL_D: /* ctrl-d, remove char at right of cursor, or if the
862 line is empty, act as end-of-file. */
864 linenoiseEditDelete(&l);
867 free(history[history_len]);
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];
876 if (l.pos != l.len-1) l.pos++;
880 case CTRL_B: /* ctrl-b */
881 linenoiseEditMoveLeft(&l);
883 case CTRL_F: /* ctrl-f */
884 linenoiseEditMoveRight(&l);
886 case CTRL_P: /* ctrl-p */
887 linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
889 case CTRL_N: /* ctrl-n */
890 linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
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;
899 /* ESC [ sequences. */
901 if (seq[1] >= '0' && seq[1] <= '9') {
902 /* Extended escape, read additional byte. */
903 if (read(l.ifd,seq+2,1) == -1) break;
906 case '3': /* Delete key. */
907 linenoiseEditDelete(&l);
914 linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
917 linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
919 case 'C': /* Right */
920 linenoiseEditMoveRight(&l);
923 linenoiseEditMoveLeft(&l);
926 linenoiseEditMoveHome(&l);
929 linenoiseEditMoveEnd(&l);
935 /* ESC O sequences. */
936 else if (seq[0] == 'O') {
939 linenoiseEditMoveHome(&l);
942 linenoiseEditMoveEnd(&l);
948 if (linenoiseEditInsert(&l,c)) return -1;
950 case CTRL_U: /* Ctrl+u, delete the whole line. */
955 case CTRL_K: /* Ctrl+k, delete from current to end of line. */
960 case CTRL_A: /* Ctrl+a, go to the start of the line */
961 linenoiseEditMoveHome(&l);
963 case CTRL_E: /* ctrl+e, go to the end of the line */
964 linenoiseEditMoveEnd(&l);
966 case CTRL_L: /* ctrl+l, clear screen */
967 linenoiseClearScreen();
970 case CTRL_W: /* ctrl+w, delete previous word */
971 linenoiseEditDeletePrevWord(&l);
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) {
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;
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;
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. */
1003 disableRawMode(STDIN_FILENO);
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) {
1016 if (enableRawMode(STDIN_FILENO) == -1) return -1;
1017 count = linenoiseEdit(STDIN_FILENO, STDOUT_FILENO, buf, buflen, prompt);
1018 disableRawMode(STDIN_FILENO);
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) {
1030 size_t len = 0, maxlen = 0;
1033 if (len == maxlen) {
1034 if (maxlen == 0) maxlen = 16;
1036 char *oldval = line;
1037 line = realloc(line,maxlen);
1039 if (oldval) free(oldval);
1043 int c = fgetc(stdin);
1044 if (c == EOF || c == '\n') {
1045 if (c == EOF && len == 0) {
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];
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()) {
1075 printf("%s",prompt);
1077 if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
1079 while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
1085 count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
1086 if (count == -1) return NULL;
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
1095 void linenoiseFree(void *ptr) {
1099 /* ================================ History ================================= */
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) {
1107 for (j = 0; j < history_len; j++)
1113 /* At exit we'll try to fix the terminal to the initial conditions. */
1114 static void linenoiseAtExit(void) {
1115 disableRawMode(STDIN_FILENO);
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.
1125 * Using a circular buffer is smarter, but a bit more complex to handle. */
1126 int linenoiseHistoryAdd(const char *line) {
1129 if (history_max_len == 0) return 0;
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));
1138 /* Don't add duplicated lines. */
1139 if (history_len && !strcmp(history[history_len-1], line)) return 0;
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) {
1147 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1150 history[history_len] = linecopy;
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) {
1162 if (len < 1) return 0;
1164 int tocopy = history_len;
1166 new = malloc(sizeof(char*)*len);
1167 if (new == NULL) return 0;
1169 /* If we can't copy everything, free the elements we'll not use. */
1173 for (j = 0; j < tocopy-len; j++) free(history[j]);
1176 memset(new,0,sizeof(char*)*len);
1177 memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy);
1181 history_max_len = len;
1182 if (history_len > history_max_len)
1183 history_len = history_max_len;
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);
1194 fp = fopen(filename,"w");
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]);
1204 /* Load the history from the specified file. If the file does not exist
1205 * zero is returned and no operation is performed.
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];
1213 if (fp == NULL) return -1;
1215 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1218 p = strchr(buf,'\r');
1219 if (!p) p = strchr(buf,'\n');
1221 linenoiseHistoryAdd(buf);