rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
# rustimal shell integration. Regenerated on every launch; edits will be lost.
# Loaded once through PROMPT_COMMAND so the normal Git Bash login setup still runs.

__RUSTIMAL=1
export -n PROMPT_COMMAND
__rustimal_first=1

# rustimal keeps $RUSTIMAL_STATE/winpath holding the Windows PATH from the
# registry. When an installer changes it, swap the new one into this shell's
# PATH (Git Bash's own folders stay in front), so no restart is needed.
__rustimal_syncpath() {
    local f="$RUSTIMAL_STATE/winpath" win="" new
    [ -n "$RUSTIMAL_STATE" ] && [ -r "$f" ] || return 0
    IFS= read -r win <"$f"
    [ -n "$win" ] || return 0
    if [ -z "${__rustimal_winpath+x}" ]; then
        __rustimal_winpath="$win"
        return 0
    fi
    [ "$win" = "$__rustimal_winpath" ] && return 0
    __rustimal_winpath="$win"
    new=$(cygpath -u -p "$win" 2>/dev/null) || return 0
    [ -n "$new" ] || return 0
    if [ -n "$ORIGINAL_PATH" ] && [[ ":$PATH:" == *":$ORIGINAL_PATH:"* ]]; then
        PATH=":$PATH:"
        PATH="${PATH/":$ORIGINAL_PATH:"/":$new:"}"
        PATH="${PATH#:}"
        PATH="${PATH%:}"
    else
        # PATH was rearranged by a profile script; just add what's missing.
        local e parts
        IFS=: read -ra parts <<<"$new"
        for e in "${parts[@]}"; do
            [[ -z "$e" || ":$PATH:" == *":$e:"* ]] || PATH+=":$e"
        done
    fi
    ORIGINAL_PATH="$new"
    hash -r
}

__rustimal_prompt() {
    local code=$? d="$PWD" head="" chev="35"
    __rustimal_syncpath
    if [ -n "$__rustimal_autocd" ]; then
        __rustimal_autocd=
        # Through eval, so that the `ls` alias applies (`ls -F --color=auto`): aliases are not
        # expanded inside a function, and the listing would come out plain and gray.
        eval ls
    fi
    while :; do
        if [ -f "$d/.git/HEAD" ]; then
            read -r head <"$d/.git/HEAD"
            break
        fi
        [ -z "$d" ] || [ "$d" = "/" ] && break
        d="${d%/*}"
    done
    case "$head" in
        "ref: refs/heads/"*) __rustimal_branch="${head#ref: refs/heads/}" ;;
        "") __rustimal_branch="" ;;
        *) __rustimal_branch="${head:0:7}" ;;
    esac
    # Full path with $HOME shown as ~; the last segment is highlighted.
    local p="$PWD" tilde='~'
    case "$PWD" in
        "$HOME") p="$tilde" ;;
        "$HOME"/*) p="$tilde${PWD#"$HOME"}" ;;
    esac
    case "$p" in
        / | "$tilde") __rustimal_parent="" __rustimal_dir="$p" ;;
        */*) __rustimal_parent="${p%/*}/" __rustimal_dir="${p##*/}" ;;
        *) __rustimal_parent="" __rustimal_dir="$p" ;;
    esac
    [ "$code" -ne 0 ] && chev="31"

    # Tell rustimal where we are (shown in the header, used for new splits).
    printf '\e]2;rustimal:%s\a' "$PWD"

    local sep='\n'
    if [ -n "$__rustimal_first" ]; then
        sep=''
        unset __rustimal_first
        # One-time tip (set by rustimal on the first run that isn't installed yet).
        if [ -n "$RUSTIMAL_HINT" ]; then
            unset RUSTIMAL_HINT
            printf '\e[90mTip: run \e[0m\e[36mrustimal --install\e[0m\e[90m to add the Start menu, Win+R and right-click entries.\e[0m\n'
        fi
    fi
    # Directory and branch are referenced, not interpolated, so odd folder names stay inert.
    PS1="${sep}\[\e[36m\]\${__rustimal_parent}\[\e[1;36m\]\${__rustimal_dir}\[\e[0m\]"
    if [ -n "$__rustimal_branch" ]; then
        PS1+=" \[\e[90m\]\${__rustimal_branch}\[\e[0m\]"
    fi
    PS1+=" \[\e[${chev}m\]❯\[\e[0m\] "
    __rustimal_armed=1
}
PROMPT_COMMAND=__rustimal_prompt

# Typing just a name does the obvious thing, as long as it isn't also a command (a real
# command, alias or function always wins):
#   folder        change into it, then list it (autocd, plus the `ls` above)
#   text file     print it
#   program       run it (.exe, .bat, scripts with the executable bit or a #! line)
#   other file    open it with its default app
# Bash calls this handler only when no command of that name exists.
shopt -s autocd 2>/dev/null

# Tab-Tab lists what can be completed. Readline draws that list in the plain text color
# unless told to color it as `ls` does (folders blue, programs green) and to add its
# markers (`/` after a folder). Only turned on where they are off, so a choice made in
# ~/.inputrc to have them on is not touched.
bind 'set colored-stats on' 2>/dev/null
bind 'set colored-completion-prefix on' 2>/dev/null
bind 'set visible-stats on' 2>/dev/null

command_not_found_handle() {
    local f="$1"
    if [ -f "$f" ]; then
        if [ -x "$f" ]; then
            "./$f" "${@:2}"
            return $?
        elif [ $# -eq 1 ]; then
            if [ ! -s "$f" ] || { [ "$(stat -c %s -- "$f")" -le 1048576 ] && grep -Iq . -- "$f"; }; then
                cat -- "$f"
            else
                open "$f"
            fi
            return $?
        fi
    fi
    printf 'bash: %s: command not found\n' "$1" >&2
    return 127
}

# VS Code in the pane. Its server has license terms of its own, which are asked about once
# and never accepted for anyone.
__rustimal_code_ready() {
    [ -n "$RUSTIMAL_REVIEW_TOKEN" ] && [ -n "$RUSTIMAL_STATE" ] && [ -t 0 ] && [ -t 1 ]
}

# Ask rustimal to open something here: `open` or `vscode`, a path, and maybe line[:column].
__rustimal_code_send() {
    printf '%s\n%s\n' "$(cygpath -aw -- "$2")" "$3" >"$RUSTIMAL_STATE/code-$RUSTIMAL_PANE.txt" || return
    printf '\e]2;__rustimal_code__:%s:%s|%s\a' "$RUSTIMAL_REVIEW_TOKEN" "$PWD" "$1"
    local answer
    if ! IFS= read -rs -t 3 answer; then
        printf 'rustimal did not answer; if you just updated it, open a new window\n' >&2
        return 1
    fi
}

# `vscode`, `vscode folder`, `vscode file`, `vscode file:20:5`: VS Code in this pane, and
# Ctrl+Shift+I switches between it and the terminal. Options (`vscode --diff a b`) and use
# outside a rustimal pane go to the VS Code you have installed (`code`).
vscode() {
    if [[ $# -gt 1 || "$1" == -* ]] || ! __rustimal_code_ready; then
        command code "${@:-.}"
        return
    fi
    local target="${1:-.}" at=""
    if [ ! -e "$target" ]; then
        if [[ "$target" =~ ^(.+):([0-9]+:[0-9]+)$ && -f "${BASH_REMATCH[1]}" ]] ||
            [[ "$target" =~ ^(.+):([0-9]+)$ && -f "${BASH_REMATCH[1]}" ]]; then
            target="${BASH_REMATCH[1]}" at="${BASH_REMATCH[2]}"
        else
            printf 'vscode: %s: no such file or folder\n' "$target" >&2
            return 1
        fi
    fi
    local accepted="$RUSTIMAL_STATE/vscode-license-accepted"
    if [ ! -f "$accepted" ]; then
        printf "VS Code runs in this pane through Microsoft's VS Code Server, which is downloaded\n"
        printf 'from Microsoft the first time and has license terms of its own:\n'
        printf '  https://aka.ms/vscode-server-license\n'
        local reply=""
        read -rp 'Do you accept them? [y/N] ' reply
        if [[ "$reply" != [yY] && "$reply" != [yY][eE][sS] ]]; then
            printf 'Not accepted, so nothing was started. `code` still opens your installed VS Code.\n'
            return 1
        fi
        : >"$accepted" || return
    fi
    __rustimal_code_send vscode "$target" "$at"
}

# Should `open` show this file in the pane? Text files, once VS Code's license has been
# accepted; web pages, pictures and scripts Windows would run keep their usual app.
__rustimal_open_here() {
    __rustimal_code_ready && [ -f "$RUSTIMAL_STATE/vscode-license-accepted" ] && [ -f "$1" ] || return 1
    case "${1,,}" in
        *.html | *.htm | *.svg | *.bat | *.cmd | *.exe | *.com | *.lnk | *.msi) return 1 ;;
    esac
    [ ! -s "$1" ] || grep -Iq . -- "$1"
}

# `open` opens the current folder in Explorer; `open path` opens a file or folder with
# its default app, `open https://...` opens a URL, and `open file:20` (or `file:20:5`) opens
# the file in your editor at that line. In a rustimal pane, text files open in VS Code there
# (once `vscode` has been set up).
open() {
    local t m
    [ $# -eq 0 ] && set -- .
    for t in "$@"; do
        case "$t" in
            *://*) ;;
            *)
                # file:LINE or file:LINE:COL (the longer form first, as `.+` is greedy)
                m=""
                if [ ! -e "$t" ] && [ -x "$RUSTIMAL_EXE" ]; then
                    if [[ "$t" =~ ^(.+):([0-9]+):([0-9]+)$ ]]; then m=1; else [[ "$t" =~ ^(.+):([0-9]+)$ ]] && m=1; fi
                fi
                if [ -n "$m" ] && [ -f "${BASH_REMATCH[1]}" ] && __rustimal_open_here "${BASH_REMATCH[1]}"; then
                    __rustimal_code_send open "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}${BASH_REMATCH[3]:+:${BASH_REMATCH[3]}}"
                    continue
                fi
                if [ -n "$m" ] && [ -f "${BASH_REMATCH[1]}" ]; then
                    "$RUSTIMAL_EXE" --open "$(cygpath -aw -- "${BASH_REMATCH[1]}")" "${BASH_REMATCH[2]}" ${BASH_REMATCH[3]:+"${BASH_REMATCH[3]}"}
                    continue
                fi
                # file:LINE that couldn't be opened at that line: open the plain file if it
                # exists, otherwise say so (cygpath would turn the ":" into "file50").
                if [ ! -e "$t" ] && [[ "$t" =~ ^(.+):([0-9]+)(:[0-9]+)?$ ]]; then
                    if [ -e "${BASH_REMATCH[1]}" ]; then
                        t="${BASH_REMATCH[1]}"
                    else
                        printf 'open: %s: no such file
' "$t" >&2
                        continue
                    fi
                fi
                if __rustimal_open_here "$t"; then
                    __rustimal_code_send open "$t" ""
                    continue
                fi
                t=$(cygpath -w -- "$t" 2>/dev/null || printf '%s' "$t") ;;
        esac
        cmd.exe //c start "" "$t"
    done
}

# `claude` with no arguments asks rustimal to show its session picker,
# then reads the choice back: a session id, "new", or an empty line to cancel.
claude() {
    if [ $# -eq 0 ] && [ -t 0 ] && [ -t 1 ]; then
        printf '\e]2;__rustimal_pick__:%s\a' "$PWD"
        local choice=""
        IFS= read -rs choice
        case "$choice" in
            "") return 0 ;;
            new) ;;
            *) set -- --resume "$choice" ;;
        esac
    fi
    printf '\e]2;__rustimal_claude__\a\e[H\e[2J'
    if [ -n "$RUSTIMAL_CLAUDE_SETTINGS" ] && [ -f "$RUSTIMAL_CLAUDE_SETTINGS" ]; then
        set -- --settings "$RUSTIMAL_CLAUDE_SETTINGS" "$@"
    fi
    command claude "$@"
}

# `t3` shows the T3 Code conversation for this folder in this pane: `t3`, `t3 ./folder`,
# `t3 -l` to list them and `t3 2` to open one. Anything else goes to T3 Code's own CLI
# (`t3 pair`, ...), so a folder has to be written as a path to not be taken for a command.
# T3 Code doesn't have to be open; if no server runs, one is started out of sight, and
# `t3 stop` ends it.
t3() {
    local dir="$PWD" number=""
    case $#:$1 in
        0:) ;;
        *:-l | *:--list | 1:stop)
            "$RUSTIMAL_EXE" --t3 "$@"
            return ;;
        1:*[!0-9]* | 1:)
            if ! { [[ "$1" == . || "$1" == .. || "$1" == */* || "$1" == *\\* ]] && [ -d "$1" ]; }; then
                __rustimal_t3cli "$@"
                return
            fi
            dir=$(cd -- "$1" && pwd) || return ;;
        1:*) number="$1" ;;
        *)
            __rustimal_t3cli "$@"
            return ;;
    esac
    if [ -z "$RUSTIMAL_REVIEW_TOKEN" ] || [ ! -t 0 ] || [ ! -t 1 ]; then
        "$RUSTIMAL_EXE" --t3 ${number:+"$number"} "$(cygpath -aw -- "$dir")"
        return
    fi
    printf '\e]2;__rustimal_t3__:%s:%s|%s\a' "$RUSTIMAL_REVIEW_TOKEN" "$dir" "$number"
    # Wait for rustimal to answer, as `review` does.
    local answer
    if ! IFS= read -rs -t 3 answer; then
        printf 'rustimal did not answer; if you just updated it, open a new window\n' >&2
        return 1
    fi
}

# `embed COMMAND [ARGS]` runs the command and shows the window it opens inside this pane: a
# Tauri or Electron app, any program with a window. The prompt is back at once, so the
# shell stays yours: Ctrl+Shift+T switches between the program and the terminal, and
# Ctrl+Shift+W closes the program. Its output goes to a file in rustimal's folder (the
# path is printed). The window is looked for among the command's own processes, so
# `embed npm run tauri dev` finds the app the dev server starts.
#
#   embed                  with nothing else: the Tauri or Electron app of this folder
#   embed ./app.exe        anything else
#   embed -f COMMAND       keep the shell waiting for it, with its output here (a dev
#                          server whose log you read, say)
#   embed browser [PAGE]   a Firefox-based browser; see `browser`, `zen` and `search`
#   embed fork [FOLDER]    Fork, the Git client; see `fork`
embed() {
    local foreground="" quiet=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -f | --foreground) foreground=1 ;;
            --quiet) quiet=1 ;;
            *) break ;;
        esac
        shift
    done
    local kind="" rest=()
    if [ "$1" = browser ] || [ "$1" = fork ]; then
        kind="$1" quiet=1
        shift
        rest=("$@")
    elif [ $# -eq 0 ]; then
        if [ -f src-tauri/tauri.conf.json ] || [ -f tauri.conf.json ]; then
            if grep -q '"tauri"' package.json 2>/dev/null; then
                set -- npm run tauri dev
            else
                set -- cargo tauri dev
            fi
        elif grep -q '"electron"' package.json 2>/dev/null; then
            set -- npm start
        else
            printf 'usage: embed [-f] COMMAND [ARGS] | embed browser [PAGE] | embed fork [FOLDER]\n' >&2
            printf '       (with no command, in a Tauri or Electron project, its app is run)\n' >&2
            return 2
        fi
        rest=("$@")
    else
        rest=("$@")
    fi
    local winpid="" reuse=""
    if [ -n "$RUSTIMAL_REVIEW_TOKEN" ] && [ -t 0 ] && [ -t 1 ]; then
        winpid=$(cat "/proc/$$/winpid" 2>/dev/null)
    fi
    if [ -n "$winpid" ]; then
        printf '\e]2;__rustimal_embed__:%s:%s|start:%s%s\a' "$RUSTIMAL_REVIEW_TOKEN" "$PWD" "$winpid" "${kind:+:$kind}"
        # Wait for rustimal to answer, as `review` does. It says "reuse" when a program of
        # this kind (the browser, Fork) is already in this pane: what is asked for then goes to
        # that one, which comes to the front.
        local answer
        if ! IFS= read -rs -t 3 answer; then
            printf 'rustimal did not answer; if you just updated it, open a new window\n' >&2
            return 1
        fi
        [ "$answer" = reuse ] && reuse=1
    fi
    if [ -n "$kind" ]; then
        set -- "${RUSTIMAL_EXE:-rustimal}" "--$kind" ${reuse:+--reuse} "${rest[@]}"
    else
        set -- "${rest[@]}"
    fi
    # Outside a rustimal pane there is no window to wait for, and a program is run as usual.
    if [ -n "$foreground" ] || { [ -z "$winpid" ] && [ -z "$kind" ]; }; then
        "$@"
        return
    fi
    local log=/dev/null
    if [ -z "$quiet" ] && [ -n "$RUSTIMAL_STATE" ] && [ -n "$RUSTIMAL_PANE" ]; then
        log="$RUSTIMAL_STATE/embed-$RUSTIMAL_PANE.log"
        printf 'embed: running in the background; its output is in %s\n' "$log"
    fi
    # A child of this shell, so that its window is found; the braces keep the shell from
    # announcing the job.
    { "$@" </dev/null >"$log" 2>&1 & disown $!; } 2>/dev/null
    return 0
}

# `browser [PAGE]` (or `zen`) shows your Firefox-based browser in this pane: Zen if it is
# installed, else Firefox. Something that is not an address is looked up with its search
# engine: `zen rust window embedding`, or `search ...`. If the browser is already open in
# this pane, the page opens in it and it comes to the front. The prompt is back at once:
# Ctrl+Shift+T switches between the browser and the terminal, Ctrl+Shift+W closes it.
# Outside a rustimal pane they just start the browser. See `embed`.
browser() {
    embed browser "$@"
}

zen() {
    embed browser "$@"
}

search() {
    if [ $# -eq 0 ]; then
        printf 'usage: search TERMS...\n' >&2
        return 2
    fi
    embed browser --search "$@"
}

# `fork [FOLDER]` shows Fork, the Git client, in this pane, on the repository of the folder (this
# one by default): a quick look at history and changes, where `pr` and the review panel are
# more than is needed. Fork runs once, so `fork` again in this pane brings the one that is open
# to the front, on the new folder. The prompt is back at once; Ctrl+Shift+T switches and
# Ctrl+Shift+W closes it. If Fork is already open on the desktop, it takes the folder there.
fork() {
    embed fork "$@"
}

__rustimal_t3cli() {
    local cli
    cli=$(type -P t3) || cli="${T3CODE_HOME:-$HOME/.t3}/bin/t3.cmd"
    "$cli" "$@"
}

# `review` opens the review panel: the current branch, or `review 12` (a pull request),
# `review my-branch`, `review a1b2c3d`, `review --uncommitted`, `review demo`. With
# --print (or --json, --prs, --explain, --help, or piped) it prints here instead.
__rustimal_panel() {
    printf '\e]2;__rustimal_review__:%s:%s|%s\a' "$RUSTIMAL_REVIEW_TOKEN" "$PWD" "$*"
    # Wait for rustimal to answer. Windows' console passes on only the latest of titles set
    # in quick succession, so the next prompt's title could otherwise replace this one.
    local answer
    if ! IFS= read -rs -t 3 answer; then
        printf 'rustimal did not answer; `review --print` shows the review here instead\n' >&2
        return 1
    fi
}

review() {
    case " $* " in
        *" --print "* | *" --json "* | *" --prs "* | *" --explain "* | *" --help "* | *" -h "* | *" --diff "* | *" --desc "*)
            "$RUSTIMAL_EXE" --review "$@"
            return ;;
    esac
    if [ -n "$RUSTIMAL_REVIEW_TOKEN" ] && [ -t 1 ]; then
        __rustimal_panel "$@"
    else
        "$RUSTIMAL_EXE" --review "$@"
    fi
}

# `pr` lists the pull requests (and branches and commits) to pick one to review,
# `pr 12` reviews that one, and `pr new [BRANCH]` opens one for a branch. There is also a coreutils `pr`, which lays out text for
# printing; any other use of the name still runs it.
pr() {
    if [ -n "$RUSTIMAL_REVIEW_TOKEN" ] && [ -t 0 ] && [ -t 1 ]; then
        if [ $# -eq 0 ]; then
            __rustimal_panel
            return
        fi
        if [ $# -ge 1 ] && [ $# -le 2 ] && [ ! -e "$1" ] && [ "$1" = new ]; then
            __rustimal_panel --new ${2:+"$2"}
            return
        fi
        if [ $# -eq 1 ] && [ ! -e "$1" ] && [[ "$1" =~ ^#?[0-9]+$ ]]; then
            __rustimal_panel "#${1#\#}"
            return
        fi
    fi
    command pr "$@"
}

# `do <task>` hands the task to Claude Code (`do -x <task>` to Codex), which works unseen
# while this pane shows the conversation. `do` alone brings the conversation back.
# DO_AGENT=codex changes the default.
__rustimal_do() {
    local agent="${DO_AGENT:-claude}"
    case "$1" in
        -x) agent=codex; shift ;;
        -c) agent=claude; shift ;;
    esac
    local task="$*"
    if [ -z "$RUSTIMAL_REVIEW_TOKEN" ] || [ -z "$RUSTIMAL_STATE" ] || [ ! -t 0 ] || [ ! -t 1 ]; then
        # Not typed in a pane (piped, say): let the agent print its answer here.
        case "$agent" in
            codex) printf '%s' "$task" | command codex exec --sandbox workspace-write - ;;
            *) printf '%s' "$task" | command claude -p --permission-mode acceptEdits ;;
        esac
        return
    fi
    printf '%s' "$task" >"$RUSTIMAL_STATE/do-$RUSTIMAL_PANE.txt" || return
    printf '\e]2;__rustimal_do__:%s:%s|%s\a' "$RUSTIMAL_REVIEW_TOKEN" "$PWD" "$agent"
    # Wait for rustimal to answer, as `review` does.
    local answer
    if ! IFS= read -rs -t 3 answer; then
        printf 'rustimal did not answer; if you just updated it, open a new window\n' >&2
        return 1
    fi
}

# `do` is a reserved word in bash, so it can't be a command. Instead, pressing Enter on a
# new line that starts with `do` rewrites it to `doit '...'` with the text quoted, so
# apostrophes, brackets and `?` need no escaping. The `do` of a loop is left alone.
doit() {
    __rustimal_do "$@"
}

# 1 once bash has asked for more of an unfinished command (the `> ` prompt).
__rustimal_more=0

__rustimal_enter() {
    local more=$__rustimal_more
    __rustimal_more=0
    # In an unfinished command, `do` belongs to a loop.
    [ "$more" = 1 ] && return
    [[ "$READLINE_LINE" =~ ^[[:space:]]*do([[:space:]]+(.*))?$ ]] || return
    local task="${BASH_REMATCH[2]}" flag="" quote="'\\''"
    if [[ "$task" =~ ^(-[cx])([[:space:]]+(.*))?$ ]]; then
        flag=" ${BASH_REMATCH[1]}" task="${BASH_REMATCH[3]}"
    fi
    task="${task%"${task##*[![:space:]]}"}"
    # Not inside ${task:+...}: the quoting works differently there.
    [ -n "$task" ] && task=" '${task//\'/$quote}'"
    READLINE_LINE="doit$flag$task"
    READLINE_POINT=${#READLINE_LINE}
}

# Bash expands PS2 each time it shows it; the array index runs the assignment.
__rustimal_none=()
PS2='${__rustimal_none[(__rustimal_more=1)*0]}'"${PS2:-> }"
# Ctrl+C drops an unfinished command. A trap of your own is left in place.
case "$(trap -p INT)" in
    "" | *__do_more*) trap '__rustimal_more=0' INT ;;
esac
# Enter: rewrite the line if needed, then accept it as usual (Ctrl+J).
bind -x '"\C-x\C-a": __rustimal_enter' 2>/dev/null
bind '"\C-m": "\C-x\C-a\C-j"' 2>/dev/null

# Tab on an empty line would make bash look up every command on PATH. With a
# Windows-sized PATH that takes ~10 seconds (the terminal looks frozen) and then
# prints thousands of names. Complete the files here instead, like `ls`.
complete -E -o filenames -f 2>/dev/null
# Never stop to ask "Display all N possibilities?"; just list them, all at once (rustimal
# scrolls, so there's no need for a --More-- pager that would also swallow clicks and typing).
bind 'set completion-query-items -1' 2>/dev/null
bind 'set page-completions off' 2>/dev/null

# Right before a command line runs: sync PATH, so a change made while the prompt
# was waiting applies to that command, and tell rustimal which command is starting
# so it can say when it's done (taskbar flash for long commands in the background).
__rustimal_preexec() {
    __rustimal_syncpath
    local cmd="${1//[[:cntrl:]]/ }" w="$1"
    printf '\e]2;__rustimal_cmd__:%s\a' "${cmd:0:200}"
    # A lone folder name that isn't also a command: autocd changes into it, and the next
    # prompt lists it. (A name with spaces comes quoted: 'My Folder'.)
    case "$w" in
        \'*\') w="${w#\'}"; w="${w%\'}" ;;
        \"*\") w="${w#\"}"; w="${w%\"}" ;;
        *[[:space:]]*) w="" ;;
    esac
    if [ -n "$w" ] && [ -d "$w" ] && [ -z "$(type -t -- "$w" 2>/dev/null)" ]; then
        __rustimal_autocd=1
    fi
}

# Runs once per command line, and only if nothing else (e.g. bash-preexec)
# already uses the DEBUG trap. What the Enter key and Ctrl+C run for `do` (below)
# is not the command line.
if [ -z "$(trap -p DEBUG)" ]; then
    trap '[ -n "$__rustimal_armed" ] && [[ $BASH_COMMAND != __rustimal_enter && $BASH_COMMAND != __rustimal_more=* ]] && { __rustimal_armed=; __rustimal_preexec "$BASH_COMMAND"; }' DEBUG
fi

# We are being sourced from the first PROMPT_COMMAND run; build the first prompt now.
__rustimal_prompt