/** * @file history.c * @brief Command history and the `fc` builtin. * * History is kept only by an interactive shell. Entries are whole * commands: a continuation line (one read at the PS2 prompt) is appended * to the entry it continues. The list lives in memory. `HISTFILE`, if * set, is read at startup and rewritten at exit. `HISTSIZE` bounds the * list (default 500). */ #include #include #include #include #include #include #include "exec.h" #include "var.h" #include "interact.h" /** @brief Entries kept when HISTSIZE is unset or not a number. */ #define HIST_DEFAULT 500 static char **hist; /**< Entries, oldest first. */ static int hist_n; /**< Number of entries. */ static int hist_cap; /**< Allocated slots in `hist`. */ static int hist_base = 1; /**< Event number of hist[0]. */ /** * @brief The current history limit. * @return HISTSIZE if it is a positive number, else the default. */ static int hist_limit(void) { long n; const char *v = var_get("HISTSIZE"); if (v && parse_long(v, &n) && n > 0 && n < 1000000) return (int)n; return HIST_DEFAULT; } /** @brief Number of entries in the history list. */ int hist_count(void) { return hist_n; } /** * @brief Fetch an entry. * @param index 0 for the oldest entry, hist_count()-1 for the newest. * @return The command text, or nullptr if `index` is out of range. */ const char *hist_entry(int index) { return index >= 0 && index < hist_n ? hist[index] : nullptr; } /** @brief Remove the newest entry (used by `fc` to erase itself). */ static void hist_drop_last(void) { if (hist_n) free(hist[--hist_n]); } /** * @brief Add a line to the history. * * Blank lines are not recorded, and neither is an exact repeat of the * newest entry. * * @param line The text, without a trailing newline. * @param len Its length. * @param append true for a continuation line: join it to the newest * entry with a newline instead of starting a new entry. */ void hist_add(const char *line, size_t len, bool append) { while (len && (line[len - 1] == '\n' || line[len - 1] == '\r')) len--; if (append && hist_n) { size_t old = strlen(hist[hist_n - 1]); char *e = xrealloc(hist[hist_n - 1], old + len + 2); e[old] = '\n'; memcpy(e + old + 1, line, len); e[old + 1 + len] = '\0'; hist[hist_n - 1] = e; return; } size_t blank = 0; while (blank < len && (line[blank] == ' ' || line[blank] == '\t')) blank++; if (blank == len) return; if (hist_n && strlen(hist[hist_n - 1]) == len && !memcmp(hist[hist_n - 1], line, len)) return; int limit = hist_limit(); while (hist_n >= limit) { free(hist[0]); memmove(hist, hist + 1, (size_t)(hist_n - 1) * sizeof *hist); hist_n--; hist_base++; } if (hist_n == hist_cap) { hist_cap = hist_cap ? hist_cap * 2 : 64; hist = xrealloc(hist, (size_t)hist_cap * sizeof *hist); } char *e = xmalloc(len + 1); memcpy(e, line, len); e[len] = '\0'; hist[hist_n++] = e; } /** * @brief Read a whole file into memory. * @param path File name. * @param lenp Receives the length. * @return Heap buffer (NUL-terminated), or nullptr if it cannot be read. */ static char *read_file(const char *path, size_t *lenp) { int fd = sys_open(path, O_RDONLY, 0); if (fd < 0) return nullptr; size_t cap = 4096; size_t len = 0; char *buf = xmalloc(cap); for (;;) { if (len + 1 >= cap) buf = xrealloc(buf, cap *= 2); ssize_t n = read(fd, buf + len, cap - len - 1); if (n < 0 && errno == EINTR) continue; if (n <= 0) break; len += (size_t)n; } close(fd); buf[len] = '\0'; *lenp = len; return buf; } /** @brief Load HISTFILE, if it is set and readable. */ void hist_init(void) { const char *path = var_get("HISTFILE"); size_t len; char *text = path && *path ? read_file(path, &len) : nullptr; if (!text) return; for (char *p = text; *p;) { size_t n = strcspn(p, "\n"); hist_add(p, n, false); p += n + (p[n] == '\n'); } free(text); } /** * @brief Write the history to HISTFILE, if it is set. * * The file holds one line per line of history. It is created with mode * 0600 because command lines can contain secrets. */ void hist_save(void) { const char *path = var_get("HISTFILE"); if (!path || !*path || !hist_n) return; int fd = sys_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); if (fd < 0) return; char buf[1024]; output o = {buf, 0, sizeof buf, fd, 0}; for (int i = 0; i < hist_n; i++) { out_puts(&o, hist[i]); out_putc(&o, '\n'); } out_flush(&o); close(fd); } /* ---- fc -------------------------------------------------------------- */ /** * @brief Resolve an `fc` operand to a history index. * * A positive number is an event number, a negative number counts back * from the newest entry, and anything else names the newest entry that * starts with that string. * * @param spec The operand. * @param newest Index of the newest entry that counts (the `fc` command * itself is excluded when listing). * @return The index, clamped to the list. -1 if a string matches nothing. */ static int hist_resolve(const char *spec, int newest) { long n; if (parse_long(spec, &n)) { long idx = n < 0 ? newest + 1 + n : n - hist_base; if (idx < 0) idx = 0; if (idx >= hist_n) idx = hist_n - 1; return (int)idx; } size_t len = strlen(spec); for (int i = hist_n - 1; i >= 0; i--) { if (!strncmp(hist[i], spec, len)) return i; } return -1; } /** * @brief Run text recalled from history: show it, record it, execute it. * @param text The command text. * @return Its exit status. */ static int hist_run(const char *text) { char *copy = xstrdup(text); out_printf(&out2, "%s\n", copy); out_flush(&out2); hist_add(copy, strlen(copy), false); jmploc jl; jmploc *prev = exc_handler; int status; if (setjmp(jl.buf) == 0) { exc_catch(&jl); status = eval_string(copy, 0); } else { exc_handler = prev; free(copy); exc_raise(exc_code); } exc_handler = prev; free(copy); return status; } /** * @brief `fc -s [old=new] [first]`: re-run a command, optionally with * one substitution. * @param old_new The "old=new" operand, or nullptr. * @param first Which command, or nullptr for the previous one. * @return The command's exit status, or 1 if there is no such command. */ static int fc_substitute(const char *old_new, const char *first) { int idx = first ? hist_resolve(first, hist_n - 1) : hist_n - 1; if (idx < 0 || idx >= hist_n) { sh_warn("fc: no such command"); return 1; } const char *text = hist[idx]; if (!old_new) return hist_run(text); const char *eq = strchr(old_new, '='); size_t olen = (size_t)(eq - old_new); const char *at = olen ? strstr(text, arena_strndup(&scratch, old_new, olen)) : nullptr; if (!at) return hist_run(text); strbuf sb; sb_init(&sb, &scratch); sb_put(&sb, text, (size_t)(at - text)); sb_puts(&sb, eq + 1); sb_puts(&sb, at + olen); return hist_run(sb_cstr(&sb)); } /** * @brief Edit history entries in an editor and run the result. * @param editor The editor command. * @param lo First index. * @param hi Last index (may be less than `lo`: reverse order). * @return The exit status of the edited commands. 1 if editing failed. */ static int fc_edit(const char *editor, int lo, int hi) { const char *tmpdir = var_get("TMPDIR"); strbuf path; sb_init(&path, &scratch); sb_puts(&path, tmpdir && *tmpdir ? tmpdir : "/tmp"); sb_puts(&path, "/zash-fc.XXXXXX"); char *file = sb_cstr(&path); int fd = mkstemp(file); if (fd < 0) { sh_warn("fc: cannot create a temporary file: %s", strerror(errno)); return 1; } if (SYS_MVS) sys_tmp_tag(fd); char buf[1024]; output o = {buf, 0, sizeof buf, fd, 0}; int step = lo <= hi ? 1 : -1; for (int i = lo;; i += step) { out_puts(&o, hist[i]); out_putc(&o, '\n'); if (i == hi) break; } out_flush(&o); if (o.err) { close(fd); unlink(file); sh_warn("fc: write error: %s", strerror(o.err)); return 1; } close(fd); output cmd = {.fd = OUT_MEM}; out_puts(&cmd, editor); out_putc(&cmd, ' '); out_quote(&cmd, file); /* TMPDIR may hold a space or a `$` */ out_write(&cmd, "", 1); jmploc jl; jmploc *prev = exc_handler; int status; if (setjmp(jl.buf)) { /* The editor command raised: the file must not be left behind. */ exc_handler = prev; free(cmd.buf); unlink(file); exc_raise(exc_code); } exc_catch(&jl); status = eval_string(cmd.buf, 0); exc_handler = prev; free(cmd.buf); size_t len = 0; char *text = status == 0 ? read_file(file, &len) : nullptr; unlink(file); if (!text) return status ? status : 1; while (len && text[len - 1] == '\n') text[--len] = '\0'; status = len ? hist_run(text) : 0; free(text); return status; } /** * @brief The `fc` builtin. * * - `fc -l [-nr] [first [last]]` lists commands (the last 16 by default); * `-n` omits the numbers and `-r` reverses the order. * - `fc -s [old=new] [first]` re-runs a command. * - `fc [-r] [-e editor] [first [last]]` edits commands and runs the * result. The editor is `-e`, else `$FCEDIT`, else `ed`. * * @return The status of what was run. 0 after listing. 1 or 2 on error. */ int builtin_fc(int argc, char **argv) { bool list = false; bool nonum = false; bool reverse = false; bool subst = false; const char *editor = nullptr; int i = 1; for (; i < argc && argv[i][0] == '-' && argv[i][1]; i++) { long num; if (parse_long(argv[i], &num)) break; /* a negative number is an operand */ if (!strcmp(argv[i], "--")) { i++; break; } for (const char *p = argv[i] + 1; *p; p++) { if (*p == 'l') { list = true; } else if (*p == 'n') { nonum = true; } else if (*p == 'r') { reverse = true; } else if (*p == 's') { subst = true; } else if (*p == 'e') { editor = p[1] ? p + 1 : i + 1 < argc ? argv[++i] : nullptr; if (!editor) { sh_warn("fc: -e: editor name expected"); return 2; } break; } else { sh_warn("fc: -%c: bad option", *p); return 2; } } } if (!opt.interactive) { sh_warn("fc: history is kept only by an interactive shell"); return 1; } /* The fc command itself is the newest entry; it is never its own * subject, and when it re-runs something it is replaced by that. */ if (!list) hist_drop_last(); int newest = list ? hist_n - 2 : hist_n - 1; if (editor && !strcmp(editor, "-")) subst = true; if (subst) { const char *old_new = i < argc && strchr(argv[i], '=') ? argv[i++] : nullptr; return fc_substitute(old_new, i < argc ? argv[i] : nullptr); } if (newest < 0) { if (!list) sh_warn("fc: history is empty"); return list ? 0 : 1; } int lo; int hi; if (i < argc) { lo = hist_resolve(argv[i], newest); hi = i + 1 < argc ? hist_resolve(argv[i + 1], newest) : list ? newest : lo; if (lo < 0 || hi < 0) { sh_warn("fc: no such command"); return 1; } if (lo > newest) lo = newest; if (hi > newest) hi = newest; } else { lo = list ? (newest > 15 ? newest - 15 : 0) : newest; hi = newest; } if (reverse) { int t = lo; lo = hi; hi = t; } if (!list) { if (!editor) editor = var_get("FCEDIT"); return fc_edit(editor && *editor ? editor : "ed", lo, hi); } int step = lo <= hi ? 1 : -1; for (int k = lo;; k += step) { if (!nonum) out_printf(&out1, "%d", hist_base + k); out_putc(&out1, '\t'); for (const char *s = hist[k]; *s; s++) { out_putc(&out1, *s); if (*s == '\n') out_putc(&out1, '\t'); } out_putc(&out1, '\n'); if (k == hi) break; } return 0; }