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