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