summaryrefslogtreecommitdiffhomepage
path: root/src/history.c
blob: e42a63485ba4ba3adf3bbc4c3a94f42de4886733 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
/**
 * @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 <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#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;
}