diff options
| author | Sean Kurtz <seankurtz75@gmail.com> | 2026-11-25 20:41:27 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-11-25 20:41:27 -0600 |
| commit | 31f697b4e619504ab894e064092528f7f73d565d (patch) | |
| tree | a05698851d28feb88d9bcf95a3530792b719b16b | |
| parent | 456955dc33f24b1e9857bdc3c11788a2358e954c (diff) | |
| parent | deb0ed011fe2cfc7058facb3f63b7feaeb8d4a8e (diff) | |
| download | zash-31f697b4e619504ab894e064092528f7f73d565d.tar.gz | |
Merge pull request #33 from skurtz97/feat/prompt-width
interactive: a prompt's width counts columns, not bytes
| -rw-r--r-- | DESIGN.md | 12 | ||||
| -rw-r--r-- | Makefile | 9 | ||||
| -rw-r--r-- | bench/README.md | 34 | ||||
| -rw-r--r-- | bench/editor.py | 99 | ||||
| -rw-r--r-- | bench/probes/fk3.c | 11 | ||||
| -rw-r--r-- | src/edit_builtin.c | 13 | ||||
| -rw-r--r-- | src/edit_libedit.c | 86 | ||||
| -rw-r--r-- | src/interact.c | 60 | ||||
| -rw-r--r-- | src/interact.h | 8 | ||||
| -rw-r--r-- | tests/linux/i-prompt-esc.exp | 4 | ||||
| -rw-r--r-- | tests/linux/i-prompt-esc.sh | 21 |
11 files changed, 338 insertions, 19 deletions
@@ -927,9 +927,19 @@ interactive shell?" has insert and command modes with counts, the common motions, `d c y` with motions, `x X r ~ D C S p P u`, history with `k j G / ? n N`. UTF-8 is handled as far as single-width characters. +- Prompt width (`esc_seq_len()` in `interact.c`, shared with the libedit + build). A prompt is measured by skipping the sequences a terminal + understands, so that colour and titles take no columns. That is more + than CSI: an OSC title or hyperlink runs to BEL or `ESC \`, DCS runs + the same way, and `tput sgr0` is the three-byte `ESC ( B` before + `ESC [ m`, so a prompt built with `$(tput ...)` is measured right. - libedit (`edit_libedit.c`) implements the same two functions: `make EDIT=libedit LDLIBS=-ledit`. The shell's own history list stays - authoritative and is copied into libedit before each line. + authoritative and is copied into libedit before each line. Control + sequences in the prompt are bracketed for `EL_PROMPT_ESC` so that + colour does not count as columns. A prompt that ends with such a + sequence gains a space: libedit attaches a literal run to the character + after it and would otherwise drop the last one. - Completion (`complete.c`) covers variables after `$`, aliases, functions, builtins and `PATH` programs in command position, and files elsewhere, with `/` after a directory. Completed text is @@ -49,7 +49,10 @@ CC = clang CSTD = -std=c23 WARN = -Wall -Wextra -Wshadow -Wstrict-prototypes -Wmissing-prototypes \ -Wconversion -Wno-sign-conversion -OPT = -O2 +# Release and fuzz builds at -O3. The sanitizer and coverage builds stay +# low on purpose: inlined frames make their reports harder to read than the +# few percent they would gain. +OPT = -O3 CFLAGS = $(CSTD) $(WARN) $(OPT) -g CPPFLAGS = -D_XOPEN_SOURCE=700 LDFLAGS = @@ -64,7 +67,7 @@ ZCC = ibm-clang # the linklist instead of the LPA. With the run-time LPA-resident the two # widths cost the same, so the shell is built at the width IBM builds for. # bench/README.md and notes/investigation.md have the measurements. -ZCFLAGS = $(CSTD) $(WARN) -O2 -m64 +ZCFLAGS = $(CSTD) $(WARN) -O3 -m64 # _POSIX_C_SOURCE=200809L: z/OS exposes SUSv4 names only through it # (_XOPEN_SOURCE 700 is not accepted). _EXT: IBM extensions (fetch()). @@ -316,7 +319,7 @@ zos-lint: # Fuzz the MVS decoders (needs clang with libFuzzer): FUZZTIME seconds. FUZZTIME = 60 fuzz-mvsfmt: fuzz/mvsfmt.c src/mvsfmt.c src/mvsfmt.h src/charset.h - $(CC) $(CSTD) $(WARN) -g -O1 -fsanitize=fuzzer,address,undefined \ + $(CC) $(CSTD) $(WARN) -g -O3 -fsanitize=fuzzer,address,undefined \ -fno-sanitize-recover=all -o $@ fuzz/mvsfmt.c src/mvsfmt.c fuzz: fuzz-mvsfmt diff --git a/bench/README.md b/bench/README.md index 2249e3c..f70dd06 100644 --- a/bench/README.md +++ b/bench/README.md @@ -305,6 +305,40 @@ The clock is `tests/tools/now.c`, ten lines, because `/bin/date` on z/OS has no sub-second format. `BENCH_N` sets the number of starts, and `BENCH_NOW` points at a different clock. +## The line editor + +`EDIT=libedit` replaces the built-in editor with libedit, and the two +costs it changes are both in the interactive path, which `run.sh` and +`startup.sh` do not touch. `editor.py` measures them on a +pseudo-terminal: `BENCH_N` starts, each timed from just before the fork +to the first byte of the prompt, then `BENCH_KEYS` keys typed one at a +time, each timed from the write to its echo. + +```sh +make EDIT=libedit LDLIBS=-ledit # writes ./zash, keep a copy +cp zash zash-libedit && make zash # the built-in one +python3 bench/editor.py ./zash ./zash-libedit +``` + +Linux, both `-O3`, 20 and then 50 starts, keys medians of 200: + +| editor | start | one key | +| --- | --- | --- | +| built-in | 0.94-1.02 ms | 7.2-8.5 us | +| libedit | 1.20-1.27 ms | 7.2-7.4 us | + +libedit pays about a third of a millisecond more to get to the prompt: +three more shared libraries to load (libedit, ncurses, and the terminfo +entry it reads), `el_init()`, an `~/.editrc` attempt, and the copy of +the shell's history into libedit. Every key costs the same either way; +the round trip is the terminal driver and the scheduler, and the editor's +own work on a key is too small to see through that. + +So the built-in editor wins a start that never edits, which is the case +`make check` and a `#!` line are; for a session spent typing, the two are +the same. Neither forks or execs per key, which is the cost that would +have mattered. + ## Address mode: 64-bit now zash is built 64-bit (AMODE 64) XPLINK, which is what the z/OS Makefile diff --git a/bench/editor.py b/bench/editor.py new file mode 100644 index 0000000..6e99cdf --- /dev/null +++ b/bench/editor.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""What the line editor costs: start to first prompt, then one key. + + bench/editor.py ./zash ./zash-libedit [more shells ...] + +Each shell is started BENCH_N times (default 20) on a pseudo-terminal, the +wall clock is read from just before the fork to the first byte of the +prompt, and then BENCH_KEYS keys (default 200) are typed one at a time, +timing each write to its echo. The median of each is reported. + +The fork itself is part of the start figure for every shell, so the +comparison is fair, but the absolute column is a little high. A key's +round trip is dominated by the terminal driver and the scheduler, which +both shells pay alike; what the numbers separate is the editor's own +work on each key. +""" +import fcntl +import os +import pty +import select +import statistics +import struct +import sys +import termios +import time +from contextlib import suppress + + +def env_int(name, default): + """A count from the environment, or the default.""" + value = os.environ.get(name) + return int(value) if value else default + + +TRIALS = env_int("BENCH_N", 20) +KEYS = env_int("BENCH_KEYS", 200) + + +def wait_output(fd, secs=5.0): + """Read one non-empty chunk of output, or fail.""" + end = time.perf_counter() + secs + while True: + left = end - time.perf_counter() + r, _, _ = select.select([fd], [], [], max(left, 0)) + if not r: + raise SystemExit("editor.py: no output from the shell") + try: + if os.read(fd, 4096): + return + except OSError: + raise SystemExit("editor.py: the shell exited") from None + + +def one_trial(exe): + """Return (seconds to first prompt, seconds per key).""" + start = time.perf_counter() + pid, fd = pty.fork() + if pid == 0: + os.environ.update(TERM="vt100", PS1="> ", PS2="> ", ENV="", + HOME=os.getcwd()) + os.execv(exe, [exe, "-i"]) # noqa: S606 - the shell under test + fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", 24, 80, 0, 0)) + wait_output(fd) + startup = time.perf_counter() - start + + for _ in range(10): + os.write(fd, b"a") + wait_output(fd) + keys = [] + for _ in range(KEYS): + t = time.perf_counter() + os.write(fd, b"a") + wait_output(fd) + keys.append(time.perf_counter() - t) + os.write(fd, b"\x15exit\r") + with suppress(ChildProcessError): + os.waitpid(pid, 0) + os.close(fd) + return startup, statistics.median(keys) + + +def main(): + shells = sys.argv[1:] + if not shells: + raise SystemExit("usage: bench/editor.py shell [shell ...]") + print(f"{'shell':<24} {'start ms':>10} {'key us':>10}") + for exe in shells: + starts, keys = [], [] + for _ in range(TRIALS): + s, k = one_trial(exe) + starts.append(s) + keys.append(k) + print(f"{exe:<24} " + f"{statistics.median(starts) * 1e3:>10.2f} " + f"{statistics.median(keys) * 1e6:>10.1f}") + + +if __name__ == "__main__": + main() diff --git a/bench/probes/fk3.c b/bench/probes/fk3.c index 2030f66..f4ec71b 100644 --- a/bench/probes/fk3.c +++ b/bench/probes/fk3.c @@ -24,7 +24,10 @@ int main(int argc, char **argv) { if (mb > 0) { p = malloc((size_t)mb * 1024 * 1024); - if (!p) { printf("malloc failed\n"); return 1; } + if (!p) { + printf("malloc failed\n"); + return 1; + } memset(p, 'x', (size_t)mb * 1024 * 1024); } @@ -32,7 +35,8 @@ int main(int argc, char **argv) { times(&a); for (int i = 0; i < n; i++) { pid_t c = fork(); - if (c == 0) _exit(0); + if (c == 0) + _exit(0); int st; waitpid(c, &st, 0); } @@ -42,7 +46,8 @@ int main(int argc, char **argv) { (b.tms_cutime - a.tms_cutime) + (b.tms_cstime - a.tms_cstime); printf(" %4ld MB: %6.2f s (%5.2f ms per fork)", mb, (double)t / 100.0, (double)t / 100.0 * 1000.0 / n); - if (p) printf(" [p[0]=%c]", p[0]); + if (p) + printf(" [p[0]=%c]", p[0]); printf("\n"); return 0; } diff --git a/src/edit_builtin.c b/src/edit_builtin.c index 4b8904b..4ae0bb2 100644 --- a/src/edit_builtin.c +++ b/src/edit_builtin.c @@ -299,7 +299,10 @@ static size_t word_right(size_t pos) { /** * @brief Columns a prompt occupies on screen. * - * Colour and other ANSI control sequences in the prompt take no room. + * Control sequences in the prompt are for the terminal, not the screen: + * colour, a title, a character-set reset from `tput`, a hyperlink. They + * are skipped, including the ones a terminal's terminfo entry writes as + * more than `ESC [` and a final byte. * * @param s The prompt (one line). * @return Its width in columns. @@ -307,12 +310,8 @@ static size_t word_right(size_t pos) { 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++; + if (*s == CH_ESC) { + s += esc_seq_len(s); continue; } w += cell_width(*s) ? 1 : 0; diff --git a/src/edit_libedit.c b/src/edit_libedit.c index d9282fc..a76844a 100644 --- a/src/edit_libedit.c +++ b/src/edit_libedit.c @@ -16,6 +16,12 @@ * 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> @@ -24,10 +30,14 @@ #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. */ @@ -37,9 +47,74 @@ static EditLine *el; */ static History *el_hist; /** - * @brief The prompt for the line being read. + * @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 const char *cur_prompt = ""; +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. @@ -48,7 +123,7 @@ static const char *cur_prompt = ""; */ static char *prompt_cb(EditLine *e) { (void)e; - return (char *)cur_prompt; + return cur_prompt ? cur_prompt : ""; } /** @@ -80,7 +155,7 @@ char *edit_readline(const char *prompt, size_t *len) { return nullptr; history(el_hist, &ev, H_SETSIZE, 100000); el_set(el, EL_HIST, history, el_hist); - el_set(el, EL_PROMPT, prompt_cb); + el_set(el, EL_PROMPT_ESC, prompt_cb, PROMPT_MARK); el_set(el, EL_SIGNAL, 0); el_source(el, nullptr); } @@ -89,7 +164,8 @@ char *edit_readline(const char *prompt, size_t *len) { for (int i = 0; i < hist_count(); i++) history(el_hist, &ev, H_ENTER, hist_entry(i)); - cur_prompt = prompt; + free(cur_prompt); + cur_prompt = prompt_marked(prompt); for (;;) { int n = 0; const char *s = el_gets(el, &n); diff --git a/src/interact.c b/src/interact.c index 4311596..575e057 100644 --- a/src/interact.c +++ b/src/interact.c @@ -8,6 +8,7 @@ * editing options is on and the terminal can do it) and records the line * in the history. */ +#include <ctype.h> #include <errno.h> #include <limits.h> #include <pwd.h> @@ -39,6 +40,65 @@ static void put_protected(strbuf *sb, const char *s) { } /** + * @brief Does this byte end a terminal control sequence? + * + * The final byte of a CSI sequence is a letter or one of the symbols + * below; the parameters and intermediates that come first are digits + * and punctuation. Spelled as characters, not as a byte range, so the + * EBCDIC build reads its own prompts the same way. + * + * @param c Candidate byte. + * @return true if it ends the sequence. + */ +static bool esc_final(char c) { + return isalpha((unsigned char)c) || + (c && strchr("@[\\]^_`{|}~", c) != nullptr); +} + +/** + * @brief Length of the terminal control sequence that starts at s. + * + * A prompt's sequences come from the terminal's terminfo entry, from + * another shell's configuration, or from whatever a search turned up, so + * every form is expected: CSI (`ESC [`, parameters and intermediates to + * a final byte), OSC (`ESC ]`, to BEL or `ESC \` and used for titles and + * hyperlinks), DCS and its relatives (to `ESC \`), and the two- and + * three-byte escapes. The three-byte ones matter: `tput sgr0` is + * `ESC ( B ESC [ m`, and `ESC ( B` resets the character set back to + * ASCII, so a prompt built with `$(tput ...)` contains it. An + * unfinished sequence runs to the end of the text. + * + * @param s Text starting with CH_ESC. + * @return Number of bytes in the sequence, at least 1. + */ +size_t esc_seq_len(const char *s) { + size_t i = 1; + if (!s[i]) + return i; + if (s[i] == '[') { /* CSI */ + for (i++; s[i] && !esc_final(s[i]); i++) + ; + return s[i] ? i + 1 : i; + } + if (s[i] == ']' || s[i] == 'P' || s[i] == 'X' || s[i] == '^' || + s[i] == '_') { /* OSC, DCS, SOS, PM, APC: to ST */ + for (i++; s[i]; i++) { + if (s[i] == '\a') + return i + 1; + if (s[i] == CH_ESC && s[i + 1] == '\\') + return i + 2; + } + return i; + } + if (strchr(" !\"#$%&'()*+,-./", s[i])) { /* ESC ( B, ESC # 8, ... */ + for (i++; s[i] && !esc_final(s[i]); i++) + ; + return s[i] ? i + 1 : i; + } + return i + 1; /* ESC 7, ESC =, ESC > */ +} + +/** * @brief Replace the FreeBSD-style backslash escapes of a prompt string. * * | Escape | Becomes | diff --git a/src/interact.h b/src/interact.h index 09a5393..065de38 100644 --- a/src/interact.h +++ b/src/interact.h @@ -60,6 +60,14 @@ typedef struct completion { } completion; const char *expand_quietly(const char *raw, bool escapes); + +/** + * @brief Length of the terminal control sequence at s, which is ESC. + * @param s Text starting with the escape character. + * @return Bytes in the sequence; control sequences in a prompt are for + * the terminal, not for the screen, so they take no columns. + */ +size_t esc_seq_len(const char *s); void complete_line(const char *line, size_t cursor, completion *c); void complete_free(completion *c); diff --git a/tests/linux/i-prompt-esc.exp b/tests/linux/i-prompt-esc.exp new file mode 100644 index 0000000..0d6e3de --- /dev/null +++ b/tests/linux/i-prompt-esc.exp @@ -0,0 +1,4 @@ +$ 32mP\e[0m> ' +]0;t(BP> Xabcdefghijklmn +]0;t(BP> exit +[status 0] diff --git a/tests/linux/i-prompt-esc.sh b/tests/linux/i-prompt-esc.sh new file mode 100644 index 0000000..18efd07 --- /dev/null +++ b/tests/linux/i-prompt-esc.sh @@ -0,0 +1,21 @@ +# Interactive: a prompt carrying sequences that are not just SGR. +# +# A terminal title (OSC, ended by BEL) and the charset reset plus colour +# that `tput sgr0` writes (`ESC ( B ESC [ m`) both come from a terminal's +# terminfo entry, and a prompt copied from elsewhere is full of them. +# None of them takes a column, so the line scrolls where a plain prompt +# of the same width would: a width rule that knows only `ESC [ ... m` +# counts the title and the `(B` as text, keeps 7 columns too few, and the +# redraw after ^A shows a shorter window than this expectation. +command -v python3 >/dev/null 2>&1 || exit 77 +python3 "$TESTS/tools/ptydrive.py" -c 16 "$TSH" <<'END' +send PS1='\\e]0;t\x07\\e(B\\e[1;32mP\\e[0m> '\r +expect P> +send abcdefghijklmn +send \x01 +send X +expect Xabcdefghijk +send \x03 +expect P> +send exit\r +END |
