/* linenoise.c -- guerrilla line editing library against the idea that a * line editing lib needs to be 20,000 lines of C code. * * You can find the latest source code at: * * http://github.com/antirez/linenoise * * Does a number of crazy assumptions that happen to be true in 99.9999% of * the 2010 UNIX computers around. * * ------------------------------------------------------------------------ * * Copyright (c) 2010-2016, Salvatore Sanfilippo * Copyright (c) 2010-2013, Pieter Noordhuis * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ------------------------------------------------------------------------ * * References: * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html * * List of escape sequences used by this program, we do everything just * with three sequences. In order to be so cheap we may have some * flickering effect with some slow terminal, but the lesser sequences * the more compatible. * * EL (Erase Line) * Sequence: ESC [ n K * Effect: if n is 0 or missing, clear from cursor to end of line * Effect: if n is 1, clear from beginning of line to cursor * Effect: if n is 2, clear entire line * * CUF (CUrsor Forward) * Sequence: ESC [ n C * Effect: moves cursor forward n chars * * CUB (CUrsor Backward) * Sequence: ESC [ n D * Effect: moves cursor backward n chars * * The following is used to get the terminal width if getting * the width with the TIOCGWINSZ ioctl fails * * DSR (Device Status Report) * Sequence: ESC [ 6 n * Effect: reports the current cusor position as ESC [ n ; m R * where n is the row and m is the column * * When multi line mode is enabled, we also use an additional escape * sequence. However multi line editing is disabled by default. * * CUU (Cursor Up) * Sequence: ESC [ n A * Effect: moves cursor up of n chars. * * CUD (Cursor Down) * Sequence: ESC [ n B * Effect: moves cursor down of n chars. * * When linenoiseClearScreen() is called, two additional escape sequences * are used in order to clear the screen and position the cursor at home * position. * * CUP (Cursor position) * Sequence: ESC [ H * Effect: moves the cursor to upper left corner * * ED (Erase display) * Sequence: ESC [ 2 J * Effect: clear the whole screen * */ #include #include #include #include #include #include #include #include #include "console_linenoise.h" extern void console_internal_error_print(const char *msg); #define ln_read(buf, cap) (ls->read ? ls->read(ls->rwctx, buf, cap) : -1) #define ln_write(text, len) (ls->write ? ls->write(ls->rwctx, text, len) : -1) #define ln_writez(text) ln_write(text, strlen(text)) void consLnStateInit(struct linenoiseState *ls) { bzero(ls, sizeof(struct linenoiseState)); ls->mlmode = false; /* Multi line mode. Default is single line. */ ls->dumbmode = false; /* Dumb mode where line editing is disabled. Off by default */ ls->echomode = true; /* Echo (meaningful only in dumb mode) */ ls->history_max_len = 16; ls->history_len = 0; ls->allowCtrlDExit = true; ls->history = NULL; ls->buf = NULL; /* Edited line buffer. */ ls->buflen = 0; /* Edited line buffer size. */ ls->prompt = NULL; /* Prompt to display. */ ls->plen = 0; /* Prompt length. */ ls->pos = 0; /* Current cursor position. */ ls->oldpos = 0; /* Previous refresh cursor position. */ ls->len = 0; /* Current edited line length. */ ls->cols = 0; /* Number of columns in terminal. */ ls->maxrows = 0; /* Maximum num of rows used so far (multiline mode) */ ls->history_index = 0; /* The history index we are currently editing. */ ls->rwctx = NULL; ls->read = NULL; ls->write = NULL; } enum KEY_ACTION { KEY_NULL = 0, /* NULL */ CTRL_A = 1, /* Ctrl+a */ CTRL_B = 2, /* Ctrl-b */ CTRL_C = 3, /* Ctrl-c */ CTRL_D = 4, /* Ctrl-d */ CTRL_E = 5, /* Ctrl-e */ CTRL_F = 6, /* Ctrl-f */ CTRL_H = 8, /* Ctrl-h */ TAB = 9, /* Tab */ CTRL_K = 11, /* Ctrl+k */ CTRL_L = 12, /* Ctrl+l */ ENTER = 10, /* Enter */ RETURN = 13, /* LF */ CTRL_N = 14, /* Ctrl-n */ CTRL_P = 16, /* Ctrl-p */ CTRL_T = 20, /* Ctrl-t */ CTRL_U = 21, /* Ctrl+u */ CTRL_W = 23, /* Ctrl+w */ ESC = 27, /* Escape */ BACKSPACE = 127 /* Backspace */ }; static void refreshLine(struct linenoiseState *ls); /* ======================= Low level terminal handling ====================== */ /* Try to get the number of columns in the current terminal, or assume 80 * if it fails. */ static inline int getColumns() { return 80; } /* Clear the screen. Used to handle ctrl+l */ void consLnClearScreen(struct linenoiseState *ls) { ln_writez("\x1b[H\x1b[2J"); } /* Beep, used for completion when there is nothing to complete or when all * the choices were already shown. */ static void linenoiseBeep(struct linenoiseState *ls) { ln_write("\x07", 1); } /* ============================== Completion ================================ */ /* Free a list of completion option populated by linenoiseAddCompletion(). */ static void freeCompletions(linenoiseCompletions *lc) { size_t i; for (i = 0; i < lc->len; i++) { console_free(lc->cvec[i]); } if (lc->cvec != NULL) { console_free(lc->cvec); } } /* This is an helper function for linenoiseEdit() and is called when the * user types the key in order to complete the string currently in the * input. * * The state of the editing is encapsulated into the pointed linenoiseState * structure as described in the structure definition. */ static int completeLine(struct linenoiseState *ls) { linenoiseCompletions lc = {0, NULL}; int nread; int nwritten; char c = 0; ls->completionCallback(ls->buf, &lc); if (lc.len == 0) { linenoiseBeep(ls); } else { size_t stop = 0; size_t i = 0; while (!stop) { /* Show completion or original buffer */ if (i < lc.len) { struct linenoiseState saved = *ls; ls->len = ls->pos = (int) strlen(lc.cvec[i]); ls->buf = lc.cvec[i]; refreshLine(ls); ls->len = saved.len; ls->pos = saved.pos; ls->buf = saved.buf; } else { refreshLine(ls); } nread = ln_read(&c, 1); if (nread <= 0) { freeCompletions(&lc); return -1; } switch (c) { case TAB: /* tab */ i = (i + 1) % (lc.len + 1); if (i == lc.len) linenoiseBeep(ls); break; case ESC: /* escape */ /* Re-show original buffer */ if (i < lc.len) refreshLine(ls); stop = 1; break; default: /* Update buffer and return */ if (i < lc.len) { nwritten = snprintf(ls->buf, ls->buflen, "%s", lc.cvec[i]); ls->len = ls->pos = nwritten; } stop = 1; break; } } } freeCompletions(&lc); return c; /* Return last read character */ } /* This function is used by the callback function registered by the user * in order to add completion options given the input string when the * user typed . See the example.c source code for a very easy to * understand example. */ void consLnAddCompletion(linenoiseCompletions *lc, const char *text) { size_t len = strlen(text); char *copy; char **cvec; copy = console_calloc(len + 1, 1); if (copy == NULL) return; memcpy(copy, text, len + 1); cvec = console_realloc(lc->cvec, sizeof(char *) * (lc->len), sizeof(char *) * (lc->len + 1)); if (cvec == NULL) { console_free(copy); return; } lc->cvec = cvec; lc->cvec[lc->len++] = copy; } /* =========================== Line editing ================================= */ /* We define a very simple "append buffer" structure, that is an heap * allocated string where we can append to. This is useful in order to * write all the escape sequences in a buffer and flush them to the standard * output in a single call, to avoid flickering effects. */ struct abuf { char *b; int len; }; static void abInit(struct abuf *ab) { ab->b = NULL; ab->len = 0; } static void abAppend(struct abuf *ab, const char *s, size_t len) { char *new = console_realloc(ab->b, ab->len, ab->len + len); if (new == NULL) return; memcpy(new + ab->len, s, len); ab->b = new; ab->len += len; } static void abFree(struct abuf *ab) { console_free(ab->b); } /* Helper of refreshSingleLine() and refreshMultiLine() to show hints * to the right of the prompt. */ static void refreshShowHints(struct abuf *ab, struct linenoiseState *ls, int plen) { char seq[64]; if (ls->hintsCallback && plen + ls->len < ls->cols) { int color = -1; int bold = 0; char *hint = ls->hintsCallback(ls->buf, &color, &bold); if (hint) { size_t hintlen = strlen(hint); int hintmaxlen = ls->cols - (plen + ls->len); if ((int)hintlen > hintmaxlen) hintlen = hintmaxlen; if (bold == 1 && color == -1) color = 37; if (color != -1 || bold != 0) snprintf(seq, 64, "\033[%d;%d;49m", bold, color); abAppend(ab, seq, strlen(seq)); abAppend(ab, hint, hintlen); if (color != -1 || bold != 0) abAppend(ab, "\033[0m", 4); /* Call the function to free the hint returned. */ if (ls->freeHintsCallback) ls->freeHintsCallback(hint); } } } /* Single line low level line refresh. * * Rewrite the currently edited line accordingly to the buffer content, * cursor position, and number of columns of the terminal. */ static void refreshSingleLine(struct linenoiseState *ls) { char seq[64]; size_t plen = ls->plen; char *buf = ls->buf; size_t len = ls->len; size_t pos = ls->pos; struct abuf ab; while (((int)(plen + pos)) >= ls->cols) { buf++; len--; pos--; } while (((int)(plen + len)) > ls->cols) { len--; } abInit(&ab); /* Cursor to left edge */ snprintf(seq, 64, "\r"); abAppend(&ab, seq, strlen(seq)); /* Write the prompt and the current buffer content */ abAppend(&ab, ls->prompt, strlen(ls->prompt)); abAppend(&ab, buf, len); /* Show hits if any. */ refreshShowHints(&ab, ls, plen); /* Erase to right */ snprintf(seq, 64, "\x1b[0K"); abAppend(&ab, seq, strlen(seq)); /* Move cursor to original position. */ snprintf(seq, 64, "\r\x1b[%dC", (int) (pos + plen)); abAppend(&ab, seq, strlen(seq)); if (ln_write(ab.b, ab.len) == -1) {} /* Can't recover from write error. */ abFree(&ab); } /* Multi line low level line refresh. * * Rewrite the currently edited line accordingly to the buffer content, * cursor position, and number of columns of the terminal. */ static void refreshMultiLine(struct linenoiseState *ls) { char seq[64]; int plen = ls->plen; int rows = (plen + ls->len + ls->cols - 1) / ls->cols; /* rows used by current buf. */ int rpos = (plen + ls->oldpos + ls->cols) / ls->cols; /* cursor relative row. */ int rpos2; /* rpos after refresh. */ int col; /* colum position, zero-based. */ int old_rows = ls->maxrows; int j; struct abuf ab; /* Update maxrows if needed. */ if (rows > (int) ls->maxrows) ls->maxrows = rows; /* First step: clear all the lines used before. To do so start by * going to the last row. */ abInit(&ab); if (old_rows - rpos > 0) { snprintf(seq, 64, "\x1b[%dB", old_rows - rpos); abAppend(&ab, seq, strlen(seq)); } /* Now for every row clear it, go up. */ for (j = 0; j < old_rows - 1; j++) { snprintf(seq, 64, "\r\x1b[0K\x1b[1A"); abAppend(&ab, seq, strlen(seq)); } /* Clean the top line. */ snprintf(seq, 64, "\r\x1b[0K"); abAppend(&ab, seq, strlen(seq)); /* Write the prompt and the current buffer content */ abAppend(&ab, ls->prompt, strlen(ls->prompt)); abAppend(&ab, ls->buf, ls->len); /* Show hits if any. */ refreshShowHints(&ab, ls, plen); /* If we are at the very end of the screen with our prompt, we need to * emit a newline and move the prompt to the first column. */ if (ls->pos && ls->pos == ls->len && (ls->pos + plen) % ls->cols == 0) { abAppend(&ab, "\n", 1); snprintf(seq, 64, "\r"); abAppend(&ab, seq, strlen(seq)); rows++; if (rows > (int) ls->maxrows) ls->maxrows = rows; } /* Move cursor to right position. */ rpos2 = (plen + ls->pos + ls->cols) / ls->cols; /* current cursor relative row. */ /* Go up till we reach the expected positon. */ if (rows - rpos2 > 0) { snprintf(seq, 64, "\x1b[%dA", rows - rpos2); abAppend(&ab, seq, strlen(seq)); } /* Set column. */ col = (plen + (int) ls->pos) % (int) ls->cols; if (col) snprintf(seq, 64, "\r\x1b[%dC", col); else snprintf(seq, 64, "\r"); abAppend(&ab, seq, strlen(seq)); ls->oldpos = ls->pos; if (ln_write(ab.b, ab.len) == -1) {} /* Can't recover from write error. */ abFree(&ab); } /* Calls the two low level functions refreshSingleLine() or * refreshMultiLine() according to the selected mode. */ static void refreshLine(struct linenoiseState *ls) { if (ls->mlmode) refreshMultiLine(ls); else refreshSingleLine(ls); } /* Insert the character 'c' at cursor current position. * * On error writing to the terminal -1 is returned, otherwise 0. */ static int linenoiseEditInsert(struct linenoiseState *ls, char c) { if (ls->len < (int)ls->buflen) { if (ls->len == ls->pos) { ls->buf[ls->pos] = c; ls->pos++; ls->len++; ls->buf[ls->len] = '\0'; if ((!ls->mlmode && (int)(ls->plen + ls->len) < ls->cols && !ls->hintsCallback)) { /* Avoid a full update of the line in the * trivial case. */ if (ln_write(&c, 1) == -1) return -1; } else { refreshLine(ls); } } else { memmove(ls->buf + ls->pos + 1, ls->buf + ls->pos, ls->len - ls->pos); ls->buf[ls->pos] = c; ls->len++; ls->pos++; ls->buf[ls->len] = '\0'; refreshLine(ls); } } return 0; } /* Move cursor on the left. */ static void linenoiseEditMoveLeft(struct linenoiseState *ls) { if (ls->pos > 0) { ls->pos--; refreshLine(ls); } } /* Move cursor on the right. */ static void linenoiseEditMoveRight(struct linenoiseState *ls) { if (ls->pos != ls->len) { ls->pos++; refreshLine(ls); } } /* Move cursor to the start of the line. */ static void linenoiseEditMoveHome(struct linenoiseState *ls) { if (ls->pos != 0) { ls->pos = 0; refreshLine(ls); } } /* Move cursor to the end of the line. */ static void linenoiseEditMoveEnd(struct linenoiseState *ls) { if (ls->pos != ls->len) { ls->pos = ls->len; refreshLine(ls); } } /* Substitute the currently edited line with the next or previous history * entry as specified by 'dir'. */ enum linenoise_history_dir { LINENOISE_HISTORY_NEXT, LINENOISE_HISTORY_PREV, }; static void linenoiseEditHistoryNext(struct linenoiseState *ls, enum linenoise_history_dir dir) { if (ls->history_len > 1) { /* Update the current history entry before to * overwrite it with the next one. */ console_free(ls->history[ls->history_len - 1 - ls->history_index]); ls->history[ls->history_len - 1 - ls->history_index] = console_strdup(ls->buf); /* Show the new entry */ ls->history_index += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1; if (ls->history_index < 0) { ls->history_index = 0; return; } else if (ls->history_index >= ls->history_len) { ls->history_index = ls->history_len - 1; return; } strncpy(ls->buf, ls->history[ls->history_len - 1 - ls->history_index], ls->buflen); ls->buf[ls->buflen - 1] = '\0'; ls->len = ls->pos = (int) strlen(ls->buf); refreshLine(ls); } } /* Delete the character at the right of the cursor without altering the cursor * position. Basically this is what happens with the "Delete" keyboard key. */ static void linenoiseEditDelete(struct linenoiseState *ls) { if (ls->len > 0 && ls->pos < ls->len) { memmove(ls->buf + ls->pos, ls->buf + ls->pos + 1, ls->len - ls->pos - 1); ls->len--; ls->buf[ls->len] = '\0'; refreshLine(ls); } } /* Backspace implementation. */ static void linenoiseEditBackspace(struct linenoiseState *ls) { if (ls->pos > 0 && ls->len > 0) { memmove(ls->buf + ls->pos - 1, ls->buf + ls->pos, ls->len - ls->pos); ls->pos--; ls->len--; ls->buf[ls->len] = '\0'; refreshLine(ls); } } /* Delete the previosu word, maintaining the cursor at the start of the * current word. */ static void linenoiseEditDeletePrevWord(struct linenoiseState *ls) { size_t old_pos = ls->pos; size_t diff; while (ls->pos > 0 && ls->buf[ls->pos - 1] == ' ') ls->pos--; while (ls->pos > 0 && ls->buf[ls->pos - 1] != ' ') ls->pos--; diff = old_pos - ls->pos; memmove(ls->buf + ls->pos, ls->buf + old_pos, ls->len - old_pos + 1); ls->len -= diff; refreshLine(ls); } /** Get line's length, skipping over ANSI codes */ static uint32_t getAnsiLen(const char *prompt) { enum { GAL_BASE, GAL_ESC, GAL_DROP_NEXT, GAL_DROP_UNTIL_ALPHA, GAL_DROP_UNTIL_X, } state = GAL_BASE; char c; char x = 0; uint32_t count = 0; while ((c = *prompt++) != 0) { switch (state) { default: case GAL_BASE: if (c == 27) { state = GAL_ESC; } else { count++; } break; case GAL_ESC: switch (c) { case '[': state = GAL_DROP_UNTIL_ALPHA; break; case '#': state = GAL_DROP_NEXT; break; case 'K': x = 'r'; state = GAL_DROP_UNTIL_X; break; case '(': case ')': state = GAL_DROP_NEXT; break; default: state = GAL_BASE; } break; case GAL_DROP_NEXT: state = GAL_BASE; break; case GAL_DROP_UNTIL_ALPHA: if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { state = GAL_BASE; } break; case GAL_DROP_UNTIL_X: if (c == x) { state = GAL_BASE; } break; } } return count; } /* This function is the core of the line editing capability of linenoise. * It expects 'fd' to be already in "raw mode" so that every key pressed * will be returned ASAP to read(). * * The resulting string is put into 'buf' when the user type enter, or * when ctrl+d is typed. * * The function returns the length of the current buffer. */ static int linenoiseEdit(struct linenoiseState *ls) { if (!ls->buf) { console_internal_error_print("LN ed no buf"); return -1; } ls->plen = getAnsiLen(ls->prompt); ls->oldpos = ls->pos = 0; ls->len = 0; ls->cols = getColumns(); ls->maxrows = 0; ls->history_index = 0; /* Buffer starts empty. */ ls->buf[0] = '\0'; /* The latest history entry is always our current buffer, that * initially is just an empty string. */ consLnHistoryAdd(ls, ""); if (ln_writez(ls->prompt) == -1) { console_internal_error_print("LN ed prompt print err"); return -1; } while (1) { char c = 0; int nread; char seq[3]; nread = ln_read(&c, 1); if (nread <= 0) { console_internal_error_print("LN ed read err"); return ls->len; // read error } if (c == 0) continue; // discard null bytes /* Only autocomplete when the callback is set. It returns < 0 when * there was an error reading from fd. Otherwise it will return the * character that should be handled next. */ if (c == TAB && ls->completionCallback != NULL) { int c2 = completeLine(ls); /* Return on errors */ if (c2 < 0) return ls->len; /* Read next character when 0 */ if (c2 == 0) continue; c = (char) c2; } switch (c) { case ENTER: /* enter */ case RETURN: /* \n */ ls->history_len--; console_free(ls->history[ls->history_len]); if (ls->mlmode) linenoiseEditMoveEnd(ls); if (ls->hintsCallback) { /* Force a refresh without hints to leave the previous * line as the user typed it after a newline. */ linenoiseHintsCallback *hc = ls->hintsCallback; ls->hintsCallback = NULL; refreshLine(ls); ls->hintsCallback = hc; } return (int) ls->len; case CTRL_C: /* ctrl-c */ if (ls->len == 0 && ls->allowCtrlDExit) { errno = EAGAIN; //console_internal_error_print("LN Ctrl+C, exit"); return -1; } else { // Same as Ctrl+U ls->buf[0] = '\0'; ls->pos = ls->len = 0; refreshLine(ls); } break; case BACKSPACE: /* backspace */ case 8: /* ctrl-h */ linenoiseEditBackspace(ls); break; case CTRL_D: /* ctrl-d, remove char at right of cursor, or if the line is empty, act as end-of-file. */ if (ls->len > 0) { linenoiseEditDelete(ls); } else { if (ls->allowCtrlDExit) { ls->history_len--; console_free(ls->history[ls->history_len]); //console_internal_error_print("LN Ctrl+D, exit"); return -1; } } break; case CTRL_T: /* ctrl-t, swaps current character with previous. */ if (ls->pos > 0 && ls->pos < ls->len) { char aux = ls->buf[ls->pos - 1]; ls->buf[ls->pos - 1] = ls->buf[ls->pos]; ls->buf[ls->pos] = aux; if (ls->pos != ls->len - 1) ls->pos++; refreshLine(ls); } break; case CTRL_B: /* ctrl-b */ linenoiseEditMoveLeft(ls); break; case CTRL_F: /* ctrl-f */ linenoiseEditMoveRight(ls); break; case CTRL_P: /* ctrl-p */ linenoiseEditHistoryNext(ls, LINENOISE_HISTORY_PREV); break; case CTRL_N: /* ctrl-n */ linenoiseEditHistoryNext(ls, LINENOISE_HISTORY_NEXT); break; case ESC: /* escape sequence */ /* Read the next two bytes representing the escape sequence. */ if (ln_read(seq, 2) < 2) break; /* ESC [ sequences. */ if (seq[0] == '[') { if (seq[1] >= '0' && seq[1] <= '9') { /* Extended escape, read additional byte. */ if (ln_read(seq + 2, 1) == -1) break; if (seq[2] == '~') { switch (seq[1]) { case '3': /* Delete key. */ linenoiseEditDelete(ls); break; } } } else { switch (seq[1]) { case 'A': /* Up */ linenoiseEditHistoryNext(ls, LINENOISE_HISTORY_PREV); break; case 'B': /* Down */ linenoiseEditHistoryNext(ls, LINENOISE_HISTORY_NEXT); break; case 'C': /* Right */ linenoiseEditMoveRight(ls); break; case 'D': /* Left */ linenoiseEditMoveLeft(ls); break; case 'H': /* Home */ linenoiseEditMoveHome(ls); break; case 'F': /* End*/ linenoiseEditMoveEnd(ls); break; } } } /* ESC O sequences. */ else if (seq[0] == 'O') { switch (seq[1]) { case 'H': /* Home */ linenoiseEditMoveHome(ls); break; case 'F': /* End*/ linenoiseEditMoveEnd(ls); break; } } break; default: if (linenoiseEditInsert(ls, c)) return -1; break; case CTRL_U: /* Ctrl+u, delete the whole line. */ ls->buf[0] = '\0'; ls->pos = ls->len = 0; refreshLine(ls); break; case CTRL_K: /* Ctrl+k, delete from current to end of line. */ ls->buf[ls->pos] = '\0'; ls->len = ls->pos; refreshLine(ls); break; case CTRL_A: /* Ctrl+a, go to the start of the line */ linenoiseEditMoveHome(ls); break; case CTRL_E: /* ctrl+e, go to the end of the line */ linenoiseEditMoveEnd(ls); break; case CTRL_L: /* ctrl+l, clear screen */ consLnClearScreen(ls); refreshLine(ls); break; case CTRL_W: /* ctrl+w, delete previous word */ linenoiseEditDeletePrevWord(ls); break; } } } static int linenoiseRaw(struct linenoiseState *ls) { int count; if (ls->buflen == 0) { errno = EINVAL; console_internal_error_print("LN raw buflen 0"); return -1; } count = linenoiseEdit(ls); if (count >= 0) ln_write("\r\n", 2); return count; } static bool last_line_ended_with_0D = false; static int linenoiseDumb(struct linenoiseState *ls) { /* dumb terminal, fall back to fgets */ ln_writez(ls->prompt); int count = 0; char c = 0; while (count < (int)ls->buflen) { int num = ln_read(&c, 1); if (num == 0) break; if (c == 0) continue; int shouldprint = 1; if (c == '\n' || c == '\r') { // prevent CRLF acting as two newlines if (c == '\n' && last_line_ended_with_0D) { last_line_ended_with_0D = false; continue; } if (c == '\r') { last_line_ended_with_0D = true; } break; } else if (c >= 0x1c && c <= 0x1f) { shouldprint = 0; /* consume arrow keys */ } else if (c == BACKSPACE || c == 0x8) { if (count > 0) { ls->buf[count - 1] = 0; count--; if (ls->echomode) ln_write("\x08 ", 2); // second x08 is printed by the fputc below } else { shouldprint = 0; } } else { ls->buf[count] = c; ++count; } if (ls->echomode && shouldprint) { ln_write(&c, 1); /* echo */ } } ls->buf[count] = 0; ln_write("\r\n", 2); return count; } static void sanitize(char *src) { char *dst = src; for (int c = *src; c != 0; src++, c = *src) { if (isprint(c)) { *dst = (char) c; ++dst; } } *dst = 0; } /* The high level function that is the main API of the linenoise library. */ int consLnReadLine(struct linenoiseState *ls) { int count = 0; if (!ls->dumbmode) { count = linenoiseRaw(ls); } else { count = linenoiseDumb(ls); } if (count > 0) { sanitize(ls->buf); count = (int) strlen(ls->buf); } return count; } /* ================================ History ================================= */ /** Free history buffer for instance */ void consLnHistoryFree(struct linenoiseState *ls) { if (ls->history) { for (int j = 0; j < ls->history_len; j++) { console_free(ls->history[j]); } console_free(ls->history); } ls->history = NULL; } /* This is the API call to add a new entry in the linenoise history. * It uses a fixed array of char pointers that are shifted (memmoved) * when the history max length is reached in order to remove the older * entry and make room for the new one, so it is not exactly suitable for huge * histories, but will work well for a few hundred of entries. * * Using a circular buffer is smarter, but a bit more complex to handle. */ int consLnHistoryAdd(struct linenoiseState *ls, const char *line) { char *linecopy; if (ls->history_max_len == 0) return 0; /* Initialization on first call. */ if (ls->history == NULL) { ls->history = console_calloc(sizeof(char *) * ls->history_max_len, 1); if (ls->history == NULL) return 0; memset(ls->history, 0, (sizeof(char *) * ls->history_max_len)); } /* Don't add duplicated lines. */ if (ls->history_len && !strcmp(ls->history[ls->history_len - 1], line)) return 0; /* Add an heap allocated copy of the line in the history. * If we reached the max length, remove the older line. */ linecopy = console_strdup(line); if (!linecopy) return 0; if (ls->history_len == ls->history_max_len) { console_free(ls->history[0]); memmove(ls->history, ls->history + 1, sizeof(char *) * (ls->history_max_len - 1)); ls->history_len--; } ls->history[ls->history_len] = linecopy; ls->history_len++; return 1; } /* Set the maximum length for the history. This function can be called even * if there is already some history, the function will make sure to retain * just the latest 'len' elements if the new history length value is smaller * than the amount of items already inside the history. */ int consLnHistorySetMaxLen(struct linenoiseState *ls, int len) { char **new; if (len < 1) return 0; if (ls->history) { int tocopy = ls->history_len; new = console_calloc(sizeof(char *) * len, 1); if (new == NULL) return 0; /* If we can't copy everything, free the elements we'll not use. */ if (len < tocopy) { int j; for (j = 0; j < tocopy - len; j++) console_free(ls->history[j]); tocopy = len; } memset(new, 0, sizeof(char *) * len); memcpy(new, ls->history + (ls->history_len - tocopy), sizeof(char *) * tocopy); console_free(ls->history); ls->history = new; } ls->history_max_len = len; if (ls->history_len > ls->history_max_len) ls->history_len = ls->history_max_len; return 1; } #if CONSOLE_FILE_SUPPORT /* Save the history in the specified file. On success 0 is returned * otherwise -1 is returned. */ int consLnHistorySave(struct linenoiseState *ls, const char *filename) { FILE *fp; int j; fp = fopen(filename, "w"); if (fp == NULL) return -1; for (j = 0; j < ls->history_len; j++) fprintf(fp, "%s\n", ls->history[j]); fclose(fp); return 0; } /* Load the history from the specified file. If the file does not exist * zero is returned and no operation is performed. * * If the file exists and the operation succeeded 0 is returned, otherwise * on error -1 is returned. */ int consLnHistoryLoad(struct linenoiseState *ls, const char *filename) { FILE *fp = fopen(filename, "r"); char buf[LINENOISE_HISTORY_MAX_LINE]; if (fp == NULL) return -1; // Discard old history, if any consLnHistoryFree(ls); while (fgets(buf, LINENOISE_HISTORY_MAX_LINE, fp) != NULL) { char *p; p = strchr(buf, '\r'); if (!p) p = strchr(buf, '\n'); if (p) *p = '\0'; consLnHistoryAdd(ls, buf); } fclose(fp); return 0; } #endif