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