Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 1 | /* linenoise.c -- VERSION 1.0 |
| 2 | * |
| 3 | * Guerrilla line editing library against the idea that a line editing lib |
| 4 | * needs to be 20,000 lines of C code. |
| 5 | * |
| 6 | * You can find the latest source code at: |
| 7 | * |
| 8 | * http://github.com/antirez/linenoise |
| 9 | * |
| 10 | * Does a number of crazy assumptions that happen to be true in 99.9999% of |
| 11 | * the 2010 UNIX computers around. |
| 12 | * |
| 13 | * ------------------------------------------------------------------------ |
| 14 | * |
| 15 | * Copyright (c) 2010-2014, Salvatore Sanfilippo <antirez at gmail dot com> |
| 16 | * Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com> |
| 17 | * |
| 18 | * All rights reserved. |
| 19 | * |
| 20 | * Redistribution and use in source and binary forms, with or without |
| 21 | * modification, are permitted provided that the following conditions are |
| 22 | * met: |
| 23 | * |
| 24 | * * Redistributions of source code must retain the above copyright |
| 25 | * notice, this list of conditions and the following disclaimer. |
| 26 | * |
| 27 | * * Redistributions in binary form must reproduce the above copyright |
| 28 | * notice, this list of conditions and the following disclaimer in the |
| 29 | * documentation and/or other materials provided with the distribution. |
| 30 | * |
| 31 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 32 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 33 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| 34 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| 35 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 36 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
| 37 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| 38 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| 39 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 40 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 41 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 42 | * |
| 43 | * ------------------------------------------------------------------------ |
| 44 | * |
| 45 | * References: |
| 46 | * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html |
| 47 | * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html |
| 48 | * |
| 49 | * Todo list: |
| 50 | * - Filter bogus Ctrl+<char> combinations. |
| 51 | * - Win32 support |
| 52 | * |
| 53 | * Bloat: |
| 54 | * - History search like Ctrl+r in readline? |
| 55 | * |
| 56 | * List of escape sequences used by this program, we do everything just |
| 57 | * with three sequences. In order to be so cheap we may have some |
| 58 | * flickering effect with some slow terminal, but the lesser sequences |
| 59 | * the more compatible. |
| 60 | * |
| 61 | * EL (Erase Line) |
| 62 | * Sequence: ESC [ n K |
| 63 | * Effect: if n is 0 or missing, clear from cursor to end of line |
| 64 | * Effect: if n is 1, clear from beginning of line to cursor |
| 65 | * Effect: if n is 2, clear entire line |
| 66 | * |
| 67 | * CUF (CUrsor Forward) |
| 68 | * Sequence: ESC [ n C |
| 69 | * Effect: moves cursor forward n chars |
| 70 | * |
| 71 | * CUB (CUrsor Backward) |
| 72 | * Sequence: ESC [ n D |
| 73 | * Effect: moves cursor backward n chars |
| 74 | * |
| 75 | * The following is used to get the terminal width if getting |
| 76 | * the width with the TIOCGWINSZ ioctl fails |
| 77 | * |
| 78 | * DSR (Device Status Report) |
| 79 | * Sequence: ESC [ 6 n |
| 80 | * Effect: reports the current cusor position as ESC [ n ; m R |
| 81 | * where n is the row and m is the column |
| 82 | * |
| 83 | * When multi line mode is enabled, we also use an additional escape |
| 84 | * sequence. However multi line editing is disabled by default. |
| 85 | * |
| 86 | * CUU (Cursor Up) |
| 87 | * Sequence: ESC [ n A |
| 88 | * Effect: moves cursor up of n chars. |
| 89 | * |
| 90 | * CUD (Cursor Down) |
| 91 | * Sequence: ESC [ n B |
| 92 | * Effect: moves cursor down of n chars. |
| 93 | * |
| 94 | * When linenoiseClearScreen() is called, two additional escape sequences |
| 95 | * are used in order to clear the screen and position the cursor at home |
| 96 | * position. |
| 97 | * |
| 98 | * CUP (Cursor position) |
| 99 | * Sequence: ESC [ H |
| 100 | * Effect: moves the cursor to upper left corner |
| 101 | * |
| 102 | * ED (Erase display) |
| 103 | * Sequence: ESC [ 2 J |
| 104 | * Effect: clear the whole screen |
| 105 | * |
| 106 | */ |
| 107 | |
| 108 | #define _GNU_SOURCE |
Radek Krejci | f8dc59a | 2020-11-25 13:47:44 +0100 | [diff] [blame] | 109 | #define _POSIX_C_SOURCE 200809L /* strdup */ |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 110 | |
Radek Krejci | 535ea9f | 2020-05-29 16:01:05 +0200 | [diff] [blame] | 111 | #include "linenoise.h" |
| 112 | |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 113 | #include <ctype.h> |
| 114 | #include <dirent.h> |
Radek Krejci | 535ea9f | 2020-05-29 16:01:05 +0200 | [diff] [blame] | 115 | #include <errno.h> |
| 116 | #include <stdio.h> |
| 117 | #include <stdlib.h> |
| 118 | #include <string.h> |
| 119 | #include <strings.h> |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 120 | #include <sys/ioctl.h> |
| 121 | #include <sys/stat.h> |
Radek Krejci | 535ea9f | 2020-05-29 16:01:05 +0200 | [diff] [blame] | 122 | #include <termios.h> |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 123 | #include <unistd.h> |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 124 | |
| 125 | #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100 |
| 126 | #define LINENOISE_MAX_LINE 4096 |
| 127 | static char *unsupported_term[] = {"dumb","cons25","emacs",NULL}; |
| 128 | static linenoiseCompletionCallback *completionCallback = NULL; |
| 129 | |
| 130 | static struct termios orig_termios; /* In order to restore at exit.*/ |
| 131 | static int mlmode = 0; /* Multi line mode. Default is single line. */ |
| 132 | static int atexit_registered = 0; /* Register atexit just 1 time. */ |
| 133 | static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN; |
| 134 | static int history_len = 0; |
| 135 | static 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. */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 140 | struct linenoiseState lss; |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 141 | |
| 142 | enum KEY_ACTION{ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 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 */ |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 162 | }; |
| 163 | |
| 164 | static void linenoiseAtExit(void); |
| 165 | int linenoiseHistoryAdd(const char *line); |
| 166 | |
| 167 | /* Debugging macro. */ |
| 168 | #if 0 |
| 169 | FILE *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 |
Michal Vasko | 151ae6c | 2021-09-23 08:23:51 +0200 | [diff] [blame] | 183 | #define lndebug(...) |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 184 | #endif |
| 185 | |
| 186 | /* ======================= Low level terminal handling ====================== */ |
| 187 | |
| 188 | /* Set if to use or not the multi line mode. */ |
| 189 | void 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. */ |
| 195 | static 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. */ |
| 206 | int 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; |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 233 | lss.rawmode = 1; |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 234 | return 0; |
| 235 | |
| 236 | fatal: |
| 237 | errno = ENOTTY; |
| 238 | return -1; |
| 239 | } |
| 240 | |
| 241 | void linenoiseDisableRawMode(int fd) { |
| 242 | /* Don't even check the return value as it's too late. */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 243 | if (lss.rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1) |
| 244 | lss.rawmode = 0; |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 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. */ |
| 250 | static 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. */ |
| 274 | static 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 | |
| 303 | failed: |
| 304 | return 80; |
| 305 | } |
| 306 | |
| 307 | /* Clear the screen. Used to handle ctrl+l */ |
| 308 | void 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. */ |
| 316 | static 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(). */ |
| 324 | static 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 Krejci | d2e4e86 | 2019-04-30 13:50:53 +0200 | [diff] [blame] | 338 | static char completeLine(struct linenoiseState *ls) { |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 339 | 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; |
Michal Vasko | f92aa75 | 2022-09-14 10:32:25 +0200 | [diff] [blame] | 417 | do { |
| 418 | /* Still fits, always at least one hint */ |
| 419 | ++hint_line_count; |
| 420 | |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 421 | char_count = 0; |
| 422 | if (hint_line_count) { |
| 423 | char_count += hint_line_count * (hint_len + 2); |
| 424 | } |
| 425 | char_count += hint_len; |
| 426 | |
| 427 | /* Too much */ |
Michal Vasko | f92aa75 | 2022-09-14 10:32:25 +0200 | [diff] [blame] | 428 | } while (char_count <= w.ws_col); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 429 | |
| 430 | while (c == 9) { |
| 431 | /* Second tab */ |
| 432 | linenoiseDisableRawMode(ls->ifd); |
| 433 | printf("\n"); |
| 434 | for (i = 0; i < lc.len; ++i) { |
| 435 | printf("%-*s", hint_len, lc.cvec[i]); |
| 436 | /* Line full or last hint */ |
| 437 | if (((i + 1) % hint_line_count == 0) || (i == lc.len - 1)) { |
| 438 | printf("\n"); |
| 439 | } else { |
| 440 | printf(" "); |
| 441 | } |
| 442 | } |
| 443 | linenoiseEnableRawMode(ls->ifd); |
| 444 | linenoiseRefreshLine(); |
| 445 | |
| 446 | /* Read a char */ |
| 447 | nread = read(ls->ifd,&c,1); |
| 448 | if (nread <= 0) { |
| 449 | freeCompletions(&lc); |
| 450 | return -1; |
| 451 | } |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | freeCompletions(&lc); |
| 456 | return c; /* Return last read character */ |
| 457 | } |
| 458 | |
| 459 | /* Register a callback function to be called for tab-completion. */ |
| 460 | void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) { |
| 461 | completionCallback = fn; |
| 462 | } |
| 463 | |
| 464 | /* This function can be called in user completion callback to fill |
| 465 | * path completion for them. hint parameter is actually the whole path |
| 466 | * and buf is unused, but included to match the completion callback prototype. */ |
| 467 | void linenoisePathCompletion(const char *buf, const char *hint, linenoiseCompletions *lc) { |
| 468 | const char *ptr; |
| 469 | char *full_path, *hint_ptr, match[FILENAME_MAX + 2]; |
| 470 | DIR *dir; |
| 471 | struct dirent *ent; |
| 472 | struct stat st; |
| 473 | |
| 474 | (void)buf; |
| 475 | |
| 476 | lc->path = 1; |
| 477 | |
| 478 | ptr = strrchr(hint, '/'); |
| 479 | |
| 480 | /* new relative path */ |
| 481 | if (ptr == NULL) { |
| 482 | full_path = malloc(2 + FILENAME_MAX + 1); |
| 483 | strcpy(full_path, "./"); |
| 484 | |
| 485 | ptr = hint; |
| 486 | } else { |
| 487 | full_path = malloc((int)(ptr - hint) + FILENAME_MAX + 1); |
| 488 | ++ptr; |
| 489 | sprintf(full_path, "%.*s", (int)(ptr - hint), hint); |
| 490 | } |
| 491 | hint_ptr = full_path + strlen(full_path); |
| 492 | |
| 493 | dir = opendir(full_path); |
| 494 | if (dir == NULL) { |
| 495 | free(full_path); |
| 496 | return; |
| 497 | } |
| 498 | |
| 499 | while ((ent = readdir(dir))) { |
| 500 | if (ent->d_name[0] == '.') { |
| 501 | continue; |
| 502 | } |
| 503 | |
| 504 | if (!strncmp(ptr, ent->d_name, strlen(ptr))) { |
| 505 | /* is it a directory? */ |
| 506 | strcpy(hint_ptr, ent->d_name); |
| 507 | if (stat(full_path, &st)) { |
| 508 | /* skip this item */ |
| 509 | continue; |
| 510 | } |
| 511 | |
| 512 | strcpy(match, ent->d_name); |
| 513 | if (S_ISDIR(st.st_mode)) { |
| 514 | strcat(match, "/"); |
| 515 | } |
| 516 | |
| 517 | linenoiseAddCompletion(lc, match); |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | free(full_path); |
| 522 | closedir(dir); |
| 523 | } |
| 524 | |
| 525 | /* This function is used by the callback function registered by the user |
| 526 | * in order to add completion options given the input string when the |
| 527 | * user typed <tab>. See the example.c source code for a very easy to |
| 528 | * understand example. */ |
| 529 | void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) { |
| 530 | size_t len = strlen(str); |
| 531 | char *copy, **cvec; |
| 532 | |
| 533 | copy = malloc(len+1); |
| 534 | if (copy == NULL) return; |
| 535 | memcpy(copy,str,len+1); |
| 536 | cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1)); |
| 537 | if (cvec == NULL) { |
| 538 | free(copy); |
| 539 | return; |
| 540 | } |
| 541 | lc->cvec = cvec; |
| 542 | lc->cvec[lc->len++] = copy; |
| 543 | } |
| 544 | |
| 545 | /* =========================== Line editing ================================= */ |
| 546 | |
| 547 | /* We define a very simple "append buffer" structure, that is an heap |
| 548 | * allocated string where we can append to. This is useful in order to |
| 549 | * write all the escape sequences in a buffer and flush them to the standard |
| 550 | * output in a single call, to avoid flickering effects. */ |
| 551 | struct abuf { |
| 552 | char *b; |
| 553 | int len; |
| 554 | }; |
| 555 | |
| 556 | static void abInit(struct abuf *ab) { |
| 557 | ab->b = NULL; |
| 558 | ab->len = 0; |
| 559 | } |
| 560 | |
| 561 | static void abAppend(struct abuf *ab, const char *s, int len) { |
| 562 | char *new = realloc(ab->b,ab->len+len); |
| 563 | |
| 564 | if (new == NULL) return; |
| 565 | memcpy(new+ab->len,s,len); |
| 566 | ab->b = new; |
| 567 | ab->len += len; |
| 568 | } |
| 569 | |
| 570 | static void abFree(struct abuf *ab) { |
| 571 | free(ab->b); |
| 572 | } |
| 573 | |
| 574 | /* Single line low level line refresh. |
| 575 | * |
| 576 | * Rewrite the currently edited line accordingly to the buffer content, |
| 577 | * cursor position, and number of columns of the terminal. */ |
| 578 | static void refreshSingleLine(struct linenoiseState *l) { |
| 579 | char seq[64]; |
| 580 | size_t plen = strlen(l->prompt); |
| 581 | int fd = l->ofd; |
| 582 | char *buf = l->buf; |
| 583 | size_t len = l->len; |
| 584 | size_t pos = l->pos; |
| 585 | struct abuf ab; |
| 586 | |
| 587 | while((plen+pos) >= l->cols) { |
| 588 | buf++; |
| 589 | len--; |
| 590 | pos--; |
| 591 | } |
| 592 | while (plen+len > l->cols) { |
| 593 | len--; |
| 594 | } |
| 595 | |
| 596 | abInit(&ab); |
| 597 | /* Cursor to left edge */ |
| 598 | snprintf(seq,64,"\r"); |
| 599 | abAppend(&ab,seq,strlen(seq)); |
| 600 | /* Write the prompt and the current buffer content */ |
| 601 | abAppend(&ab,l->prompt,strlen(l->prompt)); |
| 602 | abAppend(&ab,buf,len); |
| 603 | /* Erase to right */ |
| 604 | snprintf(seq,64,"\x1b[0K"); |
| 605 | abAppend(&ab,seq,strlen(seq)); |
| 606 | /* Move cursor to original position. */ |
| 607 | snprintf(seq,64,"\r\x1b[%dC", (int)(pos+plen)); |
| 608 | abAppend(&ab,seq,strlen(seq)); |
| 609 | if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */ |
| 610 | abFree(&ab); |
| 611 | } |
| 612 | |
| 613 | /* Multi line low level line refresh. |
| 614 | * |
| 615 | * Rewrite the currently edited line accordingly to the buffer content, |
| 616 | * cursor position, and number of columns of the terminal. */ |
| 617 | static void refreshMultiLine(struct linenoiseState *l) { |
| 618 | char seq[64]; |
| 619 | int plen = strlen(l->prompt); |
| 620 | int rows = (plen+l->len+l->cols-1)/l->cols; /* rows used by current buf. */ |
| 621 | int rpos = (plen+l->oldpos+l->cols)/l->cols; /* cursor relative row. */ |
| 622 | int rpos2; /* rpos after refresh. */ |
| 623 | int col; /* colum position, zero-based. */ |
| 624 | int old_rows = l->maxrows; |
| 625 | int fd = l->ofd, j; |
| 626 | struct abuf ab; |
| 627 | |
| 628 | /* Update maxrows if needed. */ |
| 629 | if (rows > (int)l->maxrows) l->maxrows = rows; |
| 630 | |
| 631 | /* First step: clear all the lines used before. To do so start by |
| 632 | * going to the last row. */ |
| 633 | abInit(&ab); |
| 634 | if (old_rows-rpos > 0) { |
| 635 | lndebug("go down %d", old_rows-rpos); |
| 636 | snprintf(seq,64,"\x1b[%dB", old_rows-rpos); |
| 637 | abAppend(&ab,seq,strlen(seq)); |
| 638 | } |
| 639 | |
| 640 | /* Now for every row clear it, go up. */ |
| 641 | for (j = 0; j < old_rows-1; j++) { |
| 642 | lndebug("clear+up"); |
| 643 | snprintf(seq,64,"\r\x1b[0K\x1b[1A"); |
| 644 | abAppend(&ab,seq,strlen(seq)); |
| 645 | } |
| 646 | |
| 647 | /* Clean the top line. */ |
| 648 | lndebug("clear"); |
| 649 | snprintf(seq,64,"\r\x1b[0K"); |
| 650 | abAppend(&ab,seq,strlen(seq)); |
| 651 | |
| 652 | /* Write the prompt and the current buffer content */ |
| 653 | abAppend(&ab,l->prompt,strlen(l->prompt)); |
| 654 | abAppend(&ab,l->buf,l->len); |
| 655 | |
| 656 | /* If we are at the very end of the screen with our prompt, we need to |
| 657 | * emit a newline and move the prompt to the first column. */ |
| 658 | if (l->pos && |
| 659 | l->pos == l->len && |
| 660 | (l->pos+plen) % l->cols == 0) |
| 661 | { |
| 662 | lndebug("<newline>"); |
| 663 | abAppend(&ab,"\n",1); |
| 664 | snprintf(seq,64,"\r"); |
| 665 | abAppend(&ab,seq,strlen(seq)); |
| 666 | rows++; |
| 667 | if (rows > (int)l->maxrows) l->maxrows = rows; |
| 668 | } |
| 669 | |
| 670 | /* Move cursor to right position. */ |
| 671 | rpos2 = (plen+l->pos+l->cols)/l->cols; /* current cursor relative row. */ |
| 672 | lndebug("rpos2 %d", rpos2); |
| 673 | |
| 674 | /* Go up till we reach the expected positon. */ |
| 675 | if (rows-rpos2 > 0) { |
| 676 | lndebug("go-up %d", rows-rpos2); |
| 677 | snprintf(seq,64,"\x1b[%dA", rows-rpos2); |
| 678 | abAppend(&ab,seq,strlen(seq)); |
| 679 | } |
| 680 | |
| 681 | /* Set column. */ |
| 682 | col = (plen+(int)l->pos) % (int)l->cols; |
| 683 | lndebug("set col %d", 1+col); |
| 684 | if (col) |
| 685 | snprintf(seq,64,"\r\x1b[%dC", col); |
| 686 | else |
| 687 | snprintf(seq,64,"\r"); |
| 688 | abAppend(&ab,seq,strlen(seq)); |
| 689 | |
| 690 | lndebug("\n"); |
| 691 | l->oldpos = l->pos; |
| 692 | |
| 693 | if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */ |
| 694 | abFree(&ab); |
| 695 | } |
| 696 | |
| 697 | /* Calls the two low level functions refreshSingleLine() or |
| 698 | * refreshMultiLine() according to the selected mode. */ |
| 699 | void linenoiseRefreshLine(void) { |
Michal Vasko | fe95815 | 2022-09-14 12:26:03 +0200 | [diff] [blame] | 700 | /* Update columns in case the terminal was resized */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 701 | lss.cols = getColumns(STDIN_FILENO, STDOUT_FILENO); |
Michal Vasko | fe95815 | 2022-09-14 12:26:03 +0200 | [diff] [blame] | 702 | |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 703 | if (mlmode) |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 704 | refreshMultiLine(&lss); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 705 | else |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 706 | refreshSingleLine(&lss); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 707 | } |
| 708 | |
| 709 | /* Insert the character 'c' at cursor current position. |
| 710 | * |
| 711 | * On error writing to the terminal -1 is returned, otherwise 0. */ |
| 712 | int linenoiseEditInsert(struct linenoiseState *l, char c) { |
| 713 | if (l->len < l->buflen) { |
| 714 | if (l->len == l->pos) { |
| 715 | l->buf[l->pos] = c; |
| 716 | l->pos++; |
| 717 | l->len++; |
| 718 | l->buf[l->len] = '\0'; |
| 719 | if ((!mlmode && l->plen+l->len < l->cols) /* || mlmode */) { |
| 720 | /* Avoid a full update of the line in the |
| 721 | * trivial case. */ |
| 722 | if (write(l->ofd,&c,1) == -1) return -1; |
| 723 | } else { |
| 724 | linenoiseRefreshLine(); |
| 725 | } |
| 726 | } else { |
| 727 | memmove(l->buf+l->pos+1,l->buf+l->pos,l->len-l->pos); |
| 728 | l->buf[l->pos] = c; |
| 729 | l->len++; |
| 730 | l->pos++; |
| 731 | l->buf[l->len] = '\0'; |
| 732 | linenoiseRefreshLine(); |
| 733 | } |
| 734 | } |
| 735 | return 0; |
| 736 | } |
| 737 | |
| 738 | /* Move cursor on the left. */ |
| 739 | void linenoiseEditMoveLeft(struct linenoiseState *l) { |
| 740 | if (l->pos > 0) { |
| 741 | l->pos--; |
| 742 | linenoiseRefreshLine(); |
| 743 | } |
| 744 | } |
| 745 | |
| 746 | /* Move cursor on the right. */ |
| 747 | void linenoiseEditMoveRight(struct linenoiseState *l) { |
| 748 | if (l->pos != l->len) { |
| 749 | l->pos++; |
| 750 | linenoiseRefreshLine(); |
| 751 | } |
| 752 | } |
| 753 | |
| 754 | /* Move cursor to the start of the line. */ |
| 755 | void linenoiseEditMoveHome(struct linenoiseState *l) { |
| 756 | if (l->pos != 0) { |
| 757 | l->pos = 0; |
| 758 | linenoiseRefreshLine(); |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | /* Move cursor to the end of the line. */ |
| 763 | void linenoiseEditMoveEnd(struct linenoiseState *l) { |
| 764 | if (l->pos != l->len) { |
| 765 | l->pos = l->len; |
| 766 | linenoiseRefreshLine(); |
| 767 | } |
| 768 | } |
| 769 | |
| 770 | /* Substitute the currently edited line with the next or previous history |
| 771 | * entry as specified by 'dir'. */ |
| 772 | #define LINENOISE_HISTORY_NEXT 0 |
| 773 | #define LINENOISE_HISTORY_PREV 1 |
| 774 | void linenoiseEditHistoryNext(struct linenoiseState *l, int dir) { |
| 775 | if (history_len > 1) { |
| 776 | /* Update the current history entry before to |
| 777 | * overwrite it with the next one. */ |
| 778 | free(history[history_len - 1 - l->history_index]); |
| 779 | history[history_len - 1 - l->history_index] = strdup(l->buf); |
| 780 | /* Show the new entry */ |
| 781 | l->history_index += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1; |
| 782 | if (l->history_index < 0) { |
| 783 | l->history_index = 0; |
| 784 | return; |
| 785 | } else if (l->history_index >= history_len) { |
| 786 | l->history_index = history_len-1; |
| 787 | return; |
| 788 | } |
| 789 | strncpy(l->buf,history[history_len - 1 - l->history_index],l->buflen); |
| 790 | l->buf[l->buflen-1] = '\0'; |
| 791 | l->len = l->pos = strlen(l->buf); |
| 792 | linenoiseRefreshLine(); |
| 793 | } |
| 794 | } |
| 795 | |
| 796 | /* Delete the character at the right of the cursor without altering the cursor |
| 797 | * position. Basically this is what happens with the "Delete" keyboard key. */ |
| 798 | void linenoiseEditDelete(struct linenoiseState *l) { |
| 799 | if (l->len > 0 && l->pos < l->len) { |
| 800 | memmove(l->buf+l->pos,l->buf+l->pos+1,l->len-l->pos-1); |
| 801 | l->len--; |
| 802 | l->buf[l->len] = '\0'; |
| 803 | linenoiseRefreshLine(); |
| 804 | } |
| 805 | } |
| 806 | |
| 807 | /* Backspace implementation. */ |
| 808 | void linenoiseEditBackspace(struct linenoiseState *l) { |
| 809 | if (l->pos > 0 && l->len > 0) { |
| 810 | memmove(l->buf+l->pos-1,l->buf+l->pos,l->len-l->pos); |
| 811 | l->pos--; |
| 812 | l->len--; |
| 813 | l->buf[l->len] = '\0'; |
| 814 | linenoiseRefreshLine(); |
| 815 | } |
| 816 | } |
| 817 | |
| 818 | /* Delete the previosu word, maintaining the cursor at the start of the |
| 819 | * current word. */ |
| 820 | void linenoiseEditDeletePrevWord(struct linenoiseState *l) { |
| 821 | size_t old_pos = l->pos; |
| 822 | size_t diff; |
| 823 | |
| 824 | while (l->pos > 0 && l->buf[l->pos-1] == ' ') |
| 825 | l->pos--; |
| 826 | while (l->pos > 0 && l->buf[l->pos-1] != ' ') |
| 827 | l->pos--; |
| 828 | diff = old_pos - l->pos; |
| 829 | memmove(l->buf+l->pos,l->buf+old_pos,l->len-old_pos+1); |
| 830 | l->len -= diff; |
| 831 | linenoiseRefreshLine(); |
| 832 | } |
| 833 | |
| 834 | /* This function is the core of the line editing capability of linenoise. |
| 835 | * It expects 'fd' to be already in "raw mode" so that every key pressed |
| 836 | * will be returned ASAP to read(). |
| 837 | * |
| 838 | * The resulting string is put into 'buf' when the user type enter, or |
| 839 | * when ctrl+d is typed. |
| 840 | * |
| 841 | * The function returns the length of the current buffer. */ |
| 842 | static int linenoiseEdit(int stdin_fd, int stdout_fd, char *buf, size_t buflen, const char *prompt) |
| 843 | { |
| 844 | /* Populate the linenoise state that we pass to functions implementing |
| 845 | * specific editing functionalities. */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 846 | lss.ifd = stdin_fd; |
| 847 | lss.ofd = stdout_fd; |
| 848 | lss.buf = buf; |
| 849 | lss.buflen = buflen; |
| 850 | lss.prompt = prompt; |
| 851 | lss.plen = strlen(prompt); |
| 852 | lss.oldpos = lss.pos = 0; |
| 853 | lss.len = 0; |
| 854 | lss.cols = getColumns(stdin_fd, stdout_fd); |
| 855 | lss.maxrows = 0; |
| 856 | lss.history_index = 0; |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 857 | |
| 858 | /* Buffer starts empty. */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 859 | lss.buf[0] = '\0'; |
| 860 | lss.buflen--; /* Make sure there is always space for the nulterm */ |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 861 | |
| 862 | /* The latest history entry is always our current buffer, that |
| 863 | * initially is just an empty string. */ |
| 864 | linenoiseHistoryAdd(""); |
| 865 | |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 866 | if (write(lss.ofd,prompt,lss.plen) == -1) return -1; |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 867 | while(1) { |
Radek Krejci | d2e4e86 | 2019-04-30 13:50:53 +0200 | [diff] [blame] | 868 | char c = 0; |
| 869 | int nread; |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 870 | char seq[3]; |
| 871 | |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 872 | nread = read(lss.ifd,&c,sizeof c); |
| 873 | if (nread <= 0) return lss.len; |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 874 | |
| 875 | /* Only autocomplete when the callback is set. It returns < 0 when |
| 876 | * there was an error reading from fd. Otherwise it will return the |
| 877 | * character that should be handled next. */ |
| 878 | if (c == 9 && completionCallback != NULL) { |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 879 | c = completeLine(&lss); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 880 | /* Return on errors */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 881 | if (c < 0) return lss.len; |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 882 | /* Read next character when 0 */ |
| 883 | if (c == 0) continue; |
| 884 | } |
| 885 | |
| 886 | switch(c) { |
| 887 | case ENTER: /* enter */ |
| 888 | history_len--; |
| 889 | free(history[history_len]); |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 890 | if (mlmode) linenoiseEditMoveEnd(&lss); |
| 891 | return (int)lss.len; |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 892 | case CTRL_C: /* ctrl-c */ |
| 893 | errno = EAGAIN; |
| 894 | return -1; |
| 895 | case BACKSPACE: /* backspace */ |
| 896 | case 8: /* ctrl-h */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 897 | linenoiseEditBackspace(&lss); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 898 | break; |
| 899 | case CTRL_D: /* ctrl-d, remove char at right of cursor, or if the |
| 900 | line is empty, act as end-of-file. */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 901 | if (lss.len > 0) { |
| 902 | linenoiseEditDelete(&lss); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 903 | } else { |
| 904 | history_len--; |
| 905 | free(history[history_len]); |
| 906 | return -1; |
| 907 | } |
| 908 | break; |
| 909 | case CTRL_T: /* ctrl-t, swaps current character with previous. */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 910 | if (lss.pos > 0 && lss.pos < lss.len) { |
| 911 | int aux = buf[lss.pos-1]; |
| 912 | buf[lss.pos-1] = buf[lss.pos]; |
| 913 | buf[lss.pos] = aux; |
| 914 | if (lss.pos != lss.len-1) lss.pos++; |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 915 | linenoiseRefreshLine(); |
| 916 | } |
| 917 | break; |
| 918 | case CTRL_B: /* ctrl-b */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 919 | linenoiseEditMoveLeft(&lss); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 920 | break; |
| 921 | case CTRL_F: /* ctrl-f */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 922 | linenoiseEditMoveRight(&lss); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 923 | break; |
| 924 | case CTRL_P: /* ctrl-p */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 925 | linenoiseEditHistoryNext(&lss, LINENOISE_HISTORY_PREV); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 926 | break; |
| 927 | case CTRL_N: /* ctrl-n */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 928 | linenoiseEditHistoryNext(&lss, LINENOISE_HISTORY_NEXT); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 929 | break; |
| 930 | case ESC: /* escape sequence */ |
| 931 | /* Read the next two bytes representing the escape sequence. |
| 932 | * Use two calls to handle slow terminals returning the two |
| 933 | * chars at different times. */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 934 | if (read(lss.ifd,seq,1) == -1) break; |
| 935 | if (read(lss.ifd,seq+1,1) == -1) break; |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 936 | |
| 937 | /* ESC [ sequences. */ |
| 938 | if (seq[0] == '[') { |
| 939 | if (seq[1] >= '0' && seq[1] <= '9') { |
| 940 | /* Extended escape, read additional byte. */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 941 | if (read(lss.ifd, seq + 2, 1) == -1) break; |
| 942 | if ((seq[1] == '3') && (seq[2] == '~')) { |
| 943 | /* Delete key. */ |
| 944 | linenoiseEditDelete(&lss); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 945 | } |
| 946 | } else { |
| 947 | switch(seq[1]) { |
| 948 | case 'A': /* Up */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 949 | linenoiseEditHistoryNext(&lss, LINENOISE_HISTORY_PREV); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 950 | break; |
| 951 | case 'B': /* Down */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 952 | linenoiseEditHistoryNext(&lss, LINENOISE_HISTORY_NEXT); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 953 | break; |
| 954 | case 'C': /* Right */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 955 | linenoiseEditMoveRight(&lss); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 956 | break; |
| 957 | case 'D': /* Left */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 958 | linenoiseEditMoveLeft(&lss); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 959 | break; |
| 960 | case 'H': /* Home */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 961 | linenoiseEditMoveHome(&lss); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 962 | break; |
| 963 | case 'F': /* End*/ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 964 | linenoiseEditMoveEnd(&lss); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 965 | break; |
| 966 | } |
| 967 | } |
| 968 | } |
| 969 | |
| 970 | /* ESC O sequences. */ |
| 971 | else if (seq[0] == 'O') { |
| 972 | switch(seq[1]) { |
| 973 | case 'H': /* Home */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 974 | linenoiseEditMoveHome(&lss); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 975 | break; |
| 976 | case 'F': /* End*/ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 977 | linenoiseEditMoveEnd(&lss); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 978 | break; |
| 979 | } |
| 980 | } |
| 981 | break; |
| 982 | default: |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 983 | if (linenoiseEditInsert(&lss,c)) return -1; |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 984 | break; |
| 985 | case CTRL_U: /* Ctrl+u, delete the whole line. */ |
| 986 | buf[0] = '\0'; |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 987 | lss.pos = lss.len = 0; |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 988 | linenoiseRefreshLine(); |
| 989 | break; |
| 990 | case CTRL_K: /* Ctrl+k, delete from current to end of line. */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 991 | buf[lss.pos] = '\0'; |
| 992 | lss.len = lss.pos; |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 993 | linenoiseRefreshLine(); |
| 994 | break; |
| 995 | case CTRL_A: /* Ctrl+a, go to the start of the line */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 996 | linenoiseEditMoveHome(&lss); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 997 | break; |
| 998 | case CTRL_E: /* ctrl+e, go to the end of the line */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 999 | linenoiseEditMoveEnd(&lss); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 1000 | break; |
| 1001 | case CTRL_L: /* ctrl+l, clear screen */ |
| 1002 | linenoiseClearScreen(); |
| 1003 | linenoiseRefreshLine(); |
| 1004 | break; |
| 1005 | case CTRL_W: /* ctrl+w, delete previous word */ |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 1006 | linenoiseEditDeletePrevWord(&lss); |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 1007 | break; |
| 1008 | } |
| 1009 | } |
Michal Vasko | bb0ebb8 | 2022-12-14 12:16:49 +0100 | [diff] [blame] | 1010 | return lss.len; |
Radek Krejci | ed5acc5 | 2019-04-25 15:57:04 +0200 | [diff] [blame] | 1011 | } |
| 1012 | |
| 1013 | /* This special mode is used by linenoise in order to print scan codes |
| 1014 | * on screen for debugging / development purposes. It is implemented |
| 1015 | * by the linenoise_example program using the --keycodes option. */ |
| 1016 | void linenoisePrintKeyCodes(void) { |
| 1017 | char quit[4]; |
| 1018 | |
| 1019 | printf("Linenoise key codes debugging mode.\n" |
| 1020 | "Press keys to see scan codes. Type 'quit' at any time to exit.\n"); |
| 1021 | if (linenoiseEnableRawMode(STDIN_FILENO) == -1) return; |
| 1022 | memset(quit,' ',4); |
| 1023 | while(1) { |
| 1024 | char c; |
| 1025 | int nread; |
| 1026 | |
| 1027 | nread = read(STDIN_FILENO,&c,1); |
| 1028 | if (nread <= 0) continue; |
| 1029 | memmove(quit,quit+1,sizeof(quit)-1); /* shift string to left. */ |
| 1030 | quit[sizeof(quit)-1] = c; /* Insert current char on the right. */ |
| 1031 | if (memcmp(quit,"quit",sizeof(quit)) == 0) break; |
| 1032 | |
| 1033 | printf("'%c' %02x (%d) (type quit to exit)\n", |
| 1034 | isprint(c) ? c : '?', (int)c, (int)c); |
| 1035 | printf("\r"); /* Go left edge manually, we are in raw mode. */ |
| 1036 | fflush(stdout); |
| 1037 | } |
| 1038 | linenoiseDisableRawMode(STDIN_FILENO); |
| 1039 | } |
| 1040 | |
| 1041 | /* This function calls the line editing function linenoiseEdit() using |
| 1042 | * the STDIN file descriptor set in raw mode. */ |
| 1043 | static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) { |
| 1044 | int count; |
| 1045 | |
| 1046 | if (buflen == 0) { |
| 1047 | errno = EINVAL; |
| 1048 | return -1; |
| 1049 | } |
| 1050 | if (!isatty(STDIN_FILENO)) { |
| 1051 | /* Not a tty: read from file / pipe. */ |
| 1052 | if (fgets(buf, buflen, stdin) == NULL) return -1; |
| 1053 | count = strlen(buf); |
| 1054 | if (count && buf[count-1] == '\n') { |
| 1055 | count--; |
| 1056 | buf[count] = '\0'; |
| 1057 | } |
| 1058 | } else { |
| 1059 | /* Interactive editing. */ |
| 1060 | if (linenoiseEnableRawMode(STDIN_FILENO) == -1) return -1; |
| 1061 | count = linenoiseEdit(STDIN_FILENO, STDOUT_FILENO, buf, buflen, prompt); |
| 1062 | linenoiseDisableRawMode(STDIN_FILENO); |
| 1063 | printf("\n"); |
| 1064 | } |
| 1065 | return count; |
| 1066 | } |
| 1067 | |
| 1068 | /* The high level function that is the main API of the linenoise library. |
| 1069 | * This function checks if the terminal has basic capabilities, just checking |
| 1070 | * for a blacklist of stupid terminals, and later either calls the line |
| 1071 | * editing function or uses dummy fgets() so that you will be able to type |
| 1072 | * something even in the most desperate of the conditions. */ |
| 1073 | char *linenoise(const char *prompt) { |
| 1074 | char buf[LINENOISE_MAX_LINE]; |
| 1075 | int count; |
| 1076 | |
| 1077 | if (isUnsupportedTerm()) { |
| 1078 | size_t len; |
| 1079 | |
| 1080 | printf("%s",prompt); |
| 1081 | fflush(stdout); |
| 1082 | if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL; |
| 1083 | len = strlen(buf); |
| 1084 | while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) { |
| 1085 | len--; |
| 1086 | buf[len] = '\0'; |
| 1087 | } |
| 1088 | return strdup(buf); |
| 1089 | } else { |
| 1090 | count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt); |
| 1091 | if (count == -1) return NULL; |
| 1092 | return strdup(buf); |
| 1093 | } |
| 1094 | } |
| 1095 | |
| 1096 | /* ================================ History ================================= */ |
| 1097 | |
| 1098 | /* Free the history, but does not reset it. Only used when we have to |
| 1099 | * exit() to avoid memory leaks are reported by valgrind & co. */ |
| 1100 | static void freeHistory(void) { |
| 1101 | if (history) { |
| 1102 | int j; |
| 1103 | |
| 1104 | for (j = 0; j < history_len; j++) |
| 1105 | free(history[j]); |
| 1106 | free(history); |
| 1107 | } |
| 1108 | } |
| 1109 | |
| 1110 | /* At exit we'll try to fix the terminal to the initial conditions. */ |
| 1111 | static void linenoiseAtExit(void) { |
| 1112 | linenoiseDisableRawMode(STDIN_FILENO); |
| 1113 | freeHistory(); |
| 1114 | } |
| 1115 | |
| 1116 | /* This is the API call to add a new entry in the linenoise history. |
| 1117 | * It uses a fixed array of char pointers that are shifted (memmoved) |
| 1118 | * when the history max length is reached in order to remove the older |
| 1119 | * entry and make room for the new one, so it is not exactly suitable for huge |
| 1120 | * histories, but will work well for a few hundred of entries. |
| 1121 | * |
| 1122 | * Using a circular buffer is smarter, but a bit more complex to handle. */ |
| 1123 | int linenoiseHistoryAdd(const char *line) { |
| 1124 | char *linecopy; |
| 1125 | |
| 1126 | if (history_max_len == 0) return 0; |
| 1127 | |
| 1128 | /* Initialization on first call. */ |
| 1129 | if (history == NULL) { |
| 1130 | history = malloc(sizeof(char*)*history_max_len); |
| 1131 | if (history == NULL) return 0; |
| 1132 | memset(history,0,(sizeof(char*)*history_max_len)); |
| 1133 | } |
| 1134 | |
| 1135 | /* Don't add duplicated lines. */ |
| 1136 | if (history_len && !strcmp(history[history_len-1], line)) return 0; |
| 1137 | |
| 1138 | /* Add an heap allocated copy of the line in the history. |
| 1139 | * If we reached the max length, remove the older line. */ |
| 1140 | linecopy = strdup(line); |
| 1141 | if (!linecopy) return 0; |
| 1142 | if (history_len == history_max_len) { |
| 1143 | free(history[0]); |
| 1144 | memmove(history,history+1,sizeof(char*)*(history_max_len-1)); |
| 1145 | history_len--; |
| 1146 | } |
| 1147 | history[history_len] = linecopy; |
| 1148 | history_len++; |
| 1149 | return 1; |
| 1150 | } |
| 1151 | |
| 1152 | /* Set the maximum length for the history. This function can be called even |
| 1153 | * if there is already some history, the function will make sure to retain |
| 1154 | * just the latest 'len' elements if the new history length value is smaller |
| 1155 | * than the amount of items already inside the history. */ |
| 1156 | int linenoiseHistorySetMaxLen(int len) { |
| 1157 | char **new; |
| 1158 | |
| 1159 | if (len < 1) return 0; |
| 1160 | if (history) { |
| 1161 | int tocopy = history_len; |
| 1162 | |
| 1163 | new = malloc(sizeof(char*)*len); |
| 1164 | if (new == NULL) return 0; |
| 1165 | |
| 1166 | /* If we can't copy everything, free the elements we'll not use. */ |
| 1167 | if (len < tocopy) { |
| 1168 | int j; |
| 1169 | |
| 1170 | for (j = 0; j < tocopy-len; j++) free(history[j]); |
| 1171 | tocopy = len; |
| 1172 | } |
| 1173 | memset(new,0,sizeof(char*)*len); |
| 1174 | memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy); |
| 1175 | free(history); |
| 1176 | history = new; |
| 1177 | } |
| 1178 | history_max_len = len; |
| 1179 | if (history_len > history_max_len) |
| 1180 | history_len = history_max_len; |
| 1181 | return 1; |
| 1182 | } |
| 1183 | |
| 1184 | /* Save the history in the specified file. On success 0 is returned |
| 1185 | * otherwise -1 is returned. */ |
| 1186 | int linenoiseHistorySave(const char *filename) { |
| 1187 | FILE *fp = fopen(filename,"w"); |
| 1188 | int j; |
| 1189 | |
| 1190 | if (fp == NULL) return -1; |
| 1191 | for (j = 0; j < history_len; j++) |
| 1192 | fprintf(fp,"%s\n",history[j]); |
| 1193 | fclose(fp); |
| 1194 | return 0; |
| 1195 | } |
| 1196 | |
| 1197 | /* Load the history from the specified file. If the file does not exist |
| 1198 | * zero is returned and no operation is performed. |
| 1199 | * |
| 1200 | * If the file exists and the operation succeeded 0 is returned, otherwise |
| 1201 | * on error -1 is returned. */ |
| 1202 | int linenoiseHistoryLoad(const char *filename) { |
| 1203 | FILE *fp = fopen(filename,"r"); |
| 1204 | char buf[LINENOISE_MAX_LINE]; |
| 1205 | |
| 1206 | if (fp == NULL) return -1; |
| 1207 | |
| 1208 | while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) { |
| 1209 | char *p; |
| 1210 | |
| 1211 | p = strchr(buf,'\r'); |
| 1212 | if (!p) p = strchr(buf,'\n'); |
| 1213 | if (p) *p = '\0'; |
| 1214 | linenoiseHistoryAdd(buf); |
| 1215 | } |
| 1216 | fclose(fp); |
| 1217 | return 0; |
| 1218 | } |