summaryrefslogtreecommitdiffhomepage
path: root/src/edit_libedit.c
blob: a76844a28262a7c4fc22c8523dfe302faeb26605 (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
/**
 * @file edit_libedit.c
 * @brief The line editor implemented with libedit (BSD editline).
 *
 * This is the compile-time alternative to edit_builtin.c:
 *
 *     make EDIT=libedit LDLIBS=-ledit
 *
 * It provides the same two functions, edit_usable() and edit_readline(),
 * so nothing else in the shell knows which editor is linked.  libedit
 * brings its own key bindings (including a fuller vi mode) and reads
 * `~/.editrc`.  It also brings a dependency on the library and on
 * terminfo or termcap, which is why it is not the default.
 *
 * The shell's own history list (history.c) stays the single source of
 * truth, because `fc` works on it.  Before each line is read the list is
 * copied into libedit's history so that the arrow keys and searches see
 * the same entries.
 *
 * A prompt is written by libedit and counted as it is written, so the
 * colour sequences of PS1 would be counted as visible columns and the
 * cursor would land to the right of where it belongs.  Libedit is told
 * the ignore character (EL_PROMPT_ESC) and every control sequence is
 * bracketed with it, which prints the sequence but does not count it.
 */
#include <errno.h>
#include <histedit.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "charset.h"
#include "exec.h"
#include "interact.h"
#include "shell.h"

/** @brief The character that brackets a run libedit must not count. */
enum { PROMPT_MARK = '\1' };

/**
 * @brief The libedit editor, created on first use.
 */
static EditLine *el;
/**
 * @brief libedit's copy of the history.
 */
static History *el_hist;
/**
 * @brief The prompt for the line being read, marked for libedit.
 */
static char *cur_prompt;

/**
 * @brief End of the run of control sequences that starts at s.
 *
 * Adjacent sequences share one mark pair: libedit attaches the run to
 * the character after the closing mark, and that character has to be a
 * printable one.
 *
 * @param s Text starting with CH_ESC.
 * @return The first byte after the run.
 */
static const char *ctl_run_end(const char *s) {
    do
        s += esc_seq_len(s);
    while (*s == CH_ESC);
    return s;
}

/**
 * @brief Bracket the parts of a prompt that take no room on the screen.
 *
 * libedit counts every character of the prompt as a column unless it is
 * marked.  Its literal run is attached to the character after the closing
 * mark, whose width is the run's width, so a prompt that ends with a
 * control sequence gets a space from here to be that character: libedit
 * would drop the run otherwise (prompt.c: "We lose the last literal"),
 * and counting the sequence instead would put the cursor out by its
 * length.  The extra space is visible and is counted, so the line still
 * starts where libedit thinks it does.
 *
 * @param s The prompt.
 * @return The prompt with its control sequences marked, for free().
 */
static char *prompt_marked(const char *s) {
    size_t n = strlen(s);
    const char *last = nullptr;
    for (const char *p = s; *p;) {
        if (*p != CH_ESC) {
            p++;
            continue;
        }
        n += 2;
        last = ctl_run_end(p);
        p = last;
    }
    bool trailing = last && !*last;
    char *out = xmalloc(n + (trailing ? 2 : 1));
    char *o = out;
    for (const char *p = s; *p;) {
        if (*p != CH_ESC) {
            *o++ = *p++;
            continue;
        }
        const char *e = ctl_run_end(p);
        *o++ = PROMPT_MARK;
        memcpy(o, p, (size_t)(e - p));
        o += e - p;
        *o++ = PROMPT_MARK;
        p = e;
    }
    if (trailing)
        *o++ = ' ';
    *o = '\0';
    return out;
}

/**
 * @brief libedit callback: the prompt for the line being read.
 * @param e Unused.
 * @return The prompt set by edit_readline().
 */
static char *prompt_cb(EditLine *e) {
    (void)e;
    return cur_prompt ? cur_prompt : "";
}

/**
 * @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"))
        return false;
    return isatty(0) && isatty(2);
}

/**
 * @brief Read one line with editing.
 *
 * @param prompt Text to show before the line.
 * @param len    Receives the length of the line.
 * @return The line without its newline, valid until the next call;
 *         nullptr at end of input.
 */
char *edit_readline(const char *prompt, size_t *len) {
    static char *line;
    HistEvent ev;
    if (!el) {
        el = el_init("zash", stdin, stderr, stderr);
        el_hist = history_init();
        if (!el || !el_hist)
            return nullptr;
        history(el_hist, &ev, H_SETSIZE, 100000);
        el_set(el, EL_HIST, history, el_hist);
        el_set(el, EL_PROMPT_ESC, prompt_cb, PROMPT_MARK);
        el_set(el, EL_SIGNAL, 0);
        el_source(el, nullptr);
    }
    el_set(el, EL_EDITOR, opt.vi ? "vi" : "emacs");
    history(el_hist, &ev, H_CLEAR);
    for (int i = 0; i < hist_count(); i++)
        history(el_hist, &ev, H_ENTER, hist_entry(i));

    free(cur_prompt);
    cur_prompt = prompt_marked(prompt);
    for (;;) {
        int n = 0;
        const char *s = el_gets(el, &n);
        if (s && n > 0) {
            size_t k = (size_t)n;
            while (k && (s[k - 1] == '\n' || s[k - 1] == '\r'))
                k--;
            free(line);
            line = xmalloc(k + 1);
            memcpy(line, s, k);
            line[k] = '\0';
            *len = k;
            return line;
        }
        if (n < 0 && errno == EINTR) {
            trap_poll(); /* ^C abandons the line and does not return */
            continue;
        }
        return nullptr;
    }
}

int edit_bind(const char *spec) {
    sh_warn("bind: %s: this editor reads its bindings from ~/.editrc", spec);
    return -1;
}

void edit_bind_list(void) {
    sh_warn("bind: -l: this editor reads its bindings from ~/.editrc");
}