/** * @file edit_builtin.c * @brief The built-in line editor. * * A small editor with the emacs and vi modes of bash and the BSD shells, * and with bash's default key bindings in emacs mode. It needs nothing but a * terminal that understands a handful of ANSI control sequences (carriage * return, "erase to end of line", "cursor right N", "clear screen"), so it has * no terminfo or curses dependency, which matters on z/OS. * * ## Display * * The line is drawn on a single screen row. When it is wider than the * terminal the view scrolls sideways to keep the cursor visible. Every * change redraws the row: return to column 0, write the prompt and the * visible slice of the line, erase what is left of the row, and move the * cursor to its place. That is one write() per keystroke and cannot get * out of step with the terminal the way incremental updates can. * * ## Characters * * The editor works on bytes. In an ASCII build, UTF-8 continuation * bytes are treated as part of the preceding character for cursor motion, * deletion and width, which is enough for text made of single-width * characters. Control characters in the line (a newline inside a * recalled multi-line command, for instance) are shown as `^X`. * * ## Signals * * The terminal is put in a mode where it still generates signals, so * `^C` arrives as SIGINT and interrupts the read. The editor then gives * the terminal back and lets trap_poll() abandon the line. * * The alternative editor, edit_libedit.c, implements the same two * functions with libedit. The makefile links exactly one of them. */ #include #include #include #include #include #include #include #include #include #include #include "charset.h" #include "exec.h" #include "interact.h" #include "shell.h" #include "var.h" /** @brief Keys that are not single bytes. */ enum { K_EOF = -1, /**< End of input. */ K_INTR = -2, /**< The read was interrupted by a signal. */ K_UP = 0x100, K_DOWN = 257, K_LEFT = 258, K_RIGHT = 259, K_HOME = 260, K_END = 261, K_DELETE = 262, K_WORD_LEFT = 263, K_WORD_RIGHT = 264, K_META = 0x1000, /**< Added to a byte: ESC followed by that byte. */ }; /** @brief Everything the editor knows about the line being edited. */ typedef struct editor { char *buf; /**< The line (not NUL-terminated while editing). */ size_t len; /**< Bytes in `buf`. */ size_t cap; /**< Allocated size of `buf`. */ size_t pos; /**< Cursor position, as a byte offset. */ const char *prompt; /**< Last line of the prompt. */ size_t pwidth; /**< Screen columns the prompt occupies. */ size_t off; /**< First screen cell of the line that is shown. */ int hidx; /**< History entry on show; hist_count() is the new line. */ char *pending; /**< The new line, kept while history is browsed. */ char *kill; /**< Last killed (cut) text, for yank / put. */ size_t kill_len; /**< Its length. */ struct termios saved; /**< Terminal modes to restore. */ bool raw; /**< The terminal is in editing mode. */ int unread; /**< A key pushed back by a sub-mode, or 0. */ bool vi_cmd; /**< vi mode: in command (not insert) mode. */ char *undo; /**< vi mode: the line before the last change. */ size_t undo_len; /**< Its length. */ size_t undo_pos; /**< Cursor position to restore with it. */ char search[128]; /**< vi mode: last `/` or `?` pattern. */ } editor; /** * @brief The one editor. */ static editor ed; /* ---- terminal -------------------------------------------------------- */ /** * @brief Can lines be edited on this terminal? * @return true if stdin and stderr are terminals and TERM is not "dumb". */ bool edit_usable(void) { const char *term = var_get("TERM"); if (!term || !*term || !strcmp(term, "dumb") || !strcmp(term, "emacs")) return false; return isatty(0) && isatty(2); } /** * @brief Put the terminal in editing mode. * * Input is delivered a byte at a time and not echoed. Signal generation * stays on, and output processing stays on so that "\n" still means * "start of next line". */ static void raw_on(void) { if (ed.raw || tcgetattr(0, &ed.saved) < 0) return; struct termios t = ed.saved; t.c_lflag &= ~(tcflag_t)(ICANON | ECHO | IEXTEN); t.c_iflag &= ~(tcflag_t)(IXON | ICRNL | INLCR); t.c_cc[VMIN] = 1; t.c_cc[VTIME] = 0; if (tcsetattr(0, TCSADRAIN, &t) == 0) ed.raw = true; } /** @brief Give the terminal back the modes it had before raw_on(). */ static void raw_off(void) { if (ed.raw) { tcsetattr(0, TCSADRAIN, &ed.saved); ed.raw = false; } } /** * @brief Width of the terminal. * @return Columns, or 80 if the terminal will not say. */ static size_t term_cols(void) { #ifdef TIOCGWINSZ struct winsize ws; if (ioctl(2, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0) return ws.ws_col; #endif long n; const char *v = var_get("COLUMNS"); return v && parse_long(v, &n) && n > 0 ? (size_t)n : 80; } /** * @brief Height of the terminal. * @return Rows, or 24 if the terminal will not say. */ static size_t term_rows(void) { #ifdef TIOCGWINSZ struct winsize ws; if (ioctl(2, TIOCGWINSZ, &ws) == 0 && ws.ws_row > 0) return ws.ws_row; #endif long n; const char *v = var_get("LINES"); return v && parse_long(v, &n) && n > 0 ? (size_t)n : 24; } /* ---- buffered terminal output ---------------------------------------- */ /** * @brief Bytes queued for the terminal. Sent in one write by ob_flush(). */ static char *obuf; static size_t obuf_len; static size_t obuf_cap; /** @brief Queue bytes for the terminal. */ static void ob_put(const char *s, size_t n) { if (obuf_len + n > obuf_cap) { obuf_cap = (obuf_len + n) * 2 + 64; obuf = xrealloc(obuf, obuf_cap); } memcpy(obuf + obuf_len, s, n); obuf_len += n; } /** @brief Queue a string for the terminal. */ static void ob_puts(const char *s) { ob_put(s, strlen(s)); } /** @brief Queue one byte for the terminal. */ static void ob_putc(char c) { ob_put(&c, 1); } /** * @brief Queue a control sequence: ESC `[`, an optional number, a final * letter. * @param n Parameter, or 0 for none. * @param final The letter that ends the sequence. */ static void ob_csi(size_t n, char final) { char num[INT_BUFSZ]; ob_putc(CH_ESC); ob_putc('['); if (n) ob_puts(fmt_int((intmax_t)n, num)); ob_putc(final); } /** @brief Send everything queued to the terminal in one write. */ static void ob_flush(void) { size_t done = 0; while (done < obuf_len) { ssize_t n = write(2, obuf + done, obuf_len - done); if (n < 0 && errno == EINTR) continue; if (n <= 0) break; done += (size_t)n; } obuf_len = 0; } /* ---- characters and cells -------------------------------------------- */ /** * @brief Is this byte the second or later byte of a UTF-8 character? * * Always false in an EBCDIC build, where text is single-byte. */ static bool is_cont(char c) { #if ZASH_ASCII return ((unsigned char)c & 0xc0) == 0x80; #else (void)c; return false; #endif } /** * @brief Screen cells a byte occupies: 0 for a UTF-8 continuation byte, * 2 for a control character (shown as `^X`), otherwise 1. */ static size_t cell_width(char c) { if (is_cont(c)) return 0; return iscntrl((unsigned char)c) ? 2 : 1; } /** @brief Byte offset of the character before `pos`. */ static size_t prev_char(size_t pos) { if (pos) pos--; while (pos && is_cont(ed.buf[pos])) pos--; return pos; } /** @brief Byte offset of the character after the one at `pos`. */ static size_t next_char(size_t pos) { if (pos < ed.len) pos++; while (pos < ed.len && is_cont(ed.buf[pos])) pos++; return pos; } /** @brief Is this byte part of a word, for word motions? */ static bool is_word(char c) { return isalnum((unsigned char)c) || c == '_' || is_cont(c) || ((unsigned char)c >= 0x80 && ZASH_ASCII); } /** @brief Start of the word before `pos`. */ static size_t word_left(size_t pos) { while (pos && !is_word(ed.buf[pos - 1])) pos--; while (pos && is_word(ed.buf[pos - 1])) pos--; return pos; } /** @brief End of the word after `pos`. */ static size_t word_right(size_t pos) { while (pos < ed.len && !is_word(ed.buf[pos])) pos++; while (pos < ed.len && is_word(ed.buf[pos])) pos++; return pos; } /** * @brief Columns a prompt occupies on screen. * * Colour and other ANSI control sequences in the prompt take no room. * * @param s The prompt (one line). * @return Its width in columns. */ static size_t prompt_width(const char *s) { size_t w = 0; while (*s) { if (*s == CH_ESC && s[1] == '[') { s += 2; while (*s && (isdigit((unsigned char)*s) || *s == ';' || *s == '?')) s++; if (*s) s++; continue; } w += cell_width(*s) ? 1 : 0; s++; } return w; } /* ---- drawing --------------------------------------------------------- */ /** * @brief Redraw the edited line and place the cursor. * * See the file comment for the method. `ed.off` (the horizontal scroll * position) is adjusted here so that the cursor is always on screen. */ static void refresh(void) { size_t cols = term_cols(); size_t pwidth = ed.pwidth; bool show_prompt = pwidth + 10 < cols; if (!show_prompt) pwidth = 0; size_t avail = cols - pwidth - 1; size_t cursor = 0; /* cell index of the cursor */ for (size_t i = 0; i < ed.pos; i++) cursor += cell_width(ed.buf[i]); if (cursor < ed.off) ed.off = cursor; else if (cursor >= ed.off + avail) ed.off = cursor - avail + 1; ob_putc('\r'); if (show_prompt) ob_puts(ed.prompt); size_t cell = 0; bool shown = false; for (size_t i = 0; i < ed.len; i++) { char c = ed.buf[i]; size_t w = cell_width(c); if (w == 0) { if (shown) ob_putc(c); continue; } shown = cell >= ed.off && cell + w <= ed.off + avail; if (shown) { if (w == 2) { ob_putc('^'); ob_putc(ZASH_ASCII ? (char)((unsigned char)c ^ 0x40) : '?'); } else { ob_putc(c); } } cell += w; } ob_csi(0, 'K'); ob_putc('\r'); if (pwidth + cursor > ed.off) ob_csi(pwidth + cursor - ed.off, 'C'); ob_flush(); } /* ---- changing the line ----------------------------------------------- */ /** @brief Make room for `extra` more bytes in the line. */ static void reserve(size_t extra) { if (ed.len + extra + 1 > ed.cap) { ed.cap = (ed.len + extra + 1) * 2; ed.buf = xrealloc(ed.buf, ed.cap); } } /** * @brief Insert bytes at the cursor and move the cursor past them. * @param s Bytes to insert. * @param n How many. */ static void insert(const char *s, size_t n) { reserve(n); memmove(ed.buf + ed.pos + n, ed.buf + ed.pos, ed.len - ed.pos); memcpy(ed.buf + ed.pos, s, n); ed.len += n; ed.pos += n; } /** * @brief Remove the bytes in [from, to) and put the cursor at `from`. * @param from First byte to remove. * @param to One past the last. * @param save Whether the text becomes the kill buffer (for yank). */ static void remove_range(size_t from, size_t to, bool save) { if (from >= to) return; if (save) { free(ed.kill); ed.kill_len = to - from; ed.kill = xmalloc(ed.kill_len); memcpy(ed.kill, ed.buf + from, ed.kill_len); } memmove(ed.buf + from, ed.buf + to, ed.len - to); ed.len -= to - from; ed.pos = from; } /** * @brief Replace the whole line. * @param s New contents (NUL-terminated). */ static void set_line(const char *s) { size_t n = strlen(s); ed.len = 0; reserve(n); memcpy(ed.buf, s, n); ed.len = ed.pos = n; ed.off = 0; } /** * @brief Show another history entry. * * The line being typed is remembered when the user first leaves it and * comes back when they return past the newest entry. * * @param index Entry to show. hist_count() means the line being typed. * @return false if `index` is out of range. */ static bool show_history(int index) { int count = hist_count(); if (index < 0 || index > count) return false; if (ed.hidx == count) { free(ed.pending); ed.pending = xmalloc(ed.len + 1); memcpy(ed.pending, ed.buf, ed.len); ed.pending[ed.len] = '\0'; } ed.hidx = index; set_line(index == count ? ed.pending : hist_entry(index)); return true; } /* ---- bindings -------------------------------------------------------- */ /** @brief The longest key sequence `bind` accepts. */ #define BIND_SEQ_MAX 8 /** @brief How many bindings there is room for. */ #define BIND_MAX 24 /** @brief One key sequence and the code of the action it runs. */ typedef struct binding { char seq[BIND_SEQ_MAX]; unsigned char len; int key; } binding; static binding binds[BIND_MAX]; static int nbind; /** @brief The actions `bind` can name, and the code each one runs. */ static const struct { const char *name; int key; } bind_actions[] = { {"accept-line", '\r'}, {"backward-char", CH_CTRL_B}, {"backward-word", K_WORD_LEFT}, {"beginning-of-line", CH_CTRL_A}, {"clear-screen", CH_CTRL_L}, {"complete", '\t'}, {"delete-char-backward", CH_CTRL_H}, {"delete-char-forward", CH_CTRL_D}, {"delete-word-backward", CH_CTRL_W}, {"delete-word-forward", K_META + 'd'}, {"down-history", CH_CTRL_N}, {"end-of-line", CH_CTRL_E}, {"forward-char", CH_CTRL_F}, {"forward-word", K_WORD_RIGHT}, {"kill-to-end-of-line", CH_CTRL_K}, {"kill-to-start-of-line", CH_CTRL_U}, {"transpose-chars", CH_CTRL_T}, {"up-history", CH_CTRL_P}, {"yank", CH_CTRL_Y}, }; /** * @brief The action a `bind` line gave this key sequence, or `k` itself. * * The defaults are the ones bash has. A binding only takes over for the * sequences it names. */ static int bind_key(int k, const char *seq, size_t n) { for (int i = 0; i < nbind; i++) if (binds[i].len == n && memcmp(binds[i].seq, seq, n) == 0) return binds[i].key; return k; } /** * @brief Turn the key notation of a `bind` line into bytes. * * `^X` is a control key, `^[` is Escape and `^?` is Delete. Anything else * stands for itself. The `& 0x3f` that makes `^A` into 0x01 also works on * an EBCDIC letter, where 'A' is 0xC1. * * @return 0, or -1 if the notation does not fit BIND_SEQ_MAX bytes. */ static int bind_keys(const char *s, size_t len, char *out, size_t *outlen) { size_t n = 0; for (size_t i = 0; i < len; i++) { unsigned char c = (unsigned char)s[i]; if (c == '^' && i + 1 < len) { unsigned char d = (unsigned char)s[++i]; if (d == '[') c = CH_ESC; else if (d == '?') c = CH_DEL; else c = (unsigned char)(d & 0x3f); } if (n == BIND_SEQ_MAX) return -1; out[n++] = (char)c; } if (n == 0) return -1; *outlen = n; return 0; } int edit_bind(const char *spec) { const char *eq = strchr(spec, '='); if (eq == NULL) { sh_warn("bind: %s: expected keys=action", spec); return -1; } char keys[BIND_SEQ_MAX]; size_t nk = 0; if (bind_keys(spec, (size_t)(eq - spec), keys, &nk) < 0) { sh_warn("bind: %.*s: that is not a key sequence", (int)(eq - spec), spec); return -1; } size_t nact = sizeof bind_actions / sizeof bind_actions[0]; int key = -1; for (size_t i = 0; i < nact; i++) if (strcmp(eq + 1, bind_actions[i].name) == 0) { key = bind_actions[i].key; break; } if (key < 0) { sh_warn("bind: %s: no such editing command", eq + 1); return -1; } for (int i = 0; i < nbind; i++) if (binds[i].len == nk && memcmp(binds[i].seq, keys, nk) == 0) { binds[i].key = key; return 0; } if (nbind == BIND_MAX) { sh_warn("bind: no room for another binding"); return -1; } memcpy(binds[nbind].seq, keys, nk); binds[nbind].len = (unsigned char)nk; binds[nbind].key = key; nbind++; return 0; } void edit_bind_list(void) { for (size_t i = 0; i < sizeof bind_actions / sizeof bind_actions[0]; i++) printf("%s\n", bind_actions[i].name); fflush(stdout); } /* ---- reading keys ---------------------------------------------------- */ /** * @brief Read one byte from the terminal. * @return The byte, K_EOF, or K_INTR if a signal interrupted the read. */ static int read_byte(void) { unsigned char c; ssize_t n = read(0, &c, 1); if (n == 1) return c; return n < 0 && errno == EINTR ? K_INTR : K_EOF; } /** * @brief Read one key, decoding arrow and function-key sequences. * * A key sequence starts with ESC. ESC on its own (nothing follows * within 50 ms) is returned as ESC. ESC followed by an ordinary byte is * a "meta" key. ESC `[` or ESC `O` introduces a cursor or editing key. * * @return A byte value, one of the K_ codes, or K_META plus a byte. */ static int read_key(void) { if (ed.unread) { int k = ed.unread; ed.unread = 0; return k; } int c = read_byte(); if (c < 0) return c; char seq[BIND_SEQ_MAX]; size_t n = 0; seq[n++] = (char)c; if (c != CH_ESC) return bind_key(c, seq, n); struct pollfd pfd = {.fd = 0, .events = POLLIN}; if (poll(&pfd, 1, 50) <= 0) return bind_key(CH_ESC, seq, n); c = read_byte(); if (c < 0) return c; seq[n++] = (char)c; if (c != '[' && c != 'O') { if (opt.vi) { /* vi has no meta keys: ESC, then a command */ ed.unread = c; return CH_ESC; } return bind_key(K_META + c, seq, n); } int args[2] = {0, 0}; int np = 0; for (;;) { c = read_byte(); if (c < 0) return c; if (n < BIND_SEQ_MAX) seq[n++] = (char)c; if (isdigit(c)) { args[np] = args[np] * 10 + (c - '0'); } else if (c == ';') { if (np < 1) np++; } else { break; } } bool ctrl = args[1] == 5 || args[1] == 3; /* Ctrl- or Alt-arrow */ int k; switch (c) { case 'A': k = K_UP; break; case 'B': k = K_DOWN; break; case 'C': k = ctrl ? K_WORD_RIGHT : K_RIGHT; break; case 'D': k = ctrl ? K_WORD_LEFT : K_LEFT; break; case 'H': k = K_HOME; break; case 'F': k = K_END; break; case '~': switch (args[0]) { case 1: case 7: k = K_HOME; break; case 4: case 8: k = K_END; break; case 3: k = K_DELETE; break; default: k = 0; break; } break; default: k = 0; /* a key the editor has no use for */ break; } return bind_key(k, seq, n); } /* ---- completion ------------------------------------------------------ */ /** * @brief Insert completion text, escaping characters the shell would * otherwise treat specially. * @param s Text to insert. * @param n Its length. * @param quoted The word is inside quotes: insert it unchanged. */ static void insert_escaped(const char *s, size_t n, bool quoted) { for (size_t i = 0; i < n; i++) { if (!quoted && strchr(" \t\n;&|<>()$`\\\"'*?[#~=%", s[i]) && !(i == 0 && (s[i] == '~' || s[i] == '$'))) insert("\\", 1); insert(s + i, 1); } } /** * @brief The part of a completion candidate worth showing in a list. * @param name A candidate, possibly a path, possibly ending in "/". * @return Its last path component (keeping a directory's final "/"). */ static const char *candidate_base(const char *name) { size_t n = strlen(name); for (size_t i = n > 1 ? n - 1 : 0; i-- > 0;) { if (name[i] == '/') return name + i + 1; } return name; } /** * @brief Print the completion candidates in columns below the line. * @param c The candidates. */ static void list_candidates(const completion *c) { size_t widest = 0; for (int i = 0; i < c->count; i++) { size_t w = strlen(candidate_base(c->list[i])); if (w > widest) widest = w; } size_t cols = term_cols(); size_t per_row = cols / (widest + 2); if (!per_row) per_row = 1; /* One screen: the rows left after the line being edited and the one * that says what was left out. A list longer than that is a wall to * scroll past, which is what a tab key should not produce. */ size_t rows = term_rows() > 2 ? term_rows() - 2 : 1; size_t room = per_row * rows; int shown = c->count > (int)room ? (int)room : c->count; if (shown > (int)per_row) shown -= shown % (int)per_row; /* whole rows only */ ob_puts("\n"); for (int i = 0; i < shown; i++) { const char *base = candidate_base(c->list[i]); ob_puts(base); bool end_row = (size_t)(i + 1) % per_row == 0 || i + 1 == shown; if (end_row) { ob_puts("\n"); } else { for (size_t pad = strlen(base); pad < widest + 2; pad++) ob_putc(' '); } } if (shown < c->count) { char more[48]; snprintf(more, sizeof more, "... and %d more\n", c->count - shown); ob_puts(more); } ob_flush(); } /** * @brief Does a lone candidate ending in `last` finish the word? * * Not if it is a directory (`/`), or for data set names a qualifier * with more below it (`.`) or a PDS awaiting a member (`(`): the next * Tab continues from there. */ static bool is_final(const completion *c, char last) { return last != '/' && !(c->mvs && (last == '.' || last == '(')); } /** * @brief Complete the word before the cursor (the Tab key). * * One candidate is inserted whole, followed by a space (or nothing after * a directory, so the next Tab descends into it). Several candidates * are completed as far as they agree. If that adds nothing, they are * listed. */ static void complete(void) { completion c; complete_line(ed.buf, ed.pos, &c); if (!c.count) { complete_free(&c); ob_putc('\a'); ob_flush(); return; } size_t common = strlen(c.list[0]); for (int i = 1; i < c.count; i++) { size_t k = 0; while (k < common && c.list[i][k] == c.list[0][k]) k++; common = k; } /* What the user typed, without escapes, is a prefix of every * candidate. Replace it only if completion makes it longer. */ size_t typed = 0; for (size_t i = c.start; i < ed.pos; i++) { if (ed.buf[i] == '\\' && !c.quoted && i + 1 < ed.pos) i++; typed++; } if (c.count == 1 || common > typed) { remove_range(c.start, ed.pos, false); insert_escaped(c.list[0], common, c.quoted); if (c.count == 1 && common && is_final(&c, c.list[0][common - 1])) { if (c.quote) insert(&c.quote, 1); insert(" ", 1); } } else { list_candidates(&c); } complete_free(&c); } /* ---- incremental search (emacs ^R) ----------------------------------- */ /** * @brief Search the history backwards as the user types (`^R`). * * Each printable key extends the pattern. `^R` again finds the next * older match. Backspace shortens the pattern. `^G` gives up and restores * the line. Enter accepts and runs the match. Any other key accepts the * match and is then handled as an ordinary editing key. * * @return true if the user pressed Enter on a match. */ static bool search_history(void) { char pat[128]; size_t plen = 0; int idx = hist_count(); int found = -1; char *orig = xmalloc(ed.len + 1); memcpy(orig, ed.buf, ed.len); orig[ed.len] = '\0'; bool accepted = false; for (;;) { const char *match = found >= 0 ? hist_entry(found) : ""; ob_putc('\r'); ob_puts("(search)`"); ob_put(pat, plen); ob_puts("': "); size_t room = term_cols() > plen + 16 ? term_cols() - plen - 16 : 0; for (size_t i = 0; match[i] && i < room; i++) ob_putc(iscntrl((unsigned char)match[i]) ? ' ' : match[i]); ob_csi(0, 'K'); ob_flush(); int k = read_key(); bool again = false; if (k == CH_CTRL_R) { idx = found >= 0 ? found : idx; again = true; } else if (k == CH_DEL || k == CH_CTRL_H) { if (plen) plen--; idx = hist_count(); again = true; } else if (k >= 0 && k < 0x100 && !iscntrl(k) && plen + 1 < sizeof pat) { pat[plen++] = (char)k; idx = found >= 0 ? found + 1 : idx; again = true; } if (again) { pat[plen] = '\0'; int hit = -1; for (int i = idx - 1; i >= 0 && plen; i--) { if (strstr(hist_entry(i), pat)) { hit = i; break; } } if (hit >= 0) found = hit; else if (plen) ob_putc('\a'); else found = -1; continue; } if (k == CH_CTRL_G || k == K_INTR || k == K_EOF) { set_line(orig); if (k != CH_CTRL_G) ed.unread = k; break; } if (found >= 0) { ed.hidx = hist_count(); show_history(found); } if (k == '\r' || k == '\n') accepted = true; else ed.unread = k; break; } free(orig); return accepted; } /* ---- vi mode --------------------------------------------------------- */ /** @brief vi: remember the line so that `u` can bring it back. */ static void vi_save_undo(void) { free(ed.undo); ed.undo = xmalloc(ed.len + 1); memcpy(ed.undo, ed.buf, ed.len); ed.undo_len = ed.len; ed.undo_pos = ed.pos; } /** @brief vi: is this byte blank? */ static bool vi_blank(size_t i) { return ed.buf[i] == ' ' || ed.buf[i] == '\t'; } /** * @brief vi: character class for the `w`, `b` and `e` motions. * @return 0 for blank, 1 for a word character, 2 for punctuation. */ static int vi_class(size_t i, bool big) { if (vi_blank(i)) return 0; return big || is_word(ed.buf[i]) ? 1 : 2; } /** * @brief vi: compute where a motion command takes the cursor. * * @param key The motion: one of `h l 0 ^ $ w W b B e E` or a * cursor key. * @param count Repeat count (at least 1). * @param inclusive Receives whether an operator using this motion also * takes the character at the destination (`e`, `$`). * @return The destination offset, or SIZE_MAX if `key` is not a motion. */ static size_t vi_motion(int key, int count, bool *inclusive) { size_t p = ed.pos; *inclusive = false; bool big = key == 'W' || key == 'B' || key == 'E'; switch (key) { case 'h': case K_LEFT: case CH_DEL: case CH_CTRL_H: while (count-- && p) p = prev_char(p); return p; case 'l': case ' ': case K_RIGHT: while (count-- && p < ed.len) p = next_char(p); return p; case '0': case K_HOME: return 0; case '^': p = 0; while (p < ed.len && vi_blank(p)) p++; return p; case '$': case K_END: *inclusive = true; return ed.len; case 'w': case 'W': while (count-- && p < ed.len) { int cls = vi_class(p, big); while (p < ed.len && vi_class(p, big) == cls && cls) p++; while (p < ed.len && vi_blank(p)) p++; } return p; case 'b': case 'B': while (count-- && p) { p--; while (p && vi_blank(p)) p--; int cls = vi_class(p, big); while (p && vi_class(p - 1, big) == cls) p--; } return p; case 'e': case 'E': *inclusive = true; while (count-- && p < ed.len) { p++; while (p < ed.len && vi_blank(p)) p++; if (p >= ed.len) break; int cls = vi_class(p, big); while (p + 1 < ed.len && vi_class(p + 1, big) == cls) p++; } return p < ed.len ? p : ed.len; default: return SIZE_MAX; } } /** * @brief vi: search the history for the remembered pattern. * @param backwards true to look at older entries (`/`, `n`). * @return true if a matching entry was found and is now shown. */ static bool vi_search(bool backwards) { int step = backwards ? -1 : 1; for (int i = ed.hidx + step; i >= 0 && i < hist_count(); i += step) { if (strstr(hist_entry(i), ed.search)) { show_history(i); ed.pos = 0; return true; } } return false; } /** * @brief vi: read a search pattern after `/` or `?`. * @return false if the user gave up with ESC or an interrupt. */ static bool vi_read_pattern(char lead) { size_t n = 0; for (;;) { ob_putc('\r'); ob_putc(lead); ob_put(ed.search, n); ob_csi(0, 'K'); ob_flush(); int k = read_key(); if (k == '\r' || k == '\n') break; if (k == CH_ESC || k < 0) { if (k < 0) ed.unread = k; return false; } if (k == CH_DEL || k == CH_CTRL_H) { if (n) n--; } else if (k < 0x100 && !iscntrl(k) && n + 1 < sizeof ed.search) { ed.search[n++] = (char)k; } } if (n) /* an empty pattern repeats the previous search */ ed.search[n] = '\0'; return ed.search[0] != '\0'; } /** * @brief vi: carry out one command-mode key. * * Supported: counts. The motions of vi_motion(). `i a I A` (insert); * `x X r ~` (single characters). `d c y` with a motion or doubled; * `D C` (to end of line). `p P` (put). `u` (undo). `k j - +` and the * arrow keys (history). `G` (oldest entry, or entry N). `/ ? n N` * (history search). `#` (turn the line into a comment and accept it). * * @param key The key. * @return true if the line is to be accepted as it stands. */ static bool vi_command(int key) { int count = 0; while ((key >= '1' && key <= '9') || (count && key == '0')) { count = count * 10 + (key - '0'); key = read_key(); } bool counted = count > 0; if (!count) count = 1; bool inclusive; size_t dest = vi_motion(key, count, &inclusive); if (dest != SIZE_MAX) { ed.pos = dest; return false; } switch (key) { case 'i': ed.vi_cmd = false; break; case 'a': ed.pos = next_char(ed.pos); ed.vi_cmd = false; break; case 'I': ed.pos = 0; ed.vi_cmd = false; break; case 'A': ed.pos = ed.len; ed.vi_cmd = false; break; case 'x': case K_DELETE: { size_t to = ed.pos; while (count-- && to < ed.len) to = next_char(to); vi_save_undo(); remove_range(ed.pos, to, true); break; } case 'X': { size_t from = ed.pos; while (count-- && from) from = prev_char(from); vi_save_undo(); remove_range(from, ed.pos, true); break; } case 'r': { int c = read_key(); if (c > 0 && c < 0x100 && !iscntrl(c) && ed.pos < ed.len) { vi_save_undo(); size_t p = ed.pos; remove_range(p, next_char(p), false); char ch = (char)c; insert(&ch, 1); ed.pos = p; } break; } case '~': vi_save_undo(); while (count-- && ed.pos < ed.len) { unsigned char c = (unsigned char)ed.buf[ed.pos]; ed.buf[ed.pos] = (char)(islower(c) ? toupper(c) : tolower(c)); ed.pos++; } break; case 'D': vi_save_undo(); remove_range(ed.pos, ed.len, true); break; case 'C': vi_save_undo(); remove_range(ed.pos, ed.len, true); ed.vi_cmd = false; break; case 'S': vi_save_undo(); remove_range(0, ed.len, true); ed.vi_cmd = false; break; case 'd': case 'c': case 'y': { int m = read_key(); size_t from = ed.pos; size_t to; if (m == key) { /* dd, cc, yy: the whole line */ from = 0; to = ed.len; } else { /* "cw" changes to the end of the word, as in vi. */ if (key == 'c' && (m == 'w' || m == 'W')) m = m == 'w' ? 'e' : 'E'; to = vi_motion(m, count, &inclusive); if (to == SIZE_MAX) break; if (inclusive && to < ed.len) to = next_char(to); if (to < from) { size_t t = from; from = to; to = t; } } if (key == 'y') { size_t keep = ed.pos; vi_save_undo(); remove_range(from, to, true); insert(ed.kill, ed.kill_len); ed.pos = keep < from ? keep : from; break; } vi_save_undo(); remove_range(from, to, true); if (key == 'c') ed.vi_cmd = false; break; } case 'p': case 'P': if (ed.kill_len) { vi_save_undo(); if (key == 'p') ed.pos = next_char(ed.pos); insert(ed.kill, ed.kill_len); ed.pos = prev_char(ed.pos); } break; case 'u': if (ed.undo) { char *now = xmalloc(ed.len + 1); size_t now_len = ed.len; size_t now_pos = ed.pos; memcpy(now, ed.buf, ed.len); ed.len = 0; reserve(ed.undo_len); memcpy(ed.buf, ed.undo, ed.undo_len); ed.len = ed.undo_len; ed.pos = ed.undo_pos; free(ed.undo); ed.undo = now; ed.undo_len = now_len; ed.undo_pos = now_pos; } break; case 'k': case '-': case K_UP: while (count-- && show_history(ed.hidx - 1)) ed.pos = 0; break; case 'j': case '+': case K_DOWN: while (count-- && show_history(ed.hidx + 1)) ed.pos = 0; break; case 'G': if (show_history(counted ? count - 1 : 0)) ed.pos = 0; break; case '/': case '?': if (vi_read_pattern((char)key) && !vi_search(key == '/')) ob_putc('\a'); break; case 'n': case 'N': if (!ed.search[0] || !vi_search(key == 'n')) ob_putc('\a'); break; case '#': ed.pos = 0; insert("#", 1); return true; default: break; } /* In command mode the cursor sits on a character, not after the end. */ if (ed.vi_cmd && ed.pos >= ed.len && ed.len) ed.pos = prev_char(ed.len); return false; } /* ---- the main loop --------------------------------------------------- */ /** * @brief Handle a signal that interrupted the editor. * * The terminal is handed back first, because trap_poll() usually does * not return: for `^C` at the prompt it abandons the line by raising an * exception. If it does return (a trap action ran), editing resumes. */ static void interrupted(void) { raw_off(); ob_flush(); trap_poll(); raw_on(); } /** * @brief Carry out one emacs-mode (or vi insert-mode) key. * @param k The key. * @return true if the line is to be accepted. */ static bool edit_key(int k) { switch (k) { case '\r': case '\n': return true; case CH_CTRL_A: case K_HOME: ed.pos = 0; break; case CH_CTRL_E: case K_END: ed.pos = ed.len; break; case CH_CTRL_B: case K_LEFT: ed.pos = prev_char(ed.pos); break; case CH_CTRL_F: case K_RIGHT: ed.pos = next_char(ed.pos); break; case K_META + 'b': case K_WORD_LEFT: ed.pos = word_left(ed.pos); break; case K_META + 'f': case K_WORD_RIGHT: ed.pos = word_right(ed.pos); break; case CH_CTRL_P: case K_UP: show_history(ed.hidx - 1); break; case CH_CTRL_N: case K_DOWN: show_history(ed.hidx + 1); break; case K_META + '<': show_history(0); break; case K_META + '>': show_history(hist_count()); break; case CH_DEL: case CH_CTRL_H: remove_range(prev_char(ed.pos), ed.pos, false); break; case CH_CTRL_D: case K_DELETE: remove_range(ed.pos, next_char(ed.pos), false); break; case CH_CTRL_K: remove_range(ed.pos, ed.len, true); break; case CH_CTRL_U: remove_range(0, ed.pos, true); break; case CH_CTRL_W: { size_t from = ed.pos; while (from && (ed.buf[from - 1] == ' ' || ed.buf[from - 1] == '\t')) from--; while (from && ed.buf[from - 1] != ' ' && ed.buf[from - 1] != '\t') from--; remove_range(from, ed.pos, true); break; } case K_META + CH_DEL: case K_META + CH_CTRL_H: remove_range(word_left(ed.pos), ed.pos, true); break; case K_META + 'd': remove_range(ed.pos, word_right(ed.pos), true); break; case K_META + 'u': case K_META + 'l': case K_META + 'c': { /* Change the case of the word after the cursor, as bash does. * `\c` capitalises its first character and lowercases the rest. */ size_t to = word_right(ed.pos); bool first = true; for (size_t i = ed.pos; i < to; i++) { unsigned char c = (unsigned char)ed.buf[i]; if (k == K_META + 'u') ed.buf[i] = (char)toupper(c); else if (k == K_META + 'l' || !first) ed.buf[i] = (char)tolower(c); else ed.buf[i] = (char)toupper(c); if (is_word(ed.buf[i])) first = false; } ed.pos = to; break; } case K_META + 't': { /* Transpose the words on either side of the cursor, as bash does: * word1, space, word2 becomes word2, space, word1 in place. */ size_t a1 = word_left(ed.pos), b1 = ed.pos; while (b1 > a1 && !is_word(ed.buf[b1 - 1])) b1--; size_t a2 = ed.pos; while (a2 < ed.len && !is_word(ed.buf[a2])) a2++; size_t b2 = word_right(a2); if (a1 == b1 || a2 == b2) break; /* there is no word on one side */ size_t n1 = b1 - a1, gap = a2 - b1, n2 = b2 - a2; char *tmp = xmalloc(n1 + gap + n2); memcpy(tmp, ed.buf + a2, n2); memcpy(tmp + n2, ed.buf + b1, gap); memcpy(tmp + n2 + gap, ed.buf + a1, n1); memcpy(ed.buf + a1, tmp, n1 + gap + n2); free(tmp); ed.pos = b2; break; } case K_META + '.': { /* Insert the last word of the previous line, as bash does. */ int idx = ed.hidx < hist_count() ? ed.hidx - 1 : hist_count() - 1; if (idx < 0) break; const char *h = hist_entry(idx); size_t n = strlen(h); while (n && (h[n - 1] == ' ' || h[n - 1] == '\t')) n--; size_t from = n; while (from && h[from - 1] != ' ' && h[from - 1] != '\t') from--; if (from < n) insert(h + from, n - from); break; } case K_META + '\\': { /* Delete the blanks around the cursor, as bash does. */ size_t from = ed.pos, to = ed.pos; while (from && (ed.buf[from - 1] == ' ' || ed.buf[from - 1] == '\t')) from--; while (to < ed.len && (ed.buf[to] == ' ' || ed.buf[to] == '\t')) to++; if (from < to) remove_range(from, to, false); break; } case CH_CTRL_Y: if (ed.kill_len) insert(ed.kill, ed.kill_len); break; case CH_CTRL_T: if (ed.pos && ed.len > 1) { size_t b = ed.pos < ed.len ? ed.pos : prev_char(ed.pos); size_t a = prev_char(b); size_t end = next_char(b); size_t alen = b - a; size_t blen = end - b; char tmp[16]; if (alen <= sizeof tmp) { memcpy(tmp, ed.buf + a, alen); memmove(ed.buf + a, ed.buf + b, blen); memcpy(ed.buf + a + blen, tmp, alen); ed.pos = end; } } break; case CH_CTRL_L: ob_csi(0, 'H'); ob_csi(2, 'J'); break; case CH_CTRL_R: return search_history(); case CH_CTRL_V: { int c = read_key(); if (c >= 0 && c < 0x100) { char ch = (char)c; insert(&ch, 1); } break; } case '\t': complete(); break; default: if (k > 0 && k < 0x100 && !iscntrl(k)) { char ch = (char)k; insert(&ch, 1); } break; } return false; } /** * @brief Read one line with editing. * * @param prompt Text to show before the line. If it has several lines, * all but the last are printed once and the last is the * prompt that is redrawn. * @param len Receives the length of the line. * @return The line, NUL-terminated and without a newline, valid until the * next call. NULL at end of input (`^D` on an empty line). */ char *edit_readline(const char *prompt, size_t *len) { const char *last = strrchr(prompt, '\n'); if (last) { ob_put(prompt, (size_t)(last - prompt) + 1); prompt = last + 1; } ed.prompt = prompt; ed.pwidth = prompt_width(prompt); ed.len = ed.pos = ed.off = 0; ed.hidx = hist_count(); ed.unread = 0; ed.vi_cmd = false; reserve(64); raw_on(); bool eof = false; for (;;) { refresh(); int k = read_key(); if (k == K_INTR) { interrupted(); continue; } if (k == K_EOF || (k == CH_CTRL_D && ed.len == 0)) { eof = true; break; } if (opt.vi) { if (ed.vi_cmd) { if (k == '\r' || k == '\n' || vi_command(k)) break; continue; } if (k == CH_ESC) { ed.vi_cmd = true; ed.pos = prev_char(ed.pos); continue; } /* In insert mode the basic editing keys still work. */ } if (edit_key(k)) break; } ed.pos = ed.len; if (!eof) refresh(); ob_puts("\n"); ob_flush(); raw_off(); if (eof) return NULL; ed.buf[ed.len] = '\0'; *len = ed.len; return ed.buf; }